Model a Prepaid Spending Account with Transaction Limits
Data Structure DesignModel answerLast updated
Design a class hierarchy that tracks a spending cap, running balance, and transaction history while safely handling concurrent charges and edge-case inputs.
Prepaid Spending Account
You are building the core logic for a prepaid account system. A user loads a fixed amount of money onto the account and can make purchases against that balance until it runs out.
What to build
SpendingAccount — the main class. It holds:
- the account holder's name (optional)
- a spending cap (the maximum total that can ever be charged)
- the current amount already spent
Charge — a record representing one attempted purchase. It stores:
- the charge amount
- when the attempt was made (UTC timestamp)
- a unique ID
- the billing period it belongs to
- its outcome:
PENDING,APPROVED, orDECLINED
ChargeLog — a separate, append-only store for Charge records. It has no knowledge of caps or balances; it just stores and retrieves entries.
Methods to implement
attempt_charge(amount) -> bool
Try to spend amount from the account. Return True if the charge goes through, False otherwise. A charge is approved only when it does not push the total spent past the cap. The check and the balance update must be atomic — assume the account can receive concurrent requests.
current_balance() -> Decimal
Return the total amount charged so far.
available_funds() -> Decimal
Return how much the account can still absorb.
get_period_statement() -> list[Charge]
Return all approved charges in the current billing period. Declined attempts and charges from earlier periods must not appear.
close_period() -> None
Advance to the next billing period. The running balance carries over (this is not a payment).
Constraints
- A charge must be declined if it would cause the total spent to exceed the cap — even by a fraction.
- A charge of exactly the remaining available funds must be approved.
- Zero, negative, non-numeric, and infinite values must be declined.
- Thread safety is required: two concurrent charges that together exceed the cap must not both be approved.
- Keep account state and charge history in separate objects.
Example
account = SpendingAccount(cap=1000)
account.attempt_charge(500) # True
account.attempt_charge(600) # False — would exceed cap
account.current_balance() # Decimal('500')
account.get_period_statement()
# [Charge(500, Approved)]
Edge cases to consider
- Amount is zero or negative
- Amount exactly equals the remaining available funds
- Two threads each try to charge 600 on a 1000-cap account with 500 already spent
- The charge log is empty
get_period_statement()is called afterclose_period()
Hints
Hint 1
Start by identifying the single invariant the system must protect: `0 <= balance <= cap`. Then ask yourself — where is the one place that invariant can break, and how do you guard it?
Hint 2
The race condition lives in the read-compare-write sequence on the balance. Locking only the write step is a classic bug — the check and the update must share the same critical section.
Hint 3
Use Python's `Decimal` type (constructed from a string, not a float) to store amounts. Binary floats make `0.1 + 0.2 != 0.3`, which can cause a charge at the exact cap to be wrongly declined. In production, store integer cents instead.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is an object-oriented design problem with one real correctness trap: the check-then-act race on the balance. Everything else — clean class boundaries, input validation, billing periods — is straightforward once you see the structure.
Class structure
Four pieces work together:
ChargeStatusenum —PENDING,APPROVED,DECLINED. Enums prevent typos and make comparisons safe.Charge— an immutable-ish record. It carries an ID, amount, timestamp, billing period, and status. It knows nothing about caps.ChargeLog— append-only history. It storesChargeobjects and can filter by period and status. No balance logic lives here.SpendingAccount— owns the cap, the running balance, and the current period. It composes aChargeLogand is the only object allowed to mutate the balance.
This separation means you can later swap ChargeLog for a database-backed ledger without touching the authorization path.
The core method: attempt_charge
Four steps, in order:
- Validate the input. Reject zero, negative, non-numeric, and infinite values immediately — before acquiring any lock.
- Create a
PENDINGcharge with the current period. - Inside a lock, evaluate
amount <= cap - balance. If it fits, increment the balance and set status toAPPROVED. Otherwise set it toDECLINED. The lock wraps the entire read-compare-write sequence — not just the write. - Append the charge to the log regardless of outcome (for auditability) and return
TrueorFalse.
Why the lock placement matters
The classic mistake is locking only the balance update. Consider two threads each trying to charge 600 on a 1000-cap account already at 500:
- Thread A reads
available = 500, sees 600 > 500, starts to decline - Thread B reads
available = 500before A finishes — same result, same race
The lock must cover the read and the write together. Python's threading.Lock as a context manager makes this natural.
Exact-limit case
The comparison is <=, not <. A charge equal to the remaining available funds is valid and should land the balance exactly on the cap.
Billing periods
Tag each Charge with an integer period counter rather than comparing timestamps. Clock-skew at a period boundary could otherwise assign a charge to the wrong period. get_period_statement() filters by period == current_period and status == APPROVED. Calling close_period() increments the counter; the balance intentionally carries over, because a period close is not a payment.
Money precision
Amounts are stored as Decimal values constructed from str(amount). Constructing Decimal directly from a float inherits the float's rounding error. In production, store integer cents and never touch floats for money at all.
Complexity
| Operation | Time | Space |
|---|---|---|
attempt_charge | O(1) amortized | O(1) per charge |
current_balance | O(1) | O(1) |
get_period_statement | O(n) scan | O(k) returned |
| Total storage | — | O(n) |
get_period_statement can be made O(k) by maintaining a per-period list alongside the main log. The scan is fine for interviews.
Common mistakes
- Locking only the balance write, not the check-and-write pair.
- Using
floatfor amounts — wrongly declines a charge at the exact cap. - Letting negative amounts silently act as refunds. A refund is a separate operation with its own validation.
- Returning a reference to the internal log list — callers can then mutate history. Always return a copy.
Python solution
import itertools
import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from decimal import Decimal, InvalidOperation
from enum import Enum
from typing import List, Optional
class ChargeStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
DECLINED = "DECLINED"
_id_counter = itertools.count(1)
@dataclass
class Charge:
amount: Decimal
period: int
status: ChargeStatus = ChargeStatus.PENDING
timestamp: datetime = field(
default_factory=lambda: datetime.now(timezone.utc)
)
charge_id: int = field(default_factory=lambda: next(_id_counter))
def __repr__(self) -> str:
return f"Charge({self.amount}, {self.status.value.capitalize()})"
class ChargeLog:
"""Append-only store. No knowledge of caps or balances."""
def __init__(self) -> None:
self._entries: List[Charge] = []
def append(self, charge: Charge) -> None:
self._entries.append(charge)
def approved_in_period(self, period: int) -> List[Charge]:
return [
c for c in self._entries
if c.period == period and c.status is ChargeStatus.APPROVED
]
def all_entries(self) -> List[Charge]:
return list(self._entries)
class SpendingAccount:
def __init__(
self,
cap,
holder_name: Optional[str] = None,
) -> None:
cap = Decimal(str(cap))
if cap < 0:
raise ValueError("Cap must be non-negative.")
self._cap = cap
self._balance = Decimal("0")
self._period = 1
self._log = ChargeLog()
self._lock = threading.Lock()
self.holder_name = holder_name
@staticmethod
def _parse_amount(amount) -> Optional[Decimal]:
# Reject booleans before they pass the numeric check
if isinstance(amount, bool):
return None
try:
value = Decimal(str(amount))
except (InvalidOperation, ValueError, TypeError):
return None
if not value.is_finite() or value <= 0:
return None
return value
def attempt_charge(self, amount) -> bool:
value = self._parse_amount(amount)
# The entire check-and-update must be atomic
with self._lock:
charge = Charge(
amount=value if value is not None else Decimal("0"),
period=self._period,
)
if value is not None and value <= self._cap - self._balance:
self._balance += value
charge.status = ChargeStatus.APPROVED
else:
charge.status = ChargeStatus.DECLINED
self._log.append(charge)
return charge.status is ChargeStatus.APPROVED
def current_balance(self) -> Decimal:
with self._lock:
return self._balance
def available_funds(self) -> Decimal:
with self._lock:
return self._cap - self._balance
def get_period_statement(self) -> List[Charge]:
with self._lock:
# Return a copy so callers cannot mutate internal history
return self._log.approved_in_period(self._period)
def close_period(self) -> None:
with self._lock:
self._period += 1
# --- smoke test ---
if __name__ == "__main__":
account = SpendingAccount(cap=1000, holder_name="Alex")
assert account.attempt_charge(500) is True
assert account.attempt_charge(600) is False # would exceed cap
assert account.attempt_charge(500) is True # exact remaining amount
assert account.current_balance() == Decimal("1000")
assert account.available_funds() == Decimal("0")
statement = account.get_period_statement()
assert len(statement) == 2 # only approved charges
print(statement)
# [Charge(500, Approved), Charge(500, Approved)]
account.close_period()
assert account.get_period_statement() == [] # new period, clean slate
assert account.current_balance() == Decimal("1000") # balance carries over
Two things interviewers notice immediately: the lock wraps the whole read-compare-write block (not just the write), and get_period_statement returns a new list so the caller cannot corrupt internal state.