Idempotency Keys Are Not Optional
The network will retry. Load balancers retry, client libraries retry, impatient users retry. Any write endpoint that is not idempotent is a duplicate-charge, double-order, or corrupted-state incident waiting to happen.
What an idempotency key actually guarantees
An idempotency key is a client-supplied token that says "this is the same logical operation as before." The server's contract: the first request with a given key performs the work; every subsequent request with the same key returns the original result without repeating the work.
A simple, correct implementation
Store the key with the result of the operation, inside the same transaction that performs the write.
INSERT INTO idempotency_keys (key, response, created_at)
VALUES ($1, $2, now())
ON CONFLICT (key) DO NOTHING;
If the insert affects zero rows, the key already exists — return the stored response instead of doing the work again. Because the key and the write commit together, there is no window where one succeeds without the other.
Getting the edges right
- Scope keys to a user or account so one client cannot collide with another.
- Expire keys after a reasonable window (24 hours is common) to bound storage.
- Reject key reuse with a different payload — same key plus different body is a client bug, and returning
409 Conflictsurfaces it early.
Why not just dedupe on natural keys?
Natural keys (order id, transfer reference) work when the client can generate them deterministically. But often the client does not know the id until the server assigns it. An idempotency key sidesteps that — the client generates it up front, before the operation has any identity of its own.
Takeaway
Idempotency is not a nice-to-have you bolt on after an incident. Design it into every write endpoint from day one, commit the key with the work, and retries become boring — which is exactly what you want.