Idempotent Consumers: Preventing Stale Retries With Version-Fenced Writes
Retries can let stale events overwrite newer state. This article shows how version-fenced PostgreSQL writes prevent delayed retries from moving a projection backward.
Retries usually make systems more reliable. A dependency times out, processing pauses, and the message returns later. Eventually, the operation succeeds.
That successful retry can also corrupt a projection.
Consider a consumer maintaining product data. Version 108 of product P17 starts processing but encounters an enrichment timeout. Version 109 arrives seconds later and reaches the database successfully. Five minutes afterward, version 108 returns through the retry queue and overwrites it.
Both events are legitimate. Neither is a duplicate. The database accepts valid SQL, and the consumer reports success. Yet the stored state has moved backward.
The missing guarantee is freshness. An idempotent consumer can prevent repeated execution of one operation while still allowing an older operation to replace newer state.
Why Deduplication Cannot Catch This
Suppose each product update carries a unique event identifier:
eventId=A, productId=P17, sourceVersion=108
eventId=B, productId=P17, sourceVersion=109
An idempotency check correctly treats these as different operations. Assuming failed attempts do not mark events complete, event A remains eligible for processing after its enrichment failure.
Nothing about its identity tells the consumer that version 109 has already superseded it.
Two separate questions must therefore be answered:
- Idempotency: Has this operation already been applied?
- Freshness: May this operation replace the state currently stored?
For a projection governed by an authoritative revision, the required invariant is straightforward: the persisted version must never decrease. A replay can leave it unchanged, and a newer update can advance it.
Event identifiers and source revisions serve different purposes. Preserving both avoids forcing one mechanism to provide a guarantee it cannot express.
Reproduce the Failure at the Database Boundary
The failure does not require a message broker. Two writes arriving in the wrong order are sufficient.
Start with a small PostgreSQL table:
CREATE TABLE product_view (
product_id VARCHAR(64) PRIMARY KEY,
source_version BIGINT NOT NULL,
payload JSONB NOT NULL
);
A conventional upsert accepts whichever update arrives last:
INSERT INTO product_view
(product_id, source_version, payload)
VALUES
('P17', 108, '{"name":"Keyboard","price":90}')
ON CONFLICT (product_id)
DO UPDATE SET
source_version = EXCLUDED.source_version,
payload = EXCLUDED.payload;
If version 109 already exists, this statement replaces it with version 108. The database has followed the instruction exactly. The application never expressed a freshness constraint.
This distinction matters during incident analysis. A retry queue explains why an event arrived late. The unconditional write explains why late arrival damaged state.
Why Locks and Application Checks Fall Short
A lock alone does not establish freshness. Version 109 can acquire the lock, write successfully, and release it. Version 108 can acquire that same lock later and overwrite the row. Processing was perfectly serialized, but the order was wrong.
An application-level comparison introduces a different problem:
Product current = repository.find(productId);
if (incoming.version() > current.version()) {
repository.save(incoming);
}
Starting from version 107, workers carrying 108 and 109 can both read the same row. Both comparisons pass. If the worker carrying 108 writes last, the projection regresses.
The issue is the gap between comparison and mutation. A lock covering both operations can protect this sequence when implemented correctly, but the freshness comparison remains essential.
For a single-row projection, putting the condition directly in the write makes the invariant explicit.
Make the Write Enforce Freshness
Add a version predicate to the conflict-update branch:
INSERT INTO product_view AS stored
(product_id, source_version, payload)
VALUES
('P17', 108, '{"name":"Keyboard","price":90}')
ON CONFLICT (product_id)
DO UPDATE SET
source_version = EXCLUDED.source_version,
payload = EXCLUDED.payload
WHERE stored.source_version < EXCLUDED.source_version
RETURNING product_id, source_version;
PostgreSQL evaluates the conflict-update condition against the conflicting row. Rows excluded by that condition are not returned by RETURNING. See the PostgreSQL INSERT documentation.
If 108 commits first, 109 can advance the row. If 109 commits first, 108 cannot replace it. Equal versions also leave the row unchanged.
The comparison now occurs within the database operation that controls mutation. Concurrent processing no longer depends on the newest event finishing last.
Transactions can still encounter deadlocks or serialization failures, depending on the workload and isolation level. Those failures require appropriate transaction retries; the version predicate must remain part of every attempt. PostgreSQL documents these distinctions in its transaction isolation guidance.
Establish What the Version Actually Means
The predicate is useful only when larger revisions represent newer authoritative state for the same entity.
A source-owned aggregate revision is a strong candidate. A datastore revision or producer sequence can also work when its ordering contract is explicit.
Random UUIDs establish identity without establishing order. Wall-clock timestamps require careful guarantees around clock synchronization, precision, and concurrent writers. Offsets from unrelated partitions do not provide a shared entity ordering.
The payload must also correspond to its claimed revision. If enrichment reads changing external data, retrying version 109 might produce a different payload from the first attempt. The fence prevents replacement, but the inconsistency remains worth investigating.
Define whether each event carries a complete snapshot or a dependent delta. Skipping revision 108 is safe only when 109 contains everything needed to represent the newer state. A sequence of incremental adjustments may require ordered processing or gap recovery.
Distinguish Stale Updates From Conflicting Replays
A rejected write has several possible meanings:
| incomig update | interpretation |
|---|---|
|
Lower revision |
Stale delivery |
|
Equal revision, identical payload |
Replay |
|
Equal revision, different payload |
Consistency violation |
|
Higher revision |
Eligible replacement |
The SQL predicate protects the row but does not distinguish all these outcomes.
If exact classification matters, compare against the protected row within a suitable transaction or retain revision-specific payload hashes. A later, unprotected read can observe a further update and obscure what happened during the original decision.
Same-version conflicts can reveal nondeterministic enrichment, incorrect revision assignment, or corrupted replay data. Treating them as ordinary duplicates hides a broken data contract.
Preserve Versions Across Deletion
Physical deletion creates another opening for stale retries.
Suppose version 121 deletes P17. If the row disappears entirely, a delayed version 120 encounters no conflict and inserts the product again.
Preserve the deletion revision with a tombstone:
ALTER TABLE product_view
ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE,
ALTER COLUMN payload DROP NOT NULL;
ALTER TABLE product_view
ADD CONSTRAINT valid_payload_state CHECK (
(deleted AND payload IS NULL)
OR (NOT deleted AND payload IS NOT NULL)
);
Represent deletion as a versioned write carrying deleted = TRUE and a null payload. Use the same version predicate for active records and tombstones, updating both payload and deleted from the incoming row.
A legitimate newer active revision must restore deleted = FALSE.
Tombstone retention must cover retries, delayed delivery, backfills, and supported replay windows. Removing the tombstone removes the information needed to reject older revisions.
Identifier reuse adds another complication. If revisions restart, compare an authoritative generation and revision together so generation 7, revision 1 can supersede generation 6, revision 982.
Make Rejected Writes Operationally Useful
A stale delivery should normally finish as a terminal no-op. Record the rejection and acknowledge the message. Retrying version 108 cannot make it newer than 109.
Track applied updates, stale rejections, identical replays, and conflicting revisions separately. Include entity identifiers, incoming revisions, event identifiers, and delivery paths in diagnostic records.
A sudden increase in stale rejections can expose a slow dependency, retry backlog, or unexpected replay. The fence protects correctness while those signals help explain the disruption.
This approach fits snapshot projections with a meaningful authoritative order. Concurrent independent updates may instead require merge rules or field-level versions.
The essential boundary is the write: once a newer revision is accepted, every later mutation must prove that it is allowed to advance that state.
Opinions expressed by DZone contributors are their own.