Idempotent consumers
What you will learn
An idempotent consumer makes repeated deliveries produce the same intended business effect. Use a stable event identity, verify conflicting payloads, and commit the deduplication marker with the effect. Handle ordering independently: a full snapshot can use a version fence; a delta stream generally needs gap handling.
- Design duplicate and conflicting-ID checks.
- Apply version ordering to full snapshots and distinguish delta events.
- Explain durable atomicity, acknowledgment timing and bounded retry.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. External cache and broker examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Reject conflicting duplicates and stage effect atomically
public class Main { record State(java.util.Map<String,Integer> seen,int total) {} static State apply(State s,String id,int qty){ if(qty<=0)throw new IllegalArgumentException("quantity"); Integer old=s.seen().get(id);if(old!=null){if(old!=qty)throw new IllegalArgumentException("conflict");return s;} var seen=new java.util.HashMap<>(s.seen());seen.put(id,qty); return new State(java.util.Map.copyOf(seen),Math.addExact(s.total(),qty)); } public static void main(String[] args) {var state=new State(java.util.Map.of(),0); state=apply(state,"e1",2);state=apply(state,"e1",2); try{apply(state,"e1",9);}catch(IllegalArgumentException e){System.out.println("conflict");} System.out.println(state.total()); }}Expected output:
conflict2The immutable transition models both writes succeeding or neither; it is not durable or concurrent.
Atomic effect and identity
Text diagram: receive → validate schema and tenant → begin local transaction → insert unique (tenant,eventId) marker → apply effect if first → commit → acknowledge. A repeated ID must identify the same payload; conflicting payload is an error, not a success. If the transaction fails, both marker and effect roll back. If acknowledgement fails after commit, the next delivery sees the marker and does not repeat the effect. An in-memory set cannot survive restart. A cache TTL must not be the only deduplication protection unless the entire replay horizon is contractually bounded and durable guarantees are addressed.
Out-of-order delivery and retries
For complete state snapshots, a higher version can replace an older one and a late older snapshot can be ignored. For additive delta events, ignoring a missing older delta loses work; detect gaps, buffer only within a finite budget or reconcile from the source. Retry only transient failures with backoff, jitter, finite attempts and observable failure routing. Persist retry state when restart must not reset the budget. Reuse the transactional outbox from Chapter 46 for outbound event intent; no cross-system atomicity is implied.
Ignore stale full snapshots
public class Main { record Snapshot(int version,int stock) {} public static void main(String[] args) {var current=new Snapshot(0,0); for(var incoming:java.util.List.of(new Snapshot(2,7),new Snapshot(1,9),new Snapshot(3,4))) if(incoming.version()>current.version())current=incoming; System.out.println(current); }}Expected output:
Snapshot[version=3, stock=4]This is safe for complete snapshots with ordered versions; it is not a delta event algorithm.
Atomic consumer marker and effect
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/consumer.sql; use the companion lab README.
-- PostgreSQL 17, fresh disposable schema. Fixed synthetic event delivery.CREATE TABLE IF NOT EXISTS lab_processed (tenant text, event_id text, quantity integer NOT NULL CHECK(quantity>0), PRIMARY KEY(tenant,event_id));CREATE TABLE IF NOT EXISTS lab_total (tenant text PRIMARY KEY, quantity bigint NOT NULL CHECK(quantity>=0));-- Execute the transaction twice. The second run should have no effect.BEGIN;WITH accepted AS ( INSERT INTO lab_processed(tenant,event_id,quantity) VALUES ('tenant-a','e1',2) ON CONFLICT (tenant,event_id) DO NOTHING RETURNING tenant,quantity)INSERT INTO lab_total(tenant,quantity) SELECT tenant,quantity FROM acceptedON CONFLICT (tenant) DO UPDATE SET quantity=lab_total.quantity+EXCLUDED.quantity;COMMIT;SELECT quantity FROM lab_total WHERE tenant='tenant-a';-- Expected 2. This fixed payload assumes same ID means same payload.-- General consumer must compare stored payload and reject conflicting duplicates.Predicted behavior: Two identical deliveries leave total 2.
Fixed PostgreSQL example assumes stable payload; real code must verify stored payload and transaction result before acknowledgment.
Common mistakes
Do not use a new UUID for each retry, acknowledge before committing, or store deduplication only in a short-lived cache. Do not discard a late additive event just because a newer event has arrived.
Practice
Simulate at most three attempts per delivery. For e1 fail twice then succeed; for e2 fail all three. Print attempts and outcome for each. Explain what a real retry policy must persist.
Expected output:
3:ack3:dead-letterCompare with the manual review criteria.
Official reading: Kafka design · RabbitMQ · RabbitMQ DLX · Jakarta Messaging. Cache and broker execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Idempotent consumers — knowledge check
Cache and messaging reasoning.
What must commit with the effect?
How should conflicting payloads under one event ID be handled?
When can a version fence drop an older event safely?
What if effect commits but acknowledgment fails?
What should happen after exhausting transient retries?