Blog Post

Modernization Best Practices and Reusable Assets Blog
14 MIN READ

The Odd Couple - Latches and KEEP_NULLS

David_Lyth's avatar
David_Lyth
Icon for Microsoft rankMicrosoft
May 29, 2026

Introduction

Bulk loading is one of the most heavily optimised data paths in SQL Server. When it works well, hundreds of concurrent sessions can push millions of rows per minute into large tables with minimal CPU overhead. But when it doesn't, the symptoms can be baffling: CPU sits almost idle while every session waits, and throughput collapses by orders of magnitude.

We recently worked with a customer running a large-scale data processing platform on Azure SQL Hyperscale Database. The workload used Spark to bulk-insert data from hundreds of concurrent sessions into multi-billion-row tables, each using SEQUENCE objects to generate surrogate keys. After the team switched from row-by-row inserts to parallel bulk loading - a change that should have been a clear win - job durations went from minutes to over an hour. CPU utilisation sat at 2–5% while latch waits consumed over 98% of elapsed time.

The root cause turned out to be a surprising interaction between two seemingly unrelated SQL Server features: SEQUENCE object latch modes and the KEEP_NULLS bulk insert option. Each is individually well-documented, but their combined effect under high-concurrency bulk insert workloads produced catastrophic serialisation that was not obvious from the documentation alone.

This post distils the lessons learnt from that engagement into a reusable guide. We explain the mechanism, demonstrate the issue with reproducible tests on SQL Server 2025, and provide four independent fixes - the simplest of which is a single client-side configuration change that requires no schema modifications, no table rebuilds, and no downtime.

Note: Results may vary depending on hardware, SQL Server version, and workload patterns. All tests in this post were run on SQL Server 2025 (CU3). We recommend validating in your own dev/test environment.


Background: The Ingredients

The workload used a common pattern for generating surrogate keys during bulk inserts:

  1. SEQUENCE objects - CREATE SEQUENCE ... AS NUMERIC(28,0) - provided unique IDs
  2. DEFAULT constraints - ALTER TABLE ... ADD CONSTRAINT ... DEFAULT (NEXT VALUE FOR dbo.MySequence) - auto-populated IDs for rows that didn't supply them
  3. INSERT BULK - Spark's JDBC SQLServerBulkCopy loaded data in parallel from ~350 concurrent sessions
  4. The application called sp_sequence_get_range to pre-allocate ID ranges and supplied IDs with every row - the DEFAULT was there as a safety net, not the primary path

Each component is sensible on its own. The problem emerges from their interaction.


The Problem: Two Layers of Serialisation

Layer 1: INSERT BULK Fires the DEFAULT - Even When You Supply Values

When INSERT BULK (the TDS protocol used by BCP, BULK INSERT, and JDBC SQLServerBulkCopy) runs without the KEEP_NULLS option, the engine sets an internal flag (HNT_KEEPDEFAULT) that wraps every DEFAULT-constrained column as:

ISNULL(source_value, default_expression)

The default_expression - in this case NEXT VALUE FOR - is evaluated by a Sequence Project iterator that runs unconditionally per row, before the ISNULL decides whether to use it. Even though every row in our workload supplied a valid non-NULL ID, the sequence latch was still acquired, the counter was incremented, and the generated value was discarded.

This is fundamentally different from a regular INSERT ... SELECT statement, where NEXT VALUE FOR only fires if the column is actually omitted from the column list.

Layer 2: NUMERIC Sequences Take Exclusive Latches

SQL Server's sequence generator uses different synchronisation strategies depending on the sequence data type:

Sequence TypeLatch ModeConcurrency
NUMERIC / DECIMALExclusive (EX) per rowFully serialised - one thread at a time
BIGINT / INTShared (SH) + atomic CPU incrementConcurrent - multiple threads progress

The difference is not in the sequence cache (which only reduces disk I/O) but in the in-memory latch that protects the counter. With a NUMERIC(28,0) sequence, every single row - across all 350 concurrent sessions - must wait in line for one exclusive latch.

The Combined Effect

Combining both layers produces catastrophic serialisation:

  • 350 sessions × 50,000 rows each = 17.5 million unnecessary exclusive latch acquisitions per bulk load cycle
  • Each acquisition blocks all other sessions
  • CPU sits idle while threads wait in the latch queue
  • With NUMERIC(28,0) + no KEEP_NULLS, the workload was 98% wait time and 2% CPU time

The diagnostic signature is unmistakable: LATCH_EX dominant in wait stats, low CPU utilisation, and all waiting sessions blocked on METADATA_SEQUENCE_GENERATOR.


Proving It: The KEEP_NULLS Experiment

The simplest proof is to BCP 10,000 rows - all with application-supplied IDs - and check whether the sequence counter advances.

Setup

CREATE SEQUENCE dbo.Seq_Orders
    AS NUMERIC(28, 0)
    START WITH 1 INCREMENT BY 1 CACHE 50000000;
GO

CREATE TABLE dbo.Orders
(
    OrderID     NUMERIC(28, 0)  NOT NULL
        CONSTRAINT DF_Orders_ID DEFAULT (NEXT VALUE FOR dbo.Seq_Orders),
    CustomerID  INT             NOT NULL,
    OrderDate   DATE            NOT NULL,
    Amount      DECIMAL(10, 2)  NOT NULL,
    Filler      CHAR(80)        NOT NULL DEFAULT ('x'),
    CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (OrderID)
);
GO

Generate a BCP data file with IDs 1-10,000 pre-assigned by the application.

Test 1: BCP Without KEEP_NULLS (Default Behaviour)

bcp MyDB.dbo.Orders in orders.dat -c -t"," -S localhost\sql25 -T

Result:

MetricValue
Rows stored10,000
Stored OrderIDs1-10,000 (app-supplied - correct)
Sequence current_value20,000 (advanced from 1)

The sequence advanced by at least 10,000 values, even though the stored IDs are entirely from the application. The NEXT VALUE FOR default fired per-row, consumed sequence values, and discarded them all.

Test 2: BCP With KEEP_NULLS

bcp MyDB.dbo.Orders in orders.dat -c -t"," -S localhost\sql25 -T -k

Result:

MetricValue
Rows stored10,000
Stored OrderIDs1-10,000 (app-supplied - correct)
Sequence current_value1 (unchanged)

With -k (KEEP_NULLS), the sequence did not advance at all. The ISNULL wrapper was not applied, the Sequence Project iterator was not added to the plan, and all 10,000 latch acquisitions were eliminated.

Test 3: Table Without DEFAULT (Control)

bcp MyDB.dbo.Orders_NoDefault in orders.dat -c -t"," -S localhost\sql25 -T

Result: Sequence unchanged at 1. No DEFAULT means no Sequence Project, regardless of KEEP_NULLS.

Summary

ScenarioDEFAULT ExistsKEEP_NULLSSequence Advances?Latch Per Row?
BCP (default behaviour)YesNoYes - wastedYes - serialised
BCP with -kYesYesNoNo
BCP, no DEFAULTNoN/ANoNo
Regular INSERT...SELECTYesN/ANo (column supplied)No

The fourth row is important: a standard INSERT ... SELECT that includes the OrderID column does not fire the DEFAULT. This behaviour is specific to the INSERT BULK protocol.


Proving It: NUMERIC vs BIGINT Latch Contention

Even when the DEFAULT must fire (for example, when the application genuinely relies on it), the sequence data type determines the severity of the contention.

We tested three configurations at 32 concurrent sessions, each inserting 20,000 rows via INSERT ... DEFAULT VALUES:

MetricNUMERIC(28,0)BIGINT→NUMERICBIGINT
Latch wait requests137,321723
Latch total wait (ms)37,661210384
Latch max single wait (ms)535418

(32 sessions × 20,000 rows, SQL Server 2025, localhost)

The "BIGINT→NUMERIC" column uses a BIGINT sequence feeding a NUMERIC(28,0) column. This proves that the latch mode follows the SEQUENCE type, not the column type. Changing the sequence from NUMERIC(28,0) to BIGINT is a metadata-only operation (DROP SEQUENCE + CREATE SEQUENCE AS BIGINT) that delivers a 99.4% reduction in latch waits without requiring any table rebuild.

IDENTITY Columns Have the Same Issue

The NUMERIC-vs-BIGINT latch behaviour is not limited to SEQUENCE objects - it applies equally to IDENTITY columns. An IDENTITY column defined as NUMERIC(28,0) or DECIMAL(28,0) takes an exclusive latch on the identity counter for every inserted row, while BIGINT IDENTITY uses a shared latch with atomic increments. The identity counter latch class (IDENTITYVALUE_GENERATOR) follows the same exclusive-vs-shared pattern as METADATA_SEQUENCE_GENERATOR.

For tables that use NUMERIC IDENTITY under high-concurrency insert workloads, changing the column type to BIGINT eliminates the serialisation. Unlike sequences, changing an identity column's data type requires ALTER TABLE ... ALTER COLUMN, which triggers a table rebuild for large tables. Plan this as a maintenance window operation for billion-row tables.


The Fixes

Four independent fixes address different layers of the problem. Any one of them helps; the combination eliminates the issue entirely.

Fix 1: Enable KEEP_NULLS in the Bulk Copy Client

This is the single highest-impact fix. When the application supplies all column values, enabling KEEP_NULLS prevents the engine from evaluating any DEFAULT constraint during INSERT BULK.

Spark JDBC:

.option("bulkCopyForBatchInsertKeepNulls", "true")

JDBC directly:

SQLServerBulkCopyOptions opts = new SQLServerBulkCopyOptions();
opts.setKeepNulls(true);

BCP:

bcp ... -k

BULK INSERT:

BULK INSERT dbo.Orders FROM 'data.dat' WITH (KEEPNULLS);

Impact: Eliminates 100% of unnecessary sequence latch acquisitions during bulk insert. If the application already supplies the ID column, this fix has zero behavioural side effects.

Warning: KEEP_NULLS applies to all columns, not just the sequence column. When enabled, any column where the source data contains NULL will store NULL rather than the column's DEFAULT value. If your table has other DEFAULT constraints that the application relies on - for example, CreatedDate DATE DEFAULT GETDATE() or Status VARCHAR(20) DEFAULT 'Pending' - those defaults will not fire for NULL values when KEEP_NULLS is active. Before enabling this option, verify that the application supplies values for every column, or that NULL is acceptable for columns the application omits. If some columns genuinely need their defaults, Fix 2 (dropping only the sequence DEFAULT) is the safer server-side alternative.

Fix 2: Drop the DEFAULT Constraint

If every insert path supplies the ID column, the DEFAULT constraint serves no purpose. Dropping it is an instant metadata-only DDL operation:

ALTER TABLE dbo.Orders DROP CONSTRAINT DF_Orders_ID;

Impact: Same as Fix 1, but enforced server-side. No client configuration required. Consider this if multiple applications insert into the table and you cannot guarantee all of them will set KEEP_NULLS.

Fix 3: Change NUMERIC Sequences to BIGINT

For scenarios where the DEFAULT must fire - for example, ad-hoc inserts, SSMS, or stored procedures that omit the ID column - changing the sequence type from NUMERIC(28,0) to BIGINT switches from exclusive to shared latching:

-- Wrap in a transaction so the workload never sees a moment without the DEFAULT.
-- Without the transaction, inserts that rely on the DEFAULT would fail between
-- the DROP CONSTRAINT and the ADD CONSTRAINT.

BEGIN TRANSACTION;

    -- Step 1: Record current value
    DECLARE @current BIGINT;
    SELECT @current = CAST(current_value AS BIGINT)
    FROM sys.sequences WHERE name = 'Seq_Orders';

    -- Step 2: Drop DEFAULT, drop sequence, recreate as BIGINT, re-add DEFAULT
    ALTER TABLE dbo.Orders DROP CONSTRAINT DF_Orders_ID;
    DROP SEQUENCE dbo.Seq_Orders;

    CREATE SEQUENCE dbo.Seq_Orders
        AS BIGINT
        START WITH @current INCREMENT BY 1 CACHE 50000000;

    ALTER TABLE dbo.Orders
        ADD CONSTRAINT DF_Orders_ID DEFAULT (NEXT VALUE FOR dbo.Seq_Orders) FOR OrderID;

COMMIT TRANSACTION;

Wrapping the four statements in a single transaction ensures that concurrent inserts never see a state where the DEFAULT constraint is missing. Without the transaction, any insert that relies on the DEFAULT would fail with an error between the DROP CONSTRAINT and the ADD CONSTRAINT. All four operations are metadata-only and the transaction completes in under a second. The column type (NUMERIC(28,0)) does not need to change - SQL Server implicitly converts BIGINT to NUMERIC on insert.

Impact: 99.4% reduction in latch wait time when the DEFAULT does fire. BIGINT covers values up to 9.2 × 10^18, which is sufficient for virtually all surrogate key scenarios.

Fix 4: Right-Size Sequence Cache

The sequence CACHE setting controls how many values are pre-allocated in memory before the next disk write to the system catalog. The default cache is 50, which is far too small for high-volume bulk inserts:

ALTER SEQUENCE dbo.Seq_Orders CACHE 50000000;

Impact: Reduces disk I/O during sequence value generation. This does not change the latch mode - it only reduces how often the latch must also perform a catalog write. Fix 3 addresses the latch mode; this fix addresses the I/O.


When Each Fix Applies

ScenarioFix 1 (KEEP_NULLS)Fix 2 (Drop DEFAULT)Fix 3 (BIGINT)Fix 4 (Cache)
App supplies IDs via bulk insertPrimary fixBackup/server-sideReduces residual contentionHelpful
App relies on DEFAULT for IDsN/AN/APrimary fixRequired
Mixed: some paths supply, some don'tFor bulk pathsN/AFor DEFAULT pathsRequired
SEQUENCE used in sp_sequence_get_range onlyNot neededDrop itHelpfulHelpful

How to Detect This Pattern

Wait Stats

Query sys.dm_os_wait_stats or sys.dm_os_latch_stats for the signature:

-- Check for sequence latch contention
SELECT
    latch_class,
    waiting_requests_count,
    wait_time_ms,
    max_wait_time_ms
FROM sys.dm_os_latch_stats
WHERE latch_class = 'METADATA_SEQUENCE_GENERATOR'
  AND waiting_requests_count > 0;

If METADATA_SEQUENCE_GENERATOR appears with high waiting_requests_count alongside LATCH_EX dominating sys.dm_os_wait_stats, this pattern is likely active.

Sequence Consumption Rate

Compare the sequence advance rate against actual row insertions:

-- If sequence advances much faster than rows are inserted,
-- DEFAULT is firing unnecessarily during bulk inserts
SELECT
    s.name AS sequence_name,
    CAST(s.current_value AS BIGINT) AS current_value,
    s.data_type,
    s.cache_size
FROM sys.sequences s
WHERE s.data_type IN ('numeric', 'decimal');

Sequences typed as NUMERIC or DECIMAL under high-concurrency workloads are the risk profile.

Execution Plans

Look for a Sequence Project iterator in the execution plan of INSERT BULK operations. If the application supplies the ID column, a Sequence Project indicates the DEFAULT is being evaluated unnecessarily.


Test Scripts

The scripts used for all benchmarks in this post are included below. Each can be run on any SQL Server 2019+ instance.

Setup: Database, Sequences, and Tables

USE master;
GO

IF DB_ID('LatchKeepNullsDemo') IS NOT NULL
BEGIN
    ALTER DATABASE LatchKeepNullsDemo SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    DROP DATABASE LatchKeepNullsDemo;
END
GO

CREATE DATABASE LatchKeepNullsDemo;
GO
USE LatchKeepNullsDemo;
GO

-- Table WITH NEXT VALUE FOR DEFAULT (demonstrates the problem)
CREATE SEQUENCE dbo.Seq_Orders_Numeric
    AS NUMERIC(28, 0)
    START WITH 1 INCREMENT BY 1 CACHE 50000000;
GO

CREATE TABLE dbo.Orders_WithDefault
(
    OrderID     NUMERIC(28, 0)  NOT NULL
        CONSTRAINT DF_Orders_ID DEFAULT (NEXT VALUE FOR dbo.Seq_Orders_Numeric),
    CustomerID  INT             NOT NULL,
    OrderDate   DATE            NOT NULL,
    Amount      DECIMAL(10, 2)  NOT NULL,
    Filler      CHAR(80)        NOT NULL DEFAULT ('x'),
    CONSTRAINT PK_Orders_WithDefault PRIMARY KEY CLUSTERED (OrderID)
);
GO

-- Table WITHOUT DEFAULT (control)
CREATE TABLE dbo.Orders_NoDefault
(
    OrderID     NUMERIC(28, 0)  NOT NULL,
    CustomerID  INT             NOT NULL,
    OrderDate   DATE            NOT NULL,
    Amount      DECIMAL(10, 2)  NOT NULL,
    Filler      CHAR(80)        NOT NULL DEFAULT ('x'),
    CONSTRAINT PK_Orders_NoDefault PRIMARY KEY CLUSTERED (OrderID)
);
GO

-- NUMERIC(28,0) sequence for latch test
CREATE SEQUENCE dbo.Seq_Latch_Numeric
    AS NUMERIC(28, 0) START WITH 1 INCREMENT BY 1 CACHE 50000000;
GO

CREATE TABLE dbo.Inserts_Numeric
(
    ID      NUMERIC(28, 0)  NOT NULL
        DEFAULT (NEXT VALUE FOR dbo.Seq_Latch_Numeric),
    Filler  CHAR(100)       NOT NULL DEFAULT ('x'),
    CONSTRAINT PK_Inserts_Numeric PRIMARY KEY CLUSTERED (ID)
);
GO

-- BIGINT sequence for latch test
CREATE SEQUENCE dbo.Seq_Latch_BigInt
    AS BIGINT START WITH 1 INCREMENT BY 1 CACHE 50000000;
GO

CREATE TABLE dbo.Inserts_BigInt
(
    ID      BIGINT          NOT NULL
        DEFAULT (NEXT VALUE FOR dbo.Seq_Latch_BigInt),
    Filler  CHAR(100)       NOT NULL DEFAULT ('x'),
    CONSTRAINT PK_Inserts_BigInt PRIMARY KEY CLUSTERED (ID)
);
GO

-- BIGINT sequence + NUMERIC column (proves latch follows sequence type)
CREATE SEQUENCE dbo.Seq_Latch_Mixed
    AS BIGINT START WITH 1 INCREMENT BY 1 CACHE 50000000;
GO

CREATE TABLE dbo.Inserts_Mixed
(
    ID      NUMERIC(28, 0)  NOT NULL
        DEFAULT (NEXT VALUE FOR dbo.Seq_Latch_Mixed),
    Filler  CHAR(100)       NOT NULL DEFAULT ('x'),
    CONSTRAINT PK_Inserts_Mixed PRIMARY KEY CLUSTERED (ID)
);
GO
-- Helper: Generate BCP test data with app-supplied IDs
CREATE OR ALTER PROCEDURE dbo.GenerateBCPData @RowCount INT = 10000
AS
BEGIN
    SET NOCOUNT ON;
    ;WITH Nums AS (
        SELECT TOP(@RowCount) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n
        FROM sys.all_objects a CROSS JOIN sys.all_objects b
    )
    SELECT
        CAST(n AS NUMERIC(28,0))                                        AS OrderID,
        ABS(CHECKSUM(NEWID())) % 10000 + 1                              AS CustomerID,
        CAST(DATEADD(DAY, -(n % 365), '2026-03-31') AS DATE)            AS OrderDate,
        CAST(ABS(CHECKSUM(NEWID())) % 100000 / 100.0 AS DECIMAL(10,2))  AS Amount,
        REPLICATE('x', 80)                                              AS Filler
    FROM Nums;
END
GO

Test: BCP KEEP_NULLS Comparison

# Step 1: Export test data
bcp "EXEC LatchKeepNullsDemo.dbo.GenerateBCPData @RowCount=10000" \
    queryout orders.dat -c -t"," -S localhost\sql25 -T

# Step 2: Record sequence starting value
sqlcmd -S localhost\sql25 -d LatchKeepNullsDemo -Q \
    "SELECT name, CAST(current_value AS VARCHAR(30)) AS val
     FROM sys.sequences WHERE name = 'Seq_Orders_Numeric';"

# Step 3a: BCP WITHOUT KEEP_NULLS (DEFAULT fires per-row)
bcp LatchKeepNullsDemo.dbo.Orders_WithDefault in orders.dat \
    -c -t"," -S localhost\sql25 -T

# Check: sequence should have advanced (values wasted)
sqlcmd -S localhost\sql25 -d LatchKeepNullsDemo -Q \
    "SELECT name, CAST(current_value AS VARCHAR(30)) AS val
     FROM sys.sequences WHERE name = 'Seq_Orders_Numeric';"

# Step 3b: Reset, then BCP WITH KEEP_NULLS (DEFAULT suppressed)
sqlcmd -S localhost\sql25 -d LatchKeepNullsDemo -Q \
    "TRUNCATE TABLE dbo.Orders_WithDefault;
     ALTER SEQUENCE dbo.Seq_Orders_Numeric RESTART WITH 1;"

bcp LatchKeepNullsDemo.dbo.Orders_WithDefault in orders.dat \
    -c -t"," -S localhost\sql25 -T -k

# Check: sequence should NOT have advanced
sqlcmd -S localhost\sql25 -d LatchKeepNullsDemo -Q \
    "SELECT name, CAST(current_value AS VARCHAR(30)) AS val
     FROM sys.sequences WHERE name = 'Seq_Orders_Numeric';"

Test: Concurrent Latch Comparison (PowerShell)

# Compare NUMERIC vs BIGINT sequence latch contention
# under N concurrent sessions, each inserting via INSERT...DEFAULT VALUES

param(
    [int]$Sessions = 16,
    [int]$RowsPerSession = 10000,
    [string]$Server = "localhost\sql25"
)

$db = "LatchKeepNullsDemo"

function Invoke-ConcurrentInserts {
    param([string]$TableName, [string]$Label)

    sqlcmd -S $Server -E -d $db -Q "TRUNCATE TABLE dbo.$TableName;" -b 2>&1 | Out-Null
    sqlcmd -S $Server -E -d $db `
        -Q "DBCC SQLPERF('sys.dm_os_latch_stats', CLEAR) WITH NO_INFOMSGS;" `
        -b 2>&1 | Out-Null

    $sql = "SET NOCOUNT ON; DECLARE @i INT = 0; " +
           "WHILE @i < $RowsPerSession BEGIN " +
           "INSERT INTO dbo.$TableName DEFAULT VALUES; SET @i += 1; END"

    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    $jobs = @()
    for ($s = 0; $s -lt $Sessions; $s++) {
        $jobs += Start-Job -ScriptBlock {
            param($srv, $database, $query)
            sqlcmd -S $srv -E -d $database -Q $query -b 2>&1 | Out-Null
        } -ArgumentList $Server, $db, $sql
    }
    $jobs | Wait-Job | Out-Null
    $sw.Stop()
    $jobs | Remove-Job -Force

    # Capture latch stats
    $raw = sqlcmd -S $Server -E -d $db `
        -Q "SELECT latch_class, waiting_requests_count, wait_time_ms,
            max_wait_time_ms FROM sys.dm_os_latch_stats
            WHERE latch_class = 'METADATA_SEQUENCE_GENERATOR';" `
        -W -s "," -h -1 2>&1
    $line = $raw | Where-Object { $_ -match 'METADATA' } | Select-Object -First 1

    $requests = 0; $waitMs = 0; $maxMs = 0
    if ($line -match 'METADATA_SEQUENCE_GENERATOR\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)') {
        $requests = [long]$Matches[1]; $waitMs = [long]$Matches[2]; $maxMs = [long]$Matches[3]
    }

    Write-Host ("  {0,-20} Elapsed: {1,6} ms | Latch waits: {2,8} | Wait: {3,6} ms" `
        -f $Label, $sw.ElapsedMilliseconds, $requests, $waitMs)

    return @{ Label = $Label; Elapsed = $sw.ElapsedMilliseconds;
              Requests = $requests; WaitMs = $waitMs; MaxMs = $maxMs }
}

Write-Host "Sessions: $Sessions | Rows/session: $RowsPerSession"

$rNum = Invoke-ConcurrentInserts -TableName "Inserts_Numeric" -Label "NUMERIC(28,0)"
$rMix = Invoke-ConcurrentInserts -TableName "Inserts_Mixed"   -Label "BIGINT->NUMERIC"
$rBig = Invoke-ConcurrentInserts -TableName "Inserts_BigInt"  -Label "BIGINT"

if ($rNum.WaitMs -gt 0) {
    $mixPct = [math]::Round((1 - $rMix.WaitMs / $rNum.WaitMs) * 100, 1)
    $bigPct = [math]::Round((1 - $rBig.WaitMs / $rNum.WaitMs) * 100, 1)
    Write-Host "`nBIGINT->NUMERIC latch reduction: $mixPct%"
    Write-Host "BIGINT latch reduction: $bigPct%"
}

Key Takeaways

  1. INSERT BULK without KEEP_NULLS evaluates DEFAULT expressions per-row - even when the source data supplies non-NULL values. For NEXT VALUE FOR defaults, this means one latch acquisition per row, per session, regardless of whether the value is used. This is documented behaviour, but the performance implications for sequence-based defaults under concurrency are rarely discussed.
  2. NUMERIC / DECIMAL sequences use exclusive latches; BIGINT / INT use shared latches with atomic increments. The sequence cache setting reduces disk I/O only - it does not change the latch mode. The latch mode is determined by the sequence type, not the column type.
  3. The combination creates a force multiplier. Each factor is tolerable in isolation. Exclusive latching with a few sessions is fine. Unnecessary DEFAULT evaluation at low concurrency has negligible cost. But 350 sessions × exclusive latch × per-row evaluation = complete serialisation.
  4. The diagnostic signature is clear. LATCH_EX dominant in wait stats + METADATA_SEQUENCE_GENERATOR in sys.dm_os_latch_stats + low CPU utilisation = this pattern. Low CPU under high concurrency means serialisation, not low demand.
  5. The fix is simple. Setting KeepNulls = true in the bulk copy options eliminates the issue entirely when the application supplies all values. No schema changes required, no table rebuilds, no downtime.

Documentation References


Feedback and Suggestions

If you have feedback or suggestions, please contact the Databases SQL Customer Success Engineering (Ninja) Team (datasqlninja@microsoft.com).

Note: For additional information about migrating various source databases to Azure, see the Azure Database Migration Guide.

Published May 12, 2026
Version 1.0
No CommentsBe the first to comment