KatInterview

Per-User Credit Ledger Ordered by Vector-Clock Expiry

System DesignModel answer
HardModel answerSystem Designvector-clocksidempotencyconcurrency-control

Last updated

Design a service that adds expiring credits and spends them earliest-expiry-first, where expiry and spend times are vector clocks that are only partially ordered.

You are building a credit ledger for a platform with a very large number of users. Each user receives credits that lapse at some point, and the user later spends them. Time is not measured with wall clocks. Every operation and every expiry is stamped with a vector clock.

The service supports two operations per user:

  1. add(userId, creditId, amount, expiryVc) grants amount credits that lapse at the logical time expiryVc.
  2. use(userId, amount, atVc) spends amount credits at logical time atVc.

Rules:

  • A spend must draw from the credits that expire soonest first.
  • A credit whose expiryVc <= atVc is unavailable at that spend, and expired credits can never be used.
  • Only vector clocks are available. There is no wall-clock time.

Write up a design (and the core code) that covers:

  • The API, including how retries are made safe.
  • The per-user data structures that keep inserts and spends efficient when a user holds many active credits.
  • How you compare an expiry vector clock with atVc, and how you get a deterministic "soonest first" order when vector clocks are only partially ordered (tie-break policy).
  • How you prevent double-spending and prevent spending expired credits.
  • How you treat credits with identical expiries.
  • Time and space complexity.
  • A walkthrough of tricky cases: concurrent expiries, expiry exactly equal to atVc, zero or negative amounts, and insufficient balance.

Hints

Hint 1

Define 'expired' precisely with a componentwise comparison (missing entries count as 0), then decide explicitly what happens when the expiry and atVc are concurrent. Say which choice you make and why.

Hint 2

You need a total order that never contradicts causality. Think about a key whose first component is monotone with happens-before, followed by components that only break ties between concurrent clocks.

Hint 3

Because the order is only a linear extension, 'expired' is not monotone along it. Plan the spend without mutating state, skip expired entries instead of stopping at the first one, and commit only if the full amount can be covered.