SaaS10 min read

How to Implement Idempotency in a SaaS API: Prevent Duplicate Charges and Safe Retries

Learn how to implement idempotency keys in a SaaS API to prevent duplicate charges, guarantee safe retries, and handle concurrent requests correctly in production.

Idempotency is one of those SaaS API fundamentals that most teams bolt on after their first duplicate-charge incident. An idempotent operation produces the same result no matter how many times it is called with the same input. For a SaaS product processing payments, subscription upgrades, or any state-changing request, idempotency is not an optimization — it is a correctness guarantee that prevents double charges, duplicate account creation, and corrupted billing state when networks retry requests or users double-click a submit button.

The problem is systematic. HTTP is unreliable: a client sends a request, the server processes it, the connection drops before the response arrives, and the client retries. Without idempotency, the server processes the same request twice. In a billing context, that is two charges. In a subscription context, that is two active accounts. Stripe solved this with idempotency keys — a pattern that every multi-tenant SaaS platform should implement on any non-GET endpoint that mutates billing or subscription state. This guide explains exactly how to build it end to end.

What Is Idempotency and Why Every SaaS API Needs It

An HTTP method is idempotent when calling it multiple times with the same parameters produces the same server state as calling it once. GET, PUT, and DELETE are idempotent by definition in the HTTP specification. POST is not — that is why POST requests are the primary surface where application-level idempotency controls are needed. In a SaaS context, the operations that cause the most pain when duplicated are the most critical ones: creating a charge, provisioning a tenant, upgrading a subscription plan, or sending an invoice.

  • →Network timeouts cause duplicate state mutations. A client POSTs a charge request. The server creates the charge, charges the card, and writes the transaction to the database — then the connection times out before the 200 response arrives. The client retries. The server charges the card again. The customer sees two charges; your support queue gets an angry email within the hour.
  • →Mobile clients and unreliable connections retry aggressively. Mobile apps using exponential backoff will retry POST requests that never received a response. Each retry is a potential duplicate. Applications targeting mobile need idempotency on any state-changing endpoint that matters.
  • →Frontend double-submit protection is not enough. Disabling a submit button on click prevents most accidental duplicates but does not handle concurrent tab submissions, race conditions in React state updates, or attackers who bypass the UI entirely with a direct API call.
  • →Webhooks from payment providers retry on delivery failure. Stripe, Paddle, and every other billing provider will redeliver a webhook event if your endpoint returns a 5xx or times out. Your webhook handler must be idempotent — processing the same event twice must produce the same outcome, not duplicate it.
  • →Background job queues retry failed jobs. Any queue that processes billing operations — Inngest, BullMQ, Trigger.dev — will retry a job that throws or times out. Unless the job handler is idempotent, retries produce duplicate state mutations in your database.

How Idempotency Keys Work: The Pattern Behind Stripe

Stripe introduced the Idempotency-Key HTTP request header as a standard way for clients to tell the server: 'I have already sent this request; if you have seen this key before, return the same response you returned the first time.' The key is a UUID generated by the client before the request is sent. The server stores the key alongside the response. On retry, the server finds the key and returns the cached response without executing the operation again. The operation is processed exactly once regardless of how many times the HTTP request is delivered.

  • →Generate idempotency keys on the client, not the server. The key must be created before the request is sent so that retries use the same key. Use crypto.randomUUID() in the browser or Node.js to generate a UUID for each logical operation. Never reuse a key across different operations or different users.
  • →Tie the key to the logical operation, not the HTTP connection. When a user clicks 'Upgrade Plan', generate one UUID for that upgrade intent and use it on every retry of the POST /subscriptions/upgrade request. If the user navigates away and returns to try again, generate a new key — a new user intent deserves a new idempotency scope.
  • →Send the key in a request header. The standard pattern uses Idempotency-Key as a custom request header. This keeps it out of the request body and makes it easy to extract in middleware before your route handler runs, without changing your route handler's interface.
  • →Return the same HTTP status code and response body on replay. When a server receives a known idempotency key, it must return exactly the response it returned on the first successful execution — including the same status code. If the first execution returned 409 Conflict, the replay returns 409 Conflict. The client cannot and should not distinguish a first execution from a replay.
  • →Expire keys after a TTL that exceeds your retry window. If your client retries for up to 24 hours, expire keys after 72 hours. A request arriving with a key after the TTL is treated as a new operation. Stripe stores keys for 24 hours; build your system to match or exceed the retry horizon of your client.

Designing the Idempotency Key Table in PostgreSQL

The idempotency key table is the persistent store that makes replay possible. It needs to record the key, the endpoint it was used on, the execution status, and the full response to replay. The design decisions here — particularly around uniqueness constraints and transaction boundaries — determine whether your implementation handles concurrent retries correctly and survives process crashes without producing duplicates.

  • →Use a composite unique constraint on (tenant_id, idempotency_key, endpoint_path). An idempotency key should be scoped to a tenant and an endpoint — the same UUID should not collide across different tenants or different operations. The unique constraint on these three columns enforces this at the database level and gives you a conflict target for INSERT ... ON CONFLICT.
  • →Add a status column with values 'pending', 'succeeded', and 'failed'. When a request arrives with a new key, insert a row with status = 'pending' before executing the operation. On success, update to 'succeeded' and store the response JSON. On failure, update to 'failed'. A 'pending' row on retry means another process is mid-execution — wait and poll, or return 409 Conflict immediately.
  • →Store the full response as a jsonb column alongside an integer status_code column. The replay must return the exact original response: same HTTP status code, same body. On replay, deserialize the stored row and return it verbatim — no re-execution, no recomputation.
  • →Index idempotency_key and filter by recent rows. The lookup on every request is on the hot path. A B-tree index on (tenant_id, idempotency_key, endpoint_path) performs the lookup efficiently. Add a partial index covering only rows within the TTL window (WHERE created_at > NOW() - INTERVAL '72 hours') to keep the index small as the table grows.
  • →Insert the idempotency record and the state mutation in the same database transaction. This is the most important design constraint. If you mutate state (charge the card, create the subscription) and then insert the idempotency record in separate steps, a crash between them leaves a completed operation with no idempotency record. The next retry re-executes the operation and produces a duplicate. Atomicity between mutation and key recording is non-negotiable.

Implementing an Idempotency Middleware in Next.js App Router

The cleanest implementation wraps your Next.js route handlers in an idempotency middleware that handles key extraction, lookup, locking, and replay before your business logic runs. Your route handlers remain unaware of idempotency — they execute their logic once and return a result; the middleware decides whether to execute or replay. For a production SaaS platform, this middleware belongs on every POST, PUT, and PATCH handler that mutates billing or subscription state.

  • →Step 1 — Extract and validate. Read the Idempotency-Key header. Validate it is a valid UUID v4 format. If the header is missing on an endpoint that requires it, return 400 Bad Request with a clear error message. Never silently skip idempotency on a required endpoint.
  • →Step 2 — Look up the existing record. Query the idempotency_keys table for (tenant_id, key, endpoint). If a 'succeeded' row exists, return the stored status code and response body immediately without touching your route handler. If a 'failed' row exists, return the stored error response — do not retry business logic on a client replay of a known failure.
  • →Step 3 — Insert a pending record and handle the race condition. For a new key, insert with status = 'pending'. Use INSERT ... ON CONFLICT DO NOTHING. If the insert returns 0 rows, another concurrent request beat you to it — poll the row for a few seconds until it transitions to 'succeeded' or 'failed', then return its stored response.
  • →Step 4 — Execute and persist atomically. Call your route handler. Within a database transaction, update the idempotency record to 'succeeded' or 'failed' and write the response JSON alongside the actual state mutation. Both the state change and the key update commit together — a crash between them rolls everything back, and the next delivery retries cleanly.

Handling Concurrent Requests for the Same Idempotency Key

The hardest edge case in idempotency implementation is two requests arriving with the same key at nearly the same time — a client that fires two rapid retries before the first has completed. Without explicit handling, both requests pass the initial lookup check (no existing record), both attempt to insert the pending row, and both proceed to execute the operation. This race condition produces exactly the duplicate you built idempotency to prevent.

  • →Use INSERT ... ON CONFLICT to detect concurrent first-execution attempts. INSERT INTO idempotency_keys (...) ON CONFLICT (...) DO NOTHING returns a rows-affected count. If the count is 0, another request inserted the key concurrently. The correct response is to poll the row every 100–200ms for up to a few seconds until it transitions from 'pending' to a terminal state, then return its response.
  • →Use PostgreSQL advisory locks as a lightweight distributed mutex. Before inserting the pending record, acquire a session-level advisory lock keyed on the hash of the idempotency key: SELECT pg_try_advisory_lock(hashtext(key)). If the lock is unavailable, another process holds it. Sleep briefly and retry acquiring it. Release the lock after committing the final response. Advisory locks are connection-scoped and release automatically on disconnect.
  • →Return 409 Conflict when low latency matters more than waiting. Stripe returns 409 with a Retry-After header when a request arrives for an in-flight key. The client backs off and retries. This avoids the polling wait and is simpler to implement — the trade-off is that clients must handle 409 responses explicitly and retry rather than receiving the response in-line.
  • →Never hold a database row lock across external network calls. If your operation involves calling Stripe's API, sending an email, or any other I/O, do not hold a SELECT ... FOR UPDATE lock on the idempotency row for the full duration. External calls can take seconds. Use advisory locks or the INSERT-on-conflict pattern — both are non-blocking for other rows in the table.

Idempotency for Webhook Delivery and Payment Event Processing

Outbound webhook delivery and inbound payment event processing are both retry-heavy — Stripe retries failed events for 72 hours, and your own webhook system should deliver with the same reliability. Both require application-level idempotency to prevent duplicate state mutations on the receiving end. The reliable webhook delivery guide covers the outbound delivery queue architecture in detail; this section covers the idempotency layer specifically.

  • →Use Stripe's event ID as the idempotency key for inbound webhooks. Every Stripe webhook payload includes an id field (evt_...). Store this ID in a processed_webhook_events table before processing the event. If you receive the same event ID twice, return 200 immediately without processing — Stripe stops retrying when it sees 200. Use INSERT ... ON CONFLICT DO NOTHING to handle concurrent deliveries of the same event.
  • →Process the event and record its ID in the same transaction. Within a database transaction, insert the event ID into processed_webhook_events and apply the state change — update the subscription, record the payment, provision the feature. Both commit together. If the transaction rolls back for any reason, the event is not marked processed and the next delivery retries cleanly.
  • →Distinguish business-logic failures from infrastructure failures. A webhook event that fails because of a temporary database connection error should be retried — it is an infrastructure failure. A webhook event that fails because the customer account no longer exists should be marked permanently_failed and not retried. Infinite retries on a bad event stall your processing queue and trigger duplicate side-effects on each attempt.
  • →Carry idempotency keys through your outbound delivery system. When you emit events to your customers, attach a stable event ID to each delivery record. Consumers can implement the same event-ID idempotency pattern. This is the foundation of a reliable event-driven integration — both sides deduplicate by event ID and neither side processes the same event twice.

Common Idempotency Mistakes in SaaS APIs

Most idempotency bugs appear not in the happy path but in the gap between the key lookup and the operation execution, in the transaction boundary design, or in the TTL choice. The pattern looks simple in a diagram but has specific failure modes that only surface under load, concurrent retries, or database errors.

  • →Recording the idempotency key after the operation instead of before. If your code executes the state mutation and then writes the idempotency record as a separate step, a crash between the two leaves a completed operation with no key record. The next retry re-executes the operation. Always insert the pending record before execution, in the same transaction as the mutation.
  • →Setting a TTL shorter than your retry window. If your client retries for 24 hours but keys expire after one hour, a retry at hour two is treated as a new operation and processed again. Set the key TTL to exceed your maximum retry window by a meaningful margin.
  • →Not scoping keys by endpoint path. A UUID validated only on uniqueness without an endpoint dimension allows a key generated for a subscription upgrade to replay as a charge creation if the client accidentally reuses it across endpoints. Always include the endpoint path in the uniqueness constraint.
  • →Skipping idempotency on internal service-to-service calls. Services that call each other with HTTP POST requests inside your platform face the same retry problem as external clients. Propagate the original client idempotency key downstream, or generate a deterministic derived key (a hash of the parent operation ID and the downstream endpoint). The multi-tenant SaaS architecture patterns guide covers how to design internal service boundaries to make this tractable from the start.
  • →Storing idempotency keys only in Redis without persistence. Redis is fast and convenient but loses data on eviction or restart unless you configure AOF persistence and replication. For billing operations, the idempotency store must survive server restarts. Use PostgreSQL as the source of truth; optionally front it with a Redis cache for read latency on hot keys.

Frequently Asked Questions

What is an idempotency key in an API?

An idempotency key is a unique identifier — usually a UUID generated by the client — sent with a mutating HTTP request (POST, PUT, PATCH) so the server can deduplicate retries. The server stores the key alongside the response from the first execution. If it receives the same key again, it returns the stored response without re-executing the operation. This guarantees the operation is applied exactly once regardless of how many times the HTTP request is sent.

How does Stripe implement idempotency keys?

Stripe requires or strongly recommends an Idempotency-Key header on all POST requests. When Stripe receives a request with a key it has already processed successfully, it returns the original response — the same charge object, the same subscription — without creating a new one. If a request with a known key is still in progress, Stripe returns 409 Conflict. Keys are stored for 24 hours; after expiry, the same key is treated as a new request.

How do I make a database INSERT idempotent?

Use INSERT ... ON CONFLICT DO NOTHING with a unique constraint on the natural key of the record — the combination of fields that makes a row unique for a given logical operation. For example, an orders table might use UNIQUE (user_id, cart_id, created_date). A duplicate insert attempt finds the conflict and does nothing, rather than creating a second row. For records without a natural key, use the idempotency key itself as a column with a unique constraint.

Should I use Redis or PostgreSQL to store idempotency keys?

Use PostgreSQL as the authoritative store for billing-critical idempotency keys. PostgreSQL transactions let you atomically record the key alongside the state mutation in a single commit, eliminating the gap where a crash could allow a duplicate. Redis can be used as a fast read cache for hot keys — check Redis first, fall back to PostgreSQL on a miss — but Redis must not be the only store for operations where losing the idempotency record would allow a duplicate charge.

What is the difference between an idempotent and a safe HTTP method?

Safe methods (GET, HEAD, OPTIONS) do not modify server state. Idempotent methods produce the same server state regardless of how many times they are called. All safe methods are idempotent, but not all idempotent methods are safe — DELETE is idempotent (deleting a resource twice leaves it deleted) but it does modify state. POST is neither safe nor idempotent by default, which is why POST endpoints that change state require application-level idempotency controls to be safe to retry.

How Belsoft Helps You Build Production-Grade SaaS APIs

Idempotency is one of those features that every SaaS platform needs but rarely ships correctly on the first attempt. The gap between a working prototype and a production-ready implementation is usually the concurrent-request edge case, the transaction boundary between mutation and key recording, and the TTL design that covers your actual retry window. Belsoft builds SaaS platforms and multi-tenant products from the ground up — billing infrastructure, Stripe integration, subscription management — and idempotency on every billing-critical endpoint is part of every engagement, not an afterthought.

We start every partnership with a workflow and technology audit that maps your current API surface, identifies state-mutation endpoints that lack idempotency controls, and returns a prioritized roadmap. If you are inheriting a codebase that processes Stripe events or subscription changes without idempotency, book a technical review call and we will walk through what is at risk and what a production-ready implementation looks like for your stack.

“A retry that processes twice is not a bug in your client — it is a missing correctness guarantee in your API.”

Written by

Belal Hisham

Founder & Lead Engineer, Belsoft Solutions

Ready to partner?

Let's talk about your company.

30 minutes. No pitch. We talk through how you run today and where AI and automation would help.

Book a free audit
logo

Your AI & automation transformation partner: we audit, build, and train your team, then stay embedded as you grow.

Member ofNVIDIA Inception Program

Copyright Ⓒ 2026 BelSoft. All Rights Reserved.

BELSOFT, LDA · NIPC 517893258 · Lisbon, Portugal