Networks drop, users double-tap the pay button, and a server can crash right after the PG approves a card but before it saves anything to the DB.
The first tool most of us reach for here is idempotency: sending the same request once or ten times leaves the system in the same final state as running it once.

But once I dug in, it turned out to be much more than adding an Idempotency-Key header and a Redis lock.
Many duplicate-payment incidents that happen even with idempotency keys come from scoping the key to an HTTP request instead of the user’s purchase intent, not propagating the key to the next call (2-hop), or forgetting that keys expire.

So I sorted the defenses into four layers.

Layer 1: Code and DB, where key design is half the battle

In HTTP, GET, PUT and DELETE are idempotent by definition, but POST, which handles the important state changes like payments, is not.
That’s why the client sending a unique key in a header has become the de facto standard, and the IETF is working on making the Idempotency-Key header an official standard (still a draft, not a final RFC).

The most common mistake is the double tap / multi-tab problem.
If the frontend generates a new UUID on every click, paying for the same order in two tabs sends two different keys and sails straight past the server check. The key should be tied to a business intent, like an order_id the server creates before the payment page, not to a click.

Then there’s the case of the same key arriving with a different amount.
So you store a hash of the request body (a fingerprint) alongside the key, and reject the retry if the key matches but the fingerprint doesn’t.

Modeling results with only SUCCEEDED and FAILED is risky too.
If a gateway times out but the money actually left the account, marking it FAILED invites the user to pay again. Timeouts and 5xx should be UNKNOWN, and the UI should say “Checking your payment status” instead of “Payment failed”.

Trying to block concurrent requests with SELECT then INSERT lets two threads both read “nothing there” and both run. The last line of defense is a DB unique constraint.

-- Scope keys by tenant and endpoint
CREATE TABLE idempotency_keys (
    tenant_id        VARCHAR(64)  NOT NULL,
    endpoint         VARCHAR(128) NOT NULL,
    idempotency_key  VARCHAR(128) NOT NULL,
    request_hash     CHAR(64)     NOT NULL, -- payload fingerprint (SHA-256)
    status           VARCHAR(16)  NOT NULL, -- IN_PROGRESS, COMPLETED, FAILED
    locked_until     TIMESTAMP    NULL,     -- lease expiry in case the process dies
    response_code    INT          NULL,
    response_body    JSONB        NULL,
    created_at       TIMESTAMP    NOT NULL DEFAULT NOW(),
    PRIMARY KEY (tenant_id, endpoint, idempotency_key)
);

-- Even with a different key, only one active payment per order
CREATE UNIQUE INDEX uq_active_payment_per_order
    ON payments (order_id)
    WHERE status IN ('PENDING', 'CAPTURED');

Layer 2: Redis for fast rejection, the RDB for the final record

DB constraints protect the data, but if concurrent requests flood the connection pool, the server gives out first.
Kakao Pay’s tech blog describes fixing duplicate point payouts (the “double tap” issue) by putting a Redis SETNX lock (3-second TTL) in front of the controller for a Fast Fail.

Relying on Redis alone to store idempotency records is risky though.
Keys can be evicted under memory pressure, or lost during a failure. A safer hybrid is to use Redis only as a short-lived lock that turns away concurrent entries, and keep the final status and response in an RDB transaction.

Once you have dozens of APIs, copy-pasting idempotency code into every service is a maintenance headache too.
Toss Payments recommends extracting a component (a Filter or AOP) that only validates keys, stores them and replays responses. For its own APIs it identifies a duplicate by combining Idempotency-Key with the API key, URL and HTTP method. Client SDKs should build in exponential backoff and jitter so retries don’t knock a struggling server over.

Layer 3: Kafka and webhooks need their own idempotency

“We put a key on the API, so the events must be safe too” is the most common illusion.
Message brokers and webhooks are at-least-once by nature, so both producers and consumers need separate designs.

Kafka’s enable.idempotence=true filters retry duplicates using the PID, Epoch and Sequence Number. But it only covers resend retries within a single session. It can’t stop an app from publishing the same event twice, or a consumer from re-reading the same offset after a rebalance.

On the consumer side, the most reliable approach is the Inbox pattern.
You insert the received event_id into an inbox table as a primary key, in the same local transaction as the business DB change. If the event_id already exists, the unique conflict skips it, and if the business logic fails, the inbox record rolls back with it.

Toss Payments’ migration from a legacy Oracle ledger to MySQL was also an interesting case.
When writing to the Outbox fails, they don’t roll back the whole payment. They leave a fallback log and republish later. That can flood downstream with duplicate events, so every event carries an idempotency key in its header and consumers filter on it.

Layer 4: Calling an external system ends your local transaction’s protection

Even with a perfectly idempotent internal DB and Kafka, the moment you call a bank, card company or exchange, the local transaction’s protection is gone. These are the patterns that blow up often.

Failure scenarioCauseFix
2-hop timeoutApp to payment server used a key, but payment server to PG didn’tPropagate a derived key at every hop; for providers without keys, query the transaction before retrying
Crash right after approvalServer dies after external approval but before the DB save, leaving a stuck lockUse a lease instead of a permanent lock; split work into atomic phases and resume from the last checkpoint
Timeout mismatch across layersUpper layer gives up before the lower one, so approval happens but the merchant sees a failureUnify the whole chain’s timeout around the longest lower-layer time
500 replayed foreverA transient 500 gets cached, so retries keep returning 500 after recoveryDon’t store transient errors (release the lease); cache only final rejections
State mismatch with the providerApproval response is lost, so the provider says approved and we say notAutomated network cancellation plus daily reconciliation

In the end, you have to accept that “state will drift at some point” and lay network cancellation and daily reconciliation underneath as a safety net.


How different companies approach it

The domestic financial and LINE Pay parts are inferences from public API specs and press releases, since their internals aren’t public. Keep that in mind as you read.

Traditional Korean finance is rooted in telegram-style messaging rather than REST idempotency keys.
They assign a transaction number that’s unique per day (the Open Banking bank_tran_id is the classic example), and stock amendments or cancellations reference the original order number to prevent duplicate execution. When a timeout happens, they query first, then do a network cancellation, then close it out with reconciliation after market close. People sometimes mistake the Korea Investment & Securities API’s hashkey for an idempotency key, but it’s actually an optional security feature to prevent request tampering.

LINE Pay blocks duplicates with a state machine and error codes instead of response replay.
HTTP is always 200, and the result comes in returnCode. Codes like payment in progress (1145), duplicate API call (1198) and existing orderId (1172) reveal its internal concurrency defenses. Recommending a Read Timeout of 40 seconds or more for the confirm API also looks like a way to prevent hasty retries, since it has to round-trip to external card companies and local payment providers. For reference, LINE Pay in Japan ended in April 2025, and it now centers on Taiwan and Thailand.

Comparison of Korean finance inference model and LINE Pay inference model

Global companies felt like they’d polished idempotency into a product.

Idempotency key retention periods and policy comparison across payment APIs

  • Stripe: Splits a request into atomic phases around each external call, and updates a recovery_point in the same transaction at each commit. If it dies midway, it resumes from the last point instead of starting over. API v1 keeps keys for 24 hours, v2 for 30 days.
  • PayPal: In v2 the default idempotency retention dropped to 6 hours. Retrying with an expired key is treated as a brand new transaction with no error, which can cause double charges. The lesson is that a client’s retry window must not outlive the server’s key lifetime.
  • Airbnb (Orpheus): Built idempotency as an in-process library instead of a separate service, so it shares the service’s transaction boundary. Because of replication lag, it reads and writes directly on the Primary DB instead of a read replica.
  • Robinhood: Consume from Kafka, commit the DB change and the dedup table in one transaction, publish downstream, then commit the offset last. That removed the Outbox scan bottleneck, and if it crashes midway the DB step is a no-op on re-consume. By their own measurement, latency dropped from about 20ms to under 0.1ms and throughput rose more than 10x.

Stripe Atomic Phases & Recovery Points and Robinhood Kafka + Postgres deduplication loop

Checklist

Here are five questions you can check against your own service right away.

  1. Is the key scoped to a business intent (order_id), not a click?
  2. Is Redis only for fast rejection, with the final state stored in the RDB?
  3. Are external call timeouts treated as UNKNOWN, not FAILED?
  4. Do your Kafka consumers and webhook receivers have something like an Inbox for idempotency?
  5. Is the key TTL longer than the client’s maximum retry window, and is there daily reconciliation to catch what slips through?

Idempotency feels less like defensive code against duplicate requests and more like a contract that lets you retry safely after a failure.
Starting from one unique constraint and adding layers as the service grows, through libraries, event handling, network cancellation and reconciliation, seems like the realistic path.

References