Outbox and consistency
What you will learn
A transactional outbox saves a business change and an event record in the same database transaction. A relay publishes later, so a crash cannot erase the durable intent, but duplicate delivery is still possible. Consumers must make effects idempotent.
- Design a local atomic state and event write.
- Explain relay crash windows and durable deduplication.
- Compare eventual consistency, compensation and read replicas.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. PostgreSQL and Spring examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Model state and event as one immutable result
public class Main { record State(int stock,java.util.List<String> events) {} static State reserve(State s,String id,int qty){ if(qty<=0||qty>s.stock())throw new IllegalArgumentException("quantity"); var events=new java.util.ArrayList<>(s.events());events.add(id); return new State(s.stock()-qty,java.util.List.copyOf(events)); } public static void main(String[] args) {var s=new State(5,java.util.List.of()); var next=reserve(s,"r1",2); System.out.println(next);System.out.println(s); }}Expected output:
State[stock=3, events=[r1]]State[stock=5, events=[]]One returned state contains both changes. No durable store or crash recovery is tested.
Local versus distributed consistency
Text diagram: service → database transaction (inventory + reservation + outbox) → commit → relay → broker → consumer transaction (processed event + business effect). The database boundary ends at commit; the relay and consumer use separate transactions. A crash before commit leaves neither state nor event; a crash after commit leaves a pending event. If a relay publishes and crashes before recording acknowledgment, it can publish again. Marking an event sent before acknowledgment risks loss. A stable event ID, uniqueness constraint and atomic consumer effect prevent duplicates from multiplying effects. A volatile set does not survive restart.
Retries, ordering and compensation
Use durable request IDs and compare payloads when clients retry; the same ID with conflicting data should not silently succeed. Outbox polling needs bounded batches, lease/claim policy, monitoring of backlog and appropriate ordering per aggregate, not a global ordering promise. Do not hold database locks during a slow broker call without a deliberately analyzed design. A saga is a sequence of local transactions with compensating operations; compensation can fail and is not a time reversal. Read models may be stale. Verify after real commit from a separate session and test broker acknowledgment failure and repeated delivery.
Model duplicate delivery
public class Main {
public static void main(String[] args) {var seen=new java.util.HashSet<String>();int total=0; for(String event:java.util.List.of("r1","r1","r2"))if(seen.add(event))total+=2; System.out.println(total); }}Expected output:
4Repeated event r1 does not repeat the in-memory effect. Real consumer state and effect must commit atomically.
Transactional reservation and outbox
Source-reviewed, NOT RUN. File lab-fixtures/database-architecture-v43/reserve.sql; use the companion lab README.
-- psql, disposable PostgreSQL 17 database, initial B1 stock 5.-- ON_ERROR_STOP ensures unexpected failures stop this script.BEGIN;INSERT INTO reservation(request_id, sku, quantity) VALUES ('r1','B1',2);UPDATE inventory SET stock=stock-2, version=version+1 WHERE sku='B1' AND stock>=2;-- In application code REQUIRE update count = 1, otherwise roll back.-- This fixed fixture instead checks the exact resulting state.DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM inventory WHERE sku='B1' AND stock=3 AND version=1) THEN RAISE EXCEPTION 'unexpected inventory state'; END IF;END $$;INSERT INTO outbox(event_id,sku,quantity) VALUES ('r1','B1',2);COMMIT;SELECT stock,version FROM inventory WHERE sku='B1';SELECT event_id FROM outbox ORDER BY event_id;Predicted behavior: Commits stock 3, version 1 and event r1 together on fresh data.
Fixed PostgreSQL script; production code must check update count and idempotency payload.
Atomic duplicate-safe consumption
Source-reviewed, NOT RUN. File lab-fixtures/database-architecture-v43/consumer.sql; use the companion lab README.
-- Simulated delivery of event r1, safe to execute twice in the lab.-- The production consumer validates event identity and payload first.BEGIN;WITH accepted AS ( INSERT INTO processed_event(event_id) VALUES ('r1') ON CONFLICT DO NOTHING RETURNING event_id)INSERT INTO delivery_summary(sku,total) SELECT 'B1',2 FROM accepted ON CONFLICT (sku) DO UPDATE SET total=delivery_summary.total+EXCLUDED.total;COMMIT;SELECT total FROM delivery_summary WHERE sku='B1';Predicted behavior: Running twice leaves delivery total 2.
Uses a PostgreSQL data-modifying CTE and conflict handling; broker not exercised.
Common mistakes
Do not publish directly between two local writes and call that atomic. Do not claim exactly-once delivery because an outbox exists. If the consumer commits the processed marker separately from its business effect, a crash can lose work.
Practice
Process events r1=3, r2=5, r1=3 and r3=1 with stable IDs. Print total and number of distinct events; explain what must persist in a real consumer.
Expected output:
93Compare with the manual review criteria.
Official reading: Outbox · Constraints · Retry. PostgreSQL and Spring execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Outbox and consistency — knowledge check
Database transaction and data architecture reasoning.
What is written in the same local transaction as a reservation?
A relay publishes then crashes before marking sent. What may happen?
What must commit atomically in the consumer?
What does a saga compensation do?
What should happen if the same request ID arrives with a different quantity?