Notes
Requirements
Fix the scope. There is a catalog of products with prices. A shopper adds, removes and changes quantities in a cart. Automatic offers like buy two get one free apply by themselves, and coupon codes can be entered, some of which stack. The bill shows tax and shipping. Checkout reserves stock, hands off to a payment gateway, and must be safe to retry. Search and reviews are out of scope.
Ask the questions that change the code. Do we reserve stock when an item goes into the cart? No, only at checkout, or carts would lock up the whole warehouse. If a price changes while the item sits in the cart, the checkout price wins. Offers apply first, then percent coupons, then flat ones. Two coupons combine only if both allow it. Tax is charged on the discounted amount, and an unpaid order holds stock for ten minutes.
- catalog of products with prices
- add, remove, change quantity
- automatic offers: buy 2 get 1
- coupon codes, some stackable
- tax and shipping on the bill
- checkout reserves the stock
- hand off to a payment gateway
- retrying checkout is safe
- many shoppers at once
- out of scope: search, reviews
- reserve stock on add to cart?
- no, only at checkout
- price changes while in cart?
- use the price at checkout
- percent before flat coupons?
- yes: offers, percent, flat
- two big coupons together?
- only if both are stackable
- tax on the discounted amount? yes
- unpaid order: hold 10 minutes
Entities
The entities. The catalog maps a SKU to a product with its current price. Each shopper has one cart that holds SKUs, quantities and entered coupon codes, but no prices. The inventory counts stock per SKU. Pricing turns cart lines into a bill. Checkout turns a bill into an order. Keeping prices out of the cart means a stale price can never sneak into an order.
Class diagram
Now the types. Product, line and adjustment never change after creation, so they are records. Money is a long number of cents, and every percentage is in basis points, where one thousand means ten percent. A tiny helper computes a percentage with whole numbers and rounds half up. No double ever touches money, so a bill always adds up to the last cent, and tests can compare exact numbers.
record Product(String sku, String name,
long priceCents)
record Line(Product product, int qty)
record Adjustment(String label, long cents)
static long pct(long cents, long bps) {
return (cents * bps + 5_000) / 10_000;
}
// 10 percent = 1,000 bps, rounded half up The cart
The cart is deliberately dumb. It maps each SKU to a quantity and remembers coupon codes, in insertion order so the bill reads nicely. The shop checks a SKU exists before adding it. The cart's methods are synchronized, because the same shopper may have two browser tabs open. It stores no prices and no stock, so there is nothing in it that can go stale.
Map<String, Integer> qty
= new LinkedHashMap<>();
Set<String> couponCodes
= new LinkedHashSet<>();
synchronized void add(String sku, int n)
{ qty.merge(sku, n, Integer::sum); }
synchronized void setQty(String sku, int n)
synchronized void clear() Pricing pipeline
Pricing is a pipeline. One small interface, pricing step, with one method that reads and fills a bill. The pipeline is an ordered list: subtotal, discounts, tax at eighteen percent, then shipping that is free above a threshold. Each step is tiny and testable alone, and the order is written down in one place. A new rule, like a gift wrap fee, is a new step slotted into the list.
interface PricingStep {void apply(Bill b);}
List.of(new SubtotalStep(),
new DiscountStep(),
new TaxStep(1_800),
new ShippingStep(999_00, 49_00));
Bill price(lines, coupons) {
Bill b = new Bill(lines, coupons);
steps.forEach(s -> s.apply(b));
return b; } Strategy: coupons
Each kind of discount is a Strategy behind one coupon interface. A coupon has a code, a kind, a stackable flag, and one method that returns how much it takes off the bill as it stands right now, or zero if it does not apply. Buy X get Y free, percent off with a cap and a minimum spend, and flat off are three small records. A new promotion type is a new class; the discount step does not change.
interface Coupon {
String code();
Kind kind(); // ITEM, PERCENT, FLAT
boolean stackable();
long discount(Bill bill); // 0 = no
}
record BuyXGetYFree(code, sku, buy, free)
record PercentOff(code, bps, cap,
minSpend, stackable)
record FlatOff(code, cents, minSpend, ..) Stacking rules
Stacking rules live in two places. When a code is entered, the shop refuses it if either it or a code already in the cart is not stackable. When pricing, the discount step sorts coupons by kind, so item offers come first, then percentages, then flat amounts, and each one sees the running total left by the ones before. Every discount is capped at what is left, so a bill can never go below zero.
sorted = coupons by kind:
ITEM, then PERCENT, then FLAT
for (Coupon c : sorted) {
long d = min(c.discount(b),
b.afterDiscounts());
if (d > 0) b.discounts.add(..);
else b.notes.add(code + " not met");
}
apply time: a non-stackable coupon
must be the only code in the cart Which pattern?
Interviewers often ask which pattern fits. Strategy fits each discount rule, because the rules are interchangeable. A chain, or pipeline, fits the order of steps. Decorator also works, where each discount wraps the price source below it, but then the order is hidden inside how objects were nested at startup. A plain list of steps plus coupon strategies keeps the order visible and easy to change.
- Strategy: one coupon type
- per class, same interface
- Chain / pipeline: steps run
- in a fixed, visible order
- Decorator: each discount wraps
- a price source; works, but
- order hides in object nesting
- pick: list of steps + strategies
A worked bill
Walk one cart through it. Shoes, three pairs of socks and a bottle make four thousand two hundred. Buy two get one free removes one pair of socks, three hundred. The ten percent coupon now sees three thousand nine hundred and takes three hundred and ninety. The flat coupon takes two hundred more. Tax of eighteen percent on three thousand three hundred and ten adds five hundred ninety-five point eight, and shipping is free.
- shoes 2,500 + 3 socks 900
- + bottle 800 = 4,200.00
- B2G1 socks - 300.00
- FEST10 10% of 3,900 - 390.00
- FLAT200 - 200.00
- after discounts 3,310.00
- tax 18% + 595.80
- shipping (over 999) 0.00
- total 3,905.80
Flow: checkout
The checkout flow. First the idempotency key is checked. Then, holding the cart's lock, price the cart with current catalog prices, reserve every line in the inventory, create the order with a hold that ends in ten minutes, and clear the cart. After the lock is released, hand the payment request to the gateway. If any step fails before the order exists, nothing has changed.
bill = pricing.price(lines, coupons)
if (lines.isEmpty()) throw empty
if (!inventory.reserveAll(lines))
throw out of stock
order = new Order(id, bill,
now + 10 minutes)
orders.put(id, order); cart.clear()
// after the lock:
gateway.requestPayment(id, total, key) Stock holds
Stock is reserved all or nothing. The inventory takes each line in turn, and if one SKU runs short it puts back everything it already took and fails. Taking stock moves it out of available, so nobody else can buy it, but the order is not paid yet. A sweeper runs every minute; any order still waiting for payment after its hold time is expired and its stock goes back on the shelf.
List<Line> taken = new ArrayList<>();
for (Line l : lines) {
if (!tryTake(sku(l), l.qty())) {
taken.forEach(this::putBack);
return false;
}
taken.add(l);
}
return true; Payment hand-off
Payment is a hand-off. The shop asks the gateway to charge, and the answer comes back later as a callback. Now two things can race: the paid callback and the expiry sweeper. The order status is an atomic reference, and both sides try to move it from payment pending with compare-and-set. Exactly one wins. If the payment arrives after the order already expired, the shop refunds it instead of shipping goods it no longer holds.
AtomicReference<OrderStatus> status
boolean move(OrderStatus to) {
return status.compareAndSet(
PAYMENT_PENDING, to);
}
paid callback: move(PAID)
lost the race? refund
sweeper: move(EXPIRED), release Idempotent checkout
Idempotent checkout. The app sends a key with every checkout, and retries reuse it. The shop puts a future into a concurrent map with put-if-absent. The first call wins and does the work; a retry, even one that arrives while the first is still running, finds the future and waits for the same order. If the first attempt failed before creating anything, the key is removed so the shopper can simply try again.
var mine = new CompletableFuture<Order>();
var prior = byKey.putIfAbsent(key, mine);
if (prior != null) return prior.join();
try {
Order o = placeOrder(user);
mine.complete(o); return o;
} catch (RuntimeException e) {
byKey.remove(key, mine);
mine.completeExceptionally(e);
throw e;
} Concurrency
The race that matters: a limited sneaker drop with three pairs left and ten shoppers pressing pay at once. A check-then-subtract would oversell. Each SKU's stock is an atomic integer, and taking stock is a compare-and-set loop: read, check there is enough, swap in the smaller number, retry if someone else got there first. Exactly three orders are created and seven shoppers see out of stock, every time.
Give every shared thing a safe home. Stock uses atomic integers with compare-and-set, so shoppers of different items never wait on each other. A cart is synchronized, and checkout holds that one cart's lock, so two tabs of the same shopper cannot both check out one cart. Order status is an atomic reference. Idempotency uses put-if-absent. The slow gateway call happens outside every lock.
AtomicInteger left = stock.get(sku);
while (true) {
int cur = left.get();
if (cur < n) return false;
if (left.compareAndSet(cur, cur - n))
return true;
} - stock: AtomicInteger + CAS
- cart: synchronized, and
- checkout holds the cart lock
- order status: AtomicReference
- idempotency: putIfAbsent
- of a CompletableFuture
- orders, carts, catalog:
- ConcurrentHashMap
- gateway call: outside locks
- records: immutable
Extensibility
Extending it. A category coupon is one more coupon class. Loyalty points or a gift wrap fee is one more pricing step. Tax by category means the tax step spreads cart-level discounts across lines first. In a real store, stock lives in a database, and the same compare-and-set idea becomes one conditional update that subtracts only when enough quantity is left.
- category coupon: new Coupon
- loyalty points: a new step
- tax per category: TaxStep
- splits the discount by line
- flash sale price: a step
- before discounts
- saved carts: persist sku + qty
- database stock: UPDATE .. SET
- qty = qty - n WHERE qty >= n
Testing
The full code is below the player. The demo refuses a coupon that cannot stack, prints the bill from the worked example, checks out twice with the same key and gets one order and one payment request, then pays it. A second order is left unpaid; moving a fake clock fifteen minutes expires it and returns the stock, and a late payment is refunded. Finally ten threads race for three pairs.
coupon MEGA25 -> cannot be combined bill total 3,905.80 checkout K-1 -> O1 PAYMENT_PENDING retry K-1 -> O1 again, 1 charge pay O1 -> PAID O2 unpaid, clock +15 min -> EXPIRED bottles left: 3, back to 4 late payment for O2 -> refunded race: 10 shoppers, 3 left -> 3 orders, 7 out of stock
Follow-ups
Expect these follow-ups. Should adding to cart reserve stock? Usually no; for a flash sale, a short hold is fine. What if a price changed? Reprice at checkout and show the new bill. Why percent before flat? It is a business rule, so make it explicit in one place. What if the gateway times out? Retry with the same key. And a coupon once per user is a redemption record with a unique key on user and code.
- reserve on add to cart?
- only for flash sales, short TTL
- price changed at checkout?
- reprice and show the new bill
- percent then flat, or reverse?
- a business rule: write it down
- gateway times out?
- retry with the same key
- coupon used once per user?
- a redemption table, unique key
Say it like this
Here is the short version to say out loud. The cart holds SKUs and coupon codes, nothing else. A pipeline of steps prices it: subtotal, coupon strategies in a fixed order, tax and shipping. Checkout is idempotent by key, reserves stock with compare-and-set, and holds it until the order is paid or expires, with a status compare-and-set settling that race.
- "The cart holds skus and codes.
- A pipeline of steps prices it:
- subtotal, coupon strategies in
- a fixed order, tax, shipping.
- Checkout is idempotent by key,
- reserves stock with CAS, holds
- it until paid or expired, and
- a status CAS settles the race."