LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 30 OF 42

Design a Shopping Cart with Coupons: LLD in Java

A shopping cart and checkout designed and coded: requirements, catalog, cart and lines, a pricing pipeline of steps, coupons as Strategies with stacking rules, tax and shipping in exact cents, stock holds that expire on a fake clock, the payment hand-off with order states moved by compare-and-set, idempotent checkout, the last-units race and the follow-ups, with a full Java 17 solution.

Patterns usedStrategyDecorator

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 22

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 475 lines, with a small main() demo. Save it as Shop.java, then run javac Shop.java && java Shop.

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** A cart and checkout: a pricing pipeline with stackable coupons, stock holds and idempotent orders. */
public class Shop {

    // ---------- money ----------
    /** Money is whole cents in a long; percentages are basis points (1,000 = 10 percent). */
    static String money(long cents) { return String.format("%,d.%02d", cents / 100, cents % 100); }

    /** A percentage of an amount, in integer math, rounded half up. */
    static long pct(long cents, long bps) { return (cents * bps + 5_000) / 10_000; }

    // ---------- the model ----------
    record Product(String sku, String name, long priceCents) {}

    record Line(Product product, int qty) {
        long amount() { return product.priceCents() * qty; }
    }

    record Adjustment(String label, long cents) {}

    /** One shopper's cart: SKUs, quantities and coupon codes. No prices, so nothing can go stale. */
    static final class Cart {
        private final Map<String, Integer> qty = new LinkedHashMap<>();
        private final 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) {
            if (n <= 0) qty.remove(sku);
            else qty.put(sku, n);
        }

        synchronized void addCoupon(String code) { couponCodes.add(code); }

        synchronized Map<String, Integer> items() { return new LinkedHashMap<>(qty); }

        synchronized List<String> coupons() { return List.copyOf(couponCodes); }

        synchronized void clear() {
            qty.clear();
            couponCodes.clear();
        }
    }

    /** Filled in step by step by the pricing pipeline. */
    static final class Bill {
        final List<Line> lines;
        final List<Coupon> coupons;
        final List<Adjustment> discounts = new ArrayList<>();
        final List<String> notes = new ArrayList<>();
        long subtotal;
        long tax;
        long shipping;

        Bill(List<Line> lines, List<Coupon> coupons) {
            this.lines = List.copyOf(lines);
            this.coupons = List.copyOf(coupons);
        }

        long discountTotal() { return discounts.stream().mapToLong(Adjustment::cents).sum(); }

        long afterDiscounts() { return subtotal - discountTotal(); }

        long total() { return afterDiscounts() + tax + shipping; }
    }

    // ---------- coupons: one Strategy per kind of discount ----------
    enum Kind { ITEM, PERCENT, FLAT } // applied in this order

    interface Coupon {
        String code();

        Kind kind();

        boolean stackable();

        /** How much this takes off the bill as it stands now; 0 when it does not apply. */
        long discount(Bill bill);
    }

    /** Buy 'buy' and get 'free' more of the same SKU at no cost. Applied automatically. */
    record BuyXGetYFree(String code, String sku, int buy, int free) implements Coupon {
        @Override
        public Kind kind() { return Kind.ITEM; }

        @Override
        public boolean stackable() { return true; }

        @Override
        public long discount(Bill bill) {
            for (Line l : bill.lines) {
                if (!l.product().sku().equals(sku)) continue;
                int groups = l.qty() / (buy + free);
                return (long) groups * free * l.product().priceCents();
            }
            return 0;
        }
    }

    record PercentOff(String code, long bps, long capCents, long minSpendCents, boolean stackable)
            implements Coupon {
        @Override
        public Kind kind() { return Kind.PERCENT; }

        @Override
        public long discount(Bill bill) {
            long base = bill.afterDiscounts();
            return base < minSpendCents ? 0 : Math.min(capCents, pct(base, bps));
        }
    }

    record FlatOff(String code, long cents, long minSpendCents, boolean stackable) implements Coupon {
        @Override
        public Kind kind() { return Kind.FLAT; }

        @Override
        public long discount(Bill bill) { return bill.afterDiscounts() < minSpendCents ? 0 : cents; }
    }

    // ---------- the pricing pipeline: an ordered list of small steps ----------
    interface PricingStep { void apply(Bill bill); }

    static final class SubtotalStep implements PricingStep {
        @Override
        public void apply(Bill b) { b.subtotal = b.lines.stream().mapToLong(Line::amount).sum(); }
    }

    /** Item offers, then percent, then flat; each sees the running total and never goes below zero. */
    static final class DiscountStep implements PricingStep {
        @Override
        public void apply(Bill b) {
            List<Coupon> sorted = new ArrayList<>(b.coupons);
            sorted.sort(Comparator.comparing(Coupon::kind));
            for (Coupon c : sorted) {
                long d = Math.min(c.discount(b), b.afterDiscounts());
                if (d > 0) b.discounts.add(new Adjustment(c.code(), d));
                else b.notes.add(c.code() + " does not apply yet");
            }
        }
    }

    static final class TaxStep implements PricingStep {
        private final long bps;

        TaxStep(long bps) { this.bps = bps; }

        @Override
        public void apply(Bill b) { b.tax = pct(b.afterDiscounts(), bps); }
    }

    static final class ShippingStep implements PricingStep {
        private final long freeOverCents;
        private final long feeCents;

        ShippingStep(long freeOverCents, long feeCents) {
            this.freeOverCents = freeOverCents;
            this.feeCents = feeCents;
        }

        @Override
        public void apply(Bill b) { b.shipping = b.afterDiscounts() >= freeOverCents ? 0 : feeCents; }
    }

    static final class PricingPipeline {
        private final List<PricingStep> steps;

        PricingPipeline(List<PricingStep> steps) { this.steps = List.copyOf(steps); }

        Bill price(List<Line> lines, List<Coupon> coupons) {
            Bill b = new Bill(lines, coupons);
            steps.forEach(s -> s.apply(b));
            return b;
        }
    }

    // ---------- stock ----------
    static final class Inventory {
        private final Map<String, AtomicInteger> stock = new ConcurrentHashMap<>();

        void set(String sku, int n) { stock.put(sku, new AtomicInteger(n)); }

        int available(String sku) { return stock.get(sku).get(); }

        /** Compare-and-set: the last units are never sold twice. */
        boolean tryTake(String sku, int n) {
            AtomicInteger left = stock.get(sku);
            while (true) {
                int cur = left.get();
                if (cur < n) return false;
                if (left.compareAndSet(cur, cur - n)) return true;
            }
        }

        void putBack(Line l) { stock.get(l.product().sku()).addAndGet(l.qty()); }

        /** All lines or none: on a shortage, put back whatever was already taken. */
        boolean reserveAll(List<Line> lines) {
            List<Line> taken = new ArrayList<>();
            for (Line l : lines) {
                if (!tryTake(l.product().sku(), l.qty())) {
                    taken.forEach(this::putBack);
                    return false;
                }
                taken.add(l);
            }
            return true;
        }
    }

    // ---------- orders and the payment hand-off ----------
    enum OrderStatus { PAYMENT_PENDING, PAID, PAYMENT_FAILED, EXPIRED }

    static final class Order {
        final String id;
        final String userId;
        final Bill bill;
        final Instant holdUntil;
        private final AtomicReference<OrderStatus> status =
                new AtomicReference<>(OrderStatus.PAYMENT_PENDING);

        Order(String id, String userId, Bill bill, Instant holdUntil) {
            this.id = id;
            this.userId = userId;
            this.bill = bill;
            this.holdUntil = holdUntil;
        }

        /** Paid, failed and expired all race to leave PAYMENT_PENDING; exactly one wins. */
        boolean move(OrderStatus to) { return status.compareAndSet(OrderStatus.PAYMENT_PENDING, to); }

        OrderStatus status() { return status.get(); }
    }

    interface PaymentGateway {
        void requestPayment(String orderId, long cents, String idempotencyKey);

        void refund(String orderId, long cents);
    }

    // ---------- the shop ----------
    static final Duration HOLD = Duration.ofMinutes(10);

    private final Map<String, Product> catalog = new ConcurrentHashMap<>();
    private final Map<String, Coupon> couponsByCode = new ConcurrentHashMap<>();
    private final List<Coupon> autoOffers = new ArrayList<>();
    private final Map<String, Cart> carts = new ConcurrentHashMap<>();
    private final Map<String, Order> orders = new ConcurrentHashMap<>();
    private final Map<String, CompletableFuture<Order>> byKey = new ConcurrentHashMap<>();
    private final Inventory inventory = new Inventory();
    private final AtomicLong orderSeq = new AtomicLong();
    private final PricingPipeline pricing;
    private final PaymentGateway gateway;
    private final Supplier<Instant> clock;

    Shop(PricingPipeline pricing, PaymentGateway gateway, Supplier<Instant> clock) {
        this.pricing = pricing;
        this.gateway = gateway;
        this.clock = clock;
    }

    void addProduct(Product p, int stock) {
        catalog.put(p.sku(), p);
        inventory.set(p.sku(), stock);
    }

    void addCoupon(Coupon c) { couponsByCode.put(c.code(), c); }

    void addAutoOffer(Coupon c) { autoOffers.add(c); }

    Cart cart(String userId) { return carts.computeIfAbsent(userId, k -> new Cart()); }

    void addToCart(String userId, String sku, int qty) {
        if (!catalog.containsKey(sku)) throw new IllegalArgumentException("Unknown SKU " + sku);
        if (qty <= 0) throw new IllegalArgumentException("Quantity must be positive");
        cart(userId).add(sku, qty);
    }

    /** Stacking rule: a non-stackable code must be the only code in the cart. */
    String applyCoupon(String userId, String code) {
        Coupon c = couponsByCode.get(code);
        if (c == null) return "Unknown coupon " + code;
        Cart cart = cart(userId);
        synchronized (cart) {
            List<String> current = cart.coupons();
            boolean clash = !current.isEmpty()
                    && (!c.stackable() || current.stream().anyMatch(x -> !couponsByCode.get(x).stackable()));
            if (clash) return code + " cannot be combined with " + current;
            cart.addCoupon(code);
            return code + " applied";
        }
    }

    Bill bill(String userId) { return priceCart(cart(userId)); }

    private Bill priceCart(Cart cart) {
        List<Line> lines = new ArrayList<>();
        cart.items().forEach((sku, n) -> lines.add(new Line(catalog.get(sku), n))); // price at checkout time
        List<Coupon> coupons = new ArrayList<>(autoOffers);
        cart.coupons().forEach(code -> coupons.add(couponsByCode.get(code)));
        return pricing.price(lines, coupons);
    }

    /** Idempotent: the same key always returns the same order, even while the first call is running. */
    Order checkout(String userId, String idempotencyKey) {
        CompletableFuture<Order> mine = new CompletableFuture<>();
        CompletableFuture<Order> prior = byKey.putIfAbsent(idempotencyKey, mine);
        if (prior != null) return prior.join();
        Order o;
        try {
            o = placeOrder(userId);
            mine.complete(o);
        } catch (RuntimeException e) {
            byKey.remove(idempotencyKey, mine); // nothing was created, so a retry may run again
            mine.completeExceptionally(e);
            throw e;
        }
        gateway.requestPayment(o.id, o.bill.total(), idempotencyKey); // hand-off, outside every lock
        return o;
    }

    private Order placeOrder(String userId) {
        Cart cart = cart(userId);
        synchronized (cart) { // two tabs of one shopper cannot check out the same cart twice
            Bill bill = priceCart(cart);
            if (bill.lines.isEmpty()) throw new IllegalStateException("Cart is empty");
            if (!inventory.reserveAll(bill.lines)) throw new IllegalStateException("Out of stock");
            Order o = new Order("O" + orderSeq.incrementAndGet(), userId, bill, clock.get().plus(HOLD));
            orders.put(o.id, o);
            cart.clear();
            return o;
        }
    }

    /** The gateway calls back with the result. */
    String onPaymentResult(String orderId, boolean success) {
        Order o = orders.get(orderId);
        if (success) {
            if (o.move(OrderStatus.PAID)) return orderId + " PAID";
            gateway.refund(orderId, o.bill.total()); // the hold already expired: give the money back
            return orderId + " was " + o.status() + ", late payment refunded";
        }
        if (o.move(OrderStatus.PAYMENT_FAILED)) o.bill.lines.forEach(inventory::putBack);
        return orderId + " " + o.status();
    }

    /** Run by a timer every minute: unpaid holds go back on the shelf. */
    int expireHolds() {
        Instant now = clock.get();
        int expired = 0;
        for (Order o : orders.values()) {
            if (now.isAfter(o.holdUntil) && o.move(OrderStatus.EXPIRED)) {
                o.bill.lines.forEach(inventory::putBack);
                expired++;
            }
        }
        return expired;
    }

    // ---------- demo ----------
    static final class FakeGateway implements PaymentGateway {
        final Queue<String> requests = new ConcurrentLinkedQueue<>();

        @Override
        public void requestPayment(String orderId, long cents, String key) {
            requests.add(orderId + " " + money(cents) + " key " + key);
        }

        @Override
        public void refund(String orderId, long cents) {
            System.out.println("  [gateway] refund " + orderId + " " + money(cents));
        }
    }

    static void printBill(Bill b) {
        b.lines.forEach(l -> System.out.printf("  %-14s x%d %12s%n", l.product().name(), l.qty(),
                money(l.amount())));
        System.out.printf("  %-17s %12s%n", "subtotal", money(b.subtotal));
        b.discounts.forEach(d -> System.out.printf("  %-17s %12s%n", d.label(), "-" + money(d.cents())));
        System.out.printf("  %-17s %12s%n", "tax 18%", money(b.tax));
        System.out.printf("  %-17s %12s%n", "shipping", money(b.shipping));
        System.out.printf("  %-17s %12s%n", "total", money(b.total()));
        b.notes.forEach(n -> System.out.println("  note: " + n));
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-05-01T12:00:00Z"));
        PricingPipeline pipeline = new PricingPipeline(List.of(new SubtotalStep(), new DiscountStep(),
                new TaxStep(1_800), new ShippingStep(999_00L, 49_00L)));
        FakeGateway gateway = new FakeGateway();
        Shop shop = new Shop(pipeline, gateway, now::get);
        shop.addProduct(new Product("SHOE-1", "Trail shoes", 2_500_00L), 10);
        shop.addProduct(new Product("SOCK-3", "Running socks", 300_00L), 50);
        shop.addProduct(new Product("BOTL-1", "Steel bottle", 800_00L), 5);
        shop.addProduct(new Product("DROP-9", "Limited sneaker", 9_000_00L), 3);
        shop.addAutoOffer(new BuyXGetYFree("SOCKS B2G1", "SOCK-3", 2, 1));
        shop.addCoupon(new PercentOff("FEST10", 1_000, 500_00L, 2_000_00L, true));
        shop.addCoupon(new FlatOff("FLAT200", 200_00L, 1_000_00L, true));
        shop.addCoupon(new PercentOff("MEGA25", 2_500, 2_000_00L, 0, false));

        shop.addToCart("asha", "SHOE-1", 1);
        shop.addToCart("asha", "SOCK-3", 3);
        shop.addToCart("asha", "BOTL-1", 1);
        System.out.println(shop.applyCoupon("asha", "FEST10"));
        System.out.println(shop.applyCoupon("asha", "FLAT200"));
        System.out.println(shop.applyCoupon("asha", "MEGA25"));
        Bill bill = shop.bill("asha");
        printBill(bill);
        if (bill.total() != 3_905_80L) throw new AssertionError("wrong total " + bill.total());

        // A nervous double tap: same key, same order, one payment request.
        Order first = shop.checkout("asha", "K-1");
        Order retry = shop.checkout("asha", "K-1");
        System.out.println("checkout K-1 -> " + first.id + " " + first.status() + ", retry -> " + retry.id
                + ", payment requests " + gateway.requests.size());
        if (first != retry || gateway.requests.size() != 1) throw new AssertionError("not idempotent");
        System.out.println(shop.onPaymentResult(first.id, true));

        // An abandoned order: move the fake clock instead of sleeping.
        shop.addToCart("ravi", "BOTL-1", 1);
        Order abandoned = shop.checkout("ravi", "K-2");
        System.out.println(abandoned.id + " total " + money(abandoned.bill.total()) + ", bottles left "
                + shop.inventory.available("BOTL-1"));
        now.set(now.get().plus(Duration.ofMinutes(15)));
        int expired = shop.expireHolds();
        System.out.println("expired " + expired + ", bottles left " + shop.inventory.available("BOTL-1"));
        System.out.println(shop.onPaymentResult(abandoned.id, true));

        // Ten shoppers, three limited sneakers.
        AtomicInteger sold = new AtomicInteger(), outOfStock = new AtomicInteger();
        CountDownLatch start = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            String user = "fan" + i;
            shop.addToCart(user, "DROP-9", 1);
            pool.submit(() -> {
                try {
                    start.await();
                    shop.checkout(user, "K-" + user);
                    sold.incrementAndGet();
                } catch (IllegalStateException e) {
                    outOfStock.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        start.countDown();
        pool.shutdown();
        if (!pool.awaitTermination(5, TimeUnit.SECONDS)) throw new AssertionError("race did not finish");
        System.out.println("Race: " + sold.get() + " orders, " + outOfStock.get() + " out of stock, left "
                + shop.inventory.available("DROP-9"));
        if (sold.get() != 3 || shop.inventory.available("DROP-9") != 0) throw new AssertionError("oversold");
    }
}

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.

Requirements
  • 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
Clarify first
  • 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.

Value types
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.

Cart
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.

PricingPipeline
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.

Coupon
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.

DiscountStep.apply()
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, chain or decorator?
  • 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.

One cart, priced
  • 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.

placeOrder() under cart lock
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.

Inventory.reserveAll()
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.

Order status
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.

checkout(user, key)
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.

Inventory.tryTake()
AtomicInteger left = stock.get(sku);
while (true) {
  int cur = left.get();
  if (cur < n) return false;
  if (left.compareAndSet(cur, cur - n))
    return true;
}
Thread safety checklist
  • 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.

Extension points
  • 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.

Run it
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.

Follow-ups to expect
  • 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.

In the interview
  • "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."

Interview questions

How would you model coupons and discounts so new types are easy to add?

A Coupon interface (Strategy) with code, kind, stackable and discount(bill). Percent off, flat off and buy X get Y free are separate classes. A discount step in the pricing pipeline applies them, so a new promotion is a new class with no change to existing code.

In what order should discounts, tax and shipping be applied?

Make the order explicit as a pipeline: subtotal, item offers, percent coupons, flat coupons, then tax on the discounted amount, then shipping. The exact order is a business rule; the design point is that it lives in one visible list, not scattered across classes.

How do you stop a bill from going negative when coupons stack?

Cap each discount at the amount still left after the earlier ones, and reject non-stackable codes when they are entered. Percent coupons can also carry a maximum amount and a minimum spend.

When should stock be reserved: on add to cart or at checkout?

Usually at checkout, otherwise idle carts lock up stock. The reservation is a hold with an expiry, released by a sweeper if payment never arrives. For flash sales a short hold on add to cart can be acceptable.

How do you prevent overselling the last few units?

Make the decrement atomic: an AtomicInteger per SKU with a compare-and-set loop that only subtracts when enough is left. In a database the same idea is a conditional update that subtracts quantity only where the remaining quantity is large enough, checking the affected row count.

How do you make checkout idempotent?

The client sends an idempotency key and reuses it on retries. The server stores key to result with putIfAbsent (or a unique key in the database), so a retry returns the same order and never charges twice. If the first attempt failed before creating anything, the key is removed so a retry can run.

What if the payment callback arrives after the order expired?

Both the callback and the expiry sweeper move the order out of PAYMENT_PENDING with compare-and-set, so only one wins. If expiry won, the late payment is refunded because the stock has already gone back on sale.

Why does the cart not store prices?

Prices change. Storing only SKUs and quantities means the bill is always computed from the current catalog at checkout, so a stale or tampered price cannot end up in an order.

Why use long cents and basis points instead of double?

Doubles cannot represent most decimal amounts exactly, so totals drift by a cent. Long cents plus percentages in basis points keep all math in integers, with one clearly defined rounding rule.