Sub topic 11
Preventing Older Source Data from Overwriting Newer Data
This chapter assumes you can write a PostgreSQL INSERT ... ON CONFLICT DO UPDATE keyed on a unique external ID. It also assumes you know why the load must be idempotent. If those are new, review the earlier chapters on the SQL upsert and idempotent loads first.
The problem: an upsert that trusts arrival order
A plain upsert overwrites the stored row with whatever arrives last. That is only correct if "arrives last" means "is newest at the source". Often it does not. These cases can all deliver an old version after a new one:
- A retry of a failed batch runs after a later batch has already succeeded.
- Two workers process different pages of an export, and the slower one holds older data.
- A message queue redelivers or reorders events.
- Someone replays last week's backup file to fix a different problem.
In each case the database ends up with older data than it had a moment ago. Nothing fails and no error appears. The wrong value sits in the table until someone notices.
The fix is to let the source's own notion of "newer" decide whether an update applies. The database compares a version marker from the source with the one it stored, and it skips the update if the incoming data is not newer.
Store a source version marker
You need a column that records when the source last changed the record. Two common choices:
| Marker | Example | Notes |
|---|---|---|
| Source timestamp | `2026-11-30T12:00:00Z` | Widely available. Precision and clock accuracy vary by system. |
| Source version number | `17` | Strictly increasing counters are unambiguous, but few systems expose them. |
The marker must come from the source system. Do not fill it with now() at load time. A load-time timestamp records when you wrote the row, so a replayed old file would look new and the guard would pass it.
Add the column next to the existing ones:
ALTER TABLE customers ADD COLUMN source_updated_at timestamptz;The column is nullable. Rows loaded before the column existed have no marker, and the guard has to handle that case.
Add a WHERE clause to DO UPDATE
ON CONFLICT DO UPDATE accepts a WHERE condition. When the conflict occurs, PostgreSQL evaluates the condition against the existing row (referred to by table name) and the proposed row (referred to as EXCLUDED). If the condition is false, the update is skipped and the existing row is left untouched.
INSERT INTO customers (source_system, external_id, name, email, source_updated_at)
VALUES ('crm', 'C-1001', 'Ada King', '[email protected]', '2026-11-30T12:00:00Z')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = EXCLUDED.email,
source_updated_at = EXCLUDED.source_updated_at
WHERE customers.source_updated_at IS NULL
OR customers.source_updated_at < EXCLUDED.source_updated_at;Read the condition as: "update only if we have no marker yet, or the stored marker is strictly older than the incoming one." Three outcomes are possible:
- No row has this external ID. The insert happens and the guard is never consulted.
- A row exists and the incoming data is newer. The update runs.
- A row exists and the incoming data is older or equal. Nothing is written.
The guard and the write are one statement, so the database decides atomically. You do not read the old timestamp in application code and then decide. That read-then-write pattern has a race window, which the later chapter on concurrent writers covers.
Detecting what happened
A skipped update is not an error, so the statement succeeds either way. The difference shows in the result. With RETURNING id, PostgreSQL returns a row for an insert or an applied update, and returns no row when the guard skipped the update.
INSERT INTO customers (source_system, external_id, name, email, source_updated_at)
VALUES ('crm', 'C-1001', 'Ada Old', '[email protected]', '2026-01-01T00:00:00Z')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = EXCLUDED.email,
source_updated_at = EXCLUDED.source_updated_at
WHERE customers.source_updated_at IS NULL
OR customers.source_updated_at < EXCLUDED.source_updated_at
RETURNING id;If the stored row is newer than January 2026, this returns zero rows. A loader can count zero-row results as "skipped as stale" and report that number. A large count of skipped records after a normal run usually means something upstream is replaying old data.
Seeing it run
The same logic works in SQLite 3.24 or later, which makes a self-contained demonstration possible. SQLite stores the timestamps as ISO 8601 text in one format, so string comparison matches time order.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL, "
"source_updated_at TEXT)"
)
sql = (
"INSERT INTO customers (external_id, name, source_updated_at) "
"VALUES (?, ?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET "
"name = excluded.name, "
"source_updated_at = excluded.source_updated_at "
"WHERE customers.source_updated_at IS NULL "
"OR customers.source_updated_at < excluded.source_updated_at"
)
new = ("C-1001", "Ada King", "2026-11-30T12:00:00Z")
old = ("C-1001", "Ada Lovelace", "2026-06-01T08:00:00Z")
conn.execute(sql, new) # insert
conn.execute(sql, old) # arrives late, so it is skipped
print(conn.execute("SELECT name FROM customers").fetchone()[0]) # Ada KingThe older record arrives second, yet the stored name stays Ada King. Without the WHERE clause the output would be Ada Lovelace.
Edge cases and design choices
Strict versus non-strict comparison
The example uses <, so an incoming record with an identical timestamp is skipped. That is usually right. Re-sending the same record changes nothing, which keeps the load idempotent.
Use <= when the source can change a record twice within the timestamp's precision. If the source stores whole seconds, two edits in the same second look identical, and < would drop the second one. With <=, the later arrival wins on a tie. This brings back some dependence on arrival order, but only among records the source cannot distinguish.
NULL markers
In SQL, NULL < x evaluates to unknown, which the WHERE clause treats as false. Without the IS NULL branch, rows with no stored marker would never be updated again. Include the branch deliberately, and decide what the incoming side should do when its own marker is NULL. Often the right choice is to reject such records before they reach the upsert, because they cannot be ordered.
Clock quality
Timestamps are only as reliable as the source's clock. If the source runs on several servers with skewed clocks, a genuinely newer edit can carry an earlier timestamp. A version counter maintained by the source's database avoids this. If you only have timestamps, record which field you are using and confirm with the source's owners that it updates on every change.
Deletions
A source that reports deletions has the same ordering problem. A stale "create" event arriving after a "delete" can resurrect a record. If you soft-delete (set a deleted_at column rather than removing the row), the guard protects the delete as well, because the tombstone row keeps its marker. If you hard-delete, no row remains to compare against.
Partial updates
The guard decides for the whole row. If different fields come from different sources or change independently, one row-level marker cannot order them all. Either keep a marker per source system, which the (source_system, external_id) key already supports, or keep separate markers for separate field groups.
Duplicates in one batch
The guard compares against the stored row, not against other rows in the same statement. A single INSERT ... ON CONFLICT DO UPDATE that touches the same key twice fails in PostgreSQL with "ON CONFLICT DO UPDATE command cannot affect row a second time". Collapse each batch to the newest record per external ID before sending it. The guard then protects against older data across batches, and the collapse protects within one.
Common errors
- Using load time as the marker. The guard then compares your clock with itself and blocks nothing.
- Forgetting to update the marker. If
SETomitssource_updated_at, the stored marker never advances. Every later record passes the check against the old value. - Checking in application code. A
SELECTfollowed by anUPDATEcan interleave with another writer. Put the condition in the statement. - Mixing time zones. Store
timestamptzin PostgreSQL. With text columns elsewhere, use one format, such as UTC with a trailingZ. - Treating skipped rows as failures. A skip is the guard doing its job. Count it and log it, but do not retry it.
Exercise
A table stores sourceupdatedat with second-level precision. The source sometimes edits a record twice in the same second, and your stale guard uses "customers.sourceupdatedat < EXCLUDED.sourceupdatedat". The second edit is silently lost. What is the cause, and what change fixes it with the least added risk?
Show answer
The strict "<" treats an equal timestamp as "not newer", so the second edit in the same second is skipped. Changing the comparison to "<=" lets an equal-timestamp record apply, so the later arrival wins on a tie. A safer long-term fix is to use a source-provided version counter, or a higher-precision timestamp, because "<=" still depends on arrival order for ties.