October 10, 2026•4 min read

The answer: A Conflict Is Not an Error

Adding a unique key produces duplicate-key errors everywhere, and that is not a sign the fix is wrong. Here is the order of repairs, with measured numbers for every variant.

Read in Indonesian

Lab repo

The lab lives in folder 0002.idempotency

The deliberately broken code, the dataset, and the target live in a public repo. Everything runs in Docker. make check

The interesting part of this lab is not the answer, it is the order in which it fails. Because that order is why so many people conclude "a unique key does not solve anything" — while the constraint is right and the database is right.

Key takeaways

Adding UNIQUE fixes the duplicates, then raises a new problem that is actually correct.

  • A "already exists" conflict is not a failure: from the sender's point of view it is a successful outcome.
  • The claim has to be one statement (INSERT ... ON CONFLICT DO NOTHING RETURNING), not check-then-write.
  • The first response is stored and returned as-is.
  • The number that changes is computed by the database, not read-modify-written in the app.

Measurements

Every number here comes from a measurement run, not an estimate: a clean database per variant. The suite has 21 checks. The last column: how many are still red.

variant red what is still red
initial state 11 of 21 duplicates, balance, response, reused event_id
(1) + UNIQUE (event_id) in the database, handler untouched 7 of 21 answered 2xx, response, balance
(2) + ON CONFLICT DO NOTHING claim, but the conflict is answered with a message 1 of 21 redelivery body differs
(3) + first response stored on the claim row 1 of 21 balance
(4) + balance computed by the database, not read-modify-written in Python 0 of 21 —
alternative to (2): check in the app first, then INSERT 3 of 21 26–29 of 30 concurrent deliveries answered 500

1. What is wrong is not the code, it is the assumption

The original code has no guard at all, and a comment explains why the author thought that was enough: "this endpoint answers 200 after the transaction commits, so one event reaches here exactly once."

Two events are being treated as one. In reality session.commit() and the 200 that reaches the gateway are two separate events, and the second can fail on its own. When it does, the gateway knows exactly one thing: it has not received an answer.

2. The unique key fixes the symptom, then raises a new problem — and the new problem is correct

Add UNIQUE (event_id). The duplicates stop. What appears instead:

TEXT
status: [200, 500, 500, 500]
1 of 30 concurrent deliveries answered 2xx
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation)
duplicate key value violates unique constraint "ledger_entries_event_id_key"

This is what makes people think a unique key is not the fix. What is actually wrong is our reaction to the conflict: we treat it as a failure, when from the gateway's point of view "I sent this event and it was already received" is a successful outcome.

Notice also what did not break: the row stayed single, the balance stayed correct. So a duplicate key is not a data problem — it is a response problem. The gateway never learns that its first attempt worked, so it sends again, gets another 500, sends again. What grows is not the row count, it is the error count.

3. The decision moves to the database, and the answer is stored

Two changes, both about where things are kept:

  • The claim becomes one statement instead of "check first, then write":

    SQL
    INSERT INTO processed_events (event_id, request_fingerprint)
    VALUES ($1, $2)
    ON CONFLICT (event_id) DO NOTHING
    RETURNING event_id;

    Empty means we did not get it. This is "check and write" in one operation, so there is no window two callers can slip through. There is no except to write, because a predictable conflict is not an exception.

  • The first response is stored on the claim row, and a redelivery returns it as-is.

If you choose "check in the app first, then INSERT", it is still red. That shape looks equivalent and passes manual tests; under load, 30 deliveries read the table together, all see "not there", all write. 26–29 of them are caught by the unique key and become 500s. No duplicates in the end, but your endpoint is screaming on almost every concurrent delivery.

4. The balance is not an idempotency problem, but it lives in the same lab

account.balance = account.balance + amount looks like addition. What actually happens: read the value from the database, send the new value back. Thirty transactions that read the same value will write the same value — 40,000 out of 300,000 survived.

In SQL, a single UPDATE accounts SET balance = balance + $1 WHERE id = $2 does not have that problem: the database holds the row for the duration of the update. Same lesson as the three steps before, in its purest form: if the data lives in the database, the decision lives there too.

I only really understood this part when the retries started coming from a worker instead of HTTP. A bad retry is not just one request answered twice: it can arrive at three in the morning, from another worker, for a job that is already done. Same cure, and since then I have never treated "runs once" as a guarantee.

The most tempting trap

PYTHON
try:
    session.flush()
except IntegrityError:
    pass

It looks safe because the duplicate row indeed does not get in. What you cannot see: in Postgres, a failed statement aborts the entire transaction. The next statement fails with 25P02: current transaction is aborted, and if you catch that error too and return 200, you have just said "done" for work that never happened. If you want to handle it anyway, you need a SAVEPOINT so only that statement is rolled back.

Second trap: separating the claim from the work. If the claim commits first, there is a window where the server can die — and afterwards the event is recorded as processed while the ledger and balance are empty, and every redelivery is treated as a duplicate. Duplicates show up in reports; loss does not.

What this lab does not cover

  • Side effects outside the database. If your handler also sends an email or calls a third-party API, one transaction does not help: email cannot be rolled back. That is the outbox pattern.
  • A fact arriving from two paths. In this lab one payment has one path. Once a reconciliation job closes payments whose webhook was late, every key used here stops working — and the only one that keeps working is the key that comes from the domain itself. That is the next lab.

Get better at shipping code.

Join the other developers getting tech updates, tips, and relaxed tutorials in their inbox every week.

Stay in the loop

Tech updates, coding tips, and relaxed insights straight to your inbox every week.

No spam. Unsubscribe anytime.

Read next

See all
Struktur DataWhat a Linked List Actually Is

A linked list is a linear chain of nodes, each holding data and a pointer to the next node. Here is what that chain looks like, what it costs next to an array, and the same minimal implementation in Java, Python, and JavaScript.

For developers who learn by struggling

© 2026 Inva.dev.