Interview Study Guide

Guide / System design Fundamentals

7. Idempotency — order placed once, charged once

Created · Updated · 7 min read

An operation is idempotent if doing it twice has the same effect as doing it once. In distributed systems duplicates are guaranteed: users double-click, mobile clients retry after a timeout, load balancers retry, queues redeliver. You cannot prevent duplicate requests; you prevent duplicate effects.

7.1 Why the timeout case is the hard one#

The client sends “pay ₹500”, the server charges the card, and the response is lost. The client cannot tell “failed” from “succeeded but I didn’t hear”. It must retry, so the server must recognise the retry.

7.2 The idempotency-key pattern (step by step)#

  1. Client generates a unique key per logical operation (UUID when the user opens checkout, or a hash of cart ID + version) and sends Idempotency-Key: <key> on every retry of that operation.
  2. Server, in one transaction, inserts (key, user_id, request_hash, status='IN_PROGRESS') into an idempotency_keys table with a unique constraint on key.
  3. If the insert succeeds → this is the first attempt: do the work, store the response, set status='COMPLETED'.
  4. If the insert hits the unique constraint → it’s a duplicate: if COMPLETED, return the stored response; if IN_PROGRESS, return 409/425 “still processing” (client retries later); if the request_hash differs, return 422 (same key reused for a different request).
  5. Keys expire after 24 h–7 days. If the worker crashes mid-way, a recovery job resumes or fails IN_PROGRESS rows older than a timeout.

Stripe’s API works this way; mention it.

7.3 Place the order exactly once and charge exactly once#

  • Order creation: orders table has UNIQUE(idempotency_key) (or UNIQUE(cart_id) for one order per cart). The database constraint is the final guard, not an app-level “check then insert” (that races).
  • State machine: CREATED → PAYMENT_PENDING → PAID → FULFILLED, transitions with a guarded update: UPDATE orders SET status='PAID' WHERE id=? AND status='PAYMENT_PENDING'. Only one caller can win; others see 0 rows and stop.
  • Payment call: pass your idempotency key (e.g. order_id) to the payment gateway (Stripe, Razorpay and others support this). If your service retries, the gateway returns the original charge instead of charging twice.
  • Unknown outcome: if the gateway times out, don’t retry blindly with a new key — mark PAYMENT_UNKNOWN, then reconcile: query the gateway by your reference, or wait for its webhook.
  • Webhooks are at-least-once and unordered: dedupe by the gateway’s event ID, verify the signature, and apply only valid state transitions (a payment.succeeded arriving after you already marked PAID is a no-op).
  • Daily reconciliation job: compare your ledger with the gateway’s settlement report; auto-refund duplicates. Senior candidates always mention reconciliation.
  • Ledger: record money as append-only double-entry entries (debit + credit), never as an updatable balance alone.

7.4 Avoiding duplicated work generally#

TechniqueHowUse for
Unique constraintDB rejects the second insertOrders, sign-ups, coupon redemptions
Conditional / guarded updateWHERE status = expected or version checkState transitions, inventory
Dedupe table (inbox)Store processed message_id with the side effect, same transactionQueue consumers
Natural idempotencySET balance_snapshot = X or upsert, not += XProjections, caches
Idempotent producerKafka enable.idempotence=true (sequence numbers per partition)Avoiding producer duplicates
Distributed lock / leaseOnly one worker processes a key at a timeCron jobs, expensive recomputes (pair with idempotency, never alone)
Request coalescingConcurrent identical requests share one in-flight callCache refills, expensive reads
Client-side debounceDisable button after clickUX only — never your only defence

7.5 Coupon redeemed only once (common at e-commerce companies)#

INSERT INTO redemptions(coupon_id, user_id, order_id) with UNIQUE(coupon_id, user_id) for per-user coupons; for a global usage limit, UPDATE coupons SET used = used + 1 WHERE id=? AND used < max_uses and check affected rows. Under extreme contention (flash sale), pre-load the count into Redis and use an atomic DECR / Lua script, then persist asynchronously with reconciliation.

Follow-ups: “Where do you store idempotency keys?” (same DB as the business write, so they commit atomically; Redis only if you accept a small race window). “What if two requests with the same key arrive at the same millisecond?” (the unique constraint lets exactly one insert win). “How long do you keep keys?” (longer than the client’s maximum retry window).

7.6 Implementation details that interviewers probe#

Schema for the idempotency table

CREATE TABLE idempotency_keys (
  tenant_id     BIGINT      NOT NULL,
  key           TEXT        NOT NULL,
  endpoint      TEXT        NOT NULL,             -- scope: same key on another endpoint is different
  request_hash  BYTEA       NOT NULL,             -- sha256 of canonical body
  status        TEXT        NOT NULL,             -- in_progress | done | failed
  response_code INT,
  response_body JSONB,
  locked_until  TIMESTAMPTZ,                      -- crash recovery for in_progress rows
  created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, key, endpoint)
);
-- cleanup job: DELETE WHERE created_at < now() - interval '24 hours'

Handler flow (one transaction around business work and key update)

  1. INSERT ... ON CONFLICT DO NOTHING. Inserted → we own it. Not inserted → SELECT the row.
  2. Existing row done and same request_hash → return stored response. Different hash → 422.
  3. Existing row in_progress and locked_until in the future → 409 “request in progress” (client retries later). If locked_until has passed, take over (the worker crashed).
  4. Do the work and write the response and status='done' in the same transaction as the business writes; for external calls (payment gateway) pass your key (or a derived one) to the gateway, because you cannot roll back an external side effect.

Webhook receiver dedupe. Providers deliver at-least-once and out of order. Store event_id with a unique constraint in the same transaction as the state change; ignore duplicates; verify the HMAC signature and timestamp (reject if older than 5 minutes); respond 2xx quickly and process asynchronously; handle out-of-order events by comparing event.created or version to current state, or by re-fetching the resource from the provider API.

Natural idempotency checklist: deterministic IDs generated by the client, PUT instead of POST, upserts (INSERT ... ON CONFLICT DO UPDATE), set-instead-of-increment, conditional updates with state guards (WHERE status='pending'), unique constraints on business keys ((order_id, type) for a refund).

Most asked questions#

1. What is idempotency and why does it matter in distributed systems? Repeating an operation yields the same end state. Networks lose responses and clients, queues and load balancers retry, so every write path must tolerate duplicates.

2. How do you implement idempotency keys? Client-generated key per intent; server stores key + request hash + response under a unique constraint, atomically with the work; repeats return the stored response; mismatch → 422; expire after a day.

3. How do you prevent double charges? Idempotency key at your API, the same key sent to the gateway, a state machine with guarded transitions, webhook dedupe, and a reconciliation job comparing your ledger with the gateway’s.

4. Are PUT and DELETE idempotent? PATCH? PUT and DELETE yes; PATCH depends on its operations (set vs increment).

5. How do you make a queue consumer idempotent? Dedupe table keyed by message ID in the same transaction as the side effect, or an idempotent upsert / conditional update.

Senior-level questions#

1. “The key is saved but the payment gateway call timed out. What is the state?” Unknown: mark pending_unknown, never create a second charge; query the gateway by your idempotency key or reference, or wait for the webhook; a reconciliation job resolves stragglers; the customer sees “processing”.

2. “Idempotency across services: A calls B calls C, all retry.” Propagate one end-to-end key (derive child keys deterministically hash(key, step)), make each hop idempotent, and retry at one layer only.

3. “Is exactly-once real?” Not over an unreliable network: it is effectively-once = at-least-once delivery + idempotent effects (+ transactions inside one system).

4. “How long do you keep keys?” Longer than the client’s maximum retry window (24 h typical; payments up to 30 days for webhook retries); balance storage; keep a hash of the response rather than the whole body if needed.

5. “A client reuses one key for different requests.” The request hash check returns 422/409; document that a key identifies a logical operation, and log such clients.

Quiz#

1. Why must the idempotency record and business write share a transaction?

Otherwise a crash between them leaves either a processed operation with no key (a retry repeats it) or a key with no result (a retry is blocked or returns nothing).

2. Same key, different body: what do you return?

422 (or 409): it is a client error; never silently replay the old response for a different request.

3. How do you dedupe webhooks?

Unique constraint on the provider’s event ID, inserted in the same transaction as the state change; verify signatures; handle out-of-order delivery by version or re-fetch.

4. How do you handle a crash that leaves a key in in_progress forever?

A locked_until lease: after it expires another worker can take over, or the client retry resumes the operation using the stored progress.

5. Is `UPDATE balance = balance - 10` idempotent?

No. Make it idempotent by recording the operation ID in a ledger with a unique constraint, or by setting an absolute value with a version check.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes