Idempotency keys for web APIs: stopping duplicate payments and records
How to stop retried requests and repeated webhooks from charging twice or creating duplicate records, using idempotency keys, a Redis lock and a PostgreSQL record of each result.
- Topic
- Engineering
- Published
- Updated
- Reading time
- 8 min read
Every engineering team building commercial web applications eventually confronts the nightmare of duplicate execution. A customer clicks "Submit Order" twice on a degraded mobile connection. A Stripe or Shopify webhook retries after an ephemeral gateway timeout. An upstream message queue redelivers an unacknowledged payment event. In a distributed web architecture, network communication is fundamentally unreliable: a request can succeed at the server layer while the client never receives the acknowledgment.
Without idempotency controls, these everyday glitches cause real damage: double-charged credit cards, duplicate database records, corrupted inventory levels, and out-of-sync third-party accounting ledgers. An operation is idempotent when running it twice leaves the system in the same state as running it once. For payments, subscriptions and webhooks, that is a requirement, not an optimisation.
A common mistake is to rely only on disabling the submit button, or only on a unique constraint in the database. Neither is enough on its own. In this engineering guide, we will break down the end-to-end architecture of a production-grade idempotency pipeline using Redis distributed locks and PostgreSQL state machines in Node.js, adhering to the emerging IETF HTTP idempotency specification.
Why Naive Database Constraints and Client Retries Inevitably Break
When engineering teams first attempt to solve duplicate requests, they almost always reach for one of two superficial fixes: disabling the user interface button on the client side, or applying a database-level unique constraint on an external transaction reference. Both approaches collapse under real-world production conditions.
Client-side UI safeguards are entirely useless against automated webhook deliveries, network timeouts, API consumers, and malicious actors. If a mobile app loses cellular connectivity during TLS termination, the client runtime has no way of knowing whether the request reached the origin server. A retry is mandatory, but client-side logic cannot determine whether the initial request completed, failed midway, or is currently executing inside a database transaction.
Database unique constraints, while providing a baseline safeguard against permanent duplicate record insertion, introduce severe operational vulnerabilities when used in isolation. First, a unique constraint violation throws a database exception after expensive work has already happened, such as card tokenisation, third-party fraud scoring, or automated email dispatch. Second, the exception typically bubbles up as an unhandled HTTP 500 Internal Server Error back to the client, prompting automated retry policies that amplify database connection saturation. Most critically, naive constraints cannot handle the classic "read-then-write" race condition: when two concurrent requests arrive simultaneously within milliseconds, both read the non-existence of the record, proceed to write, and cause deadlocks or inconsistent partial state.
The Architecture: Redis Distributed Locks Combined with PostgreSQL State Machines
To stop duplicate execution and give retried requests the same answer straight away, a production pipeline must decouple execution locking from persistent state storage. We accomplish this by combining an ultra-fast in-memory locking tier (Redis) with an ACID-compliant relational ledger (PostgreSQL).
The architecture relies on the standardized Idempotency-Key HTTP request header. When a client initiates a mutating state request (POST, PUT, or PATCH), it generates an opaque, cryptographically random identifier (such as a UUID v4) and passes it in the header. The backend server coordinates the request through a synchronized three-tier execution pipeline:
- Header Extraction & Request Fingerprinting: The application extracts the
Idempotency-Keyalong with the authenticated client or organization identifier. To prevent replay attacks or key reuse with altered payloads, the server computes a deterministic SHA-256 digest of the request URL, HTTP method, and serialized JSON request body. - Persistent Ledger Inspection: The server checks an
idempotency_recordstable in PostgreSQL. If a record exists with statusCOMPLETEDand the payload hash matches, the server bypasses business logic entirely and returns the cached HTTP status code, response headers, and JSON body. If the record exists but the payload hash differs, the server halts execution immediately and returns422 Unprocessable Entitywith an explicit error detailing key-fingerprint mismatch. - Atomic Distributed Lock Acquisition: If no completed record exists, the server acquires an atomic distributed lock in Redis using
SET lock:idempotency:{tenant_id}:{key} {worker_id} NX PX 30000. This command guarantees mutual exclusion: exactly one worker node can process the idempotency key, with a safe 30-second lease to prevent deadlock in the event of an abrupt process crash.
Inside the PostgreSQL transactional boundary, the worker creates an initial record in state PROCESSING. Once the business logic, third-party payment capture, and domain entities are successfully committed, the worker updates the idempotency record to COMPLETED, stores the serialized response payload, and releases the Redis lock. Any subsequent retry with the same key retrieves the exact original response without touching downstream services.
Handling In-Flight Concurrency, Retries, and Failure Recovery
The true test of an idempotency architecture is how gracefully it handles edge cases: in-flight concurrent requests, downstream API timeouts, and unexpected worker crashes.
Handling In-Flight Concurrency: Consider a scenario where an automated webhook sender fires duplicate notifications within 5 milliseconds of each other. Worker 1 acquires the Redis lock and begins processing. Worker 2 attempts to acquire the lock and fails because the key already exists with status PROCESSING. Rather than failing or blocking indefinitely, Worker 2 must return an explicit HTTP 409 Conflict status code along with a Retry-After: 2 response header. Well-behaved API clients and webhook dispatchers recognize this protocol signal, pause for two seconds and retry, by which time Worker 1 has completed and committed the cached response.
Managing Leases and Worker Crashes: If Worker 1 crashes due to an out-of-memory error or server reboot while holding the lock, the Redis 30-second expiration (PX 30000) prevents the key from remaining locked permanently. When the next retry arrives, the Redis lock has expired. The server inspects the PostgreSQL record, discovers that the record remains in state PROCESSING past its allowable execution threshold (e.g., 60 seconds), marks the prior attempt as FAILED_TIMEOUT, and safely reclaims the pipeline for a fresh execution attempt.
Header Transparency: Whenever an idempotent request returns a cached response from the ledger, the server must append an explicit diagnostic header: Idempotent-Replayed: true. This header provides immediate observability to client engineering teams, automated test suites, and API monitoring agents, proving that the duplicate call was intercepted safely without re-triggering business side effects.
Architecture Trade-offs: Memory Footprint, TTL Policies, and Storage Costs
An idempotency layer has to balance memory consumption, database storage growth, and latency overhead. Every abstraction introduces trade-offs that engineering leads must evaluate against their operational budget.
Storage Tiering and Retention Windows: Attempting to store idempotency records forever in primary relational storage leads to table bloat, degraded index scans, and bloated backup sizes. In production financial systems, idempotency keys generally require a strict 24-hour to 72-hour validity window. Any request submitted with a key older than 72 hours should be rejected with 400 Bad Request: Idempotency-Key expired. A scheduled partition drop or background worker running an automated daily cleanup query (DELETE FROM idempotency_records WHERE created_at < NOW() - INTERVAL '3 days') keeps the active table size bounded and index traversal under 1 millisecond.
Redis vs. Pure Relational Locking: Teams frequently ask whether Redis is strictly necessary if PostgreSQL supports SELECT FOR UPDATE or advisory locks. While a PostgreSQL-only architecture reduces operational surface area, acquiring relational table row locks on high-velocity ingestion endpoints creates serious connection pool contention in PgBouncer and causes write amplification during heavy traffic spikes. Redis handles hundreds of thousands of atomic lock acquisitions per second in sub-millisecond memory cycles, protecting the relational database connection pool for genuine domain transactions.
Production Engineering Decision Matrix & Implementation Checklist
Before launching an idempotency layer in production, use this comparative architecture matrix and pre-flight checklist to verify your system readiness.
Architecture Decision Matrix:
- UI Button Disabling: 0 ms latency overhead, no concurrency protection (fails on retry), zero storage cost. Recommended for internal prototypes only.
- DB Unique Constraints Only: Low overhead (< 2 ms), partial protection (bubbles up as 500 error), low storage cost. Recommended for low-traffic basic CRUD.
- Pure Postgres Advisory Locks: Moderate overhead (5-15 ms), high concurrency protection, moderate storage cost. Recommended for monolithic services without Redis.
- Redis Locks + Postgres Ledger: Minimal overhead (1-3 ms), full protection against concurrent duplicates, low auto-expiring storage cost. Recommended for financial, webhook, and high-scale SaaS APIs.
Production Pre-Flight Checklist:
- IETF Standard Compliance: Does your API parse the standard
Idempotency-Keyheader and returnIdempotent-Replayed: trueon cached responses? - Payload Digest Verification: Does the server compute a SHA-256 fingerprint of the request body to prevent key hijacking with altered parameters?
- Explicit Concurrency Handling: Does the server return
409 Conflictwith aRetry-Afterheader when a concurrent duplicate request arrives in-flight? - Bounded Lease TTL: Are Redis distributed locks configured with explicit lease timeouts (15–30s) to prevent permanent deadlocks on server crashes?
- Automated Data Pruning: Is a background retention policy configured to purge idempotency records older than 72 hours?
By implementing this Redis-and-PostgreSQL architecture, you safeguard customer trust, eliminate financial reconciliation overhead, and ensure that your web platform handles unpredictable network failures with mathematical certainty.
Written by Lay Shah, an independent developer building websites and tools for small businesses. Discuss a brief More articles