Let clients retry any write as often as they need while the server performs the side effect at most once per logical operation. Duplicates that arrive later get the original response, and duplicates that arrive while the first attempt is still running are held off.
A retry is only safe if repeating the request cannot repeat its effect. Reads get this for free. Writes that move money, send messages or create orders do not, and the network gives you no reliable way to tell whether a timed-out request failed or succeeded without telling you. Idempotency keys close that gap. The client attaches a unique key to each logical operation. The server records the key, the shape of the request and the final response, so a retry is answered from that record instead of being executed again. This guide follows one payout service through a double-payment incident and builds the fix: key scoping, request fingerprints, stored responses, leases for in-flight duplicates, and forwarding the key to downstream providers.
The problem
A situation where the obvious design starts to hurt.
Tallyhop is a delivery app whose couriers can cash out their earnings to a debit card instantly. The payouts service handles about 1,200 POST /payouts requests per minute at the Friday evening peak. Each request debits the courier's balance in Postgres and then calls Cardline, an external card processor, to push the funds.
One Friday, Cardline's p99 latency climbed to 34 seconds. The API gateway closed connections to the mobile app after 20 seconds, so the app showed a network error while the payout was still running on the server. The app's retry logic sent the same payout again, up to three times, and each attempt was treated as a new payout. The original requests finished a few seconds later. By the time the on-call engineer saw it, 412 couriers had been paid twice, about $18,600 in total, which took the finance team two weeks to recover.
The team could not simply turn retries off. Couriers on cellular networks lose connections constantly, and without retries a real share of payouts would fail and turn into support tickets. Deduplicating on courier ID and amount was also wrong: a courier who cashes out $45.20 twice in an evening has made two legitimate requests. The server needed a way to tell a retry of the same operation apart from a new operation that happens to look identical.
The solution
What the pattern proposes.
Each payout attempt carries an Idempotency-Key header, a UUID the app generates when the courier taps Cash out and stores locally until it gets a final answer. Every retry of that tap reuses the key. A new tap gets a new key.
Before doing any work, the payouts service claims the key in an idempotency_keys table in the same Postgres database as the ledger. The key is scoped to the courier, so one courier's key cannot collide with another's. The row stores a SHA-256 fingerprint of the canonicalised request body, a state (in_progress or completed), a lease expiry, and later the response status and body.
The claim is one INSERT ... ON CONFLICT DO NOTHING. If the insert wins, this request owns the operation. If the row already exists, there are four outcomes: a different fingerprint means the key was reused for a different request, so return 422; completed means return the stored response unchanged; in_progress with a live lease means another attempt is running, so return 409 with Retry-After; in_progress with an expired lease means the owner crashed, so take over the lease and continue.
The owner debits the ledger and records a recovery point in one transaction, then calls Cardline with the same key, because Cardline also deduplicates on it. A takeover after a crash can therefore never push funds twice. Final outcomes (2xx and 4xx) are stored and replayed. Transient 5xx outcomes release the key so the client can retry. A daily job drops key rows older than 24 hours, which is longer than the app's retry window.
An everyday analogy
The same idea, outside software.
Think of a coat check. When you hand over your coat you get a numbered ticket, and the attendant writes the number on a tag. If you come back and wave the same ticket again, the attendant does not take a second coat from you; they look up the tag and tell you what happened to the first one. If you show up with ticket 47 while the attendant is still hanging coat 47, they ask you to wait a moment rather than starting over. And if you show ticket 47 with a completely different coat, the attendant knows something is wrong and refuses.
Structure
The pieces and how they relate.
Participants
- Courier app (client)
- Generates a UUID when the courier taps Cash out, persists it locally, and sends it as Idempotency-Key on the first attempt and every retry until it gets a 2xx or 4xx. It never creates a new key for a retry.
- Payouts API
- Claims the scoped key before any side effect, decides between execute, replay, 409 and 422, and writes the final response back to the key row.
- idempotency_keys table
- Stores scoped key, request fingerprint, state, lease expiry, response status and body. Its primary key on (courier_id, key) makes the claim atomic. It lives in the ledger database so completion and ledger writes can share a transaction.
- Cardline processor
- The external side effect. It accepts the same idempotency key, which protects against the one case the local table cannot cover: a crash after the processor accepted the payout but before the response was stored.
- Key reaper
- Drops daily partitions of the key table once they are older than 24 hours, keeping the table near 1.7 million rows instead of growing without bound.
Pseudocode
The solution to the scenario, language-neutral.
function handlePayout(courierId, key, body):
if key is missing: return 400
scoped = courierId + ":" + key
fingerprint = sha256(canonicalJson(body))
claim = store.claim(scoped, fingerprint, leaseSeconds = 60)
// SQL: INSERT INTO idempotency_keys (...) VALUES (...)
// ON CONFLICT (courier_id, key) DO NOTHING RETURNING *
// if no row returned: SELECT ... FOR UPDATE and inspect
if claim is MISMATCH: return 422 "key reused with different body"
if claim is REPLAY: return claim.storedResponse
if claim is IN_FLIGHT: return 409 with Retry-After = claim.secondsLeft
// claim is OWNER: fresh insert, or a stale lease taken over
try:
transaction:
ledger.debit(courierId, body.amount) // skipped if already recorded for this key
store.markRecoveryPoint(scoped, "debited")
response = cardline.push(body, idempotencyKey = scoped)
if response.status >= 500:
store.release(scoped) // transient, let client retry
else:
transaction:
store.complete(scoped, response) // 2xx and 4xx are final
outbox.add("payout.completed", ...)
return response
except error:
store.release(scoped)
raiseThe code
The same solution in TypeScript, Python and PHP.
import { createHash } from "node:crypto";
type StoredResponse = { status: number; body: Record<string, unknown> };
type PayoutRequest = { amountCents: number; currency: string; cardId: string };
type Processor = (idempotencyKey: string, req: PayoutRequest) => Promise<StoredResponse>;
type KeyRecord = {
requestHash: string;
state: "in_progress" | "completed";
lockedUntil: number;
response?: StoredResponse;
};
type Claim =
| { kind: "owner" }
| { kind: "replay"; response: StoredResponse }
| { kind: "in_flight"; retryAfterSec: number }
| { kind: "mismatch" };
// In-memory stand-in for the idempotency_keys table. Each method is synchronous,
// so it is atomic on the event loop, like INSERT ... ON CONFLICT in Postgres.
class IdempotencyStore {
private records = new Map<string, KeyRecord>();
constructor(private readonly leaseMs = 60_000) {}
claim(key: string, requestHash: string, now = Date.now()): Claim {
const rec = this.records.get(key);
if (!rec) {
this.records.set(key, { requestHash, state: "in_progress", lockedUntil: now + this.leaseMs });
return { kind: "owner" };
}
if (rec.requestHash !== requestHash) return { kind: "mismatch" };
if (rec.state === "completed" && rec.response) return { kind: "replay", response: rec.response };
if (rec.lockedUntil > now) {
return { kind: "in_flight", retryAfterSec: Math.ceil((rec.lockedUntil - now) / 1000) };
}
rec.lockedUntil = now + this.leaseMs; // previous owner died: take over its lease
return { kind: "owner" };
}
complete(key: string, response: StoredResponse): void {
const rec = this.records.get(key);
if (!rec) return;
rec.state = "completed";
rec.response = response;
}
release(key: string): void {
this.records.delete(key);
}
}
function hashRequest(req: PayoutRequest): string {
const canonical = JSON.stringify(req, Object.keys(req).sort());
return createHash("sha256").update(canonical).digest("hex");
}
async function createPayout(
store: IdempotencyStore,
courierId: string,
idempotencyKey: string | undefined,
req: PayoutRequest,
processor: Processor,
): Promise<StoredResponse> {
if (!idempotencyKey) return { status: 400, body: { error: "Idempotency-Key header is required" } };
const scopedKey = `${courierId}:${idempotencyKey}`;
const claim = store.claim(scopedKey, hashRequest(req));
switch (claim.kind) {
case "mismatch":
return { status: 422, body: { error: "Key reused with a different request body" } };
case "replay":
return claim.response;
case "in_flight":
return { status: 409, body: { error: "Request in progress", retryAfterSec: claim.retryAfterSec } };
case "owner":
break;
}
try {
// Forward the same key so a takeover after a crash cannot pay twice.
const response = await processor(scopedKey, req);
if (response.status >= 500) store.release(scopedKey); // transient: allow a retry
else store.complete(scopedKey, response); // 2xx and 4xx are final: replay them
return response;
} catch (err) {
store.release(scopedKey);
throw err;
}
}
async function main(): Promise<void> {
const store = new IdempotencyStore();
const req: PayoutRequest = { amountCents: 4520, currency: "USD", cardId: "card_77" };
let calls = 0;
let duringFlight: StoredResponse | undefined;
const processor: Processor = async (_key, r) => {
calls++;
// The app times out and retries while this call is still running.
if (!duringFlight) {
duringFlight = await createPayout(store, "courier_31", "k-1f9c", r, processor);
}
return { status: 201, body: { payoutId: "po_5001", amountCents: r.amountCents } };
};
const first = await createPayout(store, "courier_31", "k-1f9c", req, processor);
const retry = await createPayout(store, "courier_31", "k-1f9c", req, processor);
const reused = await createPayout(store, "courier_31", "k-1f9c", { ...req, amountCents: 9999 }, processor);
console.log(first.status, duringFlight?.status, retry.status, reused.status); // 201 409 201 422
console.log("processor calls:", calls); // 1
}
main();import asyncio
import hashlib
import json
import math
import time
from dataclasses import dataclass
from typing import Awaitable, Callable, Optional
Processor = Callable[[str, dict], Awaitable[dict]]
@dataclass
class KeyRecord:
request_hash: str
state: str # "in_progress" or "completed"
locked_until: float
response: Optional[dict] = None
class IdempotencyStore:
"""In-memory stand-in for the idempotency_keys table.
Methods never await, so each one is atomic on the event loop,
like INSERT ... ON CONFLICT in Postgres.
"""
def __init__(self, lease_sec: float = 60.0) -> None:
self._records: dict[str, KeyRecord] = {}
self._lease = lease_sec
def claim(self, key: str, request_hash: str, now: Optional[float] = None) -> dict:
now = time.time() if now is None else now
rec = self._records.get(key)
if rec is None:
self._records[key] = KeyRecord(request_hash, "in_progress", now + self._lease)
return {"kind": "owner"}
if rec.request_hash != request_hash:
return {"kind": "mismatch"}
if rec.state == "completed" and rec.response is not None:
return {"kind": "replay", "response": rec.response}
if rec.locked_until > now:
return {"kind": "in_flight", "retry_after_sec": math.ceil(rec.locked_until - now)}
rec.locked_until = now + self._lease # previous owner died: take over its lease
return {"kind": "owner"}
def complete(self, key: str, response: dict) -> None:
rec = self._records.get(key)
if rec is None:
return
rec.state = "completed"
rec.response = response
def release(self, key: str) -> None:
self._records.pop(key, None)
def hash_request(req: dict) -> str:
canonical = json.dumps(req, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode()).hexdigest()
async def create_payout(
store: IdempotencyStore,
courier_id: str,
idempotency_key: Optional[str],
req: dict,
processor: Processor,
) -> dict:
if not idempotency_key:
return {"status": 400, "body": {"error": "Idempotency-Key header is required"}}
scoped_key = f"{courier_id}:{idempotency_key}"
claim = store.claim(scoped_key, hash_request(req))
if claim["kind"] == "mismatch":
return {"status": 422, "body": {"error": "Key reused with a different request body"}}
if claim["kind"] == "replay":
return claim["response"]
if claim["kind"] == "in_flight":
return {
"status": 409,
"body": {"error": "Request in progress", "retry_after_sec": claim["retry_after_sec"]},
}
try:
# Forward the same key so a takeover after a crash cannot pay twice.
response = await processor(scoped_key, req)
except Exception:
store.release(scoped_key)
raise
if response["status"] >= 500:
store.release(scoped_key) # transient: allow a retry
else:
store.complete(scoped_key, response) # 2xx and 4xx are final: replay them
return response
async def main() -> None:
store = IdempotencyStore()
req = {"amountCents": 4520, "currency": "USD", "cardId": "card_77"}
calls = 0
during_flight: Optional[dict] = None
async def processor(_key: str, r: dict) -> dict:
nonlocal calls, during_flight
calls += 1
# The app times out and retries while this call is still running.
if during_flight is None:
during_flight = await create_payout(store, "courier_31", "k-1f9c", r, processor)
return {"status": 201, "body": {"payoutId": "po_5001", "amountCents": r["amountCents"]}}
first = await create_payout(store, "courier_31", "k-1f9c", req, processor)
retry = await create_payout(store, "courier_31", "k-1f9c", req, processor)
reused = await create_payout(store, "courier_31", "k-1f9c", {**req, "amountCents": 9999}, processor)
print(first["status"], during_flight["status"], retry["status"], reused["status"]) # 201 409 201 422
print("processor calls:", calls) # 1
if __name__ == "__main__":
asyncio.run(main())<?php
declare(strict_types=1);
// In-memory stand-in for the idempotency_keys table. In Postgres, claim()
// is INSERT ... ON CONFLICT DO NOTHING followed by SELECT ... FOR UPDATE.
final class IdempotencyStore
{
/** @var array<string, array{hash: string, state: string, lockedUntil: float, response: ?array}> */
private array $records = [];
public function __construct(private readonly float $leaseSec = 60.0)
{
}
public function claim(string $key, string $requestHash, ?float $now = null): array
{
$now ??= microtime(true);
$rec = $this->records[$key] ?? null;
if ($rec === null) {
$this->records[$key] = [
'hash' => $requestHash,
'state' => 'in_progress',
'lockedUntil' => $now + $this->leaseSec,
'response' => null,
];
return ['kind' => 'owner'];
}
if ($rec['hash'] !== $requestHash) {
return ['kind' => 'mismatch'];
}
if ($rec['state'] === 'completed' && $rec['response'] !== null) {
return ['kind' => 'replay', 'response' => $rec['response']];
}
if ($rec['lockedUntil'] > $now) {
return ['kind' => 'in_flight', 'retryAfterSec' => (int) ceil($rec['lockedUntil'] - $now)];
}
$this->records[$key]['lockedUntil'] = $now + $this->leaseSec; // previous owner died
return ['kind' => 'owner'];
}
public function complete(string $key, array $response): void
{
if (!isset($this->records[$key])) {
return;
}
$this->records[$key]['state'] = 'completed';
$this->records[$key]['response'] = $response;
}
public function release(string $key): void
{
unset($this->records[$key]);
}
}
function hashRequest(array $req): string
{
ksort($req);
return hash('sha256', json_encode($req, JSON_THROW_ON_ERROR));
}
function createPayout(
IdempotencyStore $store,
string $courierId,
?string $idempotencyKey,
array $req,
callable $processor
): array {
if ($idempotencyKey === null || $idempotencyKey === '') {
return ['status' => 400, 'body' => ['error' => 'Idempotency-Key header is required']];
}
$scopedKey = $courierId . ':' . $idempotencyKey;
$claim = $store->claim($scopedKey, hashRequest($req));
switch ($claim['kind']) {
case 'mismatch':
return ['status' => 422, 'body' => ['error' => 'Key reused with a different request body']];
case 'replay':
return $claim['response'];
case 'in_flight':
return ['status' => 409, 'body' => ['error' => 'Request in progress', 'retryAfterSec' => $claim['retryAfterSec']]];
}
try {
// Forward the same key so a takeover after a crash cannot pay twice.
$response = $processor($scopedKey, $req);
} catch (Throwable $e) {
$store->release($scopedKey);
throw $e;
}
if ($response['status'] >= 500) {
$store->release($scopedKey); // transient: allow a retry
} else {
$store->complete($scopedKey, $response); // 2xx and 4xx are final: replay them
}
return $response;
}
$store = new IdempotencyStore();
$req = ['amountCents' => 4520, 'currency' => 'USD', 'cardId' => 'card_77'];
$calls = 0;
$duringFlight = null;
$processor = function (string $key, array $r) use (&$processor, &$calls, &$duringFlight, $store): array {
$calls++;
// The app times out and retries while this call is still running.
if ($duringFlight === null) {
$duringFlight = createPayout($store, 'courier_31', 'k-1f9c', $r, $processor);
}
return ['status' => 201, 'body' => ['payoutId' => 'po_5001', 'amountCents' => $r['amountCents']]];
};
$first = createPayout($store, 'courier_31', 'k-1f9c', $req, $processor);
$retry = createPayout($store, 'courier_31', 'k-1f9c', $req, $processor);
$reused = createPayout($store, 'courier_31', 'k-1f9c', array_merge($req, ['amountCents' => 9999]), $processor);
echo $first['status'], ' ', $duringFlight['status'], ' ', $retry['status'], ' ', $reused['status'], PHP_EOL; // 201 409 201 422
echo 'processor calls: ', $calls, PHP_EOL; // 1When to use it
Situations where it pays off.
A write has an external or irreversible side effect, such as moving money, sending an SMS or creating a shipment, and clients retry on timeouts.
A timeout tells the client nothing about whether the effect happened. The key turns the uncertain retry into a lookup that returns the original outcome.
Clients sit on unreliable networks, such as mobile apps, IoT devices or partner integrations with aggressive retry policies.
These clients will retry whether you like it or not. Making the endpoint idempotent is cheaper than trying to control every client's retry logic.
The natural request data cannot tell a retry from a new operation, like two identical $45.20 payouts in one evening.
Deduplicating on business fields either blocks legitimate repeats or misses retries. A client-generated key carries the intent explicitly.
Message consumers process at-least-once deliveries from a queue and the handler performs a write.
The message ID or an operation ID works as the key, so redeliveries after a consumer crash do not repeat the write.
How to implement it
Steps to introduce it in existing code.
Define the contract: which endpoints require Idempotency-Key, the key format (UUID v4, max 64 characters), how long keys are honoured (24 hours here), and the status codes for replay, in-flight (409 with Retry-After) and mismatch (422).
Make the client generate the key at the moment of user intent, persist it until a final 2xx or 4xx arrives, and reuse it for every retry. Review the client code, because a key generated inside the retry loop gives you no protection.
Create the key table with a primary key on (scope, key), a request fingerprint, state, lease expiry, response status, response body and created_at. Partition it by day so expiry is a cheap partition drop.
Claim the key with a single atomic insert before any side effect. On conflict, lock the existing row and compare the fingerprint, then replay, return 409, or take over an expired lease.
Store the final response in the same transaction as the business write where you can, and forward the key, or a key derived from it, to every downstream provider that supports one.
Store 2xx and deterministic 4xx responses for replay. Release the key on 5xx and on exceptions so the client can retry, and alert on rows stuck in_progress past twice the lease.
Pros and cons
What you gain and what you pay.
Pros
- Clients can retry freely on timeouts and dropped connections without risking a duplicate side effect.
- A retry gets the exact response of the original attempt, including the payout ID, so the client's state stays consistent.
- Concurrent duplicates are serialised by the database's uniqueness constraint instead of application-level locking.
- The key row doubles as an audit trail of what each client attempt actually did.
Cons
- Every protected write pays an extra insert and update, roughly 1 to 3 ms on the payouts Postgres cluster.
- Safety depends on clients generating and reusing keys correctly, which you cannot fully enforce from the server.
- Lease timing is subtle: a lease shorter than the slowest downstream call lets a second attempt run alongside the first.
- Storing response bodies grows storage, which needs partitioning and a retention job.
Trade-offs
Decisions you'll have to make, each with its price.
Key table in the ledger database rather than in Redis
You gainThe key, the ledger debit and the outbox event commit in one transaction, so a stored response can never disagree with the ledger.
You payAdds two writes per payout to the primary database, about 40 extra writes per second at the 1,200 per minute peak, and couples key throughput to that cluster.
24 hour key retention
You gainCovers the app's retry window (three retries over at most about 10 minutes) plus a courier reopening the app the next morning, while keeping about 1.7 million rows.
You payA client retrying after 24 hours is treated as a new payout. A 7 day retention would close that gap but needs about 12 million rows and larger partitions.
60 second lease on in_progress keys
You gainLonger than the 30 second Cardline timeout plus database time, so a live owner is never taken over while still calling the processor.
You payIf an instance crashes mid-payout, retries get 409 for up to 60 seconds before another instance can take over.
Strict fingerprint over the full canonical body
You gainCatches client bugs that reuse one key for different payouts and returns 422 instead of replaying the wrong amount.
You payHarmless body differences, such as a new optional field added in an app update, also trigger 422. You need to choose which fields are in the fingerprint and keep that choice stable.
How it fails
What goes wrong in production and how to prevent it.
The client generates a fresh key inside its retry loop, so every retry looks like a new operation.
What to doGenerate the key at tap time and persist it with the pending payout in local storage. Add a contract test in the app's CI that asserts the header is identical across retries, and log server-side when one courier creates two same-amount payouts within 60 seconds under different keys.
The lease is shorter than the downstream timeout, so a takeover runs alongside a still-running owner and calls the processor twice.
What to doKeep the lease above the processor timeout plus a margin (60s against 30s), alert when processor latency nears the lease, and always forward the key to Cardline so even an overlapping call is deduplicated there.
The process crashes after Cardline accepted the payout but before the response was stored, leaving the row in_progress.
What to doWhen the lease expires the next retry takes over and calls Cardline with the same key, and Cardline returns the original result. A sweeper alerts on rows still in_progress after 2 minutes.
The key table grows without bound and the claim insert slows as indexes bloat.
What to doPartition by created_at day and have the reaper drop partitions older than 24 hours. Dropping a partition is a metadata operation, unlike a DELETE that scans and rewrites millions of rows.
Keys are scoped globally, so two couriers whose apps produce the same weak key, or a malicious client, can read another courier's stored response.
What to doScope the key with the authenticated courier ID in the primary key, never trust a scope taken from the body, and reject keys that are not valid UUIDs.
In a system design interview
When to bring it up and how to explain it.
Bring it up whenever the design has a non-idempotent write behind a network hop that clients or upstream services retry: payments, payouts, order creation, sending notifications, or a queue consumer that writes. It often comes up right after you add retries or timeouts to the diagram.
What you could say
Retries are only safe if repeating the request can't repeat the effect, so I'd put idempotency keys on the payout endpoint. The app generates a UUID when the courier taps Cash out and reuses it for every retry. On the server I scope it to the courier and claim it with an insert-on-conflict into a table in the same Postgres as the ledger. The row holds a hash of the request body, a state and a lease. If I win the insert, I do the work. If the row exists, I compare the hash and return 422 on a mismatch, replay the stored response if it's completed, or return 409 with Retry-After if it's still in flight with a live lease. The lease is 60 seconds, longer than the 30 second processor timeout, so I never take over a live owner. I forward the same key to the card processor, which covers a crash after the processor paid but before I saved the response. I store 2xx and 4xx and release on 5xx, and keys expire after 24 hours through daily partition drops.
Likely follow-ups
What happens if your service crashes between calling the processor and saving the response?
The row stays in_progress. Once the 60 second lease expires, the next retry takes over and calls the processor again with the same key. The processor recognises it and returns the original payout, which I then store. A sweeper alerts on rows stuck past 2 minutes so we can see if this keeps happening.
How do you handle two identical requests that hit different instances at the same millisecond?
The primary key on (courier_id, key) decides it. Both instances run INSERT ON CONFLICT DO NOTHING, and Postgres lets exactly one insert succeed. The loser sees no returned row, selects the existing one, finds it in_progress with a live lease, and returns 409.
Why not just make the ledger write unique on some business field?
A unique constraint on something like courier plus amount blocks legitimate repeat payouts, and it only protects my own database, not the call to the card processor. The client key represents the intent itself, and I can pass it downstream to protect the external side effect too.
How would you apply this to a queue consumer instead of an HTTP API?
Use the message ID, or an operation ID the producer puts in the payload, as the key. The consumer claims it in the same transaction as its write. A redelivery after a crash then finds the completed row and simply acks the message without writing again.
Relations with other guides
Patterns it's often confused or combined with.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Retries are what create duplicates in the first place. Backoff controls how often the client retries; idempotency keys make each retry harmless. You usually need both on the same call path.
- Timeouts and Deadline Propagation
The incident started with a gateway timeout shorter than the processor's latency. The key lease must be longer than the longest downstream timeout, or takeover overlaps a still-running owner.
- Transactional Outbox: Commit State and Events Together
Completing the key row and enqueueing payout.completed in one transaction keeps the event and the stored response in agreement, so a replay never reports a payout whose event was lost.
- Saga: Multi-Service Transactions with Compensations
Each saga step that calls another service needs its own idempotency key, typically derived from the saga ID and step name, so retried or resumed steps do not double-apply.
- Competing Consumers: Many Workers, One Queue, No Duplicates
With several consumers and at-least-once delivery, the message ID used as an idempotency key keeps a redelivered message from repeating its write.
Common questions
Short answers to the usual doubts.
Why not let the server derive the key from the request body?
Because identical bodies can be legitimate separate operations. A courier who cashes out $45.20 twice in one evening sends two identical bodies, and a hash-derived key would silently drop the second payout. Only the client knows whether a request is a retry or a new intent, so the client must name the operation.
Should a duplicate that arrives mid-flight wait or get a 409?
For Tallyhop, an immediate 409 with Retry-After is better. Holding the second request open ties up a connection and a worker for up to the processor's 30 second timeout, during the exact incident when capacity is short. Short operations under about 2 seconds can poll the row for a few hundred milliseconds and return the result directly, which is friendlier to clients.
Should error responses be stored and replayed?
Store deterministic outcomes: 2xx and 4xx such as insufficient balance or an invalid card. Do not store 5xx or timeouts, because those mean the outcome is unknown or transient. If you stored a 503, every retry for the next 24 hours would get the same failure even after the processor recovered.
Can Redis hold the keys instead of Postgres?
It can, using SET NX with a TTL for the claim, and it is faster. But the key row and the ledger debit can no longer commit together, and Redis eviction under memory pressure or a failover can lose keys that were acknowledged. For money movement, the extra 1 to 3 ms of Postgres is the cheaper option.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Idempotency and retriesTake the test
- No double spend in a betting walletSolve the exercise