Incident Review · 7 min read

Why does incremental sync by updated_at silently miss records?

Background: what incremental sync and a watermark are for

AllyOS is the business system I built with Claude Code and a small team of AI agents. Every hour it pulls new and changed activity records (calls, meetings, emails and so on) from a third-party SaaS product. Pulling everything each time is too slow, so it only asks for what changed since last time. That is incremental sync.

To know where "last time" ended, you keep a marker called a watermark. The most common version: remember the largest updated_at you saw, and next run ask only for records whose updated_at is strictly later.

Think of reading a very long book, at most 500 lines a day. Each night you put in a bookmark that says "I got to 9:14:07.369". The next day you start right after that. Almost everyone builds sync this way, and this incident shows the one common case where a time-only bookmark skips pages.

The other half of the story is the cap: the vendor's search API returns at most 100 records per page, and each of our runs reads at most 5 pages, so a run pulls at most 500 records.

The symptom: after a replay, a handful of records never came back

It started with a different fix. To backfill a missing field on old emails, we rewound the email watermark by a year and let the job pull everything again. Once it caught up, almost every record had been repaired, but a small number were never fetched again. They still existed in the vendor's system and were not archived.

The decisive clue: **every missing record had an updated_at exactly equal to the watermark where some run had stopped, down to the millisecond.** Looking up that instant in the vendor's system showed several records sharing it; some had been fetched and the rest had not.

That points straight at the root cause, but "looks like" is not "is". The next step was making it fail on demand.

Reproducing it: return the ties in scrambled order

I wrote a stub of the vendor API that applies the real filter, single-field sort and paging rules, plus one crucial detail: records with the same timestamp come back in a scrambled order, because the real API does not promise any order among ties. The test chains runs together, so each run reads the cursor the previous one wrote.

The input is 490 records with distinct timestamps plus 30 records that share one timestamp (code below is generalized):

Run 1: hits the 500-record cap; record 500 is the 10th member of the tie group
       watermark := that instant
Run 2: asks only for updated_at > that instant
       -> the other 20 members of the group never show up again
Expected: all 520 after two runs. Actual: 500.

On 2026-12-01 I checked out the code from just before the fix and ran these 4 tests against it: 3 failed, 1 passed (the passing one covers a run that reaches the end in one go, which was never broken).

Root cause: "strictly greater" hides an unstated assumption

The condition updated_at > watermark silently assumes that every record at the watermark instant was already read in this run.

That is only true when the run reached the last page. Once the 500-record budget runs out and the last record sits in the middle of a tie group, the rest of that group can never satisfy "strictly greater".

It is tempting to treat "several records in the same millisecond" as a rare coincidence. It is not: bulk operations (automation workflows, bulk association, imports) stamp large batches with an identical modification time. And because the vendor's search sorts on only one field, with no defined order among ties, you cannot resume from the middle of a group using the timestamp alone.

Our incident log files this under "wrong assumption": the code was built on a belief that was false from the day it was written, not broken later by some other change.

The fix: add "which id I reached within this instant" to the cursor

The idea is an optional resume position in the cursor: "the group at the watermark instant is unfinished; continue after this id." Ids are unique and have a defined order, so "the last id I read" is something you can resume from exactly.

def fetch_window(cursor, budget=500):
    seen = []
    if cursor.tie_after is not None:          # last run left a group unfinished
        seen += search(updated_at == cursor.mark, id > cursor.tie_after,
                       order_by="id", limit=budget)
        if len(seen) == budget:               # budget gone again: advance id only
            return cursor.with_tie(seen[-1].id), seen
    rest = search(updated_at > cursor.mark, order_by="updated_at",
                  limit=budget - len(seen))
    seen += rest
    if not has_more(rest):                    # reached the end: nothing left here
        return Cursor(mark=max_time(seen, cursor.mark)), seen
    return Cursor(mark=max_time(seen), tie_after="0"), seen  # re-read group by id

Three outcomes, three cursor shapes:

  1. Reached the end: watermark = max timestamp, no resume position. Once caught up, hourly runs re-read nothing.
  2. Budget ran out: watermark = max timestamp, resume position "0", meaning "next run, first read this whole instant in id order". The few records read twice were already stored, so the write must be idempotent (writing the same record twice ends up the same as writing it once).
  3. Budget ran out while resuming: advance the id only, leave the watermark alone.

It also has to be loop-free. Each resumed page strictly advances the id and the group is finite, so it always drains. The tests include two extreme groups, a full 500-record run that all shares one instant and a 1,200-record tie group, and both drain in a bounded number of runs. Records are also de-duplicated by id within a run, so a batch write never receives the same object twice.

The cost: while catching up, every run spends one page re-reading the group, so it advances about 400 records instead of 500.

The second bug: a failed run wrote an empty cursor

While following the cursor through the code, I found a latent problem next to it: when a run failed at the outermost level, it recorded its cursor as an empty {}.

The trouble is that the reader and the writer of the cursor disagreed. The writer assumed a failed run would never be used as a starting point. The reader simply takes the most recent row, success or failure. Once an empty cursor is read, the job falls back to its default "last 24 hours", and everything between the old watermark and 24 hours ago is never fetched. It hurts most during a catch-up like the replay above.

Production records showed this had never happened yet, so no data was lost, but it was only a matter of time. The fix has two rules:

  • If the cursor was read: on failure, write "old cursor + progress of the kinds that were stored successfully", keeping the resume position.
  • If the cursor could not even be read: write no row at all, and let error monitoring report the failure.

I chose not to "write a null cursor and teach the reader to skip failed rows", because that means changing a database function too, while fixing only the writer already guarantees that a failed run never moves the watermark backwards. The trade-off: a run that failed to read its cursor does not appear in the run log. On 2026-12-01 these 3 tests run against the pre-fix code: all 3 fail.

Measured numbers

MetricValueHow we measured
Tie-group reproduction tests, before the fix3 of 4 fail2026-12-01, pre-fix commit, Deno 2.1.4
Empty-cursor reproduction tests, before the fix3 of 3 fail2026-12-01, same setup
Both suites after the fix7 of 7 pass, 120 ms of test time2026-12-01, Deno 2.1.4, Linux container
Per-run fetch cap5 pages x 100 = 500 recordsread from the code, 2026-12-01
Reproduction input490 distinct timestamps + 30 sharing onetest code, 2026-12-01
Progress per run while catching upabout 400 (one page re-reads the tie group)production observation recorded in the incident
AllyOS incident reports to date1,055, of which 64 are "wrong assumption"2026-12-01, main development branch

A checklist you can copy

  1. Audit your incremental syncs: is the filter updated_at > watermark, and is there a per-run cap? If both, you have this bug.
  2. Write a test: create a tie group, put the cap in the middle of it, and return the ties in scrambled order.
  3. Add a "within this instant, read up to id X" resume position to the cursor, and sort by the unique id when resuming.
  4. Make the write idempotent (upsert by the external id) so re-reading a group never creates duplicates.
  5. Clear the resume position when a run reaches the end, so caught-up runs re-read nothing.
  6. Check every path that writes the cursor, including error paths: write a value that is safe to start from, or write nothing.
  7. Search by mechanism, not symptom: check every place that pages by a timestamp watermark with a cap.

If the data lives in your own PostgreSQL database it is simpler: use the composite condition (updated_at, id) > (last_ts, last_id) and sort by both columns; PostgreSQL's row constructor comparison compares column by column exactly this way. For the idea of idempotency, see Idempotence on Wikipedia.

FAQ

Can't I just change ">" to ">="?

Not on its own. With ">=" every run re-reads the whole group at the watermark instant. Worse, if the group is bigger than one run's cap (say a bulk import stamped 1,000 records with the same instant), every run fills its budget inside that group, the watermark never moves, and you have an infinite loop. You need a deterministic order inside the group to resume from, and the id is the natural one.

Does this happen with my own database too?

Yes. Any API that pages by timestamp with a limit has this problem, including pagination endpoints you write yourself. In your own database, composite keyset pagination on (updated_at, id) solves it in one step; the two-phase read in this post is only needed when a third-party API sorts on a single field. My earlier post on a dropped column that old functions never complained about is another case of code resting on an unstated assumption.

How do I know whether I have already lost data?

Look for a shared fingerprint among missing records. Here it was unmistakable: every lost record's timestamp equaled a watermark where some run had stopped. After the fix, rewind the watermark to just before the first stop point, let it replay, and confirm those records come back. If your team wants data syncs that can be audited and replayed like this, take a look at my services and process.

About the author

Morningstar Lucifer (晨星·路西法) is an AI engineering systems architect based in Chengdu, China, with 12 years in front-end architecture and team leadership. Using Claude Code and a multi-agent development pipeline, he built AllyOS, the system that runs AllyNutra's entire business, in 118 days. He also built TeacherCopilot, a profitable AI product.

Written by the author together with AI. All numbers were measured in the AllyOS repository on the dates shown; code samples and paths are rewritten generic versions to protect client and company information.

Want guardrails like this? Email me The AllyOS case study (in Chinese)