These are the notes for Low-Level Design (LLD) episode 79: designing the shopping cart and checkout of an online shop. We start from the e-commerce requirements, build Product, CartItem, Cart and Order, store money safely, guard the order with an order state machine, build a coupon and discount engine from Specification objects, compute the bill with a pricing pipeline, plug in payment providers with the Strategy and Adapter patterns, and finish with an idempotent checkout that charges a customer once even when they tap Pay twice.
How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. The shop, the customers, the prices, the coupons FEST100 and DIYA20, the 5% tax, the 40-rupee delivery fee and the two payment providers PayFast and QuickPay (with their SDK classes PayFastSdk and QuickPayClient) are all made up for teaching. Nothing here describes any real company's app, prices or payment API.
The previous episode (78) designed inventory: reserving, committing and releasing stock. Checkout is where that inventory gets sold.
1. The problem: a Diwali sale order
| Real life | In the design |
|---|---|
| The billing counter prints one line per item: "Diya set × 3" | CartItem (product + quantity) inside a Cart |
| The printed bill says 689.40, to the paisa | Money stored exactly: whole paise in a long, or BigDecimal |
| "Your order is packed / shipped / delivered" | An Order with an order state machine |
| "FEST100: 100 off above 999, not on gold coins" | Coupon rules as Specification objects |
| The bill: items, offers, coupon, tax, delivery, always in that order | A pricing pipeline |
| "Card, UPI or wallet?" | Strategy: one PaymentGateway interface |
| A SIM adapter makes a nano SIM fit an older phone | Adapter: wraps each provider's SDK |
| The ration card stamped for November: no second bag this month | An idempotency key: a retried Pay charges once |
2. E-commerce requirements and the words
E-commerce means selling online. The e-commerce requirements are the list of what our checkout must do. In an interview, say them out loud before you design anything:
- Add products to a cart, change quantities, see a running subtotal.
- Apply coupons and offers, with rules marketing can change often.
- Compute a correct bill: subtotal, item offers, coupon, tax, delivery, to the paisa.
- Turn the cart into an order at checkout, and track the order's state afterwards.
- Pay through more than one payment provider, and add new ones without rewriting checkout.
- Charge exactly once, even when the network is slow and the customer taps Pay again.
Out of scope for this episode (say so in the interview): search, reviews, recommendations, warehouses (episode 78 did stock), delivery routing (next episode does delivery).
The core classes:
- Product: a thing for sale, with a name and a price. Example:
Product("Diya set", 12990), a diya set at 129.90 rupees. - CartItem: one line of the cart: a product and a quantity. Example: diya set × 3. Its total is price × quantity.
- Cart: all the cart items of one customer before they pay. It can give the subtotal (the sum of its items).
- Order: what the cart becomes at checkout: a frozen copy (a snapshot) of the items and the total, plus an id and a state. If the diya price changes tomorrow, the order still says what Asha paid.
3. Attempt 1: money as double
The obvious cart stores prices as double:
import java.util.*;
record Product(String name, double price) {} // price in rupees, as a double
record CartItem(Product product, int qty) { // one line of the cart
double total() { return product.price() * qty; } }
class Cart {
final List<CartItem> items = new ArrayList<>();
void add(Product p, int qty) { items.add(new CartItem(p, qty)); }
double subtotal() {
double sum = 0;
for (CartItem i : items) sum += i.total();
return sum; } }
public class Main { public static void main(String[] args) {
Cart cart = new Cart();
cart.add(new Product("Rangoli colours", 99.90), 3);
cart.add(new Product("Diya set", 129.90), 3);
System.out.println("Subtotal: " + cart.subtotal());
System.out.println("Equals the bill of 689.40? " + (cart.subtotal() == 689.40));
} }
Real output:
Subtotal: 689.4000000000001
Equals the bill of 689.40? false
Why it failed
A double is a floating-point number stored in binary (base two). Most decimal fractions, like 99.90, have no exact binary form, just as 1/3 has no exact decimal form (0.3333...). Java stores the nearest binary number, and the tiny errors add up. Here is what the double 99.90 really holds, printed with BigDecimal, plus the two safe ways:
import java.math.BigDecimal;
public class Main { public static void main(String[] args) {
System.out.println("double 99.90 really is: " + new BigDecimal(99.90));
BigDecimal r = new BigDecimal("99.90").multiply(BigDecimal.valueOf(3));
BigDecimal d = new BigDecimal("129.90").multiply(BigDecimal.valueOf(3));
BigDecimal sum = r.add(d);
System.out.println("BigDecimal subtotal: " + sum);
System.out.println("equals 689.40? " + sum.equals(new BigDecimal("689.40")));
System.out.println("equals 689.4? " + sum.equals(new BigDecimal("689.4")));
System.out.println("compareTo 689.4 == 0? " + (sum.compareTo(new BigDecimal("689.4")) == 0));
long paise = 9990L * 3 + 12990L * 3;
System.out.printf("long paise: %d -> %d.%02d rupees%n", paise, paise / 100, paise % 100);
} }
Real output:
double 99.90 really is: 99.900000000000005684341886080801486968994140625
BigDecimal subtotal: 689.40
equals 689.40? true
equals 689.4? false
compareTo 689.4 == 0? true
long paise: 68940 -> 689.40 rupees
Two safe ways to store money:
| Way | How | Good for |
|---|---|---|
Whole paise in a long |
99.90 rupees → 9990L paise; add and multiply whole numbers |
Fast, simple, exact; what we use in this episode |
BigDecimal |
new BigDecimal("99.90"), add, multiply, rounding modes |
Exact decimal digits; when you need percentages with explicit rounding |
Two BigDecimal traps, both visible in the output above:
new BigDecimal(99.90)(from a double) copies the double's error. Build it from a String (new BigDecimal("99.90")) or from paise (BigDecimal.valueOf(9990, 2)).equalsalso compares the scale (number of decimal places):689.40is notequalsto689.4. Compare amounts withcompareTo(...) == 0.
Print paise as rupees with String.format("%d.%02d", p / 100, p % 100): 68940 → 689.40.
4. The Order and its state machine
An enum is a fixed list of named values: CREATED, PAID, SHIPPED, DELIVERED, CANCELLED. A state machine is a set of states plus the only legal moves (transitions) between them; everything else is refused. The order state machine:
CREATED ──pay──▶ PAID ──ship──▶ SHIPPED ──deliver──▶ DELIVERED
└──cancel──▶ CANCELLED ◀──cancel──┘
From CREATED you can pay or cancel; from PAID ship or cancel; from SHIPPED only deliver; DELIVERED and CANCELLED are final. Without the machine, a status is a free string and nothing stops "cancel" on a parcel already on a truck.
import java.util.*;
record Product(String name, long paise) {} // money as whole paise: exact
record CartItem(Product product, int qty) { long total() { return product.paise() * qty; } }
class Cart { final List<CartItem> items = new ArrayList<>();
void add(Product p, int qty) { items.add(new CartItem(p, qty)); }
long subtotal() { return items.stream().mapToLong(CartItem::total).sum(); } }
enum OrderState { CREATED, PAID, SHIPPED, DELIVERED, CANCELLED;
boolean canGo(OrderState to) { return switch (this) { // the only legal moves
case CREATED -> to == PAID || to == CANCELLED;
case PAID -> to == SHIPPED || to == CANCELLED;
case SHIPPED -> to == DELIVERED;
default -> false; }; } } // DELIVERED, CANCELLED: the end
class Order { final String id; final long total; OrderState state = OrderState.CREATED;
Order(String id, Cart c) { this.id = id; total = c.subtotal(); } // a frozen snapshot
void moveTo(OrderState to) {
if (!state.canGo(to)) throw new IllegalStateException(state + " -> " + to + " not allowed");
System.out.println(id + ": " + state + " -> " + to); state = to; } }
public class Main { public static void main(String[] args) {
Cart cart = new Cart();
cart.add(new Product("Rangoli", 9990), 3); cart.add(new Product("Diya set", 12990), 3);
Order o = new Order("ORD-501", cart);
System.out.printf("Subtotal: %d.%02d rupees%n", o.total / 100, o.total % 100);
o.moveTo(OrderState.PAID); o.moveTo(OrderState.SHIPPED); o.moveTo(OrderState.CANCELLED); } }
Real output:
Subtotal: 689.40 rupees
ORD-501: CREATED -> PAID
ORD-501: PAID -> SHIPPED
Exception in thread "main" java.lang.IllegalStateException: SHIPPED -> CANCELLED not allowed
at Order.moveTo(Main.java:16)
at Main.main(Main.java:23)
- The subtotal is now exact:
689.40 rupees. moveTocheckscanGobefore changing anything, and throws an IllegalStateException (Java's exception for "this call is not allowed in the object's current state") on an illegal move. A shipped order needs a return, not a cancel (see the homework).- The
Orderconstructor copiescart.subtotal()once: a snapshot. Later changes to the cart don't touch the order.
5. Attempt 2: an if-else coupon engine
A coupon is a code that takes money off if its rules match. The coupon and discount engine is the part of the system that decides which offers apply to a cart and how much they take off. Marketing's rule for FEST100: 100 rupees off if the cart is 999 rupees or more OR it is your first order, but NEVER on a cart with gold coins.
public class Main {
// FEST100: 100 off if the cart is 999 rupees or more, OR it's your first order,
// but NEVER on a cart with gold coins. NEWUSER: 50 off a first order.
static long off(String code, long subtotal, boolean firstOrder, boolean hasGold) {
if (code.equals("FEST100")) {
if (subtotal >= 99900 || firstOrder && !hasGold) return 10000;
} else if (code.equals("NEWUSER")) {
if (firstOrder) return 5000;
}
return 0;
}
static void show(String who, long paise) {
System.out.println(who + paise / 100 + " off"); }
public static void main(String[] args) {
show("Asha, diyas, 1299: ", off("FEST100", 129900, false, false));
show("Ravi, first order, gold: ", off("FEST100", 50000, true, true));
show("Neha, gold coin, 5000: ", off("FEST100", 500000, false, true));
}
}
Real output:
Asha, diyas, 1299: 100 off
Ravi, first order, gold: 0 off
Neha, gold coin, 5000: 100 off
Why it failed
In Java, && binds tighter than || (it has higher precedence), so the condition is read as subtotal >= 99900 || (firstOrder && !hasGold). The gold check is glued only to the first-order part, and Neha's 5000-rupee gold coin gets 100 off. The deeper problem: every new coupon or rule means editing one tangled method, and nobody can test one rule on its own.
6. The fix: Specification objects and a pricing pipeline
The Specification pattern: a specification is a small object that answers one yes/no question about something, here a cart: is the subtotal at least 999? is it a first order? does it contain gold? Specifications combine with and, or and not into bigger rules, like Lego blocks. The grouping is explicit in the method calls, so the precedence bug can't happen, each rule can be tested alone, and a new coupon is built from existing rules without editing old code.
A pricing pipeline is a fixed, ordered list of steps; each step takes the cart and the running amount and returns the new amount. Ours: subtotal → item offers → coupon → tax → delivery. The order matters: tax on the amount after the coupon is not the same as tax before it.
import java.util.*; import java.util.function.*;
record Item(String name, String type, long paise, int qty, int pctOff) { // pctOff: item offer
long total() { return paise * qty; } long offer() { return total() * pctOff / 100; } }
record Cart(List<Item> items, boolean firstOrder) {
long subtotal() { return items.stream().mapToLong(Item::total).sum(); } }
interface Spec { boolean ok(Cart c); // a Specification: one rule
default Spec and(Spec o) { return c -> ok(c) && o.ok(c); }
default Spec or(Spec o) { return c -> ok(c) || o.ok(c); }
static Spec not(Spec s) { return c -> !s.ok(c); } }
record Step(String name, BiFunction<Cart, Long, Long> fn) {} // one pipeline step
public class Main { public static void main(String[] args) {
Spec min999 = c -> c.subtotal() >= 99900, first = Cart::firstOrder;
Spec hasGold = c -> c.items().stream().anyMatch(i -> i.type().equals("GOLD"));
Spec fest100 = min999.or(first).and(Spec.not(hasGold)); // reads like the rule
List<Step> pipeline = List.of(new Step("subtotal", (c, a) -> c.subtotal()),
new Step("item offers", (c, a) -> a - c.items().stream().mapToLong(Item::offer).sum()),
new Step("coupon FEST100", (c, a) -> fest100.ok(c) ? a - 10000 : a),
new Step("tax 5%", (c, a) -> a + a * 5 / 100),
new Step("delivery", (c, a) -> a >= 50000 ? a : a + 4000)); // free from 500
Cart asha = new Cart(List.of(new Item("Diya set", "DIYA", 12990, 10, 10)), false);
long a = 0; for (Step s : pipeline) { a = s.fn().apply(asha, a);
System.out.printf("%-15s %5d.%02d%n", s.name(), a / 100, a % 100); }
Cart neha = new Cart(List.of(new Item("Gold coin", "GOLD", 500000, 1, 0)), false);
System.out.println("Neha's gold coin gets FEST100? " + fest100.ok(neha)); } }
Real output:
subtotal 1299.00
item offers 1169.10
coupon FEST100 1069.10
tax 5% 1122.55
delivery 1122.55
Neha's gold coin gets FEST100? false
Spechas one abstract method,ok, so each rule is a lambda (a short unnamed function:c -> c.subtotal() >= 99900).andandorare default methods (methods with a body inside an interface);notis a static interface method.min999.or(first).and(Spec.not(hasGold))is evaluated as(min999 or first) and not hasGold: exactly marketing's sentence.- Step by step for Asha (10 diya sets at 129.90, 10% item offer): 1299.00 → 1169.10 → 1069.10 (coupon) → 1122.55 (5% tax: 106910 × 5 / 100 = 5345 paise, rounded down to the paisa by integer division) → delivery is free from 500 rupees.
- Real shops write down a rounding rule (usually "half up" to the paisa) and apply it at one place in the pipeline. With
BigDecimalyou'd usesetScale(2, RoundingMode.HALF_UP). BiFunction<Cart, Long, Long>is Java's built-in interface for a function that takes two inputs and returns one value.
7. Paying: Strategy and Adapter
A payment gateway is the outside service that actually moves the money from the customer's card or UPI account to the shop. Payment integration means calling it and handling its answer.
- Strategy pattern (the payment gateway Strategy): a family of swappable ways to do one job, behind one interface, chosen at runtime. Our interface is
PaymentGateway { String charge(String orderId, long paise); }. Checkout depends only on it, never on a provider's name. - SDK (software development kit): the library a provider gives you to call their service. Our two made-up SDKs don't match our interface or each other:
PayFastSdk.makePayment(String merchantRef, long amountPaise)returns aString;QuickPayClient.debit(String rupees, String note)wants rupees as text like"1122.55"and returns anint. - Adapter pattern (the Adapter for payment providers): a wrapper class that implements the interface we need and translates each call into the provider's own method. Neither our checkout nor the SDK changes, just like a SIM adapter changes neither the SIM nor the phone.
import java.math.BigDecimal; import java.util.*; import java.util.concurrent.*;
class PayFastSdk { int n; // made-up provider 1
String makePayment(String merchantRef, long amountPaise) { return "PF" + ++n; } }
class QuickPayClient { int n; // made-up provider 2
int debit(String rupees, String note) { return 7000 + ++n; } } // rupees: "1122.55"
interface PaymentGateway { String charge(String orderId, long paise); } // the Strategy
class PayFastAdapter implements PaymentGateway {
final PayFastSdk sdk = new PayFastSdk();
public String charge(String id, long p) { return sdk.makePayment(id, p); } }
class QuickPayAdapter implements PaymentGateway {
final QuickPayClient qp = new QuickPayClient();
public String charge(String id, long p) {
return "QP" + qp.debit(BigDecimal.valueOf(p, 2).toPlainString(), id); } }
class Checkout { final PaymentGateway gateway; Checkout(PaymentGateway g) { gateway = g; }
String pay(String key, String orderId, long paise) {
return gateway.charge(orderId, paise); } }
public class Main { public static void main(String[] args) {
for (PaymentGateway g : List.of(new PayFastAdapter(), new QuickPayAdapter())) {
Checkout co = new Checkout(g);
String first = co.pay("KEY-501", "ORD-501", 112255); // reply lost, screen spins
String again = co.pay("KEY-501", "ORD-501", 112255); // so Asha taps Pay again
System.out.println(g.getClass().getSimpleName() + " charged " + first + " and " + again);
} } }
Real output:
PayFastAdapter charged PF1 and PF2
QuickPayAdapter charged QP7001 and QP7002
The Strategy and Adapters work: the same Checkout code drives both providers. But look: two different transactions per provider. Asha's first tap went through; only the reply was lost, so the second tap charged her again.
8. The idempotent checkout
Idempotent means doing something twice has the same effect as doing it once. An idempotent checkout charges once no matter how many times Pay is tapped or retried.
An idempotency key is a unique id the app creates once per checkout attempt (here KEY-501) and sends with every retry of that attempt. The server remembers key → result; a key it has seen gets the saved result back instead of a new charge.
The fix is three lines in Checkout:
import java.math.BigDecimal; import java.util.*; import java.util.concurrent.*;
class PayFastSdk { int n; // made-up provider 1
String makePayment(String merchantRef, long amountPaise) { return "PF" + ++n; } }
class QuickPayClient { int n; // made-up provider 2
int debit(String rupees, String note) { return 7000 + ++n; } } // rupees: "1122.55"
interface PaymentGateway { String charge(String orderId, long paise); } // the Strategy
class PayFastAdapter implements PaymentGateway {
final PayFastSdk sdk = new PayFastSdk();
public String charge(String id, long p) { return sdk.makePayment(id, p); } }
class QuickPayAdapter implements PaymentGateway {
final QuickPayClient qp = new QuickPayClient();
public String charge(String id, long p) {
return "QP" + qp.debit(BigDecimal.valueOf(p, 2).toPlainString(), id); } }
class Checkout { final PaymentGateway gateway; Checkout(PaymentGateway g) { gateway = g; }
final Map<String, String> done = new ConcurrentHashMap<>(); // idempotency key -> txn
String pay(String key, String orderId, long paise) { // same key: same answer
return done.computeIfAbsent(key, k -> gateway.charge(orderId, paise)); } }
public class Main { public static void main(String[] args) {
for (PaymentGateway g : List.of(new PayFastAdapter(), new QuickPayAdapter())) {
Checkout co = new Checkout(g);
String first = co.pay("KEY-501", "ORD-501", 112255); // reply lost, screen spins
String again = co.pay("KEY-501", "ORD-501", 112255); // so Asha taps Pay again
System.out.println(g.getClass().getSimpleName() + " charged " + first + " and " + again);
} } }
Real output:
PayFastAdapter charged PF1 and PF1
QuickPayAdapter charged QP7001 and QP7001
computeIfAbsent(key, k -> ...)runs the charge only if the key is not in the map yet, stores the result, and returns it. Later calls with the same key return the stored transaction id.ConcurrentHashMapis a map many threads can use at once safely; itscomputeIfAbsentis atomic (it can't be split): if both taps arrive at the same moment, only one runs the charge and the other waits for its answer. The mini project tests that with two real threads.- If the charge throws (declined, provider down),
computeIfAbsentstores nothing, so a retry with the same key is allowed to try again. - In a real system the map is a database table with a unique constraint on the key (so it works across many servers), and the same key is passed on to the provider, which also de-duplicates on its side.
9. The class diagram
Product(name, paise) ─▶ CartItem(product, qty) ─▶ Cart(items).subtotal() money = long paise
Cart ─checkout─▶ Order(id, frozen total, state)
OrderState: CREATED ─▶ PAID ─▶ SHIPPED ─▶ DELIVERED · CREATED/PAID ─▶ CANCELLED · else: exception
Spec (Specification): ok(cart) · and · or · not → FEST100 = min999.or(first).and(not(hasGold))
Pricing pipeline (fixed order): subtotal → item offers → coupon → tax 5% → delivery
PaymentGateway (Strategy) ◁─ PayFastAdapter(PayFastSdk) · QuickPayAdapter(QuickPayClient)
Checkout.pay(key, ...) → done.computeIfAbsent(key, charge) → one key, one charge (idempotent)
10. Interview follow-ups
| Question | Answer |
|---|---|
| An item goes out of stock during checkout? | Reserve stock when the order is created (episode 78); commit on payment, release on failure or timeout. |
| Many servers? | The in-memory map protects one JVM. Store idempotency keys in the database with a unique constraint; the second insert fails and you return the stored result. |
| Duplicate inside the provider? | Pass the same key to the provider; providers de-duplicate on it too. |
| Two coupons at once? | Stacking rules (which coupons may combine), or compute each and keep the best for the customer. |
| Returns and refunds? | New states: DELIVERED → RETURN_REQUESTED → RETURNED → REFUNDED, each with its own legal moves. |
| Prices change while the item sits in the cart? | Re-price the cart at checkout through the pipeline, show the new total, then freeze it into the order. |
| Where does tax go? | In one pipeline step, after discounts, with one written rounding rule. |
| How do you add a provider? | One new Adapter class; register it; checkout code doesn't change (open for extension, closed for modification). |
11. Common mistakes
| Mistake | What you see (real) | Fix |
|---|---|---|
double for money |
Subtotal: 689.4000000000001 and Equals the bill of 689.40? false |
Whole paise in a long, or BigDecimal |
new BigDecimal(99.90) from a double |
99.900000000000005684341886080801486968994140625 |
new BigDecimal("99.90") or BigDecimal.valueOf(9990, 2) |
BigDecimal.equals for amounts |
equals 689.4? false |
compareTo(...) == 0 |
| Order status as a free string | a shipped parcel gets "cancelled" | Enum state machine: IllegalStateException: SHIPPED -> CANCELLED not allowed |
One boolean mixing the OR operator with && |
Neha, gold coin, 5000: 100 off |
Specification objects: min999.or(first).and(not(hasGold)) |
| Steps in a different order (tax before coupon) | 1000-rupee quiz cart: 845.00 instead of 840.00 | One fixed pricing pipeline |
if (provider is PayFast) ... else ... in checkout |
checkout edited for every new provider | Strategy + one Adapter per provider |
| Charging on every tap | PayFastAdapter charged PF1 and PF2 |
Idempotency key: charged PF1 and PF1 |
| Order total read live from the cart | the order changes when the cart changes | Freeze a snapshot in the Order |
Mini project: a checkout service
One CheckoutService with a coupon registry (each Coupon = a code + a Spec rule + a discount), the pricing pipeline, orders with the state machine and history, two providers behind Adapters, and an idempotent pay. The made-up PayFast SDK refuses amounts above 5000 rupees, so we can see a failed charge and a retry. The cart merges the same product into one line (Map.merge), and refuses a quantity of 0.
import java.math.BigDecimal; import java.util.*; import java.util.concurrent.*; import java.util.function.*;
record Product(String id, String name, String type, long paise) {}
record CartItem(Product product, int qty) { long total() { return product.paise() * qty; } }
class Cart {
private final Map<String, CartItem> items = new LinkedHashMap<>(); // one line per product
final boolean firstOrder;
Cart(boolean firstOrder) { this.firstOrder = firstOrder; }
void add(Product p, int qty) {
if (qty <= 0) throw new IllegalArgumentException("quantity must be positive: " + qty);
items.merge(p.id(), new CartItem(p, qty), (old, x) -> new CartItem(p, old.qty() + qty)); }
Collection<CartItem> items() { return items.values(); }
long subtotal() { return items().stream().mapToLong(CartItem::total).sum(); } }
interface Spec { boolean ok(Cart c); // Specification
default Spec and(Spec o) { return c -> ok(c) && o.ok(c); }
default Spec or(Spec o) { return c -> ok(c) || o.ok(c); }
static Spec not(Spec s) { return c -> !s.ok(c); }
static Spec minTotal(long paise) { return c -> c.subtotal() >= paise; }
static Spec hasType(String t) { return c -> c.items().stream().anyMatch(i -> i.product().type().equals(t)); }
static Spec firstOrder() { return c -> c.firstOrder; } }
record Coupon(String code, Spec rule, LongUnaryOperator discount) {}
enum OrderState { CREATED, PAID, SHIPPED, DELIVERED, CANCELLED;
boolean canGo(OrderState to) { return switch (this) {
case CREATED -> to == PAID || to == CANCELLED;
case PAID -> to == SHIPPED || to == CANCELLED;
case SHIPPED -> to == DELIVERED;
default -> false; }; } }
class Order {
final String id; final long total; final List<String> bill;
private OrderState state = OrderState.CREATED;
final List<OrderState> history = new ArrayList<>(List.of(OrderState.CREATED));
Order(String id, long total, List<String> bill) { this.id = id; this.total = total; this.bill = List.copyOf(bill); }
synchronized void moveTo(OrderState to) {
if (!state.canGo(to)) throw new IllegalStateException(id + ": " + state + " -> " + to + " not allowed");
state = to; history.add(to); }
OrderState state() { return state; } }
interface PaymentGateway { String charge(String orderId, long paise); } // Strategy
class PayFastSdk { int n; // made-up SDK 1
String makePayment(String merchantRef, long amountPaise) {
if (amountPaise > 500000) throw new RuntimeException("PayFast: limit exceeded");
return "PF" + ++n; } }
class QuickPayClient { int n; // made-up SDK 2
int debit(String rupees, String note) { return 7000 + ++n; } }
class PayFastAdapter implements PaymentGateway { final PayFastSdk sdk = new PayFastSdk();
public String charge(String id, long p) { return sdk.makePayment(id, p); } }
class QuickPayAdapter implements PaymentGateway { final QuickPayClient qp = new QuickPayClient();
public String charge(String id, long p) { return "QP" + qp.debit(BigDecimal.valueOf(p, 2).toPlainString(), id); } }
class CheckoutService {
private final Map<String, Coupon> coupons = new HashMap<>();
private final Map<String, String> paidByKey = new ConcurrentHashMap<>(); // idempotency key -> txn
private final Map<String, PaymentGateway> gateways;
private int nextOrder = 501;
CheckoutService(Map<String, PaymentGateway> gateways) { this.gateways = gateways; }
void addCoupon(Coupon c) { coupons.put(c.code(), c); }
static String rupees(long p) { return String.format("%d.%02d", p / 100, p % 100); }
Order placeOrder(Cart cart, String code, Map<String, Integer> pctOffByType) { // the pricing pipeline
List<String> bill = new ArrayList<>();
long a = cart.subtotal(); bill.add("subtotal " + rupees(a)); // 1. subtotal
long offers = cart.items().stream() // 2. item offers
.mapToLong(i -> i.total() * pctOffByType.getOrDefault(i.product().type(), 0) / 100).sum();
a -= offers; bill.add("item offers -" + rupees(offers));
Coupon c = code == null ? null : coupons.get(code); // 3. coupon
if (code != null && c == null) bill.add("coupon " + code + ": unknown");
else if (c != null && !c.rule().ok(cart)) bill.add("coupon " + code + ": rules not met");
else if (c != null) { long d = Math.min(a, c.discount().applyAsLong(a)); a -= d;
bill.add("coupon " + code + " -" + rupees(d)); }
long tax = a * 5 / 100; a += tax; bill.add("tax 5% +" + rupees(tax)); // 4. tax
long delivery = a >= 50000 ? 0 : 4000; a += delivery; // 5. delivery
bill.add("delivery +" + rupees(delivery));
return new Order("ORD-" + nextOrder++, a, bill); }
String pay(Order o, String provider, String idempotencyKey) {
return paidByKey.computeIfAbsent(idempotencyKey, k -> {
String txn = gateways.get(provider).charge(o.id, o.total); // throws: nothing stored
o.moveTo(OrderState.PAID);
return txn; }); } }
public class Main { public static void main(String[] args) throws Exception {
PayFastAdapter payFast = new PayFastAdapter();
CheckoutService shop = new CheckoutService(Map.of("PAYFAST", payFast, "QUICKPAY", new QuickPayAdapter()));
Spec fest = Spec.minTotal(99900).or(Spec.firstOrder()).and(Spec.not(Spec.hasType("GOLD")));
shop.addCoupon(new Coupon("FEST100", fest, a -> 10000));
shop.addCoupon(new Coupon("DIYA20", Spec.hasType("DIYA"), a -> Math.min(a * 20 / 100, 20000)));
Product diya = new Product("P1", "Diya set", "DIYA", 12990);
Product rangoli = new Product("P2", "Rangoli colours", "RANGOLI", 9990);
Product gold = new Product("P3", "Gold coin 1 g", "GOLD", 700000);
Cart asha = new Cart(false);
asha.add(diya, 6); asha.add(rangoli, 2); asha.add(diya, 4); // diya merges: 10
Order o1 = shop.placeOrder(asha, "FEST100", Map.of("DIYA", 10));
System.out.println(o1.id + " " + o1.bill + " = " + CheckoutService.rupees(o1.total));
ExecutorService pool = Executors.newFixedThreadPool(2); // 2 taps, same key, same moment
Callable<String> tap = () -> shop.pay(o1, "PAYFAST", "KEY-501");
List<Future<String>> taps = pool.invokeAll(List.of(tap, tap));
pool.shutdown();
System.out.println("two taps -> " + taps.get(0).get() + ", " + taps.get(1).get()
+ " | PayFast charges made: " + payFast.sdk.n + " | state " + o1.state());
Cart neha = new Cart(false); neha.add(gold, 1);
Order o2 = shop.placeOrder(neha, "FEST100", Map.of());
System.out.println(o2.id + " " + o2.bill + " = " + CheckoutService.rupees(o2.total));
try { shop.pay(o2, "PAYFAST", "KEY-502"); }
catch (RuntimeException e) { System.out.println("KEY-502 failed: " + e.getMessage() + " | state " + o2.state()); }
System.out.println("retry KEY-502 on QuickPay -> " + shop.pay(o2, "QUICKPAY", "KEY-502") + " | state " + o2.state());
o1.moveTo(OrderState.SHIPPED); o1.moveTo(OrderState.DELIVERED);
System.out.println(o1.id + " history " + o1.history);
try { o1.moveTo(OrderState.CANCELLED); } catch (IllegalStateException e) { System.out.println(e.getMessage()); }
try { asha.add(rangoli, 0); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
} }
Real output:
ORD-501 [subtotal 1498.80, item offers -129.90, coupon FEST100 -100.00, tax 5% +63.44, delivery +0.00] = 1332.34
two taps -> PF1, PF1 | PayFast charges made: 1 | state PAID
ORD-502 [subtotal 7000.00, item offers -0.00, coupon FEST100: rules not met, tax 5% +350.00, delivery +0.00] = 7350.00
KEY-502 failed: PayFast: limit exceeded | state CREATED
retry KEY-502 on QuickPay -> QP7001 | state PAID
ORD-501 history [CREATED, PAID, SHIPPED, DELIVERED]
ORD-501: DELIVERED -> CANCELLED not allowed
quantity must be positive: 0
What the run shows:
- Asha's cart: 6 diya sets, 2 rangoli colours, then 4 more diya sets merge into one line of 10. Bill: 1498.80 − 129.90 (10% off diyas) − 100.00 (FEST100) + 63.44 tax = 1332.34.
- Two taps at the same moment from two threads with
KEY-501: both getPF1, PayFast made 1 charge, and the order isPAIDonce (the secondmoveTo(PAID)never runs, which would have thrown). - Neha's gold coin:
FEST100: rules not met. PayFast refuses 7350 rupees (limit exceeded), the order staysCREATED, and because nothing was stored forKEY-502, the retry on QuickPay succeeds:QP7001,PAID. DELIVERED -> CANCELLED not allowed, andquantity must be positive: 0.- One caution:
computeIfAbsentholds a lock on that part of the map while the charge runs, so other keys landing in the same part can wait. Real systems write aPENDINGrow for the key first, call the provider outside any lock, then store the result.
Practice
1. Add RETURN_REQUESTED, RETURNED and REFUNDED to the order state machine.
Answer
Add the values to the enum and to canGo: case DELIVERED -> to == RETURN_REQUESTED;, case RETURN_REQUESTED -> to == RETURNED || to == DELIVERED; (the return was rejected), case RETURNED -> to == REFUNDED;. REFUNDED falls into default -> false, so it is final. Nothing else in Order changes: moveTo already refuses every move that canGo doesn't list.
2. Write a coupon DIYA20: 20% off, at most 200 rupees, only if the cart has diyas.
Answer
new Coupon("DIYA20", Spec.hasType("DIYA"), a -> Math.min(a * 20 / 100, 20000)): it is already registered in the mini project. The rule is a Specification; the discount is a separate function of the running amount, with the cap (20000 paise = 200 rupees) inside it. Call placeOrder(asha, "DIYA20", ...) to try it.
3. Add a third made-up provider, EasyPe, whose SDK method is boolean send(int rupeesWhole, int paise, String ref).
Answer
Write class EasyPeAdapter implements PaymentGateway holding the SDK, and in charge(id, p) call send((int) (p / 100), (int) (p % 100), id); return a transaction id if it returns true, and throw an exception if it returns false (so the idempotency map stores nothing and a retry is allowed). Register it in the gateways map. CheckoutService doesn't change: that is the point of Strategy + Adapter.
4. A customer may type two coupons. Keep the one that saves more.
Answer
For each coupon whose rule().ok(cart) is true, compute its discount on the amount after item offers; keep the largest (max by discount). Run only that one in the coupon step. Keep the comparison inside the pipeline's coupon step, so the order of steps stays fixed.
5. Why must the app create the idempotency key, and not the server?
Answer
The retry happens because the app never got the server's reply. If the server made the key, the app would never learn it and would send a request with no key (or a new one). The app creates the key once when the customer starts paying and sends the same key on every retry; that is how the server recognises "same payment again".
6. Why can't Spec.not be a default method called like hasGold.not()?
Answer
It could be: default Spec negate() { return c -> !ok(c); } works too. We made it static so the rule reads like a sentence: min999.or(first).and(Spec.not(hasGold)). Both are fine; pick one style and keep it.
Quick quiz
A cart's subtotal is 1000 rupees. The pipeline is: 10% item offer, then a 100-rupee coupon, then 5% tax. What is the final amount? (a) 840.00 (b) 845.00 (c) 850.50 (d) 945.00
Answer
(a) 840.00. 1000 − 10% = 900; − 100 = 800; + 5% = 840. Tax before the coupon gives 900 × 1.05 − 100 = 845 (b): the order of steps changes the total.
Interview questions
- What classes do you start with? Product, CartItem, Cart, Order (with OrderState), Coupon + Spec, pricing steps, PaymentGateway + Adapters, CheckoutService.
- How do you store money? Whole paise in a
long, orBigDecimalbuilt from strings; neverdouble. - Why is Order separate from Cart? The cart is a changing wish list; the order is a frozen snapshot with a lifecycle.
- How do you stop illegal state changes? An enum state machine: a table of legal moves; everything else throws.
- How do you model coupon rules? Specification objects combined with and, or, not; the discount amount is a separate function.
- Where is the coupon applied, and why does it matter? In a fixed pricing pipeline after item offers and before tax; a different order gives a different total.
- How do you support many payment providers? Strategy (one interface) plus one Adapter per provider SDK.
- What is an idempotency key? A unique id per payment attempt, sent with every retry; the server returns the stored result for a key it has seen.
- How does idempotency work on many servers? Keys in shared storage with a unique constraint, and the key passed on to the provider.
- What if payment succeeds but your server crashes before marking the order paid? On restart, or on the provider's callback, look the key up with the provider and finish the move to PAID; never charge again.
Glossary
| Term | Meaning, with an example |
|---|---|
| E-commerce | Selling online: an app or website where you order and pay |
| E-commerce requirements | What the checkout must do: cart, coupons, correct bill, pay once, order tracking |
| Product | A thing for sale with a price: Product("Diya set", 12990) |
| CartItem | One cart line: a product and a quantity: diya set × 3 |
| Cart | All of one customer's cart items before paying; gives the subtotal |
| Subtotal | The sum of the cart's item totals, before offers, coupon, tax and delivery |
| Order | The cart frozen at checkout: id, total, state: ORD-501 |
| Snapshot | A frozen copy taken at one moment; later changes don't affect it |
| Paise | Hundredths of a rupee; 99.90 rupees = 9990 paise |
long |
Java's 64-bit whole-number type; exact for paise |
double / floating point |
A binary fraction type; can't store 99.90 exactly: 689.4000000000001 |
| BigDecimal | Java's exact decimal number type: new BigDecimal("99.90") |
| Scale (BigDecimal) | The number of decimal places: 689.40 has scale 2, 689.4 scale 1 |
| Enum | A fixed list of named values: CREATED, PAID, SHIPPED, DELIVERED, CANCELLED |
| State machine | States plus the only legal moves between them; others are refused |
| Order state machine | CREATED → PAID → SHIPPED → DELIVERED, with CANCELLED from CREATED or PAID |
| Transition | One move from one state to another: PAID → SHIPPED |
| IllegalStateException | Java's exception for "not allowed in the current state": SHIPPED -> CANCELLED not allowed |
| Coupon | A code that takes money off if its rules match: FEST100 |
| Discount engine (coupon and discount engine) | The part that decides which offers apply and how much they take off |
| Item offer | A discount on one kind of item: 10% off diyas |
| Operator precedence | Which operator binds first: && (and) before the OR operator |
| Specification pattern | A rule as a small yes/no object, combinable with and, or, not |
| Specification for coupon rules | min999.or(first).and(not(hasGold)) as FEST100's rule |
| Lambda | A short unnamed function: c -> c.subtotal() >= 99900 |
| Default method | An interface method with a body: Spec.and |
| BiFunction | Java's interface for a function of two inputs: (cart, amount) -> newAmount |
| Pricing pipeline | Ordered steps that build the bill: subtotal → item offers → coupon → tax → delivery |
| Rounding rule | How an amount like 53.455 becomes 53.45 or 53.46; written once, applied once |
| Payment gateway | The outside service that moves the money |
| Payment integration | Calling the gateway and handling its answer |
| Strategy pattern | Swappable ways to do one job behind one interface |
| Payment gateway Strategy | PaymentGateway.charge(orderId, paise) with any provider behind it |
| SDK | Software development kit: the library a provider gives you, e.g. the made-up PayFastSdk |
| Adapter pattern | A wrapper that makes a class fit the interface you need |
| Adapter for payment providers | QuickPayAdapter turns charge(id, paise) into debit("1122.55", id) |
| Idempotent | Doing it twice has the same effect as once |
| Idempotency key | A unique id per payment attempt, sent with every retry: KEY-501 |
| Idempotent checkout | A checkout that charges once however many times Pay is tapped |
| Retry | Sending the same request again because no reply came |
| ConcurrentHashMap | A map many threads can use at once safely |
| computeIfAbsent | Compute and store a value only if the key is missing; atomic in ConcurrentHashMap |
| Atomic | Can't be split: no other thread can act in the middle |
| Unique constraint | A database rule that a column's value can appear only once |
| Thread | One line of work running in a program; two taps can arrive on two threads |
Summary
- E-commerce requirements: cart, coupons, a correct bill, orders with states, many providers, charge once.
- Product → CartItem → Cart → Order; the order is a frozen snapshot.
doublegave689.4000000000001; money is whole paise in along(orBigDecimal).- The order state machine refused
SHIPPED -> CANCELLEDwith a realIllegalStateException. - An if-else coupon rule gave a gold coin 100 off; Specification objects (
and,or,not) fixed it. - The pricing pipeline runs subtotal → item offers → coupon → tax → delivery, always in that order.
- A PaymentGateway Strategy with one Adapter per made-up provider (PayFast, QuickPay) keeps checkout unchanged.
- A retried tap charged twice (
PF1 and PF2); an idempotency key withcomputeIfAbsentmade itPF1 and PF1: an idempotent checkout. - Next episode: design a food delivery app: restaurants, menus, delivery partners, ETAs and live order tracking.