Per-User Credit Ledger Ordered by Vector-Clock Expiry
System DesignModel answerLast 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:
add(userId, creditId, amount, expiryVc)grantsamountcredits that lapse at the logical timeexpiryVc.use(userId, amount, atVc)spendsamountcredits at logical timeatVc.
Rules:
- A spend must draw from the credits that expire soonest first.
- A credit whose
expiryVc <= atVcis 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to state up front
- Scale. There are millions of users, and a heavy user may hold around 10^4 live credits. Users are independent, so shard by
userIdand let one writer own each user. - Expired. A credit is expired at
atVciffexpiryVc <= atVc: every component ofexpiryVcis at most the matching component ofatVc, with missing entries read as 0. This means the expiry event happened before or at the spend. Equality counts as expired. - Concurrent expiry. If
expiryVcandatVcare concurrent, we cannot prove the credit lapsed, so it is usable. This is a policy choice and I would say so explicitly. The opposite, conservative choice is also defensible, but it must be applied consistently. - Amounts. Integers in the smallest unit.
amount <= 0is invalid for both operations. - Atomicity. A spend either fully succeeds or changes nothing.
API
add(userId, creditId, amount, expiryVc) -> ok | duplicate | invalid
use(userId, opId, amount, atVc) -> [(creditId, taken)] | InsufficientCredits | invalid
balance(userId, atVc) -> int
creditId is the idempotency key for add. opId is the idempotency key for use. Retrying a use with the same opId returns the stored breakdown and does not spend twice.
Per-user state
credits: mapcreditId -> (amount, remaining, expiryVc).order: a sorted collection of(sortKey, creditId). In production use a B-tree or skip list; in the sketch below, a sorted list.applied: mapopId -> breakdownfor successful spends (TTL-bounded).- An append-only event log of adds and uses, which is the source of truth for replay and audit.
Deterministic order over a partial order
"Soonest" is only a partial order, so we need a linear extension that every replica computes identically. The sort key is:
sum(expiryVc). Ifa < bcausally thensum(a) < sum(b), so this never contradicts happens-before.- The canonical vector: drop zero entries, sort by node id, compare as tuples. This orders concurrent clocks the same way everywhere.
creditId. This resolves identical expiries.
Replaying the log therefore always yields the same spend breakdown.
Spend algorithm
- Validate and deduplicate. Reject
amount <= 0. IfopIdwas seen, return the stored result. - Plan, without mutating. Scan
orderfrom the smallest key. Skip any credit withleq(expiry, atVc). Takemin(remaining, need)from each usable credit untilneedis 0. - Check sufficiency. If
need > 0after the scan, returnInsufficientCredits. Nothing has changed. - Commit. Apply the planned decrements, delete credits that hit zero, store the result under
opId, append to the log.
Important: expiry is not monotone along the key. A low-key credit may be concurrent with atVc (usable) while a higher-key credit is already expired, and vice versa. So the scan must skip, not stop, at an expired entry.
Expired credits are not deleted at spend time. A later spend can carry an atVc concurrent with that expiry, and for that spend the credit is still valid. Deletion is only safe below a stable watermark W (the componentwise minimum of clocks that all future operations are guaranteed to dominate). Anything with expiry <= W is dead for good and can be garbage-collected, which keeps the skipped prefix short.
Safeguards
- Double-spend. One writer per user (shard leader or actor) serializes operations. Planning and commit run in one critical section. With a database, use a per-user version column with compare-and-swap, or
SELECT ... FOR UPDATE.opIddedup makes client retries harmless. - Expired use. The check runs inside the critical section against the operation's own
atVc, using<=. - Duplicate
creditId. Same payload: idempotent no-op. Different payload: reject. - Audit. Replaying the log with the deterministic order reproduces every balance and lets you assert
remaining >= 0.
Complexity
Let n be live credits, d the clock width, k the credits visited in a spend, c the credits removed.
| Operation | Time |
|---|---|
add | O(d + log n) with a tree (O(n) shift with a plain list) |
use | O(kd + clog n) |
balance | O(n*d), cacheable per watermark |
Space is O(n*d) plus the dedup table.
Reference sketch
from bisect import insort, bisect_left
def vc_leq(a: dict, b: dict) -> bool:
return all(v <= b.get(k, 0) for k, v in a.items())
def sort_key(vc: dict, credit_id: str):
norm = tuple(sorted((n, c) for n, c in vc.items() if c > 0))
return (sum(c for _, c in norm), norm, credit_id)
class InsufficientCredits(Exception):
pass
class Ledger:
def __init__(self):
self.credits = {} # id -> [amount, remaining, expiry]
self.order = [] # sorted (sort_key, id)
self.applied = {} # op_id -> breakdown
def add(self, cid, amount, expiry):
if not isinstance(amount, int) or amount <= 0:
raise ValueError("amount must be a positive integer")
if cid in self.credits:
a, _, e = self.credits[cid]
if a == amount and e == expiry:
return "duplicate"
raise ValueError("creditId reused with different payload")
self.credits[cid] = [amount, amount, dict(expiry)]
insort(self.order, (sort_key(expiry, cid), cid))
return "ok"
def use(self, op_id, amount, at_vc):
if op_id in self.applied:
return self.applied[op_id]
if not isinstance(amount, int) or amount <= 0:
raise ValueError("amount must be a positive integer")
need, plan = amount, []
for _, cid in self.order:
if need == 0:
break
_, rem, exp = self.credits[cid]
if vc_leq(exp, at_vc): # expired, including equality
continue
take = min(rem, need)
if take:
plan.append((cid, take))
need -= take
if need > 0:
raise InsufficientCredits()
for cid, take in plan: # commit
c = self.credits[cid]
c[1] -= take
if c[1] == 0:
key = (sort_key(c[2], cid), cid)
del self.order[bisect_left(self.order, key)]
del self.credits[cid]
self.applied[op_id] = plan
return plan
Walkthrough
- Equality is expired. Credit
c1(10, expiry{a:3});use 1 at {a:3}fails with insufficient credits. - Concurrent is usable. Same credit;
use 1 at {b:5}succeeds, sincea:3is not<= 0. - Earliest first.
c1(5,{a:1}),c2(5,{a:2});use 7 at {}takes 5 fromc1and 2 fromc2. - Skip, don't stop.
c1(5,{a:1}, sum 1),c2(5,{b:2}, sum 2),c3(5,{c:5}, sum 5);use 8 at {b:2}takes 5 fromc1, skipsc2(expired), takes 3 fromc3. - Identical expiries. Two credits both expiring at
{a:2}are consumed increditIdorder. - Insufficient. With 5 available,
use 6raises and leaves every balance untouched. - Invalid amounts. 0 or negative is rejected for both
addanduse. - Retry. Replaying the same
opIdreturns the original breakdown without spending again.
Common mistakes
- Sorting by a single scalar such as
sumalone, which gives a nondeterministic order for concurrent clocks. - Stopping the scan at the first expired credit.
- Mutating during planning, which leaves partial spends on failure.
- Deleting credits that look expired for one
atVcbut are still valid for another. - Treating
<instead of<=as expired.