KatInterview

Build a Thread-Safe Cart with Pluggable Promotions

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designstrategy-patternvalue-object

Last 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

  1. Exact money. Never use floats for currency. Use integer minor units (cents) or an immutable Money value object that carries a currency code and supports basic arithmetic.
  2. Cart operations. Support adding an item, removing an item by id, and changing a quantity. Quantities must be positive integers.
  3. 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.
  4. 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.
  5. 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.