Building a Future-Dated Payment Scheduler with Safe Cancellation
System DesignModel answerLast updated
Design a service that stores payments for later execution, lets users check or cancel them while pending, and guarantees no duplicate charges despite retries, crashes and time-zone quirks.
You are asked to design a backend service for payments that run at a later date and time. A user picks a payee, an amount and a future moment; the platform must charge at that moment, exactly once, and let the user revoke the request as long as it has not started processing.
What to cover
- Requirements and scale. Functional and non-functional goals, plus a back-of-the-envelope estimate of volume, peak load and storage. Assume tens of millions of users and several million scheduled payments per day, with strong clustering around moments such as midnight or the first of the month.
- API. REST or gRPC operations to create a scheduled payment, read its status (and list a user's payments), and cancel it. Describe request fields, response codes and any headers needed for safe retries.
- Data model and indexes. Tables, state machine, and the indexes that make "what is due now?" and "show me my payments" fast.
- Execution pipeline. How due payments are found, handed to workers (scheduler, queue, worker fleet) and charged through an external payment gateway.
- Duplicate protection. How you prevent double charges across client retries, repeated queue deliveries and gateway timeouts.
- Cancel vs. execute race. What happens when a user cancels at nearly the same moment the payment starts.
- Time semantics. Time zones, daylight-saving gaps and overlaps, timezone database updates, clock drift and ordering.
- Failures. Retries, backoff, dead-letter handling, and what to do when the gateway outcome is unknown.
- Consistency with the gateway. Transactional guarantees and reconciliation.
- Security and compliance. Card data handling, encryption, PII, audit.
- Scale-out and resilience. Partitioning, high availability, disaster recovery.
- Operations. Monitoring, alerting, auditing, and the SLAs you would commit to.
State your assumptions and justify the main trade-offs.
Hints
Hint 1
Treat the database as the single source of truth and the queue as a mere carrier of work. Think about what happens to a month-away job if it lives only in a delay queue.
Hint 2
Model the payment as a state machine where each transition is a compare-and-set on status and version. Both the worker start and the cancel then compete for the same row, and exactly one wins.
Hint 3
Use a deterministic idempotency key (for example the payment id) for every gateway call, reused across retries, and design an explicit 'unknown outcome' state resolved by querying or reconciling with the gateway.
Hint 4
Store the user's local wall time plus IANA zone and derive the UTC instant; decide in advance how to handle nonexistent and ambiguous local times.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale
Functional: schedule a one-time payment, read status and list payments, cancel while pending, notify on outcome. Recurring payments are a later extension.
Non-functional:
- Never double charge. Correctness beats latency.
- Timeliness: about 99.9% of payments start within 60 s of their scheduled time.
- Availability: API 99.99%. Execution can be briefly late but must never be lost.
- Auditability: every state change recorded, kept around 7 years.
Estimates (assumptions): 10M payments/day is about 115/s on average. Scheduling is bursty, so assume 20% of a day lands in one minute: 2M / 60 ≈ 33K executions/s at peak. Design for that. Storage at about 1.5 KB per payment including attempts and audit gives roughly 10M × 1.5 KB × 365 × 7 ≈ 38 TB, so use hot/cold tiering. Reads are about 10× writes.
2. API
POST /v1/scheduled-paymentswith anIdempotency-Keyheader. Body: payee, amount in integer minor units, currency, a payment-method token (never a raw card number), local time and IANA zone. Returns201with id, status and the resolved UTC instant.GET /v1/scheduled-payments/{id}and a paginated list filtered by status.POST /v1/scheduled-payments/{id}:cancelreturns200if canceled,409if already processing or finished.
Cancel is a state transition, not a delete. A replay of a create with the same key returns the stored response; the same key with a different payload returns 422.
3. Data model
Use a strongly consistent sharded relational store (Spanner, CockroachDB, or sharded Postgres), sharded by user_id.
scheduled_payment: ids, amount, currency, token, local time, zone,execute_at_utc,status,version,attempt_count,next_attempt_at,gateway_ref, timestamps.payment_attempt: per-try record including the gateway idempotency key and response code.outbox: events written in the same transaction as state changes.audit_log: append-only, written in the same transaction.
Indexes: unique (user_id, idempotency_key); a due-work index (shard_bucket, status, execute_at_utc); (user_id, created_at DESC) for listing.
State machine: SCHEDULED → QUEUED → PROCESSING → SUCCEEDED | FAILED | UNKNOWN. Only SCHEDULED and QUEUED may go to CANCELED. Every change is UPDATE ... WHERE id=? AND status=? AND version=?.
4. Execution pipeline
- Scheduler: one leader per shard bucket (lease with fencing token). Each second it selects due rows (
execute_at_utc <= now()+30s,FOR UPDATE SKIP LOCKED, batch of ~1000), flips them toQUEUEDand writes outbox rows in one transaction. - Outbox relay publishes to Kafka partitioned by
payment_id, at-least-once. - Workers (stateless, autoscaled on lag): CAS
QUEUED → PROCESSING(if it fails, ack and drop), run fraud and limit checks, call the gateway with idempotency key =payment_id, then in one transaction write the result, attempt row, ledger entry and notification event.
Delay queues are a poor fit: they have limited maximum delay and make cancellation awkward. For peaks, pre-warm workers ahead of known hot minutes, rate-limit per gateway with a token bucket, and accept spreading a midnight burst across the SLA window.
5. Idempotency
- Client → API: the idempotency key as above.
- Queue → worker: duplicates are harmless because only one worker wins the CAS and terminal states are no-ops.
- Worker → gateway: a deterministic key reused on every retry, so a retry after a timeout cannot charge twice. This is the most important guarantee.
6. Cancel race
Cancel is UPDATE ... SET status='CANCELED' WHERE status IN ('SCHEDULED','QUEUED'). The worker's CAS targets the same row, so exactly one wins. If cancel wins, the worker drops the message; if the worker wins, cancel returns 409. A product cutoff such as one minute before execution makes the UI predictable.
7. Time semantics
Store intent (local time + IANA zone) and derive UTC.
- Nonexistent local time (spring forward): shift forward to the next valid time and show the resolved instant.
- Ambiguous local time (fall back): take the first occurrence.
- tzdata changes: a job recomputes
execute_at_utcfor future rows in affected zones. Recurring payments are computed from local rules, never by adding 24 h × n. - Clock drift: NTP/chrony with alerting above about 100 ms; use the database's time as the authority for "now".
- Ordering: partition by
payment_id; useuser_idif a user needs sequential payments.
8. Failure handling
- Transient (5xx, rate limit, network): exponential backoff with jitter (1 s, 4 s, 16 s … capped near 10 min, ~6 tries). Set
next_attempt_atand return the row toSCHEDULEDso the poller re-drives it and retries survive worker crashes. - Permanent (declined, insufficient funds):
FAILEDimmediately, notify, no retry. - Ambiguous timeout: move to
UNKNOWN, never blindly mark failed. Query the gateway by idempotency key, or retry with the same key, and reconcile against gateway settlement reports. Exhausted retries go to a dead-letter queue with a runbook and alerting.
9. Consistency with the gateway
A distributed transaction with an external gateway is impossible, so use the outbox pattern, deterministic idempotency keys and reconciliation. The local ledger is updated in the same transaction as the recorded gateway result; a daily (or more frequent) reconciliation compares ledger and gateway records and raises discrepancies.
10. Security and compliance
Tokenise cards through a PCI-compliant vault so the scheduler never sees PANs. Encrypt in transit (TLS) and at rest, with KMS-managed keys and field-level encryption for PII. Apply least privilege, authorise that the caller owns the payment, and keep immutable audit logs. Limit retention of PII and support deletion requests where law allows.
11. Scale, HA and DR
Shard by user_id; the scheduler, relay and workers scale independently per bucket. Replicate across at least three zones with automatic failover; for DR, replicate to a second region (RPO near zero with synchronous or consensus replication, RTO in minutes) and rehearse failovers. After failover, the idempotency design makes re-driving in-flight payments safe.
12. Monitoring and SLAs
Track scheduling lag (now minus execute_at_utc for unstarted rows), queue lag, success rate by gateway, count of UNKNOWN payments, DLQ depth, reconciliation mismatches and clock drift. Page on lag above SLA, a growing UNKNOWN backlog or reconciliation mismatches.
Common mistakes
- Using a delay queue as the only store.
- Generating a fresh gateway idempotency key per retry.
- Treating a timeout as a failure.
- Storing only UTC and losing user intent.
- Sizing for the average rather than the peak minute.
- Hard-deleting on cancel, which destroys the audit trail.