Auren is a personal finance application with a Rust backend and a PostgreSQL ledger. It imports account transactions from Plaid, keeps a local history and calculates spending through explicit rules. The ingestion path uses Plaid's incremental sync API, which returns changes and a cursor for the next request.
A stored cursor identifies the point from which the application can safely resume. Saving C2 means the local ledger has already incorporated the changes needed to resume from C2. Both the records and that checkpoint have to survive crashes and overlapping sync requests.
Commit the ledger changes and the cursor together
The provider returns added, modified and removed transactions. An update may span several pages, each carrying a cursor. Auren collects the pages for the logical update, then writes their changes and the resulting cursor within one database transaction.
Consider two crash windows:
If the cursor is saved first and the worker crashes before saving a transaction, the next request resumes past data the ledger never received. If the transaction is saved first and the cursor remains old, the next request may fetch it again. The second case can be handled by applying changes against stable provider identities; the first has lost the position from which it could recover the missing work.
Putting the ledger writes and checkpoint update in the same database transaction eliminates that partial-commit window. Before commit, both remain at the previous version. After commit, both reflect the update. The success of an HTTP request to Plaid does not establish either state.
That protects a single synchronizer from publishing half an update. Two workers can still start from the same cursor and commit in the wrong order.
A ledger update is more than an insert
A provider's transaction feed describes changes to records over time. One purchase may first appear as pending, then as a posted transaction under a new provider identifier. A charge can be corrected. A record can be removed. Treating every added entry as a new independent expense will eventually double-count something.
Consider a deliberately simplified example. A pending purchase for $12.30 appears on Monday. On Tuesday, the provider returns a posted version for the same purchase and indicates its relationship to the pending record. A local ledger that blindly inserts the posted record now contains $24.60 of apparent spending. The transport worked perfectly. The accounting interpretation did not.
Auren's domain model distinguishes the provider transaction identity, pending-to-posted relationships and revision history. Those identities let ingestion update the durable record while analytics decide which transaction treatment is appropriate. The test suite includes cases for repeated synchronization, pending-to-posted transitions, modifications, removals and recovery after a failed sync job.
There are at least three invariants here. Replaying an already applied provider update must not create a second ledger item. A removed transaction must not keep contributing as an ordinary active purchase. An explicit user annotation should not disappear just because the provider sends a newer version of the transaction. Those are application-level properties; a database transaction alone does not decide them.
This also explains why the synchronization checkpoint and the spending total should not be coupled as a single mental model. A refresh can make correct progress while the displayed total remains the same. A refresh can also expose a pending-to-posted correction that changes the total without representing a new purchase. Correctness has to be tested at both boundaries.
Two workers, two valid transactions, one stale checkpoint
Suppose workers A and B both read C1. A fetches an update ending at C2. B observes a later set of provider changes ending at C3 and finishes first. B commits its records and writes C3. Then A commits and overwrites the shared cursor with C2.
The figure uses C1, C2 and C3 as names for successive logical positions. Real provider cursors are opaque strings. You should not compare them lexicographically or assume they contain a numeric ordering.
Neither worker performed a partial database commit. Yet the final cursor is older than the update B had already saved. Reprocessing may be harmless for an idempotent ledger, but progress tracking is now inaccurate and every consumer that assumes a forward-only checkpoint has inherited the problem.
One way to guard against this is to make cursor publication conditional on the predecessor the worker actually read. Here is generalized PostgreSQL-style SQL, not a private implementation excerpt:
UPDATE sync_state
SET cursor = $1
WHERE stream_id = $2
AND cursor IS NOT DISTINCT FROM $3;
$3 holds the cursor observed when the worker began. IS NOT DISTINCT FROM also handles a null initial cursor. If the update changes zero rows, another writer has changed the checkpoint. The stale worker must roll back its entire ledger transaction and fetch or reconcile from the current state. Rolling back only the cursor update while committing its other changes would create a new inconsistency.
A per-stream lock is another option. It reduces duplicate work and provides simple ordering, provided the lock has reliable ownership semantics. Keeping a database transaction open across multiple remote API requests is usually an unattractive way to implement that lock: network latency now holds database resources. If concurrent requests are rare, optimistic conflict detection can be enough.
This race is a constructed test schedule. It should be tested with two workers paused after reading C1, then released in a controlled order. Auren's local batch-and-cursor commit addresses atomicity; that alone does not establish the concurrent-worker property.
Why compare-and-set has to be in the same commit
The optimistic guard is easy to describe and equally easy to implement incorrectly. Imagine the worker updates the ledger in one transaction, commits, and then performs the conditional cursor update. If the condition fails, its ledger changes have already escaped. The failed checkpoint publication did not roll them back.
The whole apply operation needs a single atomic boundary. Inside it, write additions, modifications, removals and associated revisions; perform the conditional cursor update; inspect how many rows matched; and commit only if the expected predecessor was still present. If the condition fails, abort the transaction and start again from the currently stored cursor. The database is then responsible for ensuring no half-batch is published.
Whether the guard wins depends on the database's concurrency semantics. PostgreSQL will coordinate conflicting updates to the same row, but it is still worth testing the exact isolation level and statement order that the application uses. A conditional update on the cursor row protects that one checkpoint; it does not automatically serialize every unrelated side effect triggered by a sync job.
A different implementation might establish a per-connection lease before fetching any remote pages. This can reduce duplicate API traffic, but introduces its own lifecycle: leases expire, workers crash and expired owners may still be executing. If a lease is used, a fencing token can prevent a former owner from publishing work after a replacement has taken over. The choice between optimistic commits and serialized acquisition should follow the expected concurrency and cost of duplicated reads, not a preference for a particular coordination primitive.
The provider can invalidate a page sequence too
Plaid documents an error called TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION. Changes can occur during a multi-page read, invalidating the page sequence. Its guidance is to restart the entire pagination loop from the original cursor, not to resume from whichever page last succeeded (Plaid error documentation).
That rule is separate from database atomicity. A perfect local transaction cannot repair a remote batch assembled from an invalid pagination sequence.
An experiment that distinguishes the failure classes
I would use a fake provider and a real database for the boundary tests. A fake provider lets a test control which pages arrive and when; a real database exercises row locks, transaction rollbacks and the configured isolation level. The tests can force the order rather than hoping two workers collide during a fast CI run.
First, deliberately fail while applying page two of a multi-page update. Verify that the cursor and every ledger mutation remain unchanged. Next, replay a successful batch and verify that provider identities still map to one logical set of records. Then run the two-worker schedule in the diagram: both read the same original cursor, B publishes a newer position, and A attempts to publish its stale one. A should either fail the conditional update or be prevented from acquiring the same stream in the first place.
Finally, have the fake provider invalidate pagination after the first page. The client must throw away the collected partial sequence and restart from the original request cursor, rather than appending new pages onto an already inconsistent batch. This is a distinct failure from a database conflict: the database cannot validate a remote snapshot that the provider has declared invalid.
The interesting property is monotonic accepted progress under retries and concurrency. A dashboard showing a plausible total cannot establish it; the controlled interleavings can.
The checkpoint test has a precise pass condition: once the database has accepted a newer completed position, a stale worker cannot publish its older cursor over it.