Most incremental loads I've seen are built on one line.
WHERE Id > @LastLoadedId It's fast, it's easy to explain, and it passes every test you're likely to write. On a busy database it also drops rows now and then, with no error and no warning. The fact table just ends up slightly short, and nobody notices until finance asks why the warehouse and the ledger disagree by 500.00.
I wanted to see this happen rather than take it on faith, so I reproduced it on a double-entry ledger I've been building in SQL Server for a savings and credit co-op. This post walks through the reproduction, explains why it happens, and shows the fix I ended up using.
The setup
The source is an append-only ledger. Every money movement is a row in JournalEntry with two or more rows in JournalLine. Nothing is ever updated or deleted, so it looks like the easiest possible table to load incrementally. At the time of the test it held about 8,300 entries and 17,400 lines.
The target is a reporting fact table, dw.FactJournalLine, with one row per journal line.
Here is the naive load. It remembers the highest JournalEntryId it has seen and loads everything above it next time.
DECLARE @From bigint = (SELECT LastId FROM dw.NaiveWatermark), @To bigint = (SELECT MAX(JournalEntryId) FROM dbo.JournalEntry); INSERT dw.NaiveFactJournalLine (JournalLineId, JournalEntryId, Debit, Credit) SELECT jl.JournalLineId, jl.JournalEntryId, jl.Debit, jl.Credit FROM dbo.JournalLine AS jl WHERE jl.JournalEntryId > @From AND jl.JournalEntryId <= @To; UPDATE dw.NaiveWatermark SET LastId = @To; The initial full load worked perfectly. 17,392 lines in, totals matching the source to the cent.
Three sessions, one missing row
To trigger the bug you need two writers and a reader running at the same time. I used three sqlcmd sessions started together from a shell script.
- Session A posts a teller deposit of 500.00 inside a transaction, then waits 8 seconds before committing. In real life that's a slow network, a lock wait or a long trigger.
- Session B waits 2 seconds, posts a mobile deposit and commits straight away.
- Session C waits 4 seconds and runs the incremental load.
This is what came back.
15:06:17.465 A inserted JournalEntryId 8314, not committed yet 15:06:19.468 B inserted and committed JournalEntryId 8315 15:06:21.433 C naive load: 2 lines, watermark moved to id 8315 15:06:25.475 A committed 8314 A was given id 8314 first, but B committed 8315 before A finished. When the load ran, it could see 8315 and not 8314, so it loaded B's two lines and moved the watermark to 8315. Four seconds later A committed. Entry 8314 now sits below the watermark, and every future run asks for JournalEntryId > 8315. It will never be loaded.
After everything had committed I ran the load again and compared both fact tables with the source.
Reference JournalEntryId InNaiveLoad InRowversionLoad DEMO-A-150617 8314 MISSING yes DEMO-B-150617 8315 yes yes Side Lines Debits source 17400 25,630,736.85 rowversion load 17400 25,630,736.85 naive id load 17398 25,629,536.85 Two lines and 500.00 gone, and the load reported success every time.
Why it happens
An IDENTITY value is handed out when the row is inserted. The row only becomes visible to other sessions when the transaction commits. Those two moments can be seconds apart, and transactions don't commit in the order they started.
So "the highest id I can see" doesn't mean "every id below this is done". It only means "every id below this that has committed is done". Anything still in flight with a lower id gets skipped for good.
The same thing applies to a lot of other columns people use as watermarks.
-
SEQUENCEvalues, for the same reason as IDENTITY. -
CreatedAt DEFAULT SYSUTCDATETIME()columns. The timestamp is taken at insert time, not commit time. - Auto-increment keys in other databases. This isn't a SQL Server quirk. It's how transactions work.
A common workaround is to leave a safety gap, something like "only load rows older than five minutes". That makes the bug rarer, not impossible. A transaction that stays open for six minutes still slips through, and the gap adds five minutes of delay to every load.
Fixing it with rowversion and MIN_ACTIVE_ROWVERSION()
SQL Server has a column type built for this. A rowversion column gets a new value from a database-wide counter every time a row is inserted or updated. On its own that has the same problem as IDENTITY, because the value is also assigned at insert time.
The piece that makes it work is MIN_ACTIVE_ROWVERSION(). It returns the lowest rowversion that belongs to a transaction that is still open. Every row with a rowversion below that value has committed. So instead of loading "up to the highest value I can see", the load stops just before the oldest open transaction.
ALTER TABLE dbo.JournalEntry ADD RowVer rowversion NOT NULL; CREATE UNIQUE INDEX UX_JournalEntry_RowVer ON dbo.JournalEntry (RowVer); DECLARE @From binary(8) = ISNULL((SELECT NextRowVer FROM dw.LoadWatermark WHERE TableName = 'FactJournalLine'), 0x0), @To binary(8) = MIN_ACTIVE_ROWVERSION(); BEGIN TRANSACTION; INSERT dw.FactJournalLine (JournalLineId, JournalEntryId, TxnDateKey, Reference, Channel, BranchCode, GLCode, AccountNo, Debit, Credit, IsReversal) SELECT jl.JournalLineId, je.JournalEntryId, CONVERT(int, CONVERT(char(8), je.TxnDate, 112)), je.Reference, je.Channel, b.BranchCode, g.GLCode, a.AccountNo, jl.Debit, jl.Credit, IIF(je.ReversalOfEntryId IS NULL, 0, 1) FROM dbo.JournalEntry AS je JOIN dbo.JournalLine AS jl ON jl.JournalEntryId = je.JournalEntryId JOIN dbo.Branch AS b ON b.BranchId = je.BranchId JOIN dbo.GLAccount AS g ON g.GLAccountId = jl.GLAccountId LEFT JOIN dbo.Account AS a ON a.AccountId = jl.AccountId WHERE je.RowVer >= @From AND je.RowVer < @To AND NOT EXISTS (SELECT 1 FROM dw.FactJournalLine AS f WHERE f.JournalLineId = jl.JournalLineId); UPDATE dw.LoadWatermark SET NextRowVer = @To WHERE TableName = 'FactJournalLine'; COMMIT TRANSACTION; In the same three-session race, this load did something that looks wrong at first. At the 4-second mark it loaded nothing, not even B's committed entry.
15:06:21.448 C rowversion load: 0 lines, next run starts at 0x000000000000272F That's correct. B's row has a higher rowversion than A's, and A was still open, so the load stopped at A. On the next run, with A committed, it picked up both entries (4 lines), and the fact table matched the source exactly.
The trade-off is latency, not loss. A transaction that stays open for a long time holds back the load until it finishes. That's the behaviour you want for a ledger. It's also worth monitoring, because a transaction that's been open for an hour is a problem in its own right.
One more thing to know. A rowversion changes on every update, not only on insert. My ledger is append-only, so every new rowversion is a new row. On a table that gets updated you'd see the same row come through again after each change, so the load would need to upsert with MERGE instead of insert.
Make the load safe to run twice
Loads fail halfway. Schedulers retry them. Somebody runs them by hand at the wrong moment. Two small things make this one safe to rerun.
- The insert and the watermark update are in one transaction. If the insert fails, the watermark doesn't move, and the next run tries the same window again.
- The
NOT EXISTSguard skips lines that are already in the fact table. Running the load twice in a row loaded 0 lines the second time.
Prove it, every time
The bug above is silent, so the only way to catch it is to look for it. After every load I compare the fact table with the source on row count and on the sum of each money column.
SELECT 'source' AS Side, COUNT(*) AS Lines, SUM(Debit) AS Debits, SUM(Credit) AS Credits FROM dbo.JournalLine UNION ALL SELECT 'warehouse', COUNT(*), SUM(Debit), SUM(Credit) FROM dw.FactJournalLine; That check is what showed the naive load was 2 lines and 500.00 short. In a real pipeline it would run after every load and raise an alert when the two sides disagree. For financial data I'd treat a mismatch as a failed load, not a warning.
What about CDC?
SQL Server's Change Data Capture reads the transaction log, so it sees changes in commit order and also handles updates and deletes. It's the right tool when the source table changes in place. It also needs SQL Server Agent, change tables and a retention policy, and someone has to look after all of that.
For an append-only source like a ledger, rowversion plus MIN_ACTIVE_ROWVERSION() gives the same guarantee for far less machinery. Other databases have the same underlying problem and their own answers, such as logical replication in PostgreSQL.
Takeaways
-
WHERE Id > @LastIdassumes rows commit in id order. They don't. - The same goes for sequences and created-at timestamps.
- Load up to
MIN_ACTIVE_ROWVERSION(), not up to the highest value you can see. - Keep the watermark update in the same transaction as the load.
- Reconcile counts and sums against the source after every run, because this kind of bug never raises an error.
The full code, including the three-session reproduction script, is on GitHub in isaactony/sacco-ledger. Run demo/watermark_race.sh after building the database and you can watch the row go missing yourself.
Have you been bitten by this one? I'm curious what watermark column your team settled on.

