Scheduled Payment Execution and Outgoing Reporting System
Hard · System Design · Software Engineer · Online Assessment
Prompt
Architect and implement a scheduled-payment engine for a digital banking service that already handles accounts, deposits, and immediate transfers. Extend the platform with four capabilities:
- Pending Cancellation (
cancelPayment): Let an account holder abort a future payment they scheduled earlier, defining deterministic rules when a cancellation arrives right at or past the payment's scheduled execution time. - Durable Outcome Tracking (
schedulePayment): Record and surface both successful debits and failed execution attempts (for example, insufficient funds or ineligible account status) when a scheduled payment reaches its due time. - Lifecycle Cleanup of Stale Payment Records: Evict finished, cancelled, account-closed, and expired payment entries from active execution queues and hot operational storage without losing permanent accounting ledger entries.
- Outgoing Volume Ranking: Generate a ranked report of accounts ordered descending by cumulative outgoing funds debited (total money leaving each account, excluding failed or cancelled schedules), with deterministic tie-breaking.
Scope & Expectations
- Exact Semantics & Reference Implementation: Pin down tie-breaking order for simultaneous due payments, integer currency representation, boundary rules between execution and
cancelPayment, and a clean single-node reference implementation. - APIs, Data Schema, and State Machine: Specify idempotent REST endpoints, account-sharded relational schemas, partial indexes, and mutually exclusive state transitions across
PENDING,SUCCEEDED,FAILED, andCANCELLED. - Parallel Execution Without Race Conditions: Explain how to drain millions of simultaneous first-of-the-month due payments across workers while preserving per-account ordering, preventing double-debits, and separating business failures from transient infrastructure retries.
- Scalable Reporting and Retention: Show how to serve top-N outgoing-volume reports across shards (both lifetime and windowed) and purge aged operational records without database lock contention or index bloat.
Step-by-step walkthrough
Clarify the four requirements and pin down exact rules
This problem extends a core banking payment service (accounts, deposits, immediate payments, and scheduled payments) with four capabilities. Lifecycle cleanup of stale schedules and ranking accounts by cumulative outgoing volume each involve subtle edge cases, so lock down crisp, explicit rules upfront before drawing boxes or writing code.
The four requirements made concrete
cancelPaymentfor pending scheduled payments: cancels a previously scheduled payment only if the payment exists, belongs to the requestingaccount_id, and is stillPENDINGstrictly before its scheduled execution instant (now < execute_at). Ifnow >= execute_at, the payment is already due and runs (succeeding or failing) before the cancellation is evaluated.- Durable outcome tracking for
schedulePayment: whenexecute_atarrives, the system attempts to debit the account. If the account is active andbalance >= amount, the payment moves toSUCCEEDEDand debits the balance; if funds are insufficient or the account is frozen, it moves toFAILEDwith a structuredreason(INSUFFICIENT_FUNDS,ACCOUNT_FROZEN) and moves zero money. Both outcomes are saved durably, returned by status queries, and emitted as customer notifications. - Lifecycle cleanup of stale payment records: handles retirement at three levels:
- Active queue: finished payments (
SUCCEEDED,FAILED,CANCELLED) exit the execution queue immediately so workers never re-scan historical rows. - Account closure: closing an account immediately cancels all of its remaining
PENDINGscheduled payments (reason = 'ACCOUNT_CLOSED'). - Hot-storage retention: terminal payment records older than a retention window (say 90 days) are archived to cold storage and purged from hot operational tables—while immutable accounting ledger entries are kept permanently. (If evolving an older codebase, also deprecate and remove legacy fire-and-forget payment code paths.)
- Active queue: finished payments (
- Accounts ranked by cumulative outgoing funds: outgoing loss from an account's perspective means total money actually debited out of the account (completed immediate payments +
SUCCEEDEDscheduled payments;FAILEDandCANCELLEDpayments contribute0). Rank accounts bytotal_out DESC, breaking ties byaccount_id ASC, and return the topN(supporting both lifetime totals and time windows like the last 30 days).
Deterministic ordering and money invariants
- Tie-breaking rule: due payments execute in
(execute_at, creation_seq)order. If an account has$150and two scheduled payments ($90created first,$80created second) both come due att = 20, the$90payment runs first and succeeds, leaving$60, and the$80payment recordsFAILED (INSUFFICIENT_FUNDS). - Exact integer money: represent every amount as a positive 64-bit integer in minor units (the smallest unit of a currency, such as cents where
$12.50 = 1250), and enforcebalance >= 0.
Production non-functional targets
Correctness zero double-debits, zero executed cancelled payments, zero lost outcomes Execution lag < 1 minute on normal days; < 10 minutes during the 1st-of-the-month midnight spike API availability 99.99% for schedule, cancel, and status queries Durability zero data loss on single-node or availability-zone failure (synchronous standby, RPO = 0) Report freshness real-time (same transaction) for lifetime top-N; <= 2 minutes for 30-day window reportsBack-of-the-envelope numbers: why the 1st of the month drives the design
Estimate scale for a mid-to-large digital bank or programmable payments platform (20 million accounts):
Total accounts 20M Scheduled payments created 100M / month -> ~3.3M / day -> ~40 / s average, ~400 / s peak Lead time before execution up to 1 year ahead; median ~2 weeks -> ~50M-60M PENDING rows live The 1st-of-the-month spike ~35% of monthly rent, mortgage, and bill pays land on the 1st -> 35M/day ~37% of those target 00:00 local midnight (~13M), and ~47% of U.S. accounts sit in Eastern Time -> ~6,000,000 payments due at 00:00:00 ET! Target drain rate 6M payments / 600 seconds (10 min SLA) = 10,000 executions / s DB writes per execution 1 SQL txn touching 6 rows (scheduled_payment, account, ledger_entry, payment_attempt, account_outgoing, outbox) -> ~60,000 row writes / s Storage footprint ~1 KB per payment across tables/indexes -> ~100 GB / month 90 days hot (~300 GB) + 60M pending (~30 GB) = ~330 GB across cluster Read traffic status checks ~2,000 / s; top-outgoing report queries ~10 / sFour architectural insights come straight from these numbers:
- Average QPS (
40/s) is tiny, but00:00 ETon the 1st (10,000/s) is massive: one single-threaded priority queue cannot drain 6 million database transactions in 10 minutes. Execution must be parallelized across shards and workers. - Parallelism cannot break per-account order: we can execute Alice's and Bob's payments in parallel, but two due payments belonging to Alice must run sequentially in
(execute_at, creation_seq)order. - 330 GB spread across 16 shards is ~21 GB per shard: hot working sets fit comfortably in RAM on standard database instances, provided we purge old finished partitions on schedule.
- Top-N reports cannot scan all payments at read time: summing hundreds of millions of rows on every report request would take minutes; we need a pre-aggregated per-account total.
- Average QPS (
API design: schedule, cancel, status, and outgoing reports
Protect creation with an idempotency key (a unique client-generated UUID per logical schedule click so network retries return the original
payment_idrather than scheduling a duplicate payment).1. Schedule a future (or immediate delay=0) payment POST /v1/accounts/{account_id}/scheduled-payments Header: Idempotency-Key: 8f14e45f-ceea-467a-9a38-1b2c3d4e5f60 Body: { "amount_minor": 7000, "currency": "USD", "execute_at": "2026-12-01T05:00:00Z", "destination": { "to_account": "acc_99" } } -> 201 { "payment_id": "9007199254740993", "status": "PENDING", "execute_at": "2026-12-01T05:00:00Z" } -> 409 Conflict (Idempotency-Key reused with different request fields) -> 422 Unprocessable Entity (amount_minor <= 0 or closed account) 2. Cancel a pending payment POST /v1/accounts/{account_id}/scheduled-payments/{payment_id}/cancel -> 200 { "payment_id": "9007199254740993", "status": "CANCELLED", "finished_at": "..." } -> 409 { "payment_id": "...", "status": "SUCCEEDED" | "FAILED" | "CANCELLED", "reason": "NOT_PENDING" } -> 409 { "payment_id": "...", "status": "PENDING", "reason": "ALREADY_DUE" } (now >= execute_at) -> 404 Not Found (unknown payment_id or belongs to a different account) 3. Query persisted success / failure outcome & history GET /v1/accounts/{account_id}/scheduled-payments/{payment_id} -> 200 { "payment_id": "...", "status": "FAILED", "reason": "INSUFFICIENT_FUNDS", "amount_minor": 5000, "execute_at": "...", "finished_at": "...", "attempts": [ { "attempt_no": 1, "outcome": "FAILED", "reason": "INSUFFICIENT_FUNDS", "at": "..." } ] } GET /v1/accounts/{account_id}/scheduled-payments?status=FAILED&cursor=... 4. Outgoing transactions report sorted by total money out ("loss") GET /v1/reports/outgoing?window=lifetime|30d&limit=100&cursor=... -> 200 { "as_of": "2026-12-01T05:04:12Z", "rows": [ { "account_id": "acc_12", "total_out_minor": 9850000, "payment_count": 412 }, ... ] }Why
POST .../cancelinstead ofDELETE? Because banks never erase financial intent—cancelling transitions the record toCANCELLEDso customers and auditors can still see who cancelled it and when.Data model and the payment state machine
Shard PostgreSQL by
account_id(16 shards) so every table needed to execute one account's payment lives on one local shard, avoiding slow distributed transactions across machines.CREATE TABLE account ( account_id BIGINT PRIMARY KEY, balance BIGINT NOT NULL CHECK (balance >= 0), -- integer minor units (cents) currency CHAR(3) NOT NULL, status TEXT NOT NULL -- 'ACTIVE' | 'FROZEN' | 'CLOSED' ); CREATE TABLE scheduled_payment ( payment_id BIGINT NOT NULL, -- shard_seq * 64 + shard_id: monotonically increasing per shard! account_id BIGINT NOT NULL, lane SMALLINT NOT NULL, -- hash(account_id) % 1024 (ordered execution unit) amount BIGINT NOT NULL CHECK (amount > 0), currency CHAR(3) NOT NULL, destination JSONB NOT NULL, execute_at TIMESTAMPTZ NOT NULL, status TEXT NOT NULL, -- 'PENDING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED' reason TEXT, -- 'INSUFFICIENT_FUNDS' | 'ACCOUNT_FROZEN' | 'CUSTOMER' | 'ACCOUNT_CLOSED' finished_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (payment_id, execute_at) ) PARTITION BY RANGE (execute_at); -- 1 partition per month (pre-created 13 months ahead) -- Partial index: ONLY pending rows stay in this index; finished/cancelled rows vanish from it automatically! CREATE INDEX idx_due_by_lane ON scheduled_payment (lane, execute_at, payment_id) WHERE status = 'PENDING'; CREATE INDEX idx_account_history ON scheduled_payment (account_id, execute_at DESC); CREATE TABLE payment_attempt ( -- durable audit log of success, failure, or cancel payment_id BIGINT NOT NULL, attempt_no INT NOT NULL, at TIMESTAMPTZ NOT NULL, outcome TEXT NOT NULL, -- 'SUCCEEDED' | 'FAILED' | 'CANCELLED' reason TEXT, actor TEXT NOT NULL, -- 'executor:w12' | 'customer' | 'system:close_account' lease_epoch BIGINT, PRIMARY KEY (payment_id, attempt_no) ); CREATE TABLE ledger_entry ( -- permanent, never-purged accounting book entry_id BIGSERIAL PRIMARY KEY, account_id BIGINT NOT NULL, amount BIGINT NOT NULL, -- negative for outgoing debits, positive for deposits kind TEXT NOT NULL, -- 'DEPOSIT' | 'IMMEDIATE_PAY' | 'SCHEDULED_PAY' source_ref TEXT NOT NULL UNIQUE, -- 'sched:<payment_id>' prevents double debit! created_at TIMESTAMPTZ NOT NULL ); CREATE TABLE account_outgoing ( -- pre-aggregated outgoing total per account account_id BIGINT PRIMARY KEY, total_out BIGINT NOT NULL, payment_count BIGINT NOT NULL ); CREATE INDEX idx_outgoing_rank ON account_outgoing (total_out DESC, account_id ASC); CREATE TABLE outbox ( -- transactional event queue for Kafka outbox_id BIGSERIAL PRIMARY KEY, topic TEXT NOT NULL, partition_key TEXT NOT NULL, payload JSONB NOT NULL );State machine
execute at >= execute_at (ACTIVE & balance >= amount) +---------------------------------------------------------> SUCCEEDED | PENDING -----+ execute at >= execute_at (balance < amount or FROZEN) +---------------------------------------------------------> FAILED (reason persisted) | | cancelPayment at < execute_at, OR close_account +---------------------------------------------------------> CANCELLED (reason persisted)Every arrow out of
PENDINGacquires the row lock onscheduled_paymentand checksstatus = 'PENDING', guaranteeingSUCCEEDED,FAILED, andCANCELLEDare mutually exclusive terminal states.Single-node reference implementation (exact semantics & test oracle)
Before distributing across 16 shards, express all four requirements in a clean, single-process Python implementation. In coding-heavy interviews this directly answers the implementation part, and in production engineering it serves as a reference oracle (a simple, known-correct model used to verify randomized test runs against the distributed service).
Key data-structure ideas:
due_heapmin-heap (a binary tree stored in a list whose smallest(execute_at, seq, payment_id)tuple always sits at index0): pops the next due payment inO(log H)time, breaking timestamp ties by integerseq.- Lazy deletion on cancel: removing an arbitrary item from the middle of a heap takes
O(H)time. Instead,cancel_paymentsimply markspayment.status = CANCELLEDinO(1)time, and_process_dueskips non-PENDINGentries when they eventually pop.purge_obsoleteperiodically compacts dead heap entries.
import heapq from typing import Dict, List, Optional, Tuple PENDING = "PENDING" SUCCEEDED = "SUCCEEDED" FAILED = "FAILED" CANCELLED = "CANCELLED" class ScheduledPayment: def __init__( self, payment_id: str, seq: int, account_id: str, amount: int, created_at: int, execute_at: int, ) -> None: self.payment_id = payment_id self.seq = seq self.account_id = account_id self.amount = amount self.created_at = created_at self.execute_at = execute_at self.status = PENDING self.reason: Optional[str] = None self.finished_at: Optional[int] = None class BankingPaymentSystem: def __init__(self) -> None: # balances: maps active account_id -> integer balance in minor units self.balances: Dict[str, int] = {} # closed_accounts: tracks closed accounts so their history stays readable self.closed_accounts: set[str] = set() # outgoing_totals: maps account_id -> total money that actually left the account self.outgoing_totals: Dict[str, int] = {} # payments: maps payment_id -> ScheduledPayment record (both pending and terminal) self.payments: Dict[str, ScheduledPayment] = {} # due_heap: min-heap of (execute_at, seq, payment_id) for ordered execution self.due_heap: List[Tuple[int, int, str]] = [] self.next_seq = 1 def _process_due(self, now: int) -> None: """Execute every PENDING payment with execute_at <= now in (execute_at, seq) order.""" while self.due_heap and self.due_heap[0][0] <= now: execute_at, seq, payment_id = heapq.heappop(self.due_heap) payment = self.payments.get(payment_id) # Lazy deletion: skip entries already cancelled, closed, or purged. if payment is None or payment.status != PENDING: continue self._execute_one(payment) def _execute_one(self, payment: ScheduledPayment) -> None: """Debit the account on success, or persist a structured failure reason.""" acct = payment.account_id if acct in self.closed_accounts or acct not in self.balances: self._finish(payment, FAILED, "ACCOUNT_CLOSED", payment.execute_at) return current_balance = self.balances[acct] if current_balance < payment.amount: # Persist failure without moving money or increasing outgoing_totals. self._finish(payment, FAILED, "INSUFFICIENT_FUNDS", payment.execute_at) return self.balances[acct] = current_balance - payment.amount self.outgoing_totals[acct] += payment.amount self._finish(payment, SUCCEEDED, None, payment.execute_at) def _finish( self, payment: ScheduledPayment, status: str, reason: Optional[str], finished_at: int, ) -> None: payment.status = status payment.reason = reason payment.finished_at = finished_at def create_account(self, timestamp: int, account_id: str) -> bool: self._process_due(timestamp) if account_id in self.balances or account_id in self.closed_accounts: return False self.balances[account_id] = 0 self.outgoing_totals[account_id] = 0 return True def deposit(self, timestamp: int, account_id: str, amount: int) -> Optional[int]: self._process_due(timestamp) if account_id not in self.balances or amount <= 0: return None self.balances[account_id] += amount return self.balances[account_id] def pay_immediate(self, timestamp: int, account_id: str, amount: int) -> Optional[int]: self._process_due(timestamp) balance = self.balances.get(account_id) if balance is None or amount <= 0 or balance < amount: return None self.balances[account_id] = balance - amount self.outgoing_totals[account_id] += amount return self.balances[account_id] def schedule_payment( self, timestamp: int, account_id: str, amount: int, delay: int ) -> Optional[str]: self._process_due(timestamp) if account_id not in self.balances or amount <= 0 or delay < 0: return None seq = self.next_seq self.next_seq += 1 payment_id = f"payment{seq}" execute_at = timestamp + delay payment = ScheduledPayment(payment_id, seq, account_id, amount, timestamp, execute_at) self.payments[payment_id] = payment heapq.heappush(self.due_heap, (execute_at, seq, payment_id)) # If delay == 0, execute immediately before returning. self._process_due(timestamp) return payment_id def cancel_payment(self, timestamp: int, account_id: str, payment_id: str) -> bool: # Run due payments <= timestamp FIRST so a payment due at `timestamp` beats cancel! self._process_due(timestamp) payment = self.payments.get(payment_id) if payment is None or payment.account_id != account_id: return False if payment.status != PENDING: return False self._finish(payment, CANCELLED, "CUSTOMER", timestamp) return True def get_payment_status( self, timestamp: int, account_id: str, payment_id: str ) -> Optional[Tuple[str, Optional[str]]]: self._process_due(timestamp) payment = self.payments.get(payment_id) if payment is None or payment.account_id != account_id: return None return (payment.status, payment.reason) def close_account(self, timestamp: int, account_id: str) -> bool: """Obsolete case #1: closing a zero-balance account cancels all its pending payments.""" self._process_due(timestamp) if account_id not in self.balances or self.balances[account_id] != 0: return False del self.balances[account_id] self.closed_accounts.add(account_id) for payment in self.payments.values(): if payment.account_id == account_id and payment.status == PENDING: self._finish(payment, CANCELLED, "ACCOUNT_CLOSED", timestamp) return True def purge_obsolete(self, timestamp: int, retention_window: int) -> int: """Obsolete case #2: remove terminal payments older than retention_window and compact heap.""" self._process_due(timestamp) cutoff = timestamp - retention_window removed_count = 0 for payment_id in list(self.payments.keys()): payment = self.payments[payment_id] if ( payment.status != PENDING and payment.finished_at is not None and payment.finished_at <= cutoff ): del self.payments[payment_id] removed_count += 1 # Rebuild the heap keeping only live PENDING entries so cancelled ghosts don't accumulate. live_entries = [] for execute_at, seq, payment_id in self.due_heap: payment = self.payments.get(payment_id) if payment is not None and payment.status == PENDING: live_entries.append((execute_at, seq, payment_id)) heapq.heapify(live_entries) self.due_heap = live_entries return removed_count def report_outgoing_by_loss(self, timestamp: int, limit: int) -> List[Tuple[str, int]]: """Rank accounts by total outgoing amount DESC, ties broken by account_id ASC.""" self._process_due(timestamp) sortable_rows = [] for account_id, total_out in self.outgoing_totals.items(): sortable_rows.append((-total_out, account_id)) sortable_rows.sort() result = [] for neg_total, account_id in sortable_rows[:limit]: result.append((account_id, -neg_total)) return resultMini-trace of tie-breaking, failure persistence, and boundary cancellation
Time Call State after call ---- ------------------------------------------ --------------------------------------------------------- t=1 create_account("acct_7"), deposit(..., 150) balances["acct_7"] = 150, outgoing["acct_7"] = 0 t=5 schedule("acct_7", 90, delay=15) -> payment1 due_heap = [(20, 1, "payment1")] t=8 schedule("acct_7", 80, delay=12) -> payment2 due_heap = [(20, 1, "payment1"), (20, 2, "payment2")] t=9 schedule("acct_7", 40, delay=25) -> payment3 due at t=34 t=14 cancel_payment(14, "acct_7", "payment3") True! payment3 -> CANCELLED (14 < 34) t=20 cancel_payment(20, "acct_7", "payment1") _process_due(20) runs FIRST: 1) (20, 1, "payment1"): 150 >= 90 -> SUCCEEDED, bal=60 2) (20, 2, "payment2"): 60 < 80 -> FAILED (INSUFFICIENT_FUNDS) Now cancel checks payment1: status is SUCCEEDED -> returns False! t=21 report_outgoing_by_loss(21, limit=5) [("acct_7", 90)] (payment2 failed & payment3 cancelled -> add 0)High-level distributed architecture
[Clients / Mobile App / Internal Services] | v [API Gateway] (TLS, Auth, Redis rate limiting) | v [Payment API] (Stateless: Idempotency check, schedule, cancel, status) | v +--------------- 16 PostgreSQL Shards (sharded by account_id; 64 lanes per shard) --------------+ | account | scheduled_payment (monthly partitions + PENDING index) | payment_attempt | | | ledger_entry | account_outgoing (ranked index) | outbox | | Primary + synchronous standby in a separate availability zone (RPO = 0) | +-----------------------------------------------------------------------------------------------+ ^ ^ | | Poll due rows per lane | Scatter-gather top N | Outbox CDC relay | in (execute_at, payment_id) | via idx_outgoing_rank v [Executor Worker Pool] | [Kafka Event Bus] (64 workers; 16 leased lanes each) | / \ ^ | v v | Renew 15s leases + epoch [Report Service] [Notification Svc] [ClickHouse OLAP] [Lane Lease Table] - Lifetime: shard (Push / Email / (30-day & custom (1,024 lanes total) k-way merge Webhooks) window reports) - Windowed: OLAP [Partition Archiver] (Exports > 90-day-old monthly partitions to S3 Parquet, verifies, drops partition)Deep dive 1: ordered execution lanes and the race with `cancelPayment`
In production, two requirements pull in opposite directions: drain 10,000 due payments/s on the 1st of the month (parallelism) while running each account's due payments strictly in
(execute_at, payment_id)order (serialization).Why
FOR UPDATE SKIP LOCKEDon a global queue breaks correctnessA classic SQL worker pool runs
SELECT ... ORDER BY execute_at, payment_id LIMIT 1 FOR UPDATE SKIP LOCKED. If Worker A claims Alice'spayment1($70) and pauses for 10 ms on garbage collection while Worker B claims Alice'spayment2($50) and commits first,payment2steals the$100balance that belonged topayment1!Solution: 1,024 hashed execution lanes with leased single-owner fencing
Assign every account deterministically to
lane = hash(account_id) % 1024, placing 64 contiguous lanes on each of the 16 database shards. A lightweightlane_leasetable ensures at most one worker owns a lane at a time:UPDATE lane_lease SET epoch = CASE WHEN owner_id = :worker THEN epoch ELSE epoch + 1 END, owner_id = :worker, lease_until = now() + INTERVAL '15 seconds' WHERE lane = :lane AND (owner_id = :worker OR lease_until < now()) RETURNING epoch;Workers renew leases every 5 seconds. Whenever ownership changes hands after a crash,
epochincrements, acting as a fencing token (a monotonically increasing ownership counter recorded onpayment_attemptfor audit visibility). Inside one lane, the owning worker reads batches from the partial index:SELECT payment_id, account_id, amount, execute_at FROM scheduled_payment WHERE lane = :lane AND status = 'PENDING' AND execute_at <= now() ORDER BY execute_at, payment_id LIMIT 200;Subtle PostgreSQL pitfall to avoid: do not advance a watermark filter like
AND (execute_at, payment_id) > (:last_ex, :last_pid)across queries! Database sequences allocate IDs before commit, so Transaction A (payment_id = 49) can commit 2 milliseconds after Transaction B (payment_id = 50); a> 50watermark would skippayment_id = 49! Instead, always query from the head of the partial index: oncepayment_id = 50updates toSUCCEEDED, it leavesWHERE status = 'PENDING', and PostgreSQL's B-treeLP_DEADhint bits mark its dead index entry on the very first scan so subsequentLIMIT 200queries skip it in memory without waiting forVACUUM.Making
executeandcancelPayment100% race-freeBoth paths lock the
scheduled_paymentrow on the same shard and evaluateexecute_atagainst that shard's database clock (now()), eliminating clock skew between API and worker machines:-- Path A: Executor Worker transaction BEGIN; SELECT status FROM scheduled_payment WHERE payment_id = :pid AND execute_at = :ex FOR UPDATE; -- If status <> 'PENDING', another worker or a prior cancel already finished it -> COMMIT & skip! SELECT balance, status FROM account WHERE account_id = :acct FOR UPDATE; -- Branch 1 (ACTIVE and balance >= :amt): -- debit account, insert ledger_entry (source_ref = 'sched:' || :pid), -- upsert account_outgoing (+:amt), set status = 'SUCCEEDED', insert payment_attempt & outbox. -- Branch 2 (insufficient funds or FROZEN): -- leave account & outgoing untouched, set status = 'FAILED', reason = :why, -- insert payment_attempt & outbox. COMMIT; -- Path B: API cancelPayment transaction BEGIN; UPDATE scheduled_payment SET status = 'CANCELLED', reason = 'CUSTOMER', finished_at = now() WHERE payment_id = :pid AND account_id = :acct AND status = 'PENDING' AND execute_at > now(); -- If 1 row updated: insert payment_attempt ('CANCELLED') + outbox ('payment.cancelled'), COMMIT -> 200 OK. -- If 0 rows updated: COMMIT, SELECT row to distinguish 404 vs. 409 NOT_PENDING vs. 409 ALREADY_DUE.Look at why
AND execute_at > now()incancelPaymentis magic: even if the midnight burst puts the executor worker 4 minutes behind at00:04:00, a user callingcancelPaymentat00:01:00for a00:00:00payment gets409 ALREADY_DUE—matching the single-node oracle regardless of worker lag!Handling hot payroll accounts inside a lane: within a single lane, the worker can run different accounts concurrently (up to say 8 accounts in flight) as long as all due payments for the same
account_idexecute sequentially in a single per-account queue, preventing one corporate account with 50,000 payments from stalling neighbors in its lane.Deep dive 2: persisting success vs. failure and handling retries
Durably recording both successful and failed runs requires separating business failures from transient infrastructure errors:
Condition Classification Database state & customer visibility -------------------------------- --------------------- ---------------------------------------------------- Active account, balance >= amt Business SUCCESS status = SUCCEEDED, ledger debited, push notification Active account, balance < amt Business FAILURE status = FAILED (INSUFFICIENT_FUNDS), 0 moved, push Account status = FROZEN Business FAILURE status = FAILED (ACCOUNT_FROZEN), 0 moved, push DB deadlock / timeout / failover Infrastructure ERROR Transaction ROLLS BACK! Row stays PENDING; invisible exponential-backoff retry (100 ms -> 5 s)- Why mixing the two is disastrous: marking a database timeout as
FAILEDfalsely tells a customer with$10,000in their account that their rent payment bounced; conversely, retryingINSUFFICIENT_FUNDSin a tight loop hammers the database millions of times without ever succeeding. - Poison-account isolation: if a bug causes 10 consecutive transaction aborts on one specific payment, we cannot skip just that one payment and run the account's next payment (that would violate per-account creation order!). Instead, the worker temporarily parks that entire
account_idfor 60 seconds, pages on-call, and keeps draining every other account in the lane. - Exactly-once downstream effects: the transactional outbox (writing the outgoing Kafka message in the same SQL commit as
SUCCEEDED/FAILED) guarantees at-least-once delivery. Notification consumers deduplicate on(payment_id, outcome)so a customer never receives duplicate"Payment failed"texts.
- Why mixing the two is disastrous: marking a database timeout as
Deep dive 3: outgoing-loss report and removing obsolete payments
1. Fast, exact outgoing-loss reports across 16 shards
Because
account_outgoing(total_out,payment_count) is updated inside the exact same local SQL transaction as every immediate payment and everySUCCEEDEDscheduled payment, each shard'sidx_outgoing_rank (total_out DESC, account_id ASC)is always 100% consistent with the ledger.To fetch the global top
Naccounts across 16 shards without scanning 20 million rows, use scatter-gather k-way merge: any account in the global topNmust also sit in the topNof its own shard! QueryLIMIT Non all 16 shards in parallel (16 x 100 = 1,600tiny rows) and merge them in sub-millisecond time:Shard 0 top 2: [("acc_12", $98,500), ("acc_44", $91,000)] \ Shard 1 top 2: [("acc_07", $99,200), ("acc_19", $85,000)] +--> heapq.merge -> Global top 2: ... / 1. ("acc_07", $99,200) Shard 15 top 2: [("acc_03", $94,100), ("acc_88", $80,000)] / 2. ("acc_12", $98,500)import heapq from typing import Iterable, List, Tuple def merge_shard_top_n( shard_rankings: List[Iterable[Tuple[int, str]]], limit: int ) -> List[Tuple[str, int]]: """Merge pre-sorted (-total_out, account_id) streams from each shard into global top `limit`.""" top_rows: List[Tuple[str, int]] = [] for neg_total, account_id in heapq.merge(*shard_rankings): top_rows.append((account_id, -neg_total)) if len(top_rows) == limit: break return top_rowsFor time-windowed reports (
?window=30d), a single running counter cannot subtract 31-day-old payments on the fly. Streampayment.succeededevents from Kafka into a columnar OLAP store (such as ClickHouse, which stores each column contiguously on disk for fast aggregations), deduplicated bypayment_id, where summing 30 days of integer amounts takes < 1 second and common windows (24h,7d,30d) are pre-materialized every minute.2. Removing obsolete payments without table bloat
Never run
DELETE FROM scheduled_payment WHERE status <> 'PENDING' AND finished_at < now() - INTERVAL '90 days'on 100 million rows—massDELETEs generate gigabytes of write-ahead log, replication lag, and fragmented B-tree pages. Instead:- Instant queue exit: updating
statusaway from'PENDING'immediately removes the row from the partial indexidx_due_by_lane. - Account closure:
close_accountlocks theaccountrowFOR UPDATE(blocking concurrent executions) and runs one shard-localUPDATE scheduled_payment SET status = 'CANCELLED', reason = 'ACCOUNT_CLOSED' WHERE account_id = :acct AND status = 'PENDING'. - Zero-bloat monthly partition drops: because
scheduled_paymentis range-partitioned byexecute_atmonth, once a month is > 90 days in the past, an archiver verifiesCOUNT(*) FILTER (WHERE status = 'PENDING') = 0(paging an engineer if a stuck row exists!), exports the partition to S3 Parquet with row-count and sum checksums, runsALTER TABLE scheduled_payment DETACH PARTITION ... CONCURRENTLY, and drops the partition as an instant metadata operation. Lookups for > 90-day-old payment IDs fall back transparently to the S3 archive, andledger_entryis never deleted.
- Instant queue exit: updating
Scaling, failure recovery, testing, and trade-offs
Capacity math and failure modes
- 1st-of-the-month throughput:
10,000 executions/sacross 16 PostgreSQL shards is~625 txns/sper shard—comfortable on NVMe instances when benchmarked to >= 1,500 txns/s (2x headroom). Pre-warm buffer caches for the upcoming monthly partition at 23:50, and send proactive"Low balance for tomorrow's scheduled payment"alerts 24 hours ahead to cut failed runs and delight users. - Crash recovery:
- Worker crashes mid-transaction: Postgres rolls back; the 15-second lane lease expires; another worker increments
epochand resumes from the partial index. - Primary DB shard fails: synchronous cross-AZ standby promotes with zero lost commits (
RPO = 0);Idempotency-KeyandUNIQUE(source_ref)absorb all client/worker retries safely.
- Worker crashes mid-transaction: Postgres rolls back; the 15-second lane lease expires; another worker increments
- Oracle-driven verification: fuzz-test the distributed service with thousands of randomized
schedule,cancel,deposit,pay_immediate,close_account, and clock-advance steps, asserting that every balance, payment status, failure reason, andreport_outgoing_by_lossoutput matchesBankingPaymentSystembit-for-bit.
Summary of key trade-offs
- Hashed lanes vs.
SKIP LOCKEDglobal queue: adds lease coordination and hot-account isolation logic, in exchange for strict per-account(execute_at, creation_seq)fairness at 10,000 txns/s. - Strict
execute_at > now()cancel cutoff vs. "cancel until worker touches row": makes cancellation deterministic and independent of worker lag, even during midnight bursts. - In-transaction
account_outgoingupsert vs. async Redis leaderboard: adds one row update per succeeded payment, in exchange for zero drift between the report and the ledger. - Monthly partition detach/drop vs. row-by-row TTL deletes: coarsens hot retention to 1-month buckets, in exchange for zero vacuum storms or replication lag.
- 1st-of-the-month throughput:
Intuition & how it works
Think of a banking payment scheduler like a post-dated check vault organized into numbered conveyor lanes, paired with a permanent ink ledger and a live spending scoreboard: when a customer schedules a payment for the 1st of next month, we place a numbered ticket into their account's lane sorted by due time. Before execute_at arrives, the customer can pull that ticket back (cancelPayment), stamping it "CANCELLED" so an audit trail remains. Once the clock hits execute_at, a single dedicated worker for that lane processes due tickets in exact creation order—either subtracting the cash, recording a ledger line, and bumping the account's outgoing scoreboard ("SUCCEEDED"), or stamping "FAILED: INSUFFICIENT_FUNDS" without moving a cent. Months later, whole trays of old finished tickets are boxed into cold archive storage and lifted off the shelf in one motion, keeping the active vault lean.
Why do naive designs break down here? First, running a standard parallel worker pool with SELECT ... FOR UPDATE SKIP LOCKED over one shared queue lets two workers grab two simultaneous payments for the same account out of order, so a later-created payment steals the last $90 meant for an earlier-created rent payment. Second, letting cancelPayment succeed whenever status == 'PENDING' (without checking execute_at > now()) makes cancellation a race against worker lag during midnight bursts. Third, deleting expired historical rows with DELETE FROM scheduled_payment locks tables and bloats indexes at 100 million payments per month, while computing the top-outgoing report via SELECT account_id, SUM(amount) ... GROUP BY account_id scans hundreds of millions of rows on every query.
Walk through a concrete trace on account "acct_7" (starting balance $150, or 15000 integer cents) across all four features:
1. Schedule three payments:
t = 5: schedule("acct_7", $90, delay=15) -> payment1 (seq=1, due at t=20)
t = 8: schedule("acct_7", $80, delay=12) -> payment2 (seq=2, due at t=20)
t = 9: schedule("acct_7", $40, delay=25) -> payment3 (seq=3, due at t=34)
2. Cancel before due time (t = 14 < 34):
cancelPayment(14, "acct_7", "payment3") -> True! payment3 becomes CANCELLED (kept in history, skipped at t=34).
3. Tie-break execution + boundary cancel at t = 20:
Caller invokes cancelPayment(20, "acct_7", "payment1"). Because t=20 >= execute_at (20), due items run FIRST:
- (due=20, seq=1) payment1: $150 >= $90 -> SUCCEEDED! balance = $60, outgoing["acct_7"] = $90.
- (due=20, seq=2) payment2: $60 < $80 -> FAILED (INSUFFICIENT_FUNDS)! balance stays $60, outgoing stays $90.
Now cancelPayment checks payment1 -> already SUCCEEDED -> returns False (409 Conflict).
4. Outgoing-loss report & obsolete cleanup:
- report_outgoing_by_loss(t=21) reads pre-aggregated outgoing["acct_7"] -> [("acct_7", $90)].
- At t = 90 days + 34, purge_obsolete archives & drops that month's finished payment1/2/3 partition,
while keeping "acct_7"'s ledger entries and $90 outgoing total intact.
Key trade-offs
- Hashed execution lanes (
hash(account_id) % 1024) vs. a singleSKIP LOCKEDqueue. Assigning each account to one leased lane guarantees that all due payments of one account execute sequentially in(execute_at, payment_id)order while still letting 64 workers drain 10,000 payments/s across 16 PostgreSQL shards (horizontal database partitions split byaccount_id). The cost is maintaining 15-second worker leases with a fencing token (epoch, an ownership counter incremented whenever a lane changes worker) and running distinct accounts concurrently within a lane so one bulk payroll account cannot stall neighbors. - Strict
execute_at > now()cancellation rule vs. "cancel until worker executes". Enforcingexecute_at > now()against the shard's database clock makes behavior 100% deterministic even if workers lag by minutes during the00:00 ET1st-of-the-month spike, matching a single-threaded reference oracle. Allowing cancellation right up until execution feels slightly more forgiving during lag, at the cost of non-deterministic race conditions. - Lazy deletion + partial index vs. eager queue deletion. In an in-memory min-heap (a priority queue whose earliest due item sits at index
0), marking a cancelled paymentCANCELLEDinO(1)time (lazy deletion) and skipping it when popped is much simpler than maintaining a custom indexed heap, provided periodic compaction clears dead entries. In PostgreSQL, a partial index (WHERE status = 'PENDING') gives automatic queue removal the momentstatuschanges toSUCCEEDED,FAILED, orCANCELLED. - Business failure (
FAILED) vs. transient infrastructure error (rollback + retry). Insufficient funds or a frozen account commitsstatus = 'FAILED'with a visible reason and zero money moved; a database deadlock or failover rolls back the transaction cleanly so the row staysPENDINGand retries invisibly with backoff. Blurring the two either spams customers with fake failure alerts during brief hiccups or retries empty accounts forever. - In-transaction
account_outgoingaggregate vs. asynchronous streaming leaderboard. Updatingaccount_outgoinginside the same SQL transaction as the balance debit adds one local row write per succeeded payment, in exchange for lifetime rankings that never drift from the ledger and answer via fast scatter-gather (fetching the topNfrom each of the 16 shards'idx_outgoing_rankindexes and merging those 16 short sorted lists). Time-windowed reports (last 30d), whose totals shrink as old days roll off, go to a columnar OLAP store (such as ClickHouse) fed via a transactional outbox (events written in the payment transaction and relayed to Kafka). - Monthly range-partition drops vs. row-level
DELETEjobs. Partitioningscheduled_paymentbyexecute_atmonth lets an archiver export > 90-day-old finished partitions to S3 Parquet and drop the table partition in milliseconds with zero index bloat, trading exact daily retention granularity for rock-steady database performance.
Common mistakes
- Checking status before locking (
SELECT statusthenUPDATE) incancelPaymentorexecute. Without acquiring the row lock (SELECT ... FOR UPDATEor an atomicUPDATE ... WHERE status = 'PENDING' AND execute_at > now()), a payment can be both cancelled and debited in the same millisecond! - Advancing a
(execute_at, payment_id) > (:last_ex, :last_pid)cursor watermark across SQL polls. PostgreSQL sequences hand out IDs before transactions commit, sopayment_id = 49can commit 2 ms afterpayment_id = 50; a> 50filter permanently skipspayment_id = 49! Always poll from the head of theWHERE status = 'PENDING'partial index, where PostgresLP_DEADhint bits skip recently finished entries in memory. - Breaking ties lexicographically on string IDs (
"payment10" < "payment2"). Always sort and break ties on a numeric creation sequence (seqor monotonicBIGINTpayment_id), and advance shard sequences (setval) before migrating lanes between shards. - Skipping a single poison payment while continuing with that same account's later payments. If
payment1aborts repeatedly on a bug and the worker skips it to runpayment2,payment2spends the balance out of order; park the entireaccount_idtemporarily while continuing other accounts in the lane. - Counting
FAILEDorCANCELLEDpayments in the outgoing total, or failing to persist failure records. Failed runs move zero money (sooutgoing_totalsmust not change), yet theFAILEDrecord and itsreasonmust remain queryable so customers know why their bill went unpaid. - Comparing API server wall clocks against worker wall clocks. Clock drift of even 200 ms breaks the due-vs-cancel boundary; evaluate both
execute_at <= now()andexecute_at > now()using the owning database shard'snow(). - Purging
ledger_entryrows alongside obsoletescheduled_paymentrows, or using floating-point numbers for money. Operational schedule rows expire to cold storage after retention; accounting ledger entries stay forever, stored strictly as integer minor units.
Follow-up questions
- How would you support recurring payment rules such as paying rent on the first of every month in the user's local time zone? Add a
recurring_ruletable storing the recurrence schedule (RRULE), the customer's IANA time zone (such as'America/New_York', so daylight-saving transitions never shift 9:00 AM by an hour),next_occurrence_at, andstatus, while materializing only the single next upcomingscheduled_paymentrow at a time. Inside the exact same SQL transaction that finishes occurrencek(SUCCEEDEDorFAILED), compute and insert occurrencek + 1. Skipping a single month cancels just that pendingscheduled_paymentrow while spawning next month's occurrence; stopping the series setsrecurring_rule.status = 'CANCELLED'and cancels the one pending row—avoiding inserting and later deleting hundreds of future rows per user. - What changes when scheduled payments settle over asynchronous external rails like ACH, wire, or stablecoin transfers? Split execution into two phases so no database lock is ever held across an external network call: at
execute_at, lock the account, transfer the amount into an internaloutbound_clearingholding account, transitionPENDING -> SUBMITTED, and invoke the external rail usingpayment_idas the outbound idempotency key. When the rail's settlement file or webhook confirms completion, transitionSUBMITTED -> SUCCEEDEDand incrementaccount_outgoing(keepingtotal_outmonotonic so scatter-gather pagination cursors stay stable); if the rail rejects the transfer, transitionSUBMITTED -> FAILEDand return the funds fromoutbound_clearingto the customer's balance. - How can you prevent one corporate payroll account with 100,000 due payments from starving other accounts on the same worker? Running 100,000 sequential 5 ms transactions for a single account takes over 8 minutes; to prevent that one account from blocking ~6,000 consumer accounts sharing its lane, the lane worker maintains per-account sub-queues (at most one active transaction per
account_id, running up to 8 distinct accounts concurrently per lane) and routes high-volume treasury accounts to dedicated single-tenant lanes. At the API layer, also expose aPOST /v1/payment-batchesendpoint that performs one atomic lump-sum debit from the payer and fans out 100,000 independent recipient credits in parallel.
Follow-up questions
- How would you support recurring payment rules such as paying rent on the first of every month in the user's local time zone?
- What changes when scheduled payments settle over asynchronous external rails like ACH, wire, or stablecoin transfers?
- How can you prevent one corporate payroll account with 100,000 due payments from starving other accounts on the same worker?
Similar questions
- Flight Fare Aggregation and Search System
- Versioned In-Memory Store with Field TTL and Snapshots
- Tracing and Cutting Duplicate HTTP Calls in curl Clients
- Recovering Lost Time During a Pair-Programming Session
- Four-Stage Account Ledger and Payment Engine
- Minimum-Cost Flight Route With Departure Window
More Circle interview questions
- In-Memory Recipe CRUD Store Hard
- Recovering Lost Time During a Pair-Programming Session Medium
- Flight Fare Aggregation and Search System Hard Pro
- Versioned In-Memory Store with Field TTL and Snapshots Hard Pro
- Four-Stage Account Ledger and Payment Engine Medium Pro
- Minimum-Cost Flight Route With Departure Window Medium Pro
- Ledger Service With Activity Leaderboard and Time-Limited Holds Medium Pro
- Tracing and Cutting Duplicate HTTP Calls in curl Clients Medium Pro
- Half-Open UTC Timestamp Filtering on Flight Bookings Medium Pro