Credit System with Expiration and Time-Ordered Replay
Data Structure DesignModel answerLast updated
Build a credit tracking system where allocations expire, spending prioritizes earliest expiration, and operations arrive out of chronological order.
You're building the accounting layer for a cloud resource platform. User accounts hold credits that come from allocations and get consumed through usage. Each allocation has a lifetime, and unused portions vanish when that lifetime ends.
Your system must support three operations:
grant(grant_id, amount, timestamp, expiration)records an allocation ofamountcredits, valid fromtimestampthroughexpiration(exclusive).subtract(amount, timestamp)consumesamountcredits at timetimestamp.get_balance(timestamp)computes how many credits are available at timetimestamp.
Two constraints increase the complexity:
- Spending order by expiration. When credits are consumed, they must come from the valid allocation expiring soonest, then the next soonest, continuing until the full amount is covered.
- Non-chronological arrival. Operations arrive in arbitrary order. An operation with timestamp
t₁might arrive after one with timestampt₂ > t₁, yet all balance queries must remain consistent with the actual chronological sequence.
Work with a single account (multiple accounts are independent instances), positive integers for amounts, and integer timestamps.
Constraints
- Each allocation satisfies
expiration > timestamp, and everygrant_idis unique. get_balance(t)must account for every operation received so far with timestamp ≤t, regardless of arrival order.
Clarifying Questions
Before implementing, confirm:
- Is an allocation valid at exactly its
expirationtimestamp, or does it become invalid then? - If a consumption request exceeds available credits at its timestamp, what happens: rejection, partial application, or negative balance?
- When an allocation and a consumption share the same timestamp, which is processed first?
- When multiple valid allocations expire simultaneously, how is the tie broken?
- Is there a bound on how far back in time an operation can arrive?
Part 1: Core Implementation
Implement the three operations with correct handling of expiration priority and out-of-order arrivals. State time and space complexity for each operation.
Your solution should address:
- Precise semantics for boundary conditions, tie-breaking, and overdraft scenarios
- A mechanism to identify the earliest-expiring valid allocation at any timestamp
- Correct balances when a late-arriving operation predates already-processed operations
- Complexity analysis
Part 2: Production Optimization
A naive implementation might recompute from the earliest timestamp on every balance query. Discuss how you would optimize this for production workloads where replaying the entire history is too expensive.
Additional context to consider:
- Is there a cutoff after which late operations are rejected or handled as adjustments?
- Are balance queries typically for the current moment, or for arbitrary historical timestamps?
Your answer should cover:
- Maintaining intermediate state and handling invalidation when late operations arrive
- Compacting settled history so memory and computation don't grow unbounded
- Query cost and late-operation cost under the optimized approach
Hints
Hint 1
Store operations in timestamp order, not arrival order, to replay the correct sequence
Hint 2
Use a priority queue to efficiently find which allocation expires next among those currently valid
Hint 3
Consider checkpointing balances at certain timestamps to avoid full replay from the beginning
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifications
Before implementing, establish the exact semantics:
- Expiration boundary: Allocations are valid in the half-open interval
[timestamp, expiration). At timeexpiration, those credits are no longer available. - Overdraft: Consumption requests that exceed available credits are rejected entirely (return false or raise an error).
- Same-timestamp ordering: Allocations are processed before consumptions at the same timestamp.
- Expiration ties: When multiple allocations expire at the same time, tie-break by
grant_idlexicographically (or arrival order). - Late arrivals: No bound initially; the system must handle arbitrarily late operations.
Part 1: Core Implementation
Approach
The key insight is that balance queries require replaying operations in chronological order, not arrival order. We store all operations and sort them by timestamp whenever we need to compute a balance.
For each get_balance(t) call:
- Collect all allocations and consumptions with timestamp ≤
t. - Sort them by timestamp (allocations before consumptions at the same timestamp).
- Simulate forward in time, maintaining a min-heap of active allocations keyed by expiration time.
- For each consumption, greedily draw from the heap (earliest expiration first).
- Return the sum of remaining credits in the heap at time
t.
Data structures:
- A list of allocation events:
(timestamp, expiration, amount, grant_id) - A list of consumption events:
(timestamp, amount) - A min-heap during replay:
(expiration, remaining_amount, grant_id)
Implementation Sketch
import heapq
from collections import defaultdict
class CreditLedger:
def __init__(self):
self.grants = {} # grant_id -> (timestamp, expiration, amount)
self.subtractions = [] # list of (timestamp, amount)
def grant(self, grant_id, amount, timestamp, expiration):
if grant_id in self.grants:
raise ValueError("Duplicate grant_id")
self.grants[grant_id] = (timestamp, expiration, amount)
def subtract(self, amount, timestamp):
self.subtractions.append((timestamp, amount))
def get_balance(self, query_time):
# Collect all events up to query_time
events = []
for gid, (ts, exp, amt) in self.grants.items():
if ts <= query_time:
events.append((ts, 0, exp, amt, gid)) # 0 = grant
for ts, amt in self.subtractions:
if ts <= query_time:
events.append((ts, 1, amt)) # 1 = subtract
events.sort() # Sort by (timestamp, type)
active = [] # min-heap of (expiration, remaining, grant_id)
for event in events:
if event[1] == 0: # grant
ts, _, exp, amt, gid = event
# Remove expired grants
while active and active[0][0] <= ts:
heapq.heappop(active)
heapq.heappush(active, (exp, amt, gid))
else: # subtract
ts, _, amt = event
# Remove expired grants
while active and active[0][0] <= ts:
heapq.heappop(active)
# Consume from earliest expiring
needed = amt
temp = []
while needed > 0 and active:
exp, avail, gid = heapq.heappop(active)
take = min(needed, avail)
needed -= take
if avail > take:
temp.append((exp, avail - take, gid))
if needed > 0:
# Restore and reject
for item in temp:
heapq.heappush(active, item)
raise ValueError("Insufficient credits")
for item in temp:
heapq.heappush(active, item)
# Remove expired at query_time
result = []
while active:
exp, amt, gid = heapq.heappop(active)
if exp > query_time:
result.append((exp, amt, gid))
return sum(amt for _, amt, _ in result)
Complexity
- grant: O(1) to store
- subtract: O(1) to store
- get_balance: O(N log N + M log M) where N = number of allocations ≤
query_time, M = number of consumptions ≤query_time. The sort dominates; heap operations are O(log N) each. - Space: O(G + S) for G allocations and S consumptions.
Part 2: Production Optimization
Problem
Replaying from time zero on every query becomes prohibitively expensive as history grows. A production system needs:
- Checkpoints: Persist the heap state at selected timestamps so queries can start from the nearest checkpoint instead of T0.
- Compaction: Once a timestamp is "settled" (no more late operations can arrive before it), discard the detailed event log and keep only the checkpoint.
Optimized Design
Checkpoint strategy:
- Maintain checkpoints at regular intervals (e.g., every 1000 time units or every 1000 operations).
- Each checkpoint stores: timestamp, serialized heap of active allocations.
Handling late operations:
- When an operation arrives with timestamp
t < latest_checkpoint, invalidate all checkpoints ≥tand rebuild from the nearest earlier checkpoint. - If
tis before the earliest checkpoint, rebuild from T0 (expensive, but rare with a bounded lookback window).
Settled history:
- Introduce a "settle horizon": operations older than current_time − window are rejected or logged separately as corrections.
- Compact: keep only the most recent checkpoint before the settle horizon; discard earlier events.
Query cost:
- With checkpoints every K operations, a query replays at most K operations: O(K log N).
- Late operation cost: invalidate and rebuild O(M) checkpoints, where M = number of checkpoints after the late timestamp.
Production refinements:
- Store allocations and consumptions in a time-series database indexed by timestamp.
- Use
grant_ididempotency: reject duplicategrant_idto handle retries. - Audit trail: log which allocation(s) funded each consumption (for billing compliance).
Example Architecture
Timeline: T0 ----[CP1]----[CP2]----[CP3]---- now
↑ settle horizon
- Keep detailed events after settle horizon
- Keep CP2 as the last settled checkpoint
- Discard events before CP2
- Late operation at T < CP2: recompute CP2 onward
Complexity Summary
- Query (with checkpoints): O(K log N), where K = operations since last checkpoint
- Late operation: O(M·K log N), where M = invalidated checkpoints
- Space: O(K + C), where C = number of checkpoints
Common Mistakes
- Forgetting to remove expired allocations before processing each event.
- Applying expiration priority in arrival order instead of chronological order.
- Not handling same-timestamp tie-breaking consistently.
- Rebuilding checkpoints eagerly instead of lazily (causing unnecessary work).
- Allowing unbounded late arrivals without a settle horizon in production.
Testing Strategy
- Late-arriving allocation that changes a prior balance.
- Late-arriving consumption that would have failed if processed in arrival order.
- Allocation that expires exactly at a query timestamp (boundary test).
- Consumption spanning multiple allocations with different expirations.
- Rapid queries at the same timestamp after out-of-order operations.