Expiring Credit Wallet: Drain Soonest-Expiring First, Halt on Overdraft
Data Structure DesignModel answerLast updated
Design an in-memory credit ledger that consumes the earliest-expiring balance first and permanently returns None after any overdraft.
Expiring Credit Wallet
You are building an in-memory wallet for a single account that holds credits with expiration dates. Credits are granted in named buckets, each with an amount and a deadline. Charges are paid out of those buckets according to two firm rules:
Rule 1 — Spend what expires soonest. When a charge arrives, deduct from the bucket with the nearest expiration first. Once that bucket hits zero, continue into the next-soonest bucket, and so on, until the charge is fully covered.
Rule 2 — Overdraft is permanent and fatal.
If any charge cannot be fully covered by unexpired credits, the wallet enters a broken state. Every subsequent get_balance call returns None, regardless of any credits added later.
Implement the following interface. All timestamps and amounts are non-negative integers.
class CreditWallet:
def add_credit(self, amount: int, timestamp: int, expires_at: int) -> None:
"""Add `amount` credits granted at `timestamp`, valid until `expires_at`."""
def spend_credit(self, amount: int, timestamp: int) -> None:
"""Deduct `amount` credits at `timestamp`."""
def get_balance(self, timestamp: int) -> int | None:
"""Return total unexpired, unspent credits at `timestamp`, or None if broken."""
Worked example
Operations arrive in the order listed. Timestamps are spaced far enough apart that boundary edge cases do not affect the results.
| Call | What happens |
|---|---|
add_credit(10, 0, 5) | Bucket A: 10 credits, expires at t=5 |
add_credit(10, 0, 100) | Bucket B: 10 credits, expires at t=100 |
spend_credit(10, 1) | Drains A completely (A expires first) |
get_balance(10) | Returns 10 — A is expired and empty; B is intact |
spend_credit(15, 20) | Only 10 credits available; wallet breaks |
get_balance(30) | Returns None |
If the charge at t=1 had been taken from B instead, A would have expired unused and get_balance(10) would return 0 — so the consumption order is the whole point.
Questions to settle before coding
Before you start, think through (and state) your conventions for:
- Is a credit still usable at exactly its
expires_attimestamp, or has it already expired? - Can calls arrive out of order, or are timestamps always non-decreasing?
- If a grant and a charge share the same timestamp, can that grant cover that charge?
- When the wallet breaks, does
Noneapply to every future query, or only to queries whose timestamp is at or after the overdrafting charge? - How should invalid inputs be handled (e.g., negative amount,
expires_at ≤ timestamp)?
Part 1 — Implement the wallet
Write a working implementation of the three methods. State the time complexity of each.
Your answer should demonstrate:
- Correct multi-bucket drainage in a single charge.
- Expired credits excluded both from
get_balanceand from covering charges. - A broken state that persists unconditionally.
- Your chosen conventions, stated clearly.
Part 2 — Scaling to very high transaction volume
Suppose one account accumulates millions of grants and charges over its lifetime. How would you evolve the design?
Before answering, consider:
- Is the pressure many accounts with sparse activity, or a few accounts with dense activity?
- Must you still answer balance queries for arbitrary past timestamps?
Your answer should address:
- Where the Part 1 design accumulates unbounded state and what bounds it.
- How to serve historical or out-of-order queries without replaying the full log every time.
- What changes if the wallet must survive process restarts, handle duplicate requests, or spread across multiple nodes.
Hints
Hint 1
A min-heap keyed on expiration time gives you O(log n) access to the soonest-expiring bucket — you can pop and partially drain buckets in one pass through the heap during a charge.
Hint 2
Set a simple boolean flag the moment an overdraft occurs; every get_balance check reads that flag first, before touching any bucket or doing any expiry filtering.
Hint 3
For Part 2, think about what 'compacting' means for a ledger: a periodic snapshot of the remaining bucket state lets you discard all history before that point, so you only replay a bounded suffix of events for any query.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Conventions to State First
Good answers open by locking down the ambiguous cases before writing a single line of code. Reasonable choices:
- Expiry boundary: a credit is usable at timestamps
t < expires_at; it is expired att == expires_at. This matches the half-open interval[granted_at, expires_at). - Call ordering: calls arrive in non-decreasing timestamp order. Out-of-order calls are explicitly out of scope for Part 1.
- Same-timestamp grant + charge: the grant is usable for charges at the same timestamp (the credit is live at
[timestamp, expires_at)). - Broken state scope: once an overdraft occurs, every subsequent
get_balancereturnsNone— including calls with timestamps earlier than the overdraft, if out-of-order calls were allowed (not an issue under our ordering assumption, but worth stating). - Invalid input: raise
ValueErrorfor negative amounts orexpires_at <= timestamp.
Part 1 — Implementation
Data structure choice
Each bucket is a (expires_at, remaining_amount) pair. We need to pop the soonest-expiring bucket first, which is exactly a min-heap keyed on expires_at. Python's heapq fits directly.
import heapq
from typing import Optional
class CreditWallet:
def __init__(self):
# min-heap of (expires_at, remaining_amount)
self._heap: list[tuple[int, int]] = []
self._broken = False
def add_credit(self, amount: int, timestamp: int, expires_at: int) -> None:
if amount < 0 or expires_at <= timestamp:
raise ValueError("Invalid credit parameters")
heapq.heappush(self._heap, (expires_at, amount))
def spend_credit(self, amount: int, timestamp: int) -> None:
if amount < 0:
raise ValueError("Spend amount must be non-negative")
if self._broken:
return # already broken; charges are no-ops
remaining = amount
leftovers: list[tuple[int, int]] = []
while remaining > 0 and self._heap:
exp, bal = heapq.heappop(self._heap)
if exp <= timestamp:
continue # expired — discard silently
if bal <= remaining:
remaining -= bal
# bucket fully consumed; don't push back
else:
leftovers.append((exp, bal - remaining))
remaining = 0
for item in leftovers:
heapq.heappush(self._heap, item)
if remaining > 0:
self._broken = True
def get_balance(self, timestamp: int) -> Optional[int]:
if self._broken:
return None
return sum(bal for exp, bal in self._heap if exp > timestamp)
Complexity
| Operation | Time | Notes |
|---|---|---|
add_credit | O(log n) | single heap push |
spend_credit | O(k log n) | k = buckets drained or skipped; each pop/push is O(log n) |
get_balance | O(n) | linear scan to filter expired buckets |
n is the number of active (unexpired) buckets. Under our call-ordering assumption, expired buckets are cleaned out lazily during spend_credit, so n stays bounded by the number of grants that haven't been fully consumed or expired yet.
Common mistakes
- Forgetting to skip expired buckets inside
spend_credit. If you only filter inget_balance, you can accidentally count an expired bucket as available and then not trigger the overdraft when you should. - Not pushing partially drained buckets back. Popping and discarding a partially used bucket is a silent data loss bug.
- Mutating heap entries in-place. Tuples are immutable; you must pop, modify, and push back.
- Letting
spend_creditproceed normally after the wallet is already broken. The broken state should be a fast exit, not a continued drain.
Part 2 — Scaling to High Volume
Where Part 1 breaks down
The heap grows without bound if credits are added faster than they are consumed or expired. get_balance already does an O(n) scan; with millions of buckets that is unacceptable. Even spend_credit degrades when it must pop through large runs of expired buckets.
Fix 1 — Lazy expiry pruning with a sentinel
During every spend_credit and get_balance, pop and discard buckets from the heap whose expires_at <= current_timestamp. Since calls are non-decreasing in time, anything expired now will never become relevant again. This keeps the heap size proportional to the number of live buckets, not total history.
Fix 2 — Periodic snapshots ("compaction")
For an account with years of activity, even the live bucket count can grow large. A background job (or an in-process trigger when the heap exceeds a threshold) can:
- Freeze a snapshot: serialize the current heap state and the
_brokenflag. - Record the snapshot timestamp.
- Discard all events older than the snapshot.
Any query for timestamp >= snapshot_time can start from the snapshot and only replay events after it. This bounds replay cost to a configurable window (e.g., the last 24 hours of activity).
Fix 3 — Historical queries
If arbitrary past-timestamp queries are required, store the full event log (append-only). Answer historical queries by replaying from the nearest snapshot before the query timestamp. Trade-off: storage grows with history; consider archiving cold log segments to object storage (S3, GCS) and loading them on demand.
Fix 4 — Multi-process scaling
- Partition by account ID. Each shard owns a subset of accounts; no cross-shard coordination is needed for single-account operations.
- Durability. Persist each event to a write-ahead log before acknowledging it. On restart, replay from the last snapshot + suffix of the log.
- Idempotency. Assign each
add_creditandspend_credita client-generated request ID. Before applying an operation, check whether that ID was already processed — critical for retry safety, especially for the terminal overdraft rule (replaying an already-applied overdraft charge must not break a wallet that has since recovered, or double-count a spend). - Consistency. For a single account, a single-writer model (one process owns each account's state) avoids concurrent modification entirely. If horizontal scaling within an account is ever needed, you'd need a distributed lock or a conflict-free ledger structure, but that is rarely justified for a per-account wallet.