Backend Architecture··2 min read

Designing Idempotent Payment and Billing APIs: Preventing Double Charges Under Network Retries

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Designing Idempotent Payment and Billing APIs: Preventing Double Charges Under Network Retries

Why Mobile Retries and Webhook Re-Deliveries Cause Double Charges

In distributed systems, there is no such thing as exactly-once network delivery. When a client sends POST /api/v1/payments and the TCP connection drops after your server charged the credit card but before the client received the 200 OK response, the client will retry.

To guarantee exactly-once business execution over an at-least-once network, every state-mutating endpoint must require an Idempotency-Key header.


1. The Idempotency Key State Machine in PostgreSQL

Simply checking SELECT * FROM idempotency_keys WHERE key = $1 before running the payment is broken - two concurrent retries arriving 2 milliseconds apart will both see no record and both charge the card.

Instead, we atomically claim the key first using INSERT ... ON CONFLICT DO NOTHING:

CREATE TABLE idempotency_records (
    idempotency_key VARCHAR(128) NOT NULL,
    tenant_id UUID NOT NULL,
    request_hash CHAR(64) NOT NULL,
    status VARCHAR(24) NOT NULL, -- 'IN_PROGRESS', 'COMPLETED'
    response_code INT,
    response_body JSONB,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (tenant_id, idempotency_key)
);

2. Handling Concurrent In-Flight Retries and Parameter Mismatches

When a request arrives with Idempotency-Key: ord_99281:

  1. First Arrival: INSERT succeeds with status = 'IN_PROGRESS'. The handler executes the payment, updates the row to status = 'COMPLETED' with the serialized response_body, and returns 201 Created.
  2. Duplicate Arrival While Still In-Flight (status = 'IN_PROGRESS'): Returns HTTP 409 Conflict (Retry-After: 2) so the client waits for the original request to finish rather than opening a second charge.
  3. Duplicate Arrival After Completion (status = 'COMPLETED'): Verifies that request_hash matches the original request body (returning 422 Unprocessable Entity if the client reused the same key for a different amount), and immediately replays the stored response_body without touching the payment gateway.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles