The trap Why an application check is not enough
javaLooks safe, is not
if (!repository.existsByProviderAndTransactionId(provider, transactionId)) {
repository.save(payment); // two concurrent requests can both reach this line
}Two requests can arrive at the same moment, both find no existing payment, and both insert one. The database must enforce the rule. And in PostgreSQL a failed insert aborts the surrounding transaction, so instead of catching an exception, use INSERT ... ON CONFLICT DO NOTHING RETURNING id: one statement, no race, and an empty result tells you it was a repeat.
A race that happens once a month is hard to see, so a good test forces it. This program sends two identical requests at the same moment, released together by a latch. In the first table, a barrier holds each request until both have finished their check, which is exactly the bad interleaving. The second table does what a unique index does: the check and the insert are one atomic step.
javaRaceDemo.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class RaceDemo {
record Key(String provider, String transactionId) {}
interface PaymentTable {
String save(Key key) throws Exception;
int rowsFor(Key key);
}
/** No unique constraint: the application checks first, then inserts. */
static class CheckThenInsert implements PaymentTable {
private final List<Key> rows = new ArrayList<>();
private final CyclicBarrier bothChecked = new CyclicBarrier(2);
public String save(Key key) throws Exception {
boolean exists;
synchronized (rows) { exists = rows.contains(key); } // the check
bothChecked.await(2, TimeUnit.SECONDS); // test hook: both requests have checked
if (exists) return "repeat";
synchronized (rows) { rows.add(key); } // the insert
return "inserted";
}
public int rowsFor(Key key) {
synchronized (rows) { return (int) rows.stream().filter(key::equals).count(); }
}
}
/** UNIQUE (provider, transaction id): checking and inserting are one atomic step, like a database index. */
static class UniqueConstraint implements PaymentTable {
private final ConcurrentHashMap<Key, String> rows = new ConcurrentHashMap<>();
private final CyclicBarrier bothArrived = new CyclicBarrier(2);
public String save(Key key) throws Exception {
bothArrived.await(2, TimeUnit.SECONDS); // same pressure: both arrive together
return rows.putIfAbsent(key, "stored") == null ? "inserted" : "repeat, returned the stored row";
}
public int rowsFor(Key key) {
return rows.containsKey(key) ? 1 : 0;
}
}
/** Releases two identical requests at the same moment and reports what happened. */
static void race(String title, PaymentTable table) throws Exception {
Key key = new Key("PROVIDER_A", "PAY-77821");
CountDownLatch start = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<String>> results = new ArrayList<>();
for (int i = 0; i < 2; i++) {
results.add(pool.submit(() -> {
start.await();
return table.save(key);
}));
}
start.countDown();
List<String> outcomes = new ArrayList<>();
for (Future<String> f : results) outcomes.add(f.get(5, TimeUnit.SECONDS));
pool.shutdown();
outcomes.sort(null); // the order the threads finish in varies; the outcomes do not
int rows = table.rowsFor(key);
System.out.println(title);
System.out.println(" outcomes: " + String.join(", ", outcomes));
System.out.println(" rows stored: " + rows + (rows == 1 ? " (one payment)" : " (one payment stored twice)"));
}
public static void main(String[] args) throws Exception {
race("Check, then insert: two requests for PAY-77821 at the same moment", new CheckThenInsert());
System.out.println();
race("Unique constraint: the same two requests", new UniqueConstraint());
}
}Output
Check, then insert: two requests for PAY-77821 at the same moment
outcomes: inserted, inserted
rows stored: 2 (one payment stored twice)
Unique constraint: the same two requests
outcomes: inserted, repeat, returned the stored row
rows stored: 1 (one payment)Real output from Java 17.0.18 running this program (fictional data), November 22, 2026.
Same requests, same timing, different guarantee. Check-then-insert stored one payment twice; the constraint stored it once and told the second request it was a repeat. In the real service the atomic step is the database: the unique index on (provider_id, provider_transaction_id), used through INSERT ... ON CONFLICT DO NOTHING. Write the same kind of test against the real database, with two connections and a latch, and keep it in the build.
Run it Duplicates, conflicts, outbox and consumers in SQL
sqlingestion.sql
-- FDE Module 07, Lessons 05 and 07: idempotent ingestion, the outbox, idempotent consumers and
-- duplicate-match protection. Fictional Apex data. Run from web/: sqlite3 < tools/fde/m07/ingestion.sql
-- The SQL is PostgreSQL-compatible apart from the column types; SQLite is used so anyone can run it.
-- payload_sha256 is the SHA-256 of the normalized payload 'provider|transaction|loan|amount|currency|timestamp'.
.headers on
.mode column
CREATE TABLE payment_transaction (
id INTEGER PRIMARY KEY,
provider_id TEXT NOT NULL,
provider_transaction_id TEXT NOT NULL,
amount_minor_units INTEGER NOT NULL CHECK (amount_minor_units > 0),
currency TEXT NOT NULL,
payload_sha256 TEXT NOT NULL CHECK (length(payload_sha256) = 64), -- full SHA-256 of the normalized payload
UNIQUE (provider_id, provider_transaction_id)
);
CREATE TABLE outbox_event (
id INTEGER PRIMARY KEY,
aggregate_id INTEGER NOT NULL,
event_type TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING'
);
.print '-- 1. First delivery of PAY-77821: insert the payment and its outbox row in one transaction'
BEGIN;
INSERT INTO payment_transaction (provider_id, provider_transaction_id, amount_minor_units, currency, payload_sha256)
VALUES ('PROVIDER_A', 'PAY-77821', 42550, 'USD', 'c1901f6e2d3efedd8f3c44cf4a497a3f070c6f3223c66d24fc6ba0ef2534b36b')
ON CONFLICT (provider_id, provider_transaction_id) DO NOTHING
RETURNING id AS new_payment_id;
INSERT INTO outbox_event (aggregate_id, event_type)
SELECT id, 'PaymentReceived' FROM payment_transaction
WHERE provider_id = 'PROVIDER_A' AND provider_transaction_id = 'PAY-77821'
AND NOT EXISTS (SELECT 1 FROM outbox_event WHERE aggregate_id = payment_transaction.id);
COMMIT;
.print ''
.print '-- 2. Same delivery again: no row comes back, so the service looks up the stored one'
INSERT INTO payment_transaction (provider_id, provider_transaction_id, amount_minor_units, currency, payload_sha256)
VALUES ('PROVIDER_A', 'PAY-77821', 42550, 'USD', 'c1901f6e2d3efedd8f3c44cf4a497a3f070c6f3223c66d24fc6ba0ef2534b36b')
ON CONFLICT (provider_id, provider_transaction_id) DO NOTHING
RETURNING id AS new_payment_id;
SELECT id AS existing_id,
CASE WHEN payload_sha256 = 'c1901f6e2d3efedd8f3c44cf4a497a3f070c6f3223c66d24fc6ba0ef2534b36b' THEN 'DUPLICATE: return stored result'
ELSE 'CONFLICT: same ID, different content' END AS outcome
FROM payment_transaction WHERE provider_id = 'PROVIDER_A' AND provider_transaction_id = 'PAY-77821';
.print ''
.print '-- 3. Same ID but a different amount: never accept it silently'
INSERT INTO payment_transaction (provider_id, provider_transaction_id, amount_minor_units, currency, payload_sha256)
VALUES ('PROVIDER_A', 'PAY-77821', 45250, 'USD', '5033b43207aa0ccb1ca41a95443dc0db690be227f4c12fd3a2bbcdf360d9e146')
ON CONFLICT (provider_id, provider_transaction_id) DO NOTHING
RETURNING id AS new_payment_id;
SELECT id AS existing_id,
CASE WHEN payload_sha256 = '5033b43207aa0ccb1ca41a95443dc0db690be227f4c12fd3a2bbcdf360d9e146' THEN 'DUPLICATE: return stored result'
ELSE 'CONFLICT: same ID, different content' END AS outcome
FROM payment_transaction WHERE provider_id = 'PROVIDER_A' AND provider_transaction_id = 'PAY-77821';
.print ''
.print '-- State after three deliveries'
SELECT (SELECT COUNT(*) FROM payment_transaction) AS payments,
(SELECT COUNT(*) FROM outbox_event) AS outbox_events;
-- Consumer side: remember each processed event in the same transaction as its business change.
CREATE TABLE processed_event (
consumer TEXT NOT NULL,
event_id INTEGER NOT NULL,
PRIMARY KEY (consumer, event_id)
);
.print ''
.print '-- 4. The reconciliation consumer receives outbox event 1 twice (a redelivery after a crash)'
INSERT INTO processed_event VALUES ('reconciliation', 1) ON CONFLICT DO NOTHING RETURNING event_id AS processed_now;
INSERT INTO processed_event VALUES ('reconciliation', 1) ON CONFLICT DO NOTHING RETURNING event_id AS processed_now;
SELECT COUNT(*) AS times_processed FROM processed_event WHERE event_id = 1;
-- Matching: a settlement record can be MATCHED to at most one payment.
CREATE TABLE reconciliation_result (
id INTEGER PRIMARY KEY,
payment_id INTEGER NOT NULL,
settlement_record_id INTEGER,
match_status TEXT NOT NULL
);
CREATE UNIQUE INDEX one_match_per_settlement
ON reconciliation_result (settlement_record_id) WHERE match_status = 'MATCHED';
CREATE UNIQUE INDEX one_match_per_payment
ON reconciliation_result (payment_id) WHERE match_status = 'MATCHED';
.print ''
.print '-- 5. Two workers race to match settlement 501; the second insert must fail'
INSERT INTO reconciliation_result (payment_id, settlement_record_id, match_status) VALUES (1, 501, 'MATCHED');
INSERT INTO reconciliation_result (payment_id, settlement_record_id, match_status) VALUES (2, 501, 'MATCHED');
SELECT payment_id, settlement_record_id, match_status FROM reconciliation_result;Output
-- 1. First delivery of PAY-77821: insert the payment and its outbox row in one transaction
new_payment_id
--------------
1
-- 2. Same delivery again: no row comes back, so the service looks up the stored one
existing_id outcome
----------- -------------------------------
1 DUPLICATE: return stored result
-- 3. Same ID but a different amount: never accept it silently
existing_id outcome
----------- ------------------------------------
1 CONFLICT: same ID, different content
-- State after three deliveries
payments outbox_events
-------- -------------
1 1
-- 4. The reconciliation consumer receives outbox event 1 twice (a redelivery after a crash)
processed_now
-------------
1
times_processed
---------------
1
-- 5. Two workers race to match settlement 501; the second insert must fail
Error near line 90: UNIQUE constraint failed: reconciliation_result.settlement_record_id
payment_id settlement_record_id match_status
---------- -------------------- ------------
1 501 MATCHEDReal output from SQLite 3.54 running this script (fictional data), November 22, 2026. The SQL is PostgreSQL-compatible apart from the column types.
- Every lookup is scoped by provider and transaction ID together, never by the transaction ID alone: two providers can use the same ID. And the payload hash is the full 64-character SHA-256, enforced by a check on the column; a shortened hash makes accidental collisions far more likely.
- Steps 1 to 3: three deliveries of PAY-77821 stored one payment and one outbox event. The exact repeat returned the stored result; the same ID with a different amount (45250 instead of 42550) was flagged as a conflict instead of being accepted.
- Step 4: the consumer recorded event 1 once; the redelivery inserted nothing, so the business change is not applied twice.
- Step 5: the partial unique index refused a second MATCHED row for settlement 501. Lesson 07 relies on this.
Publish reliably Implement the transactional outbox
javaStore the payment and its event together (Spring Boot sketch)
@Transactional
public IngestionResult store(CanonicalPayment p, String payloadSha256) {
Optional<Long> newId = payments.insertIfAbsent(p, payloadSha256); // ON CONFLICT DO NOTHING RETURNING id
if (newId.isEmpty()) {
StoredPayment existing = payments.find(p.provider(), p.providerTransactionId());
return existing.payloadSha256().equals(payloadSha256)
? IngestionResult.duplicate(existing)
: IngestionResult.conflict(existing); // alert, change nothing
}
outbox.add(OutboxEvent.of("Payment", newId.get(), "PaymentReceived", 1, eventPayload(p)));
return IngestionResult.created(newId.get()); // both rows commit together, or neither
}A separate publisher reads pending outbox rows and sends them to the broker, then marks them published. Several publisher copies can run safely if each claims rows with SELECT ... FOR UPDATE SKIP LOCKED. Keep publish attempts and the last error on the row, version the payload, leave out sensitive data, and clean up published rows according to policy.
textoutbox_event (logical columns)
id, aggregate_type, aggregate_id
event_type, event_version, payload
status PENDING, PUBLISHED or FAILED
publish_attempts, last_error
created_at, published_atThe other side Consumers must be idempotent too
Even if the publisher sends a message once, the consumer may receive it twice: it commits, crashes before acknowledging, and the broker redelivers. Record each processed event ID in a processed_event table, in the same transaction as the business change, so a redelivery finds the row and does nothing.
When it fails Retries and dead letters
| Decide | Apex example |
|---|---|
| Retryable failures | Database connection lost, broker unavailable, timeout |
| Permanent failures | Malformed event, unknown event version, failed validation |
| Retry delay and maximum attempts | Exponential backoff with jitter, for example five attempts |
| Dead-letter destination | A dead-letter queue, with an alert when it is not empty |
| Replay authorization | Platform on-call may replay after classifying the failure; the replay is audited |
Practice Implement reliable processing
Practical exercise
Exercise 05: a reliable payment event pipeline
Make the payment slice safe under repeats, races and crashes.
- The unique payment identity constraint and duplicate and conflict handling.
- The outbox table and a publisher that is safe with several copies.
- A consumer with processed-event tracking.
- A retry policy and dead-letter or quarantine handling.
Show sample tests
- Concurrent duplicates: 20 threads post the same notification; exactly one row and one outbox event exist.
- Conflict: the same ID with a different amount returns 409 and changes nothing.
- Broker down: payments commit, outbox rows stay PENDING, and publish after the broker returns.
- Redelivery: the same event delivered twice changes the reconciliation state once.
3 questions
Check your understanding
What you can do now
- Explain and avoid the check-then-insert race.
- Tell duplicates from conflicts.
- Implement a transactional outbox and an idempotent consumer.
- Define bounded retries and dead-letter handling.