Advertise here — become a partner
Advertise here — become a partner
Programming / Tech

Idempotency: the same request without duplicate effect

You are a didactic distributed systems engineer. Help me with idempotency: the scenario is [DESCRIBE: the sensitive operation — payment, order, email send, resource creation —, how it's called: public API, frontend with retry, queue, webhook], stack [STACK + DATABASE], and the trigger is [TRIGGER: client clicked 2x and charged 2x, retry duplicated order, queue redelivered message, I want to prevent before it happens]. Deliver: the concept nailed with the inevitable why (idempotent = executing N times has the effect of 1; and why it's not optional: on the network, timeout is ambiguous — lost response doesn't say if it executed: the client WILL resend, the queue WILL redeliver — at-least-once is reality, exactly-once is built BY ME with idempotency), the map of what already is and what isn't (GET/PUT/DELETE naturally idempotent — if implemented right; the POST that creates and the debit that sums: the villains — MY endpoints classified), the idempotency key implemented end-to-end (the client generates UUID per OPERATION — not per attempt: same ID on retry — sent in header Idempotency-Key; the server: the key checked BEFORE executing — seen? return the SAVED response from first execution, with same status: don't re-execute or respond differently; new? execute, save key + response ATOMICALLY with the effect — the transaction that prevents the race window; the key's TTL honest — 24h+ for payment; the complete example in my stack with table/Redis drawn, including the case of the request STILL processing — the 409/retry-after instead of executing in parallel), the structural alternatives when they fit (the natural domain key — the UNIQUE constraint the database enforces for free: order by (user, cart); the operation reformulated as naturally idempotent — the SET instead of INCREMENT; the upsert), idempotent consumption of queues and webhooks (the event ID processed registered in the SAME transaction as the effect — the inbox pattern: the example), real pitfalls (idempotency only on API with effect outside — the email fired before saving the key; the response regravated differently; cache as idempotency record without atomicity), tests that prove it (same request 2x in sequence AND in parallel — the race condition test), and if I paste code: the operation hardened step by step. Objective: the double-click, the retry and the redelivery becoming non-events — charged once, created once, sent once, always.
Advertise here — become a partner Advertise here — become a partner