System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Food Delivery Cost Dashboard

A corrected delivery arrives after an earlier aggregate was published.

◐ MediumSystem 071 min2 prerequisites
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

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 / inputResponse 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

  1. Accept delivery eventsDelivery sources, ingestion , and Kafka
  2. Calculate costCost worker and effective-rate lookup
  3. Record and projectPostgreSQL rate history, ledger, totals, and aggregate worker
  4. 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.

Food Delivery Cost Dashboard
G driver->api 1. Send delivery or correction api->q 2. Publish versioned event q->worker 3. Consume delivery event worker->ledger 4. Read effective rate worker->ledger 5. Commit ledger and dedup ledger->agg 6. Read committed ledger agg->ledger 7. Write partial totals dash->ledger 8. Read totals and cutoff driver Delivery Sources compute api Ingestion API compute q → Kafka: Delivery Events messaging worker Cost Calculator compute ledger PostgreSQL: Rate History, Ledger and Totals state · durable agg Aggregate Worker compute dash Accounting Dashboard edge
  • Compute
  • Messaging
  • State
  • Edge

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

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

Backend service

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

Backend service

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

Queue / event stream

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

Stream / batch processing

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

Relational database

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

Stream / batch processing

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

Client / user

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.

Deep dive 1

Use the rate that applied when the work happened

Keep rate history and price each delivery interval using the agreed rule.

Read the explanation and worked example
How it works

Store rate versions with effective time ranges and specify which work intervals they price. Split a delivery interval if the business rule changes within it. The calculator records both the input event version and the rate version so the result can be explained later.

Walk through an example

A delivery starts before a rate increase and ends after it. Applying the latest rate to the whole interval can produce a different answer every time the job is replayed.

Failure and recovery

Keep historical rates immutable or version corrections explicitly. Reject overlapping ambiguous rate ranges and route unresolved cases to instead of silently guessing.

Why this helps

Using today's rate for a late event can change the charge every time it is replayed.

What you give up

Splitting work across rate changes adds calculation rules. Record the rate version so corrections and audits can reproduce the result.

Deep dive 2

Do not charge again when an event repeats

Commit the ledger entry and processed-event identity in one transaction.

Read the explanation and worked example
How it works

Choose a ledger identity such as delivery ID plus event version. In one transaction, insert the processed identity and corresponding financial fact, protected by a unique constraint. Repeated input returns the stored outcome rather than adding another charge.

Walk through an example

A worker commits five dollars of cost and crashes before committing its queue progress. The replay finds that same ledger identity and adds zero new dollars.

Failure and recovery

Corrections need their own version or compensating entry, not deletion of the audit trail. Test a crash before commit, after commit and after acknowledgement to show where duplicates are suppressed.

Why this helps

Checking for a duplicate and then incrementing separately leaves a race that can count the same work twice.

What you give up

Explicit corrections add ledger rows, but preserve who changed the amount and why. Avoid replacing financial history without an audit trail.

Deep dive 3

Avoid one total row becoming the bottleneck

Update smaller totals and combine them for the dashboard.

Read the explanation and worked example
How it works

A single global running-total row becomes a write bottleneck. Maintain partial totals by a bounded partition such as region and accounting period, and derive the dashboard by summing those partials. Keep durable processing positions or versions so retrying an update does not double-add it.

Walk through an example

A busy city contributes most deliveries. Hashing every update to one global total serializes otherwise independent ledger transactions.

Failure and recovery

Recompute partials from the ledger and publish a verified generation. Dashboard staleness is a separate promise from ledger correctness; expose the last fully applied cutoff.

Why this helps

Every unconditional update to one global row creates contention and makes duplicate increments difficult to repair.

What you give up

Versioned absolute totals are easier to replay than blind increments. They still need regular checks against the authoritative ledger.

Deep dive 4

What happens if a region fails?

Recover the ledger before letting a new region change financial totals.

Read the explanation and worked example
How it works

Choose one fenced ledger authority for each accounting partition. Replicate immutable financial facts and their applied cutoff; regional dashboards are projections that can be rebuilt, not independent places allowed to increment the same total.

Walk through an example

A standby is promoted before the last committed ledger entries have arrived.

Failure and recovery

Pause uncertain accounting acceptance or reconcile from durable evidence, then rebuild partial totals at a verified cutoff. Never guess missing charges by incrementing both regions.

Why this helps

Ledger truth and reporting freshness are separate guarantees.

What you give up

Zero-loss regional ledger acceptance requires an appropriate remote durability barrier; asynchronous reporting is cheaper and can remain temporarily stale.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Use the rate that applied when the work happenedSplitting 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 repeatsExplicit 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 bottleneckVersioned 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

Failure investigation

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 / failureImpactRecovery mechanismAlternative / tradeoff
Rate lookup missingThe 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 commitInput is replayed without a matching .Unique delivery/version and transactionally stored dedup suppress duplicate entries.Queue transport remains at least once.
Aggregate projection stallsDashboard 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 ratePreviously 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

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleScope delivery cost, corrections, and dashboard freshness. Estimate event throughput and flag contention on a global total.
15–30 minHigh-level designTrace a versioned delivery event through Kafka and the calculator to PostgreSQL. Show rate lookup, ledger writes, and derived totals.
30–45 minDeep divesExplain which rate version prices a delivery and why ledger commits with the financial entry.
45–55 minFailure and recoveryWalk through a crash after ledger commit or a stale total. Replay from a and expose the last applied cutoff.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.
On this page
  1. Problem statement
  2. Functional requirements
  3. Non-functional requirements
  4. Back-of-the-envelope estimates
  5. Entities
  6. API design
  7. High-level design
  8. High-level design component walkthrough
  9. Engineering control room
  10. Deep dives — decisions, failures and recovery
  11. Tradeoffs and alternatives
  12. Production scars & failure modes
  13. 90-second interview summary
  14. Explain it without looking
  15. Revision checklist
  16. 60-minute interview walkthrough

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram