Quick revision
The short answer
I would propose one shared pattern, packaged as a small library with tests, built on three rules. Upserts are conditional on a version or source timestamp, DO UPDATE ... WHERE target.version < EXCLUDED.version, so stale or out-of-order messages are ignored; batches are sorted by key before upserting so concurrent batches lock rows in the same order and cannot deadlock; and deletes are explicit, through tombstones or soft-delete columns, or through full reconciliation of snapshots with MERGE ... WHEN NOT MATCHED BY SOURCE. Periodic counts and checksums against the source then show whether any drift remains.
What to remember
In this answer, we fixed three recurring failures with three rules: version-conditional upserts that ignore stale messages, batches sorted by key so concurrent transactions lock rows in the same order, and explicit deletes through tombstones, soft deletes or snapshot reconciliation with MERGE ... WHEN NOT MATCHED BY SOURCE. Packaging them as a small shared library with a test kit for idempotency and ordering, and monitoring drift with counts and checksums, stops each team from rediscovering the same incidents.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would propose one shared pattern, packaged as a small library with tests, built on three rules. Upserts are conditional on a version or source timestamp, DO UPDATE ... WHERE target.version < EXCLUDED.version, so stale or out-of-order messages are ignored; batches are sorted by key before upserting so concurrent batches lock rows in the same order and cannot deadlock; and deletes are explicit, through tombstones or soft-delete columns, or through full reconciliation of snapshots with MERGE ... WHEN NOT MATCHED BY SOURCE. Periodic counts and checksums against the source then show whether any drift remains.
Why this question is asked
Syncing reference data, such as products, exchange rates, store lists or customer master data, from external systems is the kind of work every team does and few teams think hard about. Each team writes its own upsert, and each one is correct for the happy path. Then the incidents start: a newer price overwritten by an older one that arrived late, deadlocks in the nightly job, and stores that were closed months ago still showing in the app. Interviewers ask this design question because it combines concurrency, ordering, deletion semantics and team leadership. In this answer, we will look at each failure in turn, see the fix for it, and then package the fixes into one shared approach with monitoring.
1Lost Updates From Out-of-Order Messages
Messages from external systems do not always arrive in the order they were produced. A retry, a second consumer instance, or a partition rebalance can deliver version 8 of a product after version 9. A plain upsert, DO UPDATE SET price = EXCLUDED.price, applies whatever arrives last, so the newer price 9 is overwritten by the older price 8, and nothing signals an error. This is a lost update.
The fix is to make the upsert conditional on a version that comes from the source: a version number, a sequence, or the source system's modification timestamp. We store it in the row and only apply a change when it is newer.
Notice that the WHERE belongs to the DO UPDATE clause. When it is false, the row is left as it is and the statement reports 0 rows, which the library can log as a stale message. The version must come from the source, not from our clock: timestamps taken at receive time would just record the wrong order faithfully. This also makes the operation idempotent, since replaying version 9 a second time is ignored too.
2Deadlocks Between Concurrent Batches
Batch upserts lock every row they touch until the transaction commits. If batch 1 upserts A then B, and batch 2 upserts B then A at the same time, each holds one lock and waits for the other. PostgreSQL detects the cycle after deadlock_timeout and aborts one transaction with a deadlock error.
6 messages in order. Play them, or step through them one at a time.
If both batches sorted by key, both would lock A first and the second would simply wait.
The fix is simple and very effective: sort every batch by its key before upserting, in Java or with ORDER BY in an INSERT ... SELECT from staging. Then all transactions acquire locks in the same order, and a cycle cannot form; at worst one batch waits briefly for another. Keeping batches moderate, a few thousand rows per transaction, also keeps waits short.
3Rows That Should Have Been Deleted
An upsert only ever inserts and updates. If the source system deletes a store, a stream of upserts has nothing to say about it, so the store stays in our table forever. Deletes have to be designed explicitly, and there are two families of solutions depending on what the source gives us.
If the source sends change events, it should send deletes as tombstones: a message saying store 17 is deleted, with a version. We apply it like any other change, conditional on the version, either removing the row or setting a deleted_at column if consumers need to see that it existed. If the source only gives us full snapshots, such as a nightly file of all active stores, we reconcile: everything in the snapshot is upserted, and everything in our table that is not in the snapshot is deleted.
WHEN NOT MATCHED BY SOURCE was added in PostgreSQL 17; on older versions a separate DELETE ... WHERE NOT EXISTS in the same transaction does the same. Reconciliation needs a safety check: if the snapshot is unexpectedly empty or half the usual size because the export failed, the job must refuse to run, otherwise it would delete most of the table.
4Packaging It as a Shared Library
Each of these rules is easy to state and easy to forget, which is why every team reinventing them keeps having incidents. So I would provide a small shared library, built with two or three teams who have been hurt the most, that exposes a narrow API: give it a table description, a key, a version column and a batch, and it generates the conditional upsert, sorts the batch, applies tombstones and runs reconciliation with the safety checks.
- Source adapters (per team)read events, files or APIs
- ReferenceSync libraryversion checks, sorting, tombstones, reconciliation
- Test kitshuffled order, duplicates, concurrency
- PostgreSQL tablesone unique key and version column per table
- Drift monitorcounts and checksums against the source
5 layers, from the top down. Step through them one at a time.
The library comes with a test kit that each team runs against its own table: deliver the same messages in shuffled order and assert the final state is the same, deliver every message twice and assert nothing changes, run two batches concurrently and assert no deadlock. Those tests encode the guarantees we want, idempotency and order-independence, in a form teams can reuse. The library should stay small; a team with an unusual source can still write its own code, as long as it passes the same test kit.
5Monitoring Drift Against the Source
Even with correct code, data can drift: a consumer was down, a message was lost in a misconfigured topic, someone fixed a row by hand. So I would run a periodic drift check per dataset that compares our copy with the source. The cheapest version compares counts; a stronger version compares checksums per key range, for example an md5 over the concatenated key and version values of each block of 10,000 keys, so we can find exactly which range differs and re-sync only that range. The results go on a dashboard and alert when drift exceeds a threshold.
6Follow-up questions
What if the source system has no version or timestamp?
Then we cannot tell old from new, and we should ask the source owners to add one, because without it no consumer can guarantee correctness. In the meantime, a single ordered stream, such as one Kafka partition per key, consumed by one consumer at a time, preserves order, and a full snapshot reconciliation on a schedule repairs whatever goes wrong.
Should the shared approach be a platform service instead of a library?
A central sync service gives more control but makes every team depend on one team's roadmap. I would start with a library and test kit, because they fix the incidents quickly with little coordination, and only consider a service if many teams sync the same datasets, at which point the better answer may be one owning service that publishes the data.
7Conclusion
In this answer, we fixed three recurring failures with three rules: version-conditional upserts that ignore stale messages, batches sorted by key so concurrent transactions lock rows in the same order, and explicit deletes through tombstones, soft deletes or snapshot reconciliation with MERGE ... WHEN NOT MATCHED BY SOURCE. Packaging them as a small shared library with a test kit for idempotency and ordering, and monitoring drift with counts and checksums, stops each team from rediscovering the same incidents.
Open with
Each incident has a clear cause, so I'd propose one shared pattern that fixes all three. For lost updates from out-of-order messages, every upsert becomes conditional on a version from the source: ON CONFLICT DO UPDATE ...
Then, if they want more
WHERE target.version is less than EXCLUDED.version, so a late older message is ignored, and replays become idempotent. For deadlocks, batches are sorted by key before upserting, so concurrent transactions always lock rows in the same order and can't form a cycle, and batches stay moderate in size.
For rows that should have been deleted, deletes are explicit: if the source sends events, it sends tombstones with versions that we apply as deletes or soft deletes; if it sends full snapshots, we reconcile with MERGE, including WHEN NOT MATCHED BY SOURCE THEN DELETE on PostgreSQL 17, with a safety check that refuses a suspiciously small snapshot.
I'd package this as a small shared library with a test kit that shuffles message order, duplicates messages and runs concurrent batches, built together with the teams who've had the most incidents, rather than each team reinventing it. Finally, a drift monitor compares counts and per-range checksums against the source, so we notice and repair any remaining divergence.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 17
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Several teams sync reference data from external systems into PostgreSQL with...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/f34e17cff0/