Let’s talk

The charge inside the transaction

To make payment atomic, you wrap it in one database transaction: save the payment, charge the card, mark the order paid. The bank is slow and the transaction dies while waiting. What's left?

In 30 seconds

The problem
Customers are charged and your database has no record of it. Then they pay again.
Why it happens
The bank call sits inside the transaction. When the transaction dies mid-wait, the rollback erases the payment row and the order, but the bank's charge isn't a database write, so it stays.
The fix
Airbnb's three phases: commit a pending row, call the bank with no transaction open, then record the result in a short transaction.
In an interview
Never call the network inside a database transaction. A rollback can't take back a charge. Commit a pending record, call the bank with nothing open, then record the result in a short transaction.

Why it matters

Wrapping it all in a transaction is a good instinct, and it works whenever the bank answers fast. Our proof runs 50 payments against a fast bank and every one commits.

In our run, every 5th charge took 400ms during a sale, and Postgres's idle_in_transaction_session_timeout killed transactions idle longer than 150ms. Those 10 transactions rolled back after the bank had charged: 10 charges with no record. The customers saw "Payment failed", tried again, and paid twice: ₹20,000 extra. With the three phases, the same slow charges left every payment recorded once.

Words you need

Transaction
A group of changes the database treats as one: all of them are saved, or none of them.
Timeout
Giving up on waiting for a reply. It tells you the reply did not arrive in time, not whether the work was done.
Idempotency key
A unique id the client creates once per payment and sends with every retry of it. The server uses it to recognise a retry and return the first result instead of charging again.
Atomic
Done as one step that nothing can interrupt. Another request sees it either not started or fully finished.

Picture it

Priya pays ₹2,000 during a sale. The bank takes 400ms to answer.

One transaction around the bank call

  1. BEGIN, insert payment
  2. Call the bank, transaction idle
  3. Postgres kills the idle transaction
  4. ROLLBACK: payment row gone, order unpaid
  5. Bank already charged ₹2,000

Money taken, no record. Priya taps "try again" and pays twice.

Claim, charge, record

  1. Insert pending row, committed
  2. Call the bank, nothing open
  3. Short transaction: payment succeeded, order paid

Charged once, recorded once. A slow bank is just slow.

The fixes people try

  • One big transaction

    Fails
    BEGIN; insert; charge(); update; COMMIT

    A rollback undoes database writes only. The charge survives it with no record.

  • Raise the timeout

    Fails
    idle_in_transaction_session_timeout = 0

    A failover or dropped connection still kills it. And long open transactions hold locks and connections under load.

  • Refund in the catch block

    Half a fix
    catch { bank.refund() }

    Only if the process survives to run it. The one that died usually doesn't.

  • Claim, charge, record

    Works
    commit pending → charge → short transaction

    There's always a record that a charge was attempted, and nothing waits on the network with a transaction open.

  • Transactional outbox

    Works
    insert 'charge requested' + worker

    Good when the charge can happen in the background. The worker retries with the same key.

The fix and its cost

A transaction promises all-or-nothing for the database. The bank isn't in the database, so wrapping the call doesn't make it part of the promise. It just keeps a connection and its locks idle while you wait.

Split it the way Airbnb's Orpheus does: no network calls in the pre-RPC and post-RPC phases, no database work in the RPC phase. Commit a pending row first, call the bank with nothing open, then mark the payment succeeded and the order paid in one short transaction.

If something dies between the charge and the final write, the pending row is still there saying a charge was attempted, which is exactly what you need to reconcile it.

What it costs

Payments can sit in pending, so you need a way to resolve them: ask the processor for the charge's status and finish the record. That's the next trap.

Interviewers also listen for: what atomic covers

Atomic means all-or-nothing inside one system. Across your database and a bank, there is no shared transaction, so you design for the gap: record intent first, then reconcile.

Check yourself

  1. 1Why doesn't the rollback undo the charge?Show answer

    A rollback undoes database writes. The charge happened at the bank over the network, which the transaction knows nothing about.

  2. 2Why is the pending row committed before calling the bank?Show answer

    So that whatever happens during the call, there's a record that a charge was attempted, and a retry with the same key can find it.

  3. 3Why does the customer end up paying twice?Show answer

    They see "Payment failed" and start a new payment. A new attempt has a new key, so nothing stops the second charge.

The code

GitHub

pay.bug.ts

import type { Pool } from "pg";

// "Make it atomic": one transaction around the whole payment.
export async function pay(db: Pool, bank: Bank, req: PayRequest) {
  const client = await db.connect();
  try {
    await client.query("BEGIN");
    await client.query(
      `INSERT INTO payments (idempotency_key, order_id, amount, status)
       VALUES ($1, $2, $3, 'pending')`,
      [req.idempotencyKey, req.orderId, req.amount],
    );
    // The transaction stays open while we wait on the bank.
    // If it dies here (timeout, failover, dropped connection), the ROLLBACK
    // erases both writes. The bank's charge is not a database write: it stays.
    const charge = await bank.charge(req.orderId, req.amount, { idempotencyKey: req.idempotencyKey });
    await client.query("UPDATE payments SET status = 'succeeded', charge_id = $2 WHERE idempotency_key = $1", [req.idempotencyKey, charge.id]);
    await client.query("UPDATE orders SET status = 'paid' WHERE id = $1", [req.orderId]);
    await client.query("COMMIT");
    return { status: "PAID", chargeId: charge.id };
  } catch (err) {
    await client.query("ROLLBACK");
    throw err; // the app shows "Payment failed, try again"
  } finally {
    client.release();
  }
}

Example code. The tested version, with a proof test against real Postgres, lands in the repo.

Star the repo for the runnable version

Each trap in this world ships with the bug, the fix and a proof test that fires concurrent requests at a real database.

Remember

A rollback can't take back a charge. Commit a pending record, call the bank with nothing open, record the result after.