Building a Reliable Future-Dated Money Transfer Scheduler
System DesignModel answerLast updated
Design a service that fires transfers at a chosen future time, moves money atomically between accounts, and skips any transfer whose source balance is too low at that moment.
Problem
Design a feature that lets users register a money transfer to take place at a specific moment in the future. When that moment arrives, the system must carry out the transfer, adjust the balances of both accounts involved, and not carry it out if the paying account lacks enough funds at that time.
What to cover
In your answer, walk through:
- Requirements and assumptions. Functional behavior, the meaning of "on time", ordering rules, and expected scale including bursts.
- API and data model. How transfers are created, cancelled and listed, and how money and state are stored.
- Architecture. How the system notices that a transfer is due and how it gets executed.
- The execution step. How you guarantee each transfer runs once, balances stay correct, and an insufficient balance results in a skip rather than a partial or overdrawn payment.
- Failure modes and trade-offs. Worker crashes, duplicate triggers, cancel-versus-execute races, load spikes, and accounts living on different shards.
- Validation and rollout. How you would test and release this safely.
If you want an extra challenge, describe how you would implement a simplified single-process version where every operation carries a timestamp and all transfers due at or before that timestamp must be processed before the operation itself.
Hints
Hint 1
Split the problem into two parts: something that decides when a transfer becomes due, and something that moves the money correctly. Most correctness lives in the second part.
Hint 2
Make the state change itself the guard: a conditional update that only succeeds if the transfer is still in its initial state means duplicates and races become harmless no-ops.
Hint 3
Combine the balance check and the debit into one conditional statement, and lock accounts in a consistent order to avoid deadlocks. For a simulated clock, a min-heap ordered by due time plus a sequence number gives deterministic processing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Treat this as two cooperating pieces:
- Scheduler: decides when a transfer fires.
- Transfer engine: decides how money moves, atomically and exactly once.
Most of the value in an answer is correctness (exactly-once, atomic balance changes, defined behavior on insufficient funds), not exotic infrastructure.
Requirements
Functional
schedule(source, target, amount, execute_at, idempotency_key)returns apayment_id.- At
execute_at, debit and credit in one atomic step. - If the source balance is below
amountat execution time, skip: no partial payment, no overdraft. Mark itSKIPPEDand notify the user. A check at scheduling time is meaningless because balances change. - Users can cancel a pending transfer and list their pending ones.
Clarifications to state
- A skip is terminal; retry-on-skip can be added later as a policy.
- Ties at the same timestamp are ordered by
(execute_at, created_seq)so outcomes are deterministic when one transfer affects the next one's funds. - Recurring transfers are an extension: after a run, create the next occurrence.
Non-functional
- Exactly-once effect: never twice, never silently lost.
- "Exactly on time" realistically means never early, never missed, bounded lateness (for example under 1 second).
- Conservation of money: total balance never changes.
Scale: assume 10M transfers per day, about 115 per second on average, but with bursts (midnight, month start, payday) of perhaps 100x, around 10k per second for minutes. Roughly 200 B per row gives about 2 GB per day, so keep pending rows in a hot table and archive finished ones.
API
POST /payments/scheduled {source, target, amount, currency, execute_at_utc, idempotency_key}
DELETE /payments/scheduled/{id} -> CANCELLED (only if still SCHEDULED)
GET /accounts/{id}/scheduled -> list with statuses
The idempotency key stops client retries from creating duplicates. Store all times in UTC and convert only at the edges.
Data model
accounts(id, balance BIGINT in minor units, version, updated_at)scheduled_payments(id, source_id, target_id, amount, execute_at, status, created_seq, attempt_count, failure_reason, idempotency_key UNIQUE)with index on(status, execute_at)ledger_entries(id, payment_id, account_id, delta, created_at), append-only double entry
Statuses: SCHEDULED, EXECUTING, COMPLETED, SKIPPED, CANCELLED. Money is always integer minor units, never floats.
Architecture
- API service validates and inserts
SCHEDULEDrows. - Dispatcher finds due work:
- Polling query:
WHERE status='SCHEDULED' AND execute_at <= now() ORDER BY execute_at, created_seq LIMIT N FOR UPDATE SKIP LOCKED. - For precision, a pre-loader pulls the next minute's transfers into an in-memory timer wheel or delay queue so they fire within milliseconds.
- The DB poll remains as a safety net after crashes.
- Polling query:
- Workers run the transfer transaction. Partition by
hash(source_id)so one account's transfers are handled in order by one worker. - Notifier reads
COMPLETED/SKIPPEDevents from a transactional outbox.
Kafka delay topics or Redis sorted-set buckets can serve as triggers, but the database row is the source of truth; the queue only nudges.
The execution transaction
Everything happens in one DB transaction:
-- 1. Claim (exactly-once guard)
UPDATE scheduled_payments SET status='EXECUTING'
WHERE id=:pid AND status='SCHEDULED'; -- 0 rows => stop
-- 2. Lock both accounts in fixed order to avoid deadlock
SELECT id FROM accounts WHERE id IN (:a,:b) ORDER BY id FOR UPDATE;
-- 3. Conditional debit
UPDATE accounts SET balance = balance - :amt
WHERE id=:src AND balance >= :amt;
-- 0 rows => mark SKIPPED (INSUFFICIENT_FUNDS), write outbox event, COMMIT
-- 4. Credit target, write two ledger rows, mark COMPLETED, write outbox event, COMMIT
Why it is correct:
- Exactly once: only one worker can flip
SCHEDULEDtoEXECUTING; duplicate triggers become no-ops. - Crash safety: a crash before commit rolls back, leaving
SCHEDULED, so it is picked up again. - No overdraft: the check and the debit are a single statement, so there is no window for the balance to change in between.
- Cancel vs. execute: cancel is also a compare-and-set on
status='SCHEDULED'; whichever commits first wins. - Cross-shard accounts: use a saga (debit with reservation, credit, compensate on failure), or keep balances in one consistently sharded ledger service. Trade-off: saga adds complexity and temporary intermediate states; a single ledger limits horizontal scaling.
Handling bursts
- Pre-load and shard by time bucket and by account hash.
- Scale workers horizontally;
SKIP LOCKEDlets them share a queue without contention. - Apply backpressure and monitor lateness (now minus
execute_at) as the main SLO metric.
Simulated-clock variant
When each operation carries a timestamp, first process everything due at or before t, then handle the operation. Use a min-heap on (execute_at, seq):
import heapq, itertools
class Bank:
def __init__(self):
self.bal = {}
self.heap = [] # (execute_at, seq, pid)
self.payments = {}
self.seq = itertools.count()
def _process_due(self, t):
while self.heap and self.heap[0][0] <= t:
_, _, pid = heapq.heappop(self.heap)
p = self.payments[pid]
if p["status"] != "SCHEDULED":
continue # cancelled
if self.bal.get(p["src"], 0) >= p["amt"]:
self.bal[p["src"]] -= p["amt"]
self.bal[p["dst"]] = self.bal.get(p["dst"], 0) + p["amt"]
p["status"] = "COMPLETED"
else:
p["status"] = "SKIPPED"
def schedule(self, t, pid, src, dst, amt, at):
self._process_due(t)
self.payments[pid] = dict(src=src, dst=dst, amt=amt, status="SCHEDULED")
heapq.heappush(self.heap, (at, next(self.seq), pid))
def cancel(self, t, pid):
self._process_due(t)
p = self.payments.get(pid)
if p and p["status"] == "SCHEDULED":
p["status"] = "CANCELLED"
return True
return False
Complexity: each schedule or execution costs O(log n); cancel is O(1) via lazy deletion.
Testing and rollout
- Unit and property tests: total money conserved, no negative balances, each payment reaches one terminal state.
- Fault injection: kill workers mid-transaction, duplicate triggers, delayed clocks.
- Concurrency tests: cancel racing with execute, many transfers from one account.
- Roll out behind a flag, start with small amounts or internal accounts, shadow-run against the ledger, and alert on lateness, stuck
EXECUTINGrows, and reconciliation drift.
Common mistakes
- Checking balance at schedule time only.
- Separate read-then-write balance checks (race condition).
- Using floats for money.
- Trusting the queue instead of the DB row as the source of truth.
- Locking accounts in inconsistent order, causing deadlocks.
- Promising literally zero-latency execution.
- Leaving tie-breaking undefined at identical timestamps.