What you will be able to do
- Walk the INSERT diagnosis flowchart and name the bounding resource from the wait type.
- Choose between row-by-row, set-based, and bulk load and state the log cost of each.
- Explain the sequential-key hot-page convoy and the three ways to spread it.
- Design an idempotent insert that is safe under retries and concurrency.
- State what constraints and triggers charge per row and when a staging table earns its cost.
Concepts covered
An insert looks like one operation but pays four costs - the row’s own write, the log record, the index maintenance, and whatever contention the key shape invites. The diagnosis is finding which of the four is the ceiling, because the fix for each is different and fixing the wrong one adds cost without speed.
The analogy for the hot page is a supermarket that funnels every shopper through one checkout
while the other lanes sit closed - a sequential key sends every inserter to the same last page of
the index, so the queue is a property of the key shape, not of the hardware. The most common
beginner mistake is the commit-per-row loop: autocommit inserts pay one log flush per row and hit
the WRITELOG ceiling long before the table itself is under load, while batching the same rows
into one transaction removes most of the cost and changes nothing else.
The INSERT throughput flowchart
Slow INSERT - which ceiling
Top wait?
WRITELOG, PAGELATCH, LCK_M, or low waits with high CPU
Log flush, hot page, blocking, or index maintenance - the wait picks the branch
WRITELOG high?
Commit-flush bound - too many small commits
Batch rows into one transaction - one flush instead of one per row
PAGELATCH on last page?
Sequential-key convoy - all inserters fight one page
Spread the key: non-sequential, OPTIMIZE_FOR_SEQUENTIAL_KEY, or reverse the key
Else - maintenance cost
Indexes, triggers, constraints per row
Each index is a second write; stage the load and index afterward
Commit frequency - the log-flush ceiling
Every COMMIT pays one log flush (WRITELOG). The difference between commit-per-row and
commit-per-batch is not a few percent - it is the difference between a flush per row and a flush
per thousand:
-- Inefficient: one flush per row
INSERT INTO dbo.events (...) VALUES (@a, @b); -- in a loop, autocommit
-- Optimised: one flush for the whole batch
BEGIN TRAN;
INSERT INTO dbo.events (...) SELECT ... FROM @batch;
COMMIT;
Bulk paths go further - BULK INSERT writes extents, not rows, and under SIMPLE/BULK_LOGGED
with TABLOCK on an empty or indexed-empty table it is minimally logged: only the extent
allocations are logged. The full prerequisite matrix is in the mechanism course; the rule here is
that a fully-logged bulk load under FULL recovery is a log-growth incident, not a speed problem.
The hot page - sequential-key contention
An ever-increasing key - IDENTITY, datetime DEFAULT, NEWID() sorted - sends every insert to
the same physical last page of the clustered index. Under concurrency every inserter queues on
a buffer latch for that page: throughput plateaus while CPU idles, all waiting PAGELATCH_EX.
Three real fixes, each with a price:
- A non-sequential key - a hash, a reversed key, or a natural key that spreads inserts across the tree. Costs the “hot recent data” locality that made the sequential key attractive.
OPTIMIZE_FOR_SEQUENTIAL_KEY(2019+) - a table/index hint that lets the engine queue inserters fairly on the last page instead of racing on the latch. Does not remove the contention; makes it scale better.- Accept and bound it - on moderate load the convoy is invisible; measure before paying for a fix.
The other per-row taxes
- Every index - each nonclustered index is a second write per row: insert the key, possibly split a page. Five indexes means five writes plus the row.
- Constraints -
CHECKandFOREIGN KEYvalidate per row; a foreign key is a lookup into the parent table for every inserted row. - Triggers -
AFTER INSERTruns once per statement but inside the transaction, and a trigger that itself writes multiplies the log and lock cost. - Idempotency - concurrent retries need a guard: a
UNIQUEconstraint plusINSERT ... WHERE NOT EXISTS, orMERGEwithHOLDLOCK- because a retry on a plain insert produces duplicates, and a retry on a transaction produces phantom failures.
The honest pattern for heavy ingest
Stage and swap: bulk-load into a heap staging table (minimally logged, no index maintenance),
validate and deduplicate there, then INSERT ... SELECT into the real table in batches, or ALTER TABLE ... SWITCH the staged partition in as one metadata operation. The staging table costs a
second copy of the data; it buys a load that never touches the hot table’s index structure until it
is clean.
The diagnostic toolkit
-- Are inserts waiting, and on what - run during the load
SELECT session_id, wait_type, wait_resource, blocking_session_id
FROM sys.dm_exec_requests r JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
WHERE wait_type IN ('WRITELOG','PAGELATCH_EX','PAGELATCH_UP','LCK_M_X');
-- Expected: WRITELOG -> commit-bound; PAGELATCH on one page -> hot page;
-- LCK_M_X with a blocker -> a real lock fight, not a latch.
-- The hot page's identity
SELECT wait_resource FROM sys.dm_os_waiting_tasks
WHERE wait_type LIKE 'PAGELATCH%' GROUP BY wait_resource ORDER BY COUNT(*) DESC;
-- Expected: one page id dominates - that is the last page of the sequential key.
What to measure, before and after
| Metric | Instrument | The pass criterion |
|---|---|---|
| Inserts/second | A timed batch loop | Throughput rises; it is the point of the fix |
WRITELOG wait |
Wait-stats delta | Falls when commits are batched |
PAGELATCH_* on the hot page |
dm_os_waiting_tasks |
Disappears or spreads after the key fix |
| Log bytes | sys.dm_io_virtual_file_stats on the log file |
A bulk load under minimal logging writes far less |
Advanced exercise and answer key
Exercise. An ingest workload commits each row individually and is WRITELOG-bound. A colleague
proposes delayed durability to fix it. State the two real fixes, the risk delayed durability adds,
and how you would decide.
Answer. The real fixes: batch the commits (one flush per N rows - the honest fix, no durability loss) or a bulk/minimally-logged path if the load is large. Delayed durability returns the commit before the flush - faster, but a crash loses acknowledged commits in the window. Decision: batching first, always; delayed durability only if the workload can tolerate the loss window, and it is a documented durability trade, not a performance freebie.
Guided practice
A beginner exercise, worked step by step in a scratch database. It times the same insert volume two ways so the log-flush ceiling is something you have felt, not just read about.
- Build the events table. In a scratch database run
CREATE TABLE dbo.events (id BIGINT IDENTITY PRIMARY KEY, a INT NOT NULL, b INT NOT NULL);Check: an empty clustered table on an ever-increasing key - the sequential-key shape this lesson is about. - Time a commit-per-row loop. Run
SET NOCOUNT ON; DECLARE @i INT = 0; WHILE @i < 10000 BEGIN INSERT INTO dbo.events (a, b) VALUES (@i, @i); SET @i += 1; ENDand record the elapsed time. Check: it completes, but each autocommittedINSERTpaid one log flush - the elapsed time is theWRITELOGceiling made visible. If it felt instant, raise the row count until the flush cost shows; the count is a convenience, the one-commit-per-row shape is the point. - Time the same volume as one transaction. Wrap a batch in a single transaction - for example
BEGIN TRAN; INSERT INTO dbo.events (a, b) SELECT TOP (10000) object_id, object_id + 1 FROM sys.all_objects; COMMIT;Check: the same volume lands much faster because the batch pays one flush instead of one per row. If the times were similar, confirm the batch ran inside one transaction - the flush count is the variable being changed. Revisit the commit-frequency section. - Find the hot page. While a long single-row insert loop runs in one session, run the file’s
toolkit query in another:
SELECT wait_resource FROM sys.dm_os_waiting_tasks WHERE wait_type LIKE 'PAGELATCH%' GROUP BY wait_resource ORDER BY COUNT(*) DESC;Check: one page id dominates - the last page of the sequential clustered key. If nothing appears, the loop finished before the sample; run it longer and sample again. Revisit the sequential-key section. - Match each ceiling to its fix. For each branch of the throughput flowchart, state the fix
you would apply to this workload.
Check: commit-per-row leads to batched transactions, or a bulk path when the load is large;
PAGELATCHon one page leads to spreading the key - a non-sequential key,OPTIMIZE_FOR_SEQUENTIAL_KEYon 2019+, or accepting and bounding it; per-row maintenance leads to the stage-and-swap pattern. Any pairing you had to guess is a section to reread.
Check your understanding
Ordered easy to hard. Answer each before reading the answer; a wrong answer names where to look.
- Why is one batch in a transaction faster than the same rows committed individually?
Every
COMMITpays one log flush, so commit-per-row pays a flush per row while the batch pays one for everything. The row work is identical - the commit count is the whole difference. Revisit the log-flush ceiling if you attributed it to overhead generally. - What is the hot page, and what kind of wait does it produce?
An ever-increasing key sends every insert to the last leaf page of the clustered index, and
concurrent inserters queue on that page’s buffer latch -
PAGELATCH_EX. It is a latch on a page structure held for microseconds, not a lock held to commit. Revisit the sequential-key section if you described it as row locking. - Why does
OPTIMIZE_FOR_SEQUENTIAL_KEYnot remove the contention? It queues the inserters fairly on the last page instead of letting them race on the latch - it makes the convoy scale better but does not spread the inserts. Spreading needs a non-sequential key, which costs the hot-recent-data locality. Revisit the three fixes. - Why is a fully-logged
BULK INSERTunderFULLrecovery a risk rather than a fix? It becomes a log-growth incident, not a speed problem - minimal logging only applies underSIMPLEorBULK_LOGGEDwithTABLOCKon an empty or indexed-empty table. Revisit the bulk-path paragraph if you assumed bulk was automatically minimally logged. - A retry of a plain insert produced duplicates. What is the honest guard, and why did the plain
insert fail?
Nothing enforced the deduplication, so the retried row simply landed again. The guard is a
UNIQUEconstraint plusINSERT ... WHERE NOT EXISTS, orMERGEwithHOLDLOCK. Revisit the idempotency point in the per-row taxes.
Where SQL Server sits
How this component relates to the rest of the stack. Items without a link are not covered here yet.
Deployed with
Commonly run alongside
- Windows Failover Clustering