Payments On-Call
Three incidents in Forkful's orders service: restaurants credited twice, payments stuck in the wrong state, and a nightly payout that paid twice. Each one is a write that is not safe to repeat, and each fix makes the database, not the process, the thing that decides.
On this page
The codebase
Forkful is a food-ordering marketplace. Customers pay through Paybridge, Paybridge tells the service what happened to each payment by webhook, and every night a job pays each restaurant its balance.
Two API processes (api-1 and api-2) and two job hosts (jobs-1 and jobs-2) share one SQLite database. That detail is the key to all three incidents: anything kept in memory is invisible to the other process.
You do not need to read the whole service. Every incident lives on one of two paths: the webhook path that turns Paybridge's events into ledger entries, or the payout path that turns ledger balances into transfers.
Where things live
app/api/routes/webhooks.pyPOST /webhooks/paybridge: checks the signature and hands the delivery to the webhook service.app/services/webhooks.pyhandle_delivery: decides whether a delivery is new, applies its event and records it.app/services/payments.pyapply_event: sets the payment's and the order's status, and posts credits and refunds.app/services/ledger.pyThe restaurants' ledger: capture credits, refund debits and payout debits.app/services/payouts.pypay_out_period: works out who is due and asks Paybridge for each transfer.app/jobs/run_payouts.pyrun_payout_job: the nightly entry point the scheduler calls. Its signature is fixed.app/providers/paybridge/Paybridge's client: payments, transfers (with an optional Idempotency-Key) and signatures.app/db/session.py's transaction(), the models, and repositories that flush but never commit.incidents/One evidence file per incident: timeline, logs and Paybridge's documentation. Read it first.candidate_tests/test_candidate.pyYour tests. conftest.py's fixtures (seed, checkout, make_event, deliver, paybridge) work here.Rules that shape every fix
- Keep the HTTP API, Paybridge's webhook contract (signature check, a 2xx for every delivery Paybridge need not resend) and
run_payout_job's signature. - Add tables, columns and constraints freely. Keep the existing columns.
- SQLite allows one writer at a time and ignores
with_for_update(), so locks have to come from constraints and transactions. tests/,conftest.pyand the dependencies are locked.
How to work each incident
- Diagnose from the evidence before asking for code. Name the cause in your own words and quote the log lines that show it.
- Ask for failing tests before the fix, and name the cases they must cover, including the hard one: two processes at once, or a failure partway.
- Press Test and watch them fail. Then say what failed, with the value you saw.
- List what the fix must survive, then describe the design yourself: the constraint, the transaction, the answer Paybridge gets.
- Press Test again after the last change. If it is still red, name the failing test and the value it showed, ask for the fix, and press Test again before you move on.
Restaurants paid twice
What the ticket asks
After Paybridge's 40-minute outage it resent its webhook deliveries, and 61 payments now have two capture credits: $1,247.80 Forkful never received.
Find why a capture credits twice, reproduce it in a test, and fix it so each capture credits its restaurant once, however and whenever Paybridge delivers it.
Where to look
incidents/01-paid-twice.mdThe three restaurants' logs each show a different way the same event lands twice.app/services/webhooks.pyhandle_delivery's dedupe check is the bug. Look at what it keys on and how many transactions it opens.app/services/payments.pyapply_event opens its own transaction, so the credit commits before the delivery is recorded.app/db/models/webhook.pyThe record that should make a repeat impossible. Its event_id is indexed but not unique.app/db/repositories/menus.pyadd_item shows the codebase's pattern: flush, catch IntegrityError, raise a named ConflictError.What the evidence shows
evt_Gu7mhmWXCb4k5KNAarfLdv2G arrives at 14:06 and again at 14:43 with a new delivery id. Both credit 2875.evt_e0Hw3tTSN2dzOGUeB9O4dnWx reaches api-1 and api-2 4 ms apart. Both pass the check.The cause
- The dedupe keys on the delivery id, which every retry changes, so it never catches a retry.
- The check, the credit and the record are three separate transactions, so two overlapping deliveries both pass the check.
- The credit commits before the record, so a failure in between leaves a credit with no record, and the retry credits again.
The fix
- Make the event id unique in the database, so a second delivery of an event cannot be recorded, on any process.
- Record the delivery and apply its event in one transaction, so both land or neither does.
- Answer a duplicate with 200 and duplicate: true, not 409, because Paybridge stops resending only on a 2xx.
- Catch only that duplicate error. Every other failure still returns 500, so Paybridge retries it.
app/db/models/webhook.pyOne row per event: the event id gets a unique constraint. class WebhookDelivery(Base): __tablename__ = "webhook_deliveries"+ __table_args__ = (UniqueConstraint("event_id"),) delivery_id: Mapped[str] = mapped_column(String(64), primary_key=True)- event_id: Mapped[str] = mapped_column(String(64), index=True)+ event_id: Mapped[str] = mapped_column(String(64))app/db/repositories/webhooks.pyThe insert turns the constraint violation into a named error, as menus.add_item does. The dead delivery-id lookup goes.-def get_delivery(session: Session, delivery_id: str) -> WebhookDelivery | None:- return session.get(WebhookDelivery, delivery_id)+class EventAlreadyHandled(ConflictError):+ default_code = "event_already_handled" def record_delivery(session, *, delivery_id, event_id, ...) -> WebhookDelivery: session.add(delivery)- session.flush()+ try:+ session.flush()+ except IntegrityError as error:+ raise EventAlreadyHandled(f"Paybridge event {event_id} has been handled already") from errorapp/services/webhooks.pyRecord first, then apply, in one transaction. A duplicate rolls back and is answered as a duplicate.- with transaction(session_factory) as session:- seen = webhooks.get_delivery(session, delivery.delivery_id)- if seen is not None:- return DeliveryOutcome.DUPLICATE- payments.apply_event(session_factory, event, clock=clock, outbox=outbox)- with transaction(session_factory) as session:- webhooks.record_delivery(session, ...)+ try:+ with transaction(session_factory) as session:+ webhooks.record_delivery(session, delivery_id=..., event_id=event.id, ...)+ applied = payments.apply_event(session, event, now=received_at) if is_payment_event(event.type) else None+ except EventAlreadyHandled:+ return DeliveryOutcome.DUPLICATE+ if applied is not None:+ payments.announce(outbox, applied, now=received_at)app/services/payments.pyapply_event works in the caller's session, and notifications move to announce(), called after the commit.-def apply_event(session_factory, event, *, clock, outbox) -> AppliedEvent:- with transaction(session_factory) as session:- ...+def apply_event(session: Session, event: PaybridgeEvent, *, now: datetime) -> AppliedEvent:+ ...++def announce(outbox: Outbox, result: AppliedEvent, *, now: datetime) -> None:+ """Call it after the commit, so nobody hears of a change that was rolled back."""Tests that prove it
- The same capture resent with a new delivery id: one credit of 1549.
- Two deliveries of one event at once on two app instances, both threads held at a
threading.Barrierbefore their first write: one credit. - A delivery that fails right after the credit, then its retry: one credit.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. The new tests fail on the code as it is: the retry test ends with a balance of 3098.
- Verification: Reproduced first, 8 points
- Verification: Hard case tested, 6 points
- Press Test. Every test passes after the last change.
- Verification: Run after last change, 6 points
- Continue. The stage closes. Scope, correctness and code quality are judged on the final code.
- Direction: Scope, 4 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
Charged but pending, refunds lost
What the ticket asks
While Paybridge delivered the events its outage held back, 23 customers were charged but their orders still show pending, and nine refunds ($86.45) never came off the restaurants' balances.
Find why, reproduce both problems in tests, and fix it so a payment's status, its order's status and the balance come out right whatever order the events arrive in. A repeated delivery still counts once.
Where to look
incidents/02-out-of-order.mdPho Saigon Corner shows the status problem, Sakura Ramen House the lost refund.app/services/payments.pyEach handler sets the status from whichever event arrived last. _refunded drops a refund that comes before its capture.app/db/models/payment.pyWhere the status lives. Nothing records which event set it.app/providers/paybridge/events.pyEvery event carries a sequence. Today it is only logged.What the evidence shows
refund.ignored_uncaptured, and is still answered 200, so Paybridge never resends it.The cause
- The status comes from whichever event arrived last. sequence, the one field that orders a payment's events, is never used.
- A refund that arrives before its capture is dropped but acknowledged, so it is lost for good.
The fix
- The status follows Paybridge's sequence: an event older than the one the status came from leaves the status alone.
- Keep that sequence in the database, next to the status, because a payment's events reach both API processes.
- Every event still counts, whatever the order: its amount is recorded and its credit or refund debit posted. A refund before its capture still debits.
- Work a refund's status out from the amounts: refunded only when 0 < captured ≤ refunded.
app/db/models/payment.pyThe payment remembers which event its status came from. status: Mapped[str] = mapped_column(String(24))+ status_sequence: Mapped[int] = mapped_column(default=0)+ """The sequence of the newest event the status comes from; 0 until an event arrives."""app/services/payments.pyOne function settles the status by sequence. The handlers always apply their amounts and ledger entries.+def _settle_status(session, payment, order, event, now) -> None:+ if event.sequence > payment.status_sequence:+ newest, sequence = EventType(event.type), event.sequence+ else:+ newest, sequence = EVENT_FOR_STATUS[PaymentStatus(payment.status)], payment.status_sequence+ status = _status_for(newest, payment)+ payments.update_payment(session, payment, status=status, status_sequence=sequence, now=now)+ orders.set_payment_status(session, order, status, ORDER_STATUS_FOR_PAYMENT[status], now=now)app/services/payments.py (_refunded)The branch that dropped an early refund goes. The refund always debits.- if payment.status not in REFUNDABLE_STATUSES:- log.warning("refund.ignored_uncaptured", ...)- return False, None- refunded_cents = payments.add_refund(session, payment, amount_cents, now=now)- status = PaymentStatus.REFUNDED if refunded_cents >= payment.captured_cents else ...- _set_status(session, payment, order, status, now)+ payments.add_refund(session, payment, amount_cents, now=now)+ _settle_status(session, payment, order, event, now) return ledger.debit_refund(session, payment, amount_cents=amount_cents, event_id=event.id, now=now)Tests that prove it
- The capture (sequence 2) before the authorization (sequence 1): the order stays confirmed.
- A refund of 500 before its capture: the balance ends at 1049.
- Every ordering of one payment's authorized, captured and refunded events: the same final status and balance.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. The order is still pending after the capture-first case. The refund-first case ends at 1549.
- Verification: Reproduced first, 8 points
- Verification: Both problems tested, 6 points
- Press Test. Every test passes after the last change.
- Verification: Run after last change, 6 points
- Continue. The stage closes. Scope, correctness and code quality are judged on the final code.
- Direction: Scope, 5 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
The first run left the module docstring saying an early refund cannot be applied, which cost half a tidiness point. The fix message above now asks for it, and the second run scored 100.
The nightly payout ran twice
What the ticket asks
Twice this week the nightly payout paid restaurants twice: once after a run that failed partway was rerun by hand, once when a deploy started two runs at the same moment.
Find why, reproduce both in tests, and fix it so each restaurant is paid its balance once a day, however a run fails, is rerun or overlaps another. The earlier fixes stay fixed.
Where to look
incidents/03-payout-twice.mdThursday's timeout and rerun, Saturday's two runs, and Paybridge's page on idempotency keys.app/services/payouts.py_pay asks for the transfer with no key and records the payout only after Paybridge answers.app/db/models/payout.pyNothing in the schema stops a second payout for the same restaurant and day.app/providers/paybridge/client.pytransfers.create already accepts an idempotency_key. Nobody passes one.app/jobs/run_payouts.pyThe entry point the scheduler calls. Keep its signature.What the evidence shows
run_payouts for 2026-10-23 starts on jobs-1 and jobs-2 at once. Both read the same balances and both pay.The cause
- Each transfer is requested with no idempotency key, and the payout is recorded only after Paybridge answers. A timeout after the transfer was made leaves no record, and the rerun pays again.
- Nothing stops two runs from reading the same balances and both paying.
The fix
- Before asking for a transfer, claim the restaurant's payout for the day in a table with a unique (restaurant, period). A second run cannot claim it.
- Send every request for that payout with the same key, payout:{restaurant}:{period}, so a retry or a rerun gets the original transfer.
- When Paybridge answers, write the payout, its ledger debit and the claim marked sent in one transaction.
- A failure leaves the claim pending. Every run first asks again for pending claims, with the same key, so a rerun finishes what an earlier run started.
app/db/models/payout.pyA claim per restaurant and period, taken before the transfer.+class PayoutClaim(Base):+ __tablename__ = "payout_claims"+ __table_args__ = (UniqueConstraint("restaurant_id", "period"), ...)++ restaurant_id: Mapped[str] = mapped_column(ForeignKey("restaurants.id"))+ period: Mapped[date]+ amount_cents: Mapped[int]+ idempotency_key: Mapped[str] = mapped_column(String(255))+ status: Mapped[str] = mapped_column(String(16)) # pending | sent+ payout_id: Mapped[str | None] = mapped_column(ForeignKey("payouts.id"))app/db/repositories/payouts.pyThe stable key, the claim insert with its named error, and a conditional mark-sent.+def idempotency_key(restaurant_id: str, period: date) -> str:+ return f"payout:{restaurant_id}:{period.isoformat()}"++def claim(session, *, restaurant_id, period, amount_cents, destination, now) -> PayoutClaim:+ session.add(claimed)+ try:+ session.flush()+ except IntegrityError as error:+ raise PayoutAlreadyClaimed(...) from errorapp/services/payouts.pyPending claims first, then claim, send with the key, and record together.- due = restaurants_due(session_factory)+ attempts = _send_pending(session_factory, transfers, clock=clock)+ still_pending = {attempt.restaurant_id for attempt in attempts if attempt.failed}+ due = [owed for owed in restaurants_due(session_factory) if owed.restaurant_id not in still_pending] for restaurant in due:- paid.append(_pay(session_factory, transfers, restaurant, period=period, clock=clock))+ claimed = _claim(session_factory, restaurant, period=period, clock=clock)+ if claimed is not None:+ attempts.append(_send(session_factory, transfers, claimed, clock=clock)) - transfer = transfers.create(due.destination, due.amount_cents)+ transfer = transfers.create(claimed.destination, claimed.amount_cents, idempotency_key=claimed.idempotency_key) + with transaction(session_factory) as session:+ payout = payouts.create(session, ...)+ payouts.mark_sent(session, claimed.id, payout_id=payout.id, now=now)+ ledger.debit_payout(session, payout, now=now)Tests that prove it
- A transfer whose answer is lost after Paybridge made it, then a rerun: one transfer.
- A 503 that made no transfer, then a rerun: one transfer.
- Two runs at once, each held at a
threading.Barrierbefore its first write: one transfer per restaurant.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. After the lost answer and the rerun, Luigi's gets two transfers of 1549. The two-runs test pays twice too.
- Verification: Reproduced first, 8 points
- Verification: Both incidents tested, 6 points
- Press Test. Every test passes after the last change.
- Verification: Run after last change, 6 points
- Submit. The stage closes. Scope, correctness and code quality are judged on the final code.
- Direction: Scope, 4 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.
A clean run scored 100. An earlier run scored 95, losing Scope and half of Named the cases to scoring variation, not to anything the conversation left out.