How One Retry Charged a Customer Twice: Designing Bulletproof Idempotent APIs in Production
A user clicks Pay Now on a flaky mobile connection. The request reaches your server, charges their card, and commits the order—but the HTTP response drops before reaching the client. Two seconds later, the client automat
A user clicks Pay Now on a flaky mobile connection. The request reaches your server, charges their card, and commits the order—but the HTTP response drops before reaching the client. Two seconds later, the client automatically retries the exact same POST /api/orders request.
Without idempotency, your backend processes the retry as a brand-new request and charges the customer twice.
In distributed web systems, network timeouts, load balancer retries, and duplicate webhook deliveries from payment gateways are guaranteed to happen. Here is how to design production APIs that safely absorb duplicate requests without corrupting data.
1. Why Simple SELECT Before INSERT Fails Under Concurrency
A common first attempt at preventing duplicates looks like checking if a transaction already exists before creating it:
// Broken under concurrent retries: two requests pass the check at the same millisecond
const existing = await db.orders.findByRequestId(requestId);
if (!existing) {
await chargePaymentGateway(amount);
await db.orders.create({ requestId, amount });
}
When two identical requests hit two worker instances 3 milliseconds apart, both queries return null, both workers charge the card, and you end up with a classic TOCTOU (Time-of-Check to Time-of-Use) race condition.
2. The Idempotency-Key Pattern (How Stripe & Modern APIs Do It)
To make non-idempotent operations (POST, PATCH) safe to retry, require the client to generate a unique UUID (Idempotency-Key header) per logical user action and persist its lifecycle in your database or Redis:
-
Atomic Lock / Unique Constraint: Insert a record keyed by
(user_id, idempotency_key)with statusIN_PROGRESSinside a database transaction backed by aUNIQUEindex. -
Concurrent Duplicate Handling: If a second request arrives with the same key while status is
IN_PROGRESS, return409 Conflict(or wait briefly) instead of executing side effects twice. -
Response Replay: Once the operation succeeds, store the serialized HTTP status code and JSON response body alongside status
COMPLETED. Any future retry with that key immediately returns the cached response without touching payment or inventory services.
3. Guarding Against Payload Mismatches
What if a buggy client reuses the same Idempotency-Key with a different dollar amount or item list?
Store a SHA-256 hash of the canonical request body alongside the key. When a retry arrives, compare the incoming payload hash against the stored hash—if they differ, reject immediately with 422 Unprocessable Entity so a stale key never masks a modified request.
4. Handling Webhook Retries with Database Unique Constraints
External providers (Stripe, Razorpay, GitHub, Twilio) guarantee at-least-once delivery, meaning the exact same webhook event will occasionally fire twice in parallel.
Instead of relying on in-memory flags, use your database's UNIQUE constraint on provider_event_id as the final source of truth:
INSERT INTO processed_webhooks (event_id, payload, processed_at)
VALUES ($1, $2, NOW())
ON CONFLICT (event_id) DO NOTHING;
If rowCount === 0, another worker has already claimed that event—return 200 OK immediately so the provider stops retrying.
5. Set a Sensible TTL for Idempotency Records
Idempotency keys are meant to protect against short-term network retries, not act as permanent storage. Run a scheduled cleanup job (or Redis TTL) to expire completed keys after 24 to 72 hours, keeping your lookup index fast and lean.
The Production Takeaway
Retries are not edge cases—they are normal network behavior. Combining client-generated idempotency keys, database unique constraints, and cached response replay turns fragile endpoints into systems that survive network chaos cleanly.
Have you ever had to untangle duplicate orders or webhook race conditions in production? Share how your stack handles idempotency in the comments!
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.