Build a Thread-Safe Cart with Pluggable Promotions
Data Structure DesignModel answerLast updated
Design an in-memory shopping cart with exact money arithmetic, strategy-based promotions, an itemized receipt, and safe concurrent updates.
Task
Design the classes for an in-memory shopping cart used by an online store. The cart should manage its contents, compute prices exactly, accept new promotion types without being edited, produce an itemized receipt, and behave correctly when several threads use it at once.
Requirements
- Exact money. Never use floats for currency. Use integer minor units (cents) or an immutable
Moneyvalue object that carries a currency code and supports basic arithmetic. - Cart operations. Support adding an item, removing an item by id, and changing a quantity. Quantities must be positive integers.
- Pluggable promotions. Model promotions with the Strategy pattern. Adding a new kind (percentage off over a threshold, "buy X get Y free", a flat order-level discount) must not require changes to the cart class.
- Receipt. Checkout returns a record containing the line subtotals, every applied discount together with the identifier of the rule that produced it, and the final total.
- Thread safety. Concurrent additions, updates, removals and checkouts must not corrupt state or produce a total computed from half-updated data.
Suggested interface
class Money:
def __init__(self, amount_in_cents: int, currency: str = "USD"): ...
class Item:
def __init__(self, item_id: str, name: str, price: Money): ...
class PromotionRule(ABC):
@abstractmethod
def apply(self, cart_snapshot: "CartSnapshot") -> list["AppliedDiscount"]: ...
class ShoppingCart:
def __init__(self, user_id: str): ...
def add_item(self, item: Item, quantity: int) -> None: ...
def remove_item(self, item_id: str) -> None: ...
def update_quantity(self, item_id: str, quantity: int) -> None: ...
def apply_promotions(self, rules: list[PromotionRule]) -> "Receipt": ...
Example
cart = ShoppingCart(user_id="user_123")
cart.add_item(Item("SKU_A", "Keyboard", Money(5000)), 2) # $100.00
cart.add_item(Item("SKU_B", "Mouse", Money(2500)), 1) # $25.00
rules = [ThresholdPercentageDiscount(threshold=Money(10000), percentage=10)]
receipt = cart.apply_promotions(rules)
# Subtotal: $125.00
# Discounts: [AppliedDiscount(name="10% off over $100", amount=-$12.50)]
# Total: $112.50
Edge cases to handle
- Setting a quantity to zero must either remove the line or raise a clearly defined validation error. State which one you choose.
- Adding an item whose currency differs from the cart's currency must raise a validation error.
- If the discounts add up to more than the subtotal, the final total is floored at 0 cents.
Explain your class design and the reasoning behind it, then give code for the key parts.
Hints
Hint 1
Make Money an immutable value object holding an int number of cents plus a currency, and have every operation check that the currencies match. Do rounding in exactly one place, using integer arithmetic.
Hint 2
Separate mutable state from calculation. Copy the cart into an immutable snapshot while holding a lock, then hand only that snapshot to the promotion rules.
Hint 3
Each promotion returns a list of discount records tagged with a rule id. The cart just loops over the rules and sums the results, then clamps the total at zero.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Design overview
The design has four parts.
Moneyis an immutable value object. It stores integer cents and a currency code. Every binary operation validates the currency and raisesCurrencyMismatchErroron a mismatch. Floats never appear, and the only rounding is in the percentage helper.- Promotions are strategies.
PromotionRule.apply(snapshot)returns a list ofAppliedDiscount(rule_id, name, amount). The cart does not know any concrete rule, so it is open for extension and closed for modification. - Mutable state is isolated. The cart's only mutable data is a dict of
item_id -> CartLine, guarded by onethreading.RLock. Checkout copies the dict into an immutableCartSnapshotunder the lock, then releases it and runs the rules against the copy. - The receipt is an immutable audit record. It holds the lines, the subtotal, the tagged discounts and the final total.
Code
from __future__ import annotations
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
class CurrencyMismatchError(ValueError):
pass
@dataclass(frozen=True)
class Money:
amount_in_cents: int
currency: str = "USD"
def __post_init__(self):
if type(self.amount_in_cents) is not int:
raise TypeError("cents must be an int")
def _same(self, o: Money) -> None:
if self.currency != o.currency:
raise CurrencyMismatchError(f"{self.currency} vs {o.currency}")
def __add__(self, o): self._same(o); return Money(self.amount_in_cents + o.amount_in_cents, self.currency)
def __sub__(self, o): self._same(o); return Money(self.amount_in_cents - o.amount_in_cents, self.currency)
def __mul__(self, n: int): return Money(self.amount_in_cents * n, self.currency)
def __gt__(self, o): self._same(o); return self.amount_in_cents > o.amount_in_cents
def percent(self, pct: int) -> Money:
# half-up rounding using integers only
return Money((self.amount_in_cents * pct + 50) // 100, self.currency)
def __str__(self):
c = abs(self.amount_in_cents)
return f"{'-' if self.amount_in_cents < 0 else ''}${c // 100}.{c % 100:02d}"
@dataclass(frozen=True)
class Item:
item_id: str
name: str
price: Money
@dataclass(frozen=True)
class CartLine:
item: Item
quantity: int
@property
def subtotal(self) -> Money:
return self.item.price * self.quantity
@dataclass(frozen=True)
class CartSnapshot:
user_id: str
currency: str
lines: tuple[CartLine, ...]
@property
def subtotal(self) -> Money:
total = Money(0, self.currency)
for ln in self.lines:
total = total + ln.subtotal
return total
@dataclass(frozen=True)
class AppliedDiscount:
rule_id: str
name: str
amount: Money # positive magnitude, shown as a deduction
@dataclass(frozen=True)
class Receipt:
lines: tuple[CartLine, ...]
subtotal: Money
discounts: tuple[AppliedDiscount, ...]
total: Money
class PromotionRule(ABC):
@abstractmethod
def apply(self, snap: CartSnapshot) -> list[AppliedDiscount]: ...
class ThresholdPercentageDiscount(PromotionRule):
def __init__(self, threshold: Money, percentage: int):
self.threshold, self.pct = threshold, percentage
def apply(self, snap):
sub = snap.subtotal
if sub > self.threshold:
return [AppliedDiscount(f"THRESH_PCT_{self.pct}",
f"{self.pct}% off over {self.threshold}",
sub.percent(self.pct))]
return []
class BuyXGetYFree(PromotionRule):
def __init__(self, item_id: str, buy: int, free: int):
self.item_id, self.buy, self.free = item_id, buy, free
def apply(self, snap):
out = []
for ln in snap.lines:
if ln.item.item_id == self.item_id:
groups = ln.quantity // (self.buy + self.free)
if groups:
out.append(AppliedDiscount(
f"BXGY_{self.item_id}", f"Buy {self.buy} get {self.free} free",
ln.item.price * (groups * self.free)))
return out
class FlatOrderDiscount(PromotionRule):
def __init__(self, amount: Money): self.amount = amount
def apply(self, snap):
return [AppliedDiscount("FLAT", f"{self.amount} off", self.amount)]
class ShoppingCart:
def __init__(self, user_id: str):
self.user_id = user_id
self._lines: dict[str, CartLine] = {}
self._currency: str | None = None
self._lock = threading.RLock()
@staticmethod
def _check_qty(q):
if type(q) is not int or q <= 0:
raise ValueError("quantity must be a positive int")
def add_item(self, item: Item, quantity: int) -> None:
self._check_qty(quantity)
with self._lock:
if self._currency and item.price.currency != self._currency:
raise CurrencyMismatchError("cart currency differs from item")
cur = self._lines.get(item.item_id)
if cur and cur.item.price != item.price:
raise ValueError("price changed for existing line")
qty = quantity + (cur.quantity if cur else 0)
self._lines[item.item_id] = CartLine(item, qty)
self._currency = item.price.currency
def remove_item(self, item_id: str) -> None:
with self._lock:
del self._lines[item_id] # KeyError if unknown
if not self._lines:
self._currency = None
def update_quantity(self, item_id: str, quantity: int) -> None:
if quantity == 0:
return self.remove_item(item_id) # documented contract
self._check_qty(quantity)
with self._lock:
self._lines[item_id] = CartLine(self._lines[item_id].item, quantity)
def apply_promotions(self, rules: list[PromotionRule]) -> Receipt:
with self._lock:
snap = CartSnapshot(self.user_id, self._currency or "USD",
tuple(self._lines.values()))
discounts = [d for r in rules for d in r.apply(snap)]
sub = snap.subtotal
total = sub
for d in discounts:
total = total - d.amount
if total.amount_in_cents < 0:
total = Money(0, snap.currency)
return Receipt(snap.lines, sub, tuple(discounts), total)
Why this works
- Exactness. Integer addition, subtraction and multiplication are exact. Percentages use
(cents * pct + 50) // 100, which is deterministic half-up rounding in one place. - Currency safety. The cart fixes its currency on the first add, so a mismatched add fails before any state changes. The currency resets when the cart becomes empty.
- Concurrency. Validation and write happen inside the same critical section, so there is no check-then-act race. An
RLockletsupdate_quantity(…, 0)callremove_itemwithout deadlocking. A checkout racing with an update sees the state fully before or fully after the update. - Rule isolation. Rules receive frozen dataclasses and tuples, so a buggy rule cannot corrupt the cart. Slow rules run outside the lock and do not block other threads.
- Auditability. Every discount carries its
rule_id, and the receipt lists all of them even when the total is clamped to zero.
Complexity
With n distinct lines and R rules:
add_item,remove_itemandupdate_quantityare O(1) on average.- Taking the snapshot is O(n) in time and space.
apply_promotionsis roughly O(n·R), since each rule typically scans the lines once.
Edge-case contract
| Case | Behavior |
|---|---|
update_quantity(id, 0) | Removes the line |
Non-positive, non-int or bool quantity | ValueError |
Unknown item_id on remove or update | KeyError |
| Re-adding the same SKU | Quantity increases; a different price raises |
| Mixed currencies | CurrencyMismatchError |
| Discounts exceed subtotal | Total floored at 0 |
| Empty cart | Zero receipt, no threshold rule fires |
Trade-offs and common mistakes
- Using floats or
Decimalcasually. Floats cause drift.Decimalworks but still needs a stated rounding rule. - Putting promotion logic in
ShoppingCartwithif/elifchains. This breaks the open/closed principle. - Running rules while holding the lock. This hurts throughput. Worse, rules that read live cart state can see inconsistent data.
- Locking only writes. A checkout that reads without the lock can observe a half-applied update.
- Exposing the internal dict. Callers could then mutate state without the lock. Return immutable copies.
- Ignoring rule ordering. Percentage rules applied before or after a flat discount give different results. Here every rule sees the original snapshot, so results do not depend on order. If stacking is required, add an explicit priority or a pipeline stage.
- Locking granularity. One lock per cart is sufficient because carts are per user and contention is low. A global lock would serialize unrelated users.
Possible extensions include per-rule caps, mutually exclusive promotions, tax calculation as a further strategy, and persisting receipts for audit.