cd ../blog

Building an Idempotent Write Path

Retries are inevitable, so exactly-once is a lie you implement with idempotency keys. A pattern for making duplicate writes boring.

"Exactly-once delivery" is marketing. Networks time out, clients retry, and the same request arrives twice. What you can actually build is exactly-once effect — and the tool for that is an idempotency key attached to every mutating request.

# the key is a promise

The client generates a unique key per logical operation and sends it with the write. The server records the key alongside the result of the first execution. If the same key shows up again, you return the stored result instead of doing the work twice.

write_path.sql
-- one row per idempotency key, uniqueness enforced by the DB
INSERT INTO requests (key, status)
VALUES ($1, 'in_progress')
ON CONFLICT (key) DO NOTHING
RETURNING id;

The uniqueness constraint is doing the real work here. If the insert conflicts, another attempt already owns this key — you wait for or return its result rather than racing it. Make the key's lifetime long enough to outlive any retry window, and duplicate writes become the most boring part of your system.