Expiring Resource Credit Ledger with Out-of-Order Events
Data Structure DesignModel answerLast updated
Design an in-memory compute credit ledger handling expiring grants, usage subtractions with earliest-expiration priority, out-of-order event ingestion, and point-in-time balance queries.
Design an in-memory credit ledger system for allocating and consuming compute capacity (e.g., GPU execution time).
Credits are issued via grants that are active during a specific time window. Usage is recorded via subtractions. Callers can query the total unexpired and unconsumed balance at any arbitrary historical or present timestamp $t$.
Events may arrive out of chronological order.
System Operations
add_credit(grant_id, amount, timestamp, expiration)Registers a credit grant ofamountunits. The grant becomes active attimestampand expires atexpiration. It is usable in the half-open interval $[timestamp, expiration)$.subtract(amount, timestamp)Registers credit consumption ofamountunits attimestamp.get_balance(timestamp)Calculates and returns the total usable, non-expired credits remaining attimestamp, accounting for all events registered with an event timestamp $\le timestamp$.
Rules & Determinism
- Lazy Evaluation:
add_creditandsubtractmerely record events. Ledger balance evaluation happens when queries are issued. - Tie-Breaking: If an addition and a subtraction share the same timestamp, process credit additions before subtractions. If multiple subtractions share a timestamp, apply them in the order they were recorded.
- Earliest Expiration First (EEF): When consuming credits at timestamp $t$, draw from active grants that have the earliest expiration time. If the grant expiring earliest cannot cover the requested amount, consume it entirely and draw the remainder from the grant with the next earliest expiration time.
- Overdraft Limit: If a subtraction exceeds total available active credits at timestamp $t$, exhaust all active credits (reducing balance to 0) and ignore the unsatisfied portion. Subtractions never result in a negative balance or create debt against future grants.
- Retroactive Mutation: An out-of-order event arriving at timestamp $t_{late}$ logically updates state for all time steps $t \ge t_{late}$.
Implementation Requirements
Part 1: Baseline Replay
Implement the ledger API assuming replaying events from time zero on every get_balance query is acceptable.
Part 2: Optimized Point-in-Time Ledger
Replaying from time zero per query scales poorly ($O(N \log N)$ per query). Design an optimized approach using snapshot checkpointing and selective invalidation.
Explain:
- The checkpointing data structure and memory footprint.
- How out-of-order event insertion invalidates cached checkpoints.
- The role and runtime complexity of priority queues and binary search in the query path.
Hints
Hint 1
Sort events primarily by timestamp. At equal timestamps, process credit additions before subtractions.
Hint 2
Use a min-heap ordered by grant expiration time to greedily select which credits to deduct first.
Hint 3
For Part 2, store chronological state checkpoints. When an event arrives with timestamp t, drop or invalidate all checkpoints with timestamp >= t.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
The core challenge revolves around computing point-in-time balances across expiring resource allocations with priority-based usage deduction and out-of-order event delivery.
Key Domain Rules:
- Grants are active on $[timestamp, expiration)$.
- Subtractions at time $t$ greedily consume active grants prioritized by minimum
expiration. - Events occurring at $t_{event} \le T_{query}$ must be processed in deterministic chronological order.
Part 1: Baseline Replay Approach
In the baseline version, we append all incoming operations to an internal log. When get_balance(T) is called:
- Filter events with $timestamp \le T$.
- Sort filtered events chronologically:
- Primary key:
timestamp(ascending) - Secondary key:
event_type(ADDbeforeSUBTRACT) - Tertiary key: Ingestion sequence (preserves insertion order for tied subtractions)
- Primary key:
- Maintain a min-heap of active grants ordered by
expiration. - Iterate through sorted events:
- Purge grants from the heap where
expiration$\le$ current event timestamp. - For
ADD: Insert[expiration, remaining_amount, grant_id]into the heap. - For
SUBTRACT: Pop from heap top (earliest expiration) and deduct until the subtraction amount is satisfied or the heap is empty.
- Purge grants from the heap where
- Purge expired grants up to time $T$, then sum the remaining quantities in the heap.
Part 1 Complexity
add_credit/subtract: $O(1)$ append.get_balance(T): $O(N \log N)$ time, where $N$ is the number of events up to time $T$.
Part 2: Optimized Ledger with Checkpointing & Invalidation
To avoid $O(N \log N)$ replay overhead on every query, we maintain cached state snapshots (checkpoints).
Checkpoint Design & Maintenance
- Event Log: Maintained as a sorted sequence. When new events arrive out of order, insert them in correct relative position (using binary search or list sorting).
- Checkpoints: A list of
(timestamp, snapshot_heap)pairs.- A snapshot captures the min-heap state of unexpired active grants immediately after processing all events at that timestamp.
- Invalidation Strategy: When an out-of-order event arrives at $t_{late}$:
- All existing checkpoints with $timestamp \ge t_{late}$ are invalidated and removed.
- Checkpoints before $t_{late}$ remain valid.
Query Execution with Checkpoints
When get_balance(T) is called:
- Use binary search (
bisect_right) on cached checkpoints to find the latest valid checkpoint at $t_{snap} \le T$. - Clone the snapshot heap from $t_{snap}$.
- Replay only events in the time range $(t_{snap}, T]$.
- Cache the resulting state at $T$ as a new checkpoint to accelerate future queries.
Complete Python Implementation
import heapq
from bisect import bisect_left, bisect_right
class CreditLedger:
def __init__(self):
# Event list: tuple of (timestamp, event_type, seq_id, payload)
# event_type: 0 for ADD, 1 for SUBTRACT
self.events = []
self.seq_counter = 0
self.is_sorted = True
# Checkpoints: list of (timestamp, state_list)
# state_list contains tuples: (expiration, remaining_amount, grant_id)
self.checkpoints = []
def add_credit(self, grant_id: str, amount: int, timestamp: int, expiration: int):
if expiration <= timestamp or amount <= 0:
return # Invalid interval or empty grant
self.seq_counter += 1
# Priority 0 for ADD ensures additions process before subtractions at same time
event = (timestamp, 0, self.seq_counter, (grant_id, amount, expiration))
self.events.append(event)
self.is_sorted = False
self._invalidate_checkpoints(timestamp)
def subtract(self, amount: int, timestamp: int):
if amount <= 0:
return
self.seq_counter += 1
# Priority 1 for SUBTRACT
event = (timestamp, 1, self.seq_counter, amount)
self.events.append(event)
self.is_sorted = False
self._invalidate_checkpoints(timestamp)
def _invalidate_checkpoints(self, timestamp: int):
"""Removes all checkpoints at or after the invalidated timestamp."""
chk_times = [c[0] for c in self.checkpoints]
idx = bisect_left(chk_times, timestamp)
self.checkpoints = self.checkpoints[:idx]
def _ensure_sorted(self):
if not self.is_sorted:
# Sort order: timestamp ASC, event_type ASC (ADD < SUBTRACT), seq_counter ASC
self.events.sort(key=lambda x: (x[0], x[1], x[2]))
self.is_sorted = True
def get_balance(self, timestamp: int) -> int:
self._ensure_sorted()
# Find closest snapshot <= timestamp
chk_times = [c[0] for c in self.checkpoints]
chk_idx = bisect_right(chk_times, timestamp) - 1
if chk_idx >= 0:
start_time, saved_state = self.checkpoints[chk_idx]
# Deep copy active grants heap: [expiration, remaining_amount, grant_id]
heap = [list(item) for item in saved_state]
heapq.heapify(heap)
else:
start_time = -1
heap = []
# Find event window (start_time, timestamp]
event_times = [e[0] for e in self.events]
start_ev_idx = 0 if start_time == -1 else bisect_right(event_times, start_time)
end_ev_idx = bisect_right(event_times, timestamp)
# Replay events in range
for i in range(start_ev_idx, end_ev_idx):
ev_time, ev_type, _, payload = self.events[i]
# Purge expired grants prior to processing current event
while heap and heap[0][0] <= ev_time:
heapq.heappop(heap)
if ev_type == 0: # ADD
grant_id, amount, exp = payload
heapq.heappush(heap, [exp, amount, grant_id])
elif ev_type == 1: # SUBTRACT
rem_sub = payload
while heap and rem_sub > 0:
# Remove expired grants
if heap[0][0] <= ev_time:
heapq.heappop(heap)
continue
# Deduct from grant expiring earliest
if heap[0][1] <= rem_sub:
rem_sub -= heap[0][1]
heapq.heappop(heap)
else:
heap[0][1] -= rem_sub
rem_sub = 0
# Purge grants that expire exactly at or before target timestamp
while heap and heap[0][0] <= timestamp:
heapq.heappop(heap)
# Calculate final usable balance
total_balance = sum(item[1] for item in heap)
# Cache checkpoint for current query timestamp
# Save snapshot as immutable tuple list
snapshot = [tuple(item) for item in heap]
# Replace or append checkpoint at timestamp
insert_idx = bisect_left(chk_times, timestamp)
if insert_idx < len(self.checkpoints) and self.checkpoints[insert_idx][0] == timestamp:
self.checkpoints[insert_idx] = (timestamp, snapshot)
else:
self.checkpoints.insert(insert_idx, (timestamp, snapshot))
return total_balance
Complexity & Design Trade-offs
| Operation | Baseline (Part 1) | Optimized (Part 2) |
|---|---|---|
add_credit / subtract | $O(1)$ append | $O(1)$ lazy write + $O(K)$ checkpoint truncation |
get_balance (Warm Cache) | $O(N \log N)$ total replay | $O(M \log G)$ where $M \ll N$ is events since snapshot, $G$ active grants |
get_balance (Cold Cache) | $O(N \log N)$ total replay | $O(N \log G)$ baseline replay + $O(G)$ checkpoint save |
- Heap Role: The min-heap guarantees $O(\log G)$ greedy selection during subtractions. It does not eliminate event ordering costs; chronological ordering is enforced by binary search / sorting over events.
- Cache Invalidation: Frequent severely late events ($t_{late} \ll t_{now}$) invalidate large ranges of checkpoints, degrading performance toward Part 1 baseline. Conversely, mostly in-order events with localized late arrivals benefit significantly from checkpointing.