Thread-Safe Ledger for Courier Payouts and Client Invoices
Data Structure DesignModel answerLast updated
Design an in-memory, thread-safe ledger that upserts delivery records and serves instant per-courier earnings and per-client invoice totals in integer cents.
Courier Payout and Client Invoice Ledger
You are building the core of a billing component for a delivery marketplace. Completed deliveries stream in continuously, and the service must answer two questions immediately: how much has a given courier earned, and how much does a given client owe?
Everything lives in process memory. There is no database in scope for the core design, though you may discuss persistence at the end.
Required operations
record_delivery(delivery_id, driver_id, company_id, amount_cents)Registers a completed delivery. Ifdelivery_idwas recorded before, the new call replaces the earlier record.get_driver_total(driver_id)Returns the sum of amounts currently attributed to that driver.get_company_bill(company_id)Returns the sum of amounts currently attributed to that company.
Non-functional requirements
- The service must be safe under concurrent calls from many threads.
- Reads should complete in well under a millisecond.
- Money is held as integer cents. No floating-point arithmetic.
Scale
- Around 100,000 drivers and 1,000 companies.
- About 5,000 delivery events per second, with bursts of heavy concurrency at peak times.
Example
ledger = BillingEngine()
ledger.record_delivery("d1", "dr_1", "c_1", 500)
ledger.record_delivery("d2", "dr_1", "c_1", 300)
ledger.get_driver_total("dr_1") # 800
ledger.get_company_bill("c_1") # 800
Edge cases to address
- A delivery that was already recorded (and possibly already invoiced) is submitted again with different data.
- Empty identifiers and zero-amount deliveries.
What to deliver
Describe the data model and the API contract, justify your concurrency strategy, give working code, state time and space complexity, and discuss how the design would change if load grew substantially or if state had to survive restarts.
Hints
Hint 1
Avoid summing over all deliveries on every read. Think about keeping a running total per driver and per company, and adjusting it by a delta on each write.
Hint 2
To make re-recording a delivery correct, you need to remember what each delivery contributed previously, including which driver and company it was credited to. Reverse the old contribution, then apply the new one.
Hint 3
An update touches several maps in a read-modify-write sequence. Decide what must be atomic, and compare one global lock against striped locks or a single-writer queue given only ~5k writes per second.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first
- Upsert semantics. Re-recording an existing
delivery_idreplaces the old record. I would allow the driver or company to change too, since handling it costs almost nothing. - Validation. Reject empty or non-string IDs and non-integer amounts. Negative amounts are rejected in the base design (credits would be modelled as explicit adjustments). A zero amount is valid, for example a waived fee or promo. Unknown drivers or companies return
0. - Read consistency. Once a write returns, both the driver total and the company total must reflect it. A reader must never see only one of them updated.
- "Already billed". If invoices have been issued, silently rewriting totals is risky. I would ask what the business wants and cover that below.
Scale check. 5,000 events/s is one event per ~200 µs. A critical section of a couple of microseconds means a single lock is about 1% utilized. Raw history at ~100 bytes per event would be roughly 40 GB per day, so retention matters if every event is kept.
2. Data model
| Structure | Key | Value | Purpose |
|---|---|---|---|
deliveries | delivery_id | (driver_id, company_id, amount_cents) | Needed to compute deltas on update |
driver_totals | driver_id | int cents | O(1) reads |
company_totals | company_id | int cents | O(1) reads |
The core idea is incremental aggregation. Each write applies a delta, so reads are a single dictionary lookup.
- New delivery: add the amount to its driver and company.
- Existing delivery: subtract the stored amount from the previously stored driver and company, then add the new amount to the new driver and company. This handles amount changes and reassignment uniformly.
3. Implementation
import threading
from dataclasses import dataclass
@dataclass(frozen=True)
class _Record:
driver_id: str
company_id: str
amount_cents: int
class BillingEngine:
def __init__(self) -> None:
self._records: dict[str, _Record] = {}
self._driver_totals: dict[str, int] = {}
self._company_totals: dict[str, int] = {}
self._lock = threading.Lock()
@staticmethod
def _validate(delivery_id, driver_id, company_id, amount_cents) -> None:
for name, v in (("delivery_id", delivery_id),
("driver_id", driver_id),
("company_id", company_id)):
if not isinstance(v, str) or not v:
raise ValueError(f"{name} must be a non-empty string")
if not isinstance(amount_cents, int) or isinstance(amount_cents, bool):
raise TypeError("amount_cents must be an int")
if amount_cents < 0:
raise ValueError("amount_cents must be >= 0")
def record_delivery(self, delivery_id, driver_id, company_id, amount_cents) -> None:
self._validate(delivery_id, driver_id, company_id, amount_cents)
new = _Record(driver_id, company_id, amount_cents)
with self._lock:
old = self._records.get(delivery_id)
if old is not None:
self._driver_totals[old.driver_id] -= old.amount_cents
self._company_totals[old.company_id] -= old.amount_cents
self._records[delivery_id] = new
self._driver_totals[driver_id] = (
self._driver_totals.get(driver_id, 0) + amount_cents)
self._company_totals[company_id] = (
self._company_totals.get(company_id, 0) + amount_cents)
def get_driver_total(self, driver_id) -> int:
with self._lock:
return self._driver_totals.get(driver_id, 0)
def get_company_bill(self, company_id) -> int:
with self._lock:
return self._company_totals.get(company_id, 0)
Walking through the example: d1 (500) and d2 (300) both credit dr_1 and c_1, giving 800 each. If d1 is then re-recorded as 200, the old 500 is reversed and 200 added, so both totals become 500.
Complexity. Every operation is O(1) average time. Space is O(D + R + C) for deliveries, drivers and companies.
4. Concurrency
An upsert is a read-modify-write across three maps. If two threads upsert the same delivery_id simultaneously, both may read the same old record and both subtract it, permanently corrupting the totals. In CPython the GIL makes single dict operations atomic, but not this sequence. The lock also keeps driver and company totals in step, so a reader cannot see a half-applied write.
Why one lock is fine here. At 5k writes/s with microsecond critical sections, contention is negligible. It is simple and obviously correct. Stating this plainly is better than over-engineering.
If load grows 100x or the runtime has no GIL:
- Lock striping. Stripe by
delivery_idfor the record map, and use separate stripes or atomic adders for totals. Always acquire multiple locks in a fixed order to avoid deadlock. The cost is losing cross-map atomicity, so a reader might briefly see one total ahead of the other. That is acceptable for a dashboard but not for an invoice snapshot. - Single-writer queue. Producers enqueue events and one thread applies them without locks. This also yields an ordered log for persistence.
- Read-write lock. Useful only if reads dominate and critical sections are long, which is not the case here.
5. Updating an already-billed delivery
Clarify what "billed" means. If an invoice has been issued, mutating the open total is wrong. Add a settled flag or invoice ID per delivery, then either reject the update or book it as an adjustment (credit or debit) into the next invoice. The delta new - old computed by this design is exactly that adjustment amount.
6. Trade-offs and extensions
- Incremental vs. compute-on-read. Incremental totals give O(1) reads at the cost of a small write overhead and a risk of drift if there is a bug. Mitigate with a periodic reconciliation job that recomputes totals from
recordsand alerts on mismatch. - Memory. 100k drivers, 1k companies and a few million live deliveries fit comfortably in memory. For unbounded history, archive settled deliveries and keep only totals.
- Durability. In-memory state is lost on restart. Append each event to a write-ahead log (or Kafka topic) before applying it, and periodically snapshot. Recovery is snapshot plus log replay. Since upserts are idempotent per
delivery_id, replay is safe. - Scaling out. Shard by
company_idfor invoices. Driver totals then need either a second partitioning or an asynchronous rollup, which makes them eventually consistent. - Money. Integer cents avoid floating-point error. Use 64-bit integers in Java or Go. Multi-currency would require a currency field and per-currency totals.
7. Common mistakes
- Summing all deliveries on every read, which makes reads O(N).
- Adding the new amount on update without reversing the old one, which double counts.
- Reversing the old amount from the new driver or company instead of the stored ones.
- Using floats for money.
- Locking only the writes, or locking each map separately, which allows torn reads.
- Treating zero-amount deliveries as invalid, or empty IDs as valid.