Food Delivery Cost Dashboard
A corrected delivery arrives after an earlier aggregate was published.
Topic tools
Layout updated
Problem statement
Design a dashboard that tracks delivery labor costs. Operators can see how much deliveries cost across shifts and locations, using the rates that applied when the work was done.
Functional requirements
- Record completed deliveries and corrections.
- Calculate costs using the rate valid at delivery time.
- Show totals and an auditable correction history.
Non-functional requirements
- Show updated dashboard totals within about 5 s.
- Count each delivery version once and retain correction history.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 10M deliveries/day ≈ 116/s average; 10× peak ≈ 1.16k/s |
| 500 bytes/ledger entry × 10M ≈ 5 GB/day |
Entities
| Entity / logical owner |
|---|
| Delivery(deliveryId, eventVersion, driverId, start, end) |
| Rate(driverId, effectiveFrom, version, hourlyAmount, currency) |
| Ledger(entryId, deliveryId, version, amount, reversalOf) and Aggregate(, , total) |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/delivery-events {eventId, deliveryId, version, times} | Durable acceptance; repeated eventId returns original result. |
GET/costs?from=...&to=... | Total, currency, asOf and status. |
POST/corrections {deliveryId, expectedVersion, reason, correctedTimes} | Append reversal/new entry with audit identity; never silently edit settled history. |
High-level design
How to draw this design
- Accept delivery eventsDelivery sources, ingestion , and Kafka
- Calculate costCost worker and effective-rate lookup
- Record and projectPostgreSQL rate history, ledger, totals, and aggregate worker
- Report costsAccounting dashboard and applied cutoff
Read the effective rate, append the ledger entry, update partial totals, then serve the dashboard.
- State ownership
- The ledger and rate history are authoritative. Totals can be rebuilt from the ledger.
- Scale
- Split partial totals to avoid serializing all writes on one global row.
- Correctness
- Commit the financial entry and dedup identity together.
- Failure and recovery
- Replay from the last applied position and show the reporting cutoff while totals catch up.
Food Delivery Cost Dashboard
One PostgreSQL database per accounting contains rate history, the cost ledger, and dashboard totals. The calculator writes financial facts. The aggregate worker derives totals, and the dashboard reads them at a visible cutoff.
- Compute
- Messaging
- State
- Edge
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 8 flow steps
High-level design component walkthrough
Delivery Sources
Send completed deliveries / timestamps
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Late, duplicate, or corrected events
Connected operations: Send delivery or correction
Ingestion API
Validate delivery and driver identifiers
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Validation adds write path overhead
Connected operations: Send delivery or correction; Publish versioned event
Kafka: Delivery Events
Durably absorb delivery updates
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: Queue lag makes dashboard stale
Connected operations: Publish versioned event; Consume delivery event
Cost Calculator
Apply duration × hourly rate per delivery
Why, tradeoff and connected operations
Compute derived state away from request handlers; checkpoints and govern recovery.
Tradeoff: Rate changes require historical lookup
Connected operations: Consume delivery event; Read effective rate; Commit ledger and dedup
PostgreSQL: Rate History, Ledger and Totals
One database per accounting . Rate history and the ledger are authoritative. Dashboard totals are a rebuildable projection.
Why, tradeoff and connected operations
PostgreSQL commits a ledger entry and its record together. Effective-rate history and indexed totals support explainable dashboard calculations. fits accounting correctness; a separate analytical store is unnecessary until report volume justifies it.
Tradeoff: Separate read and write budgets so reporting does not starve ledger commits. A database outage can interrupt both paths. A projection lag or worker outage leaves ledger writes available.
Connected operations: Read effective rate; Commit ledger and dedup; Read committed ledger; Write partial totals; Read totals and cutoff
Aggregate Worker
Maintain total; correct reversals idempotently
Why, tradeoff and connected operations
Compute derived state away from request handlers; checkpoints and govern recovery.
Tradeoff: Hot global total; replay handling
Connected operations: Read committed ledger; Write partial totals
Accounting Dashboard
Read current total with freshness indicator
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Displayed total may be delayed
Connected operations: Read totals and cutoff
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Use the rate that applied when the work happened | Splitting work across rate changes adds calculation rules. Record the rate version so corrections and audits can reproduce the result. |
| Do not charge again when an event repeats | Explicit corrections add ledger rows, but preserve who changed the amount and why. Avoid replacing financial history without an audit trail. |
| Avoid one total row becoming the bottleneck | Versioned absolute totals are easier to replay than blind increments. They still need regular checks against the authoritative ledger. |
| What happens if a region fails? | Zero-loss regional ledger acceptance requires an appropriate remote durability barrier; asynchronous reporting is cheaper and can remain temporarily stale. |
Production scars & failure modes
A corrected delivery arrives after an earlier aggregate was published.
Look for: Compare event version, original ledger identity and aggregate revision.
Recovery and invariant: Record a correction or replacement with an auditable identity; rebuild or revise totals idempotently using the rate valid at event time.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Rate lookup missing | The worker cannot correctly price a delivery. | Park the event with an explicit unresolved status; retry after history is available. | Guessing a rate produces incorrect financial totals. |
| Worker crash after ledger commit | Input is replayed without a matching . | Unique delivery/version and transactionally stored dedup suppress duplicate entries. | Queue transport remains at least once. |
| Aggregate projection stalls | Dashboard totals become stale while the database and ledger writers stay healthy. | Replay committed ledger entries from the aggregate , or rebuild and publish a verified generation. | A shared PostgreSQL outage affects both paths. Reserve write capacity for the ledger and report the last applied cutoff. |
| Corrected duration or rate | Previously displayed total changes. | Append reversal and replacement, then project both idempotently and show revision. | Provisional reporting is fast; reconciled reporting uses an explicit cutoff. |
90-second interview summary
I would make the financial ledger the authority and treat dashboard totals as derived views. Delivery events enter a durable queue with stable delivery/version identities. A calculator resolves the rate and billable interval rule effective when the work occurred, not whatever rate happens to be current during replay.
In one PostgreSQL transaction, the worker records a unique processed-event identity and its ledger fact. If it crashes after commit but before acknowledgement, redelivery finds the existing result and adds no new charge. Corrections are explicit versions or compensating facts so the audit trail remains explainable.
A global total row would concentrate writes, so I would maintain bounded partial totals by accounting partition and period. Their durable applied positions allow retry-safe updates, and the dashboard sums partials at a visible cutoff. rebuilds a verified total generation from the ledger rather than blindly applying another increment.
Each accounting partition has one fenced write authority. Regional dashboard replicas can be stale, while ledger promotion must establish the committed history and declare any asynchronous replication loss window. I would watch duplicate suppression, unresolved rate intervals, aggregate lag and differences. The tradeoff is more ledger/projection state in exchange for auditable accounting and scalable reporting.
Explain it without looking
Explain use the rate that applied when the work happened
Reveal answer
Keep rate history and price each delivery interval using the agreed rule.
Using today's rate for a late event can change the charge every time it is replayed.
Splitting work across rate changes adds calculation rules. Record the rate version so corrections and audits can reproduce the result.
Explain do not charge again when an event repeats
Reveal answer
Commit the ledger entry and processed-event identity in one transaction.
Checking for a duplicate and then incrementing separately leaves a race that can count the same work twice.
Explicit corrections add ledger rows, but preserve who changed the amount and why. Avoid replacing financial history without an audit trail.
Explain avoid one total row becoming the bottleneck
Reveal answer
Update smaller totals and combine them for the dashboard.
Every unconditional update to one global row creates contention and makes duplicate increments difficult to repair.
Versioned absolute totals are easier to replay than blind increments. They still need regular checks against the authoritative ledger.
Explain what happens if a region fails?
Reveal answer
Recover the ledger before letting a new region change financial totals.
Ledger truth and reporting freshness are separate guarantees.
Zero-loss regional ledger acceptance requires an appropriate remote durability barrier; asynchronous reporting is cheaper and can remain temporarily stale.
Revision checklist
Revision checklist
- Reconstruct use the rate that applied when the work happened: Keep rate history and price each delivery interval using the agreed rule.
- Reconstruct do not charge again when an event repeats: Commit the ledger entry and processed-event identity in one transaction.
- Reconstruct avoid one total row becoming the bottleneck: Update smaller totals and combine them for the dashboard.
- Reconstruct what happens if a region fails?: Recover the ledger before letting a new region change financial totals.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope delivery cost, corrections, and dashboard freshness. Estimate event throughput and flag contention on a global total. |
| 15–30 min | High-level design | Trace a versioned delivery event through Kafka and the calculator to PostgreSQL. Show rate lookup, ledger writes, and derived totals. |
| 30–45 min | Deep dives | Explain which rate version prices a delivery and why ledger commits with the financial entry. |
| 45–55 min | Failure and recovery | Walk through a crash after ledger commit or a stale total. Replay from a and expose the last applied cutoff. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough