The version check worked. It rejected the second request with a 409, exactly as designed. The customer was still refunded twice. This is the shape of optimistic locking race condition we keep finding in code audits: the lock protects a row, and the money moved somewhere the row can't see.

The system is a composite of a pattern we have seen in admin consoles, so there are no client details here. The mechanics are the part worth keeping.

The setup that looked safe

An orders table with an integer version column. An admin console where support staff click "Refund". A REST endpoint that does roughly this:

  1. Read the order, including its version.
  2. Validate that the refund amount does not exceed the remaining refundable balance.
  3. Call the payment provider's refund API.
  4. Write the result with UPDATE orders SET refunded = refunded + :amt, version = version + 1 WHERE id = :id AND version = :v.

There were two idempotency mechanisms, and that is where the trouble started. The console's HTTP client retried on timeout and generated a fresh UUID per attempt as an Idempotency-Key header. The server forwarded a key to the payment provider too, but derived it as refund:{order_id}:{version}. Each layer was idempotent by its own definition. They did not agree on what "the same request" meant.

The exact interleaving

The provider call was slow that day, around nine seconds. The console's timeout was eight.

  • t=0: Request A arrives. It reads the order at version 7, validates, and calls the provider with key refund:42:7.
  • t=8s: The console times out and retries. The retry is request B with a new client UUID. B reads the order. A has not committed, so it is still version 7. Validation passes, because refunded is still zero.
  • t=9s: A's provider call returns. A runs its UPDATE with WHERE version = 7. It succeeds and the version becomes 8.
  • t=9.5s: B's provider call also goes out. If B's key had matched A's, the provider would have deduplicated it. But a mid-flight refactor had moved the key derivation onto a request-scoped value, so B sent a different key. The provider processes a second refund.
  • t=10s: B's UPDATE runs with WHERE version = 7, matches zero rows, and returns 409.

The operator saw an error on the retry and an eventual success from the first request, so the screen looked fine. The ledger was off by one refund, and nothing in our database recorded the second one, because the write that would have recorded it was the one the version check rejected.

Why the version column was the wrong tool

Optimistic locking answers one question: did this row change between my read and my write? It says nothing about side effects that happen between those two points. The provider call sat inside the read-modify-write window, so it escaped the guard. The check fired correctly and too late.

The two key schemes also disagreed. A key derived from state (version) changes when state changes. A key generated per attempt changes on every retry. Neither identifies the operator's intent, which is "refund this order for this amount, once."

The fix: one key per intent, claimed before the side effect

We changed three things.

1. The key is minted once per user action. The console generates the idempotency key when the operator opens the refund dialog and reuses it for every retry of that action. A new dialog gets a new key. The key now names the intent.

2. A refunds table with a uniqueness constraint.

CREATE TABLE refunds (
  id             uuid PRIMARY KEY,
  order_id       bigint NOT NULL REFERENCES orders(id),
  client_key     uuid   NOT NULL,
  amount         bigint NOT NULL CHECK (amount > 0),
  status         text   NOT NULL DEFAULT 'pending',
  provider_ref   text,
  created_at     timestamptz NOT NULL DEFAULT now(),
  UNIQUE (order_id, client_key)
);

3. Claim first, then call the provider. The handler inserts a pending row inside a transaction that also checks the remaining balance. INSERT ... ON CONFLICT (order_id, client_key) DO NOTHING decides who owns the action. If the insert returns a row, this request owns the refund and proceeds. If not, it loads the existing row and returns its current status instead of calling the provider. The provider key is the refund row's id, which is stable across retries by construction.

Replaying the old interleaving now goes like this. A inserts the pending row. B, arriving at t=8s with the same client key, hits the conflict and gets back "pending". It never touches the provider. When A finishes, it marks the row succeeded and the console polls to the final state. The version column stays, but it now guards balance arithmetic, which is its proper job.

The failure modes we still had to handle

  • Crash between claim and provider call. The row sits in pending forever. A reconciliation job re-drives stale pending rows using the same provider key, so the provider deduplicates if the first call did go through.
  • Same key, different amount. That is a client bug or a tampered request. We reject it with a 422 rather than silently returning the old result.
  • Balance check under concurrency. Two different intents, two different keys, same order. The balance check runs in the claim transaction under a row lock (SELECT ... FOR UPDATE on the order), so the second claim sees the first.

What to check in your own code

Grep for any external call, whether payments, email, or a webhook, that sits between a read and a version-checked write. Then ask two questions. Who generates the idempotency key, and at what scope? Is the intent recorded durably before the side effect, or only after? If the answers are "per attempt" and "after", the lock is guarding the wrong thing.

orithLabs does this kind of backend review and code audit for teams who already have a working admin dashboard and a nagging feeling about its money paths. If you'd like a second pair of engineering eyes on a design like this, you'd be talking directly to the people who write the code.