Databases Bug Report

A payment API call inside a database transaction held row locks for 30 seconds

When the payment provider slowed down, our checkout stopped for everyone, not just for card payments. Each checkout held row locks on stock and the order while it waited for an HTTP response inside the transaction. How we found it in pg_stat_activity and moved the I/O out.

Mateusz Kowalczyk Mateusz Kowalczyk @mateuszkowalczyk · November 19, 2026 · 8 min read · 82 Views
Banner: an external HTTP call holding database row locks inside a transaction

Our payment provider had a partial outage one afternoon: their API answered, but slowly, many requests taking 20 to 30 seconds. We expected card checkouts to be slow during that time. We did not expect every checkout to stall, including orders paid with gift cards or invoices, which do not call the provider at all. The connection pool to PostgreSQL hit its limit within four minutes, and the storefront started returning 503 errors on pages that only read data.

During the incident, pg_stat_activity showed the shape of the problem:

SELECT pid, state, now() - xact_start AS xact_age, wait_event_type, wait_event, left(query, 60) AS query
FROM pg_stat_activity
WHERE datname = 'shop' AND state <> 'idle'
ORDER BY xact_age DESC
LIMIT 8;
  pid  |        state        | xact_age  | wait_event_type |  wait_event   |                       query
-------+---------------------+-----------+-----------------+---------------+------------------------------------------------
 48211 | idle in transaction | 00:00:27  | Client          | ClientRead    | UPDATE stock SET reserved = reserved + 1 WHERE
 48230 | idle in transaction | 00:00:25  | Client          | ClientRead    | UPDATE stock SET reserved = reserved + 1 WHERE
 48244 | active              | 00:00:24  | Lock            | transactionid | UPDATE stock SET reserved = reserved + 1 WHERE
 48251 | active              | 00:00:22  | Lock            | transactionid | UPDATE stock SET reserved = reserved + 1 WHERE
 ...

idle in transaction means a connection has an open transaction and is waiting for the application to send the next statement. Those sessions had updated stock rows, holding their row locks, and then gone quiet for nearly half a minute. Other checkouts trying to reserve the same popular products were active but waiting on a lock (wait_event_type = Lock).

The application side matched: those idle sessions belonged to request threads blocked on an HTTP call to the payment provider.

The checkout code

def checkout(cart, payment):
    with db.transaction():
        order = Order.create(cart)
        for item in cart.items:
            Stock.reserve(item.sku, item.qty)         # UPDATE stock ... (row lock)
        if payment.method == "card":
            result = provider.charge(payment.token, order.total)   # HTTP, up to 30 s
            order.mark_paid(result.charge_id)
        else:
            order.mark_pending(payment.method)
    return order

The intent was reasonable: if the charge fails, roll back the stock reservation and the order, all in one place. But the transaction stayed open, with locks held on stock rows, for as long as the provider took to answer.

Why non-card checkouts stalled too

Gift card checkouts did not call the provider, but they still reserved stock. When a gift card order included a product that a card order had already locked, it waited behind it. Bestsellers appear in most carts, so most checkouts queued on a handful of rows. Each waiting checkout also held a database connection, and the pool ran out. Once the pool was exhausted, even read-only page views could not get a connection.

Locks live as long as the transaction

In PostgreSQL, an UPDATE takes a row-level lock that is held until the transaction ends, not until the statement ends. Any other transaction that wants to update or lock the same row waits. That is what makes transactions safe, and it is why the length of a transaction matters so much: the longer it lasts, the longer everyone else waits.

Network calls are the worst thing to put inside a transaction because their duration is outside your control. A database statement takes milliseconds; an HTTP call to a third party takes anywhere from 100 milliseconds to the full timeout. In our case the client timeout was 30 seconds.

Rolling back does not undo the outside world

The design also had a correctness flaw. A transaction makes your database changes atomic. It does not make the payment provider part of the transaction. Consider:

  1. The charge succeeds at the provider.
  2. The response is slow; our HTTP client times out after 30 seconds.
  3. We raise an exception, the transaction rolls back, the order disappears.
  4. The customer has been charged for an order that does not exist.

We found 14 charges from that afternoon with no matching order, exactly this sequence.

Environment

Item Value
Database PostgreSQL 16, pool of 80 connections per app cluster
App Python 3.12 web workers
Provider timeout 30 s client-side
Hot rows top 20 products appear in about 60% of carts

1. Split the work into short transactions around the call

The checkout became three steps, each with its own short transaction, and the HTTP call outside all of them:

def checkout(cart, payment):
    # step 1: create the order and reserve stock, commit immediately
    with db.transaction():
        order = Order.create(cart, status="awaiting_payment")
        for item in cart.items:
            Stock.reserve(item.sku, item.qty)

    if payment.method != "card":
        with db.transaction():
            order.mark_pending(payment.method)
        return order

    # step 2: call the provider with no transaction open
    try:
        result = provider.charge(payment.token, order.total,
                                 idempotency_key=f"order-{order.id}", timeout=10)
    except provider.Declined:
        with db.transaction():                      # step 3a: release
            order.mark_failed()
            Stock.release_for(order)
        raise
    except provider.Timeout:
        # outcome unknown: leave it for reconciliation, do not release stock yet
        PaymentCheck.schedule(order.id, delay_seconds=30)
        return order

    with db.transaction():                          # step 3b: confirm
        order.mark_paid(result.charge_id)
    return order

Each transaction now lasts a few milliseconds. A slow provider makes card checkouts slow, but the stock locks are released long before the HTTP call starts.

Reserving stock is now a committed state, awaiting_payment, instead of something hidden inside an open transaction. That means the system must handle orders stuck in that state.

2. Reconcile instead of guessing on timeouts

A timeout means "we do not know". The PaymentCheck job asks the provider about the charge using the same idempotency key. If the charge succeeded, the order is marked paid. If it failed or does not exist, the order is failed and stock released. A sweeper also releases stock for orders left in awaiting_payment for more than 15 minutes, after one final check with the provider.

The idempotency key is what makes this safe. If the customer retries, or our job retries the charge, the provider recognises the same key and does not charge twice.

3. Use an outbox for side effects that must follow a commit

Some side effects, such as sending the confirmation email and notifying the warehouse, must happen if and only if the order is confirmed. Calling those services inside the transaction has the same lock problem; calling them after the commit risks losing them if the process crashes in between. We write an outbox row in the same transaction instead:

with db.transaction():
    order.mark_paid(result.charge_id)
    Outbox.add("order.paid", {"order_id": order.id})

A separate worker reads the outbox and delivers the events, retrying until they succeed. The database commit is the single point that decides whether the event exists.

4. Database-side guardrails

So that a future mistake cannot hold locks for half a minute again, we set timeouts for the application role:

ALTER ROLE shop_app SET idle_in_transaction_session_timeout = '5s';
ALTER ROLE shop_app SET lock_timeout = '3s';

idle_in_transaction_session_timeout terminates a session that sits idle inside a transaction longer than the limit, which releases its locks. lock_timeout makes a statement fail instead of waiting indefinitely for a lock. Both turn a pile-up into fast, visible errors.

1. A test with a slow provider. We point the checkout at a fake provider that sleeps for 20 seconds, start one card checkout, then run a gift card checkout for the same product:

def test_slow_provider_does_not_block_other_checkouts(slow_provider, product):
    t = threading.Thread(target=checkout, args=(cart_with(product), card_payment()))
    t.start()
    time.sleep(0.5)                                   # card checkout is now waiting on HTTP

    started = time.monotonic()
    checkout(cart_with(product), gift_card_payment())
    assert time.monotonic() - started < 1.0

On the old code the gift card checkout took 20 seconds. Now it takes about 40 ms.

2. Lock monitoring. We added a check that alerts if any application session is idle in transaction for longer than 2 seconds, from pg_stat_activity, and a dashboard of lock wait time per statement from pg_stat_statements. Both stayed flat during the provider's next slow period a month later.

3. Reconciliation. We refunded the 14 orphaned charges from the incident. The reconciliation job has since resolved every timeout case automatically; the daily report of charges without orders has been empty.

4. Security implications. Moving the call out of the transaction created a new state that could be abused: a client starting many checkouts and never paying could hold stock in awaiting_payment. The 15-minute sweeper, plus a per-account limit on unpaid orders, bounds that.

Takeaways

  • Row locks last until the transaction ends. Never wait on a network call while holding them.
  • A database rollback does not undo a charge at a third party. Treat the call as a separate step with its own success, failure and unknown outcomes.
  • Commit short transactions around the call, and reconcile unknown outcomes using an idempotency key.
  • Set idle_in_transaction_session_timeout and lock_timeout so mistakes fail fast.

References: PostgreSQL explicit locking, PostgreSQL pg_stat_activity, PostgreSQL client connection defaults.

Add a label

#postgresql #payments #transactions #outbox-pattern #row-locks
Written by
Mateusz Kowalczyk @mateuszkowalczyk

I started as an application developer and drifted toward the database because that is where our incidents kept ending up. For the last eight years I have looked after PostgreSQL and MySQL clusters for e-commerce and SaaS teams, from schema reviews to late-night failovers. Relational databases are well documented, yet the same surprises keep catching good engineers: a NOT IN that returns nothing because of one NULL, an index silently skipped after a type conversion, a FOR UPDATE that locked far more than intended, a replica that disagreed with its primary after promotion. In each post I reproduce the problem on a small dataset, read the plan or lock output together with you, explain the rule behind it and show the fix with numbers before and after. Where engines differ, I run the same test on both and show the results side by side.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.