KatInterview

Thread-Safe Ledger for Courier Payouts and Client Invoices

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencyhash-mapincremental-aggregation

Last 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

  1. record_delivery(delivery_id, driver_id, company_id, amount_cents) Registers a completed delivery. If delivery_id was recorded before, the new call replaces the earlier record.
  2. get_driver_total(driver_id) Returns the sum of amounts currently attributed to that driver.
  3. 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.