Building a Reliable Earnings Pipeline for Gig Delivery Couriers
System DesignModel answerLast updated
Design a service that turns courier delivery lifecycle events into correct, auditable payouts, covering idempotency, ordering, time zones, data repair, and reconciliation.
Courier Payout Service
A delivery platform employs independent couriers. A Delivery service emits lifecycle events for every job, and a separate Payout service must turn those events into money owed to each courier.
Each event carries a courier ID, a job ID, a timestamp, and a status of accepted, fulfilled, or cancelled. Some simpler variants emit only accept and fulfill events.
Design the Payout service end to end and justify your choices in each area below.
- Interfaces. How does Delivery hand events to Payout (synchronous or asynchronous)? Define the event schema and the read API couriers use to see their earnings. What should that response include, and why?
- Pay rules. What is paid on each status, how do cancellations change pay, and which timestamp determines the period an earning belongs to? Explain how totals over a window and per-job breakdowns are computed.
- Time. How are timestamps represented? How do you handle time zones, daylight saving transitions, event ordering, and late or out-of-order events?
- Storage. Which tables, indexes, or in-memory structures support high write throughput, deduplication, lookups by courier and time range, and cheap recalculation?
- Idempotency and delivery guarantees. How do you avoid paying twice when the transport is at-least-once?
- Bad or missing data. Assume inputs are valid for the happy path, then explain how you detect and repair: a fulfill with no prior accept, an accept that never completes, duplicates, and out-of-order delivery.
- Batch vs. streaming. How do near-real-time earnings coexist with finalization at period close? How do you backfill and reconcile?
- Reliability. Cover retries, timeouts, circuit breakers, dead-letter queues, logging, and metrics.
- Consistency and operations. State your consistency guarantees, invariants you would check, monitoring and alerts, schema versioning and contract testing, and the trade-offs you accept.
If time allows, sketch the main classes and methods for event ingestion and payout calculation, plus the query API for a courier's earnings over a local-time pay period, including DST behavior.
Hints
Hint 1
Start with scale: a few million jobs a day is only hundreds to low thousands of events per second, so the difficulty is correctness and repair, not throughput.
Hint 2
Separate raw events (append-only, deduplicated by event ID) from derived state (a per-job state machine) and from money (an append-only ledger with a deterministic idempotency key per job and entry type).
Hint 3
Attribute pay to the event time of the terminal event, store everything in UTC, and convert local period boundaries with an IANA zone using half-open intervals so DST weeks are 167 or 169 hours.
Hint 4
Never mutate closed periods: corrections become reversal or adjustment entries in the current open period, and a reconciler compares against the Delivery source of truth to find stuck or missing jobs.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale
Functional: ingest lifecycle events, compute per-job earnings, let couriers query earnings (lifetime, per local pay period, per job), and pay out once per period.
Non-functional: correctness over latency (never double-pay, never silently drop pay), provisional earnings visible within seconds, and every number auditable and replayable.
Rough scale (state assumptions): about 5M jobs/day at 2-3 events each gives roughly 15M events/day, around 175/s average and 1-2k/s at peak. Reads are perhaps 10x writes and spike at dinner time and payday. This is modest; the hard parts are ordering, idempotency, and remediation.
2. Interfaces
Delivery to Payout is asynchronous via a log such as Kafka. A synchronous call would tie Delivery's availability to Payout, while a log gives buffering and replay for backfills. Partition by job_id so one job's events stay ordered per producer.
Event schema (Protobuf with a schema registry, backward-compatible changes only):
event_id(producer-generated, stable across retries),schema_versionjob_id,courier_id,type(ACCEPTED, FULFILLED, CANCELLED)event_time(UTC epoch millis, set at the source)cancel_reason(customer, merchant, courier-unassigned),offer_centson accept
Read API: GET /v1/couriers/{id}/earnings?periodStart=YYYY-MM-DD&periodEnd=YYYY-MM-DD, using local dates with the zone taken from the courier's market. The response returns the period window in UTC, a period status (OPEN, CLOSED, PAID), period total, lifetime total, paginated line items, and adjustments. Totals answer "what will I get", line items build trust and reduce support load, status signals whether numbers are provisional, and adjustments explain late corrections.
3. Pay rules
Version the rules (rule_version) so recalculation is reproducible.
| Situation | Effect |
|---|---|
| ACCEPTED | No pay; record courier and lock quoted offer_cents |
| FULFILLED | Pay the offer plus tips/adjustments |
| CANCELLED, customer or merchant fault, after accept | Partial pay per rate card |
| CANCELLED, courier unassigned | Zero |
| Cancel arriving after a paid fulfillment | Emit a REVERSAL entry, never edit the original |
Attribution: use the event time of the terminal event (fulfilled_at or cancelled_at), not ingestion time. A job accepted at 23:50 Sunday and fulfilled at 00:20 Monday belongs to Monday's period.
Calculation: period total is the sum of ledger amounts for the courier with effective_ts in [startUtc, endUtc). Lifetime total is a maintained running sum, verifiable against the ledger.
4. Time handling
- Store instants as UTC epoch millis; store the courier's IANA zone, not a fixed offset.
- Convert local
[start 00:00, end 00:00)to UTC using a zone library. DST weeks naturally become 167 or 169 hours. Half-open intervals avoid double counting at boundaries. - Do not trust arrival order. A per-job state machine merges by
event_time, so an early FULFILLED waits for its ACCEPTED. - Late events in an open period simply update it. After close (period end plus a grace window, say 48h), late events become ADJUSTMENT entries in the current open period. Closed periods stay immutable.
5. Data model
raw_events(event_id PK, job_id, courier_id, type, event_time, ingested_at, payload, schema_version): append-only audit log and replay source; the PK dedups.job_state(job_id PK, courier_id, status, accepted_at, fulfilled_at, cancelled_at, offer_cents, version): optimistic concurrency onversion.ledger_entries(entry_id PK, idempotency_key UNIQUE, courier_id, job_id, entry_type, amount_cents, effective_ts, rule_version, created_at)with index(courier_id, effective_ts): append-only.period_summary(courier_id, period_id, total_cents, status): materialized read model.payouts(payout_id, courier_id, period_id UNIQUE, amount_cents, status, processor_idempotency_key).
Money is integer cents. Relational storage such as Postgres sharded by courier_id is enough at this scale and gives transactions.
6. Idempotency and delivery semantics
Exactly-once transport is not realistic; build at-least-once delivery plus idempotent processing:
- Insert into
raw_eventswithON CONFLICT DO NOTHING. If it was a duplicate, ack and stop. - In one DB transaction, update
job_stateand insert ledger entries with a deterministic key such ashash(job_id, entry_type, rule_version). - Commit the transaction, then commit the consumer offset. A crash between them causes redelivery, which the unique constraints absorb.
The ledger key means a job can yield at most one EARNING even if a producer re-emits with a new event_id. Outbound payouts use period_id UNIQUE plus the processor's idempotency key, so retries are safe.
7. Bad and missing data
| Case | Detection | Remediation |
|---|---|---|
| FULFILL without ACCEPT | fulfilled_at set, no accepted_at | Hold as pending; after about 1h query Delivery's source of truth; pay if confirmed, else alert and queue for manual review |
| ACCEPT never completes | Open state older than SLA (e.g. 6h) | Reconcile against Delivery, synthesize the missing event tagged source=RECONCILER; pay nothing until resolved |
| Duplicates | event_id or idempotency-key conflict | Drop and count in a metric |
| Out of order | event_time regressions | State machine; invalid transitions (FULFILL after CANCEL) go to review |
| Corrupt or schema-invalid | Deserialization/validation failure | Dead-letter queue with replay tooling |
8. Streaming, batch, backfill
Streaming yields provisional earnings in seconds. A nightly batch job compares per-job counts and amounts between the Delivery warehouse and the ledger, flagging missing jobs, amount mismatches, and stuck states. At period close, a finalization job freezes the period, computes the total from the ledger, and creates the payout row. Backfills replay raw_events through the same deterministic code path; idempotency keys make replays safe, and a rule-version bump produces adjustment entries rather than edits.
9. Reliability
- Retry transient DB and downstream errors with exponential backoff and jitter; set timeouts on every call.
- Circuit-break calls to Delivery's lookup API and the payment processor.
- Poison messages go to a DLQ after bounded retries, with alerts on DLQ depth.
- Wrap handler logic in try/catch at the message boundary, logging
event_id,job_id, and outcome, and emitting metrics for lag, dedup rate, DLQ rate, and pending-state age.
10. Consistency, monitoring, trade-offs
- Invariants: ledger sum equals
period_summary; at most one EARNING per job; no payout for an open period; payout amount equals ledger sum at close. - Alerts: consumer lag, spike in synthesized events, reconciliation drift above a threshold, and payout failures.
- Contracts: schema registry with compatibility checks and consumer-driven contract tests.
- Trade-offs: reads are eventually consistent, so earnings are provisional until close; this buys decoupling and resilience. Immutable ledgers cost storage but give auditability. A grace window delays finality but captures most late data.
Common mistakes
- Attributing pay by ingestion time or by accept time.
- Relying on arrival order or on "exactly-once" claims.
- Mutating closed periods instead of appending adjustments.
- Using fixed UTC offsets or ignoring DST.
- Using floats for money.
- Paying on fulfill-without-accept without verification.