SyntaxPilot
Courses/Low-Level Design/Lesson 78
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 78 of 90

Design an inventory management system

inventory requirementsProductSKUWarehouseStockLevelstock in and outreservations vs committed stocklow-stock alertsreorder pointObserver for alertsconcurrency on stock updatesaudit trail

These are the notes for Low-Level Design (LLD) episode 78: designing an inventory management system, the software that knows how much of everything is on the shelves. We start from the inventory requirements, separate a Product from a SKU, keep one StockLevel per SKU per Warehouse, record stock in and stock out, watch a real race sell 5 packets to 20 customers, fix it with synchronized stock updates, split stock into reserved vs committed, warn the buyer at the reorder point with low-stock alerts built on the Observer pattern, and finish with an append-only audit trail that replays to the number on hand.

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 race demo uses real threads, so its numbers can change from run to run and machine to machine; the notes say so where it matters and show a real run. The kirana store, the SKUs (NDL-70G, TEA-250G), the warehouses, the people (Asha, Ravi, Imran) and all numbers are made up for teaching. Nothing here describes any real company's inventory system.

Episode 75 built seat holds that expire, and episode 35 introduced the Observer pattern; this episode uses both ideas. The next episode (79) designs the shopping cart and checkout that sells this stock.

1. The problem: the kirana store storeroom

A kirana store is a small neighbourhood grocery shop. Ours has a storeroom at the back.

Real life In the design
"Noodles 70 g: 5 packets" written on the storeroom door A StockLevel: one number per SKU per warehouse
Twenty phone orders at 8 pm, and the helper says "yes, available" to all of them Overselling, caused by a race condition
"Keep two aside, I'm paying now" Reserved stock: promised, not sold, not on sale either
The customer pays and walks out with the packets Committed stock: it really leaves (stock out)
"Only 8 left, call the supplier" The reorder point and a low-stock alert
The owner, the buyer and the dashboard all want to hear about it The Observer pattern
The notebook: "14:05, Ravi, 5 packets thrown away, wet in the rain" The audit trail

2. Inventory requirements and the words

The inventory requirements are the list of what the system must do. Say them out loud in an interview before designing anything:

  1. Record stock in (goods arrive, for example from a supplier) and stock out (goods leave, because someone bought them or they were damaged).
  2. Never oversell: never accept more orders than there is stock, even when many orders arrive at the same moment.
  3. Hold stock for customers who are paying, and give it back if payment fails.
  4. Alert someone before stock runs out, early enough for the supplier to deliver.
  5. Keep a record of every change: when, which item, how many, why, and who.

Out of scope for this episode (say so in the interview): prices, carts and payment (episode 79), supplier contracts, barcode scanners, accounting.

The core words:

  • Product: what the customer thinks of. Example: Masala noodles.
  • SKU (stock keeping unit): one exact item you can count on a shelf. The 70 g pack and the 280 g pack are two SKUs of one product, with codes like NDL-70G and NDL-280G. You count SKUs, never products: "we have 12 masala noodles" is useless if the customer wants the big pack.
  • Warehouse: a building that holds stock. Example: the Pune warehouse.
  • StockLevel: how many of one SKU sit in one warehouse. Pune has its own count of NDL-70G; Mumbai has another.
  • On hand: the number physically in the building.
  • Stock in / stock out: a movement that raises / lowers the on-hand number.

3. Attempt 1: one number per SKU, many orders

The simplest inventory is a map from SKU to a number. sell does three steps: read the number, check there's enough, write the new number. The Thread.sleep(10) stands for the time a real system spends on payment and the database between the check and the write.

To make twenty customers order at the same moment, we use a thread pool of 20 threads (ExecutorService) and a starting gun, a CountDownLatch with count 1: every task waits on go.await(), and go.countDown() releases all of them together (the same trick as episode 75). Each submit returns a Future, a handle to a result that arrives later; f.get() waits for it.

import java.util.*;  import java.util.concurrent.*;
public class Main {
    static final Map<String, Integer> stock = new HashMap<>(Map.of("NDL-70G", 5));   // 5 packets left
    static boolean sell(String sku, int qty) throws InterruptedException {
        int have = stock.get(sku);                              // 1. read
        if (have < qty) return false;                           // 2. check
        Thread.sleep(10);                                       // ...payment, database...
        stock.put(sku, have - qty);                             // 3. write
        return true; }
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(20);     // 20 customers order at once
        CountDownLatch go = new CountDownLatch(1);
        List<Future<Boolean>> orders = new ArrayList<>();
        for (int i = 0; i < 20; i++)
            orders.add(pool.submit(() -> { go.await();  return sell("NDL-70G", 1); }));
        go.countDown();
        int accepted = 0;  for (Future<Boolean> f : orders) if (f.get()) accepted++;
        pool.shutdown();
        System.out.println("5 packets, orders accepted: " + accepted
                           + ", stock now says: " + stock.get("NDL-70G"));
    } }

Real output (this is a real race, so the numbers can differ on another machine or run; every run on this machine printed the same line):

5 packets, orders accepted: 20, stock now says: 4

Twenty orders accepted for five packets. And the stock says 4, as if only one packet was sold. Fifteen customers will get a "sorry" call, and the number on the screen is simply wrong.

Why it failed

A race condition is a bug where the result depends on which thread runs first. Here:

  1. All 20 threads read 5 before any of them wrote. So every check (5 < 1? no) passed.
  2. Each thread then wrote 5 - 1 = 4. The same 4, twenty times. Nineteen sales simply vanished from the count (a lost update).

The read, the check and the write are three separate steps, and other threads can run between them. Making the map a ConcurrentHashMap does not help: each single get and put is safe, but the three steps together are still not one step (see the common-mistakes table, where we ran it and got the same 20 and 4).

The fix: one step, one thread at a time

The read, check and write must be one step that only one thread runs at a time. In Java, a synchronized method does exactly that: a thread must take the object's lock (its "key") before entering any synchronized method of that object, and other threads wait until it leaves. A step that can't be split like this is called atomic. This is concurrency on stock updates done right: many threads can call the methods, but the stock changes one complete step at a time.

4. Reserved vs committed stock

The next problem is right behind the first. A customer in the middle of paying isn't a sale yet. If we subtract stock the moment someone adds it to a cart, the app shows 0 while the shelf is full of packets in carts nobody will ever pay for. If we wait until payment, two people can pay for the last packet.

So stock gets two numbers:

Number Meaning Example
On hand Physically in the building 5
Reserved Promised to carts that are paying, not yet gone 5
Available What a new customer can still order: on hand − reserved 0

And three operations:

  • Reserve (customer starts paying): check available and add to reserved, in one synchronized step. A reservation is that promise.
  • Commit (payment succeeded): the stock really goes out. Lower both reserved and on hand. Stock that has been committed is committed stock.
  • Release (payment failed or the cart was abandoned): lower reserved only. The packets are back on sale.
import java.util.*;  import java.util.concurrent.*;
record Product(String name) {}                                  // what the customer thinks of
record Sku(String code, Product product, String size) {}        // one exact thing on a shelf
class StockLevel {                                              // one SKU in one warehouse
    private int onHand, reserved;                               // in the building / promised to carts
    synchronized void stockIn(int q) { onHand += q; }
    synchronized boolean reserve(int q) {                       // check + reserve: one step
        if (onHand - reserved < q) return false;
        reserved += q;  return true; }
    synchronized void commit(int q) { reserved -= q;  onHand -= q; }   // paid and shipped: stock out
    synchronized void release(int q) { reserved -= q; }                // payment failed: back on sale
    synchronized String show() {
        return "on hand " + onHand + ", reserved " + reserved + ", available " + (onHand - reserved); } }
class Warehouse {
    final String city;  final Map<String, StockLevel> levels = new ConcurrentHashMap<>();
    Warehouse(String city) { this.city = city; }
    StockLevel of(Sku s) { return levels.computeIfAbsent(s.code(), k -> new StockLevel()); } }
public class Main { public static void main(String[] args) throws Exception {
    Sku small = new Sku("NDL-70G", new Product("Masala noodles"), "70 g");
    Warehouse pune = new Warehouse("Pune");  pune.of(small).stockIn(5);
    ExecutorService pool = Executors.newFixedThreadPool(20);  List<Future<Boolean>> tries = new ArrayList<>();
    for (int i = 0; i < 20; i++) tries.add(pool.submit(() -> pune.of(small).reserve(1)));
    int ok = 0;  for (Future<Boolean> f : tries) if (f.get()) ok++;
    pool.shutdown();
    System.out.println("20 customers, 5 packets -> reserved: " + ok + " | " + pune.of(small).show());
    pune.of(small).commit(3);  pune.of(small).release(2);               // 3 paid, 2 payments failed
    System.out.println("3 paid, 2 failed -> " + pune.of(small).show()); } }

Real output:

20 customers, 5 packets -> reserved: 5 | on hand 5, reserved 5, available 0
3 paid, 2 failed -> on hand 2, reserved 0, available 2

Line by line:

  • record Product(String name) and record Sku(String code, Product product, String size): a record is a short Java class for plain data; the compiler writes the constructor, the getters (code(), product()) and equals. A SKU points to its product.
  • StockLevel holds onHand and reserved as private fields, so nothing outside can change them without going through a synchronized method.
  • reserve does check + reserve in one synchronized step: 20 threads tried, exactly 5 succeeded, and available is 0, so nobody else can order.
  • commit(3): three customers paid, on hand drops from 5 to 2. release(2): two payments failed, those 2 packets are available again: on hand 2, reserved 0, available 2.
  • Warehouse keeps one StockLevel per SKU code in a ConcurrentHashMap (a map many threads can use at once safely). computeIfAbsent creates the stock level the first time a SKU is seen, and does it atomically, so two threads can't create two different levels for the same SKU.

Ran it three more times: every run printed the same two lines, because the race is gone.

Note: this release has no check. If the "payment failed" message arrives twice, reserved goes negative and available becomes bigger than on hand. We ran that in the common-mistakes table (reserved -2, available 7); the mini project refuses it.

5. The reorder point

Next problem: the shelf runs empty, and nobody notices until a customer hears "out of stock". Ordering more takes time.

  • Lead time: how many days the supplier takes to deliver after you order. Ours: 2 days.
  • Safety stock: a few extra packets kept for a bad day (sales higher than usual, a late truck). Ours: 2.
  • Reorder point: the stock level at which you must order again:
reorder point = daily sales × lead time + safety stock
              = 4 a day     × 2 days    + 2
              = 10

If you order when 10 are left, the 8 you'll sell during the 2 days of lead time come from the shelf, and the 2 spare packets cover a bad day. Order at 0 and the shelf is empty for 2 days.

A low-stock alert is the message sent when stock reaches the reorder point. Two rules:

  1. Alert once per dip, not on every sale below the point. Sales at 10, 9, 8, 7 must not send four SMS messages. Remember "already alerted", and reset that when a delivery takes stock back above the point.
  2. Don't hard-code who gets told. Today the buyer and a dashboard; tomorrow an SMS service.

6. Low-stock alerts with the Observer pattern

The obvious attempt

StockLevel calls each interested party by name: buyer.reorder(...), dashboard.show(...). Every new target (SMS, email, an auto-order bot) means opening StockLevel and editing it. That is tight coupling: the stock class knows too much about the classes around it.

The fix: Observer

The Observer pattern (episode 35): one object, the subject, keeps a list of observers (also called listeners) that have subscribed to it, and notifies all of them when something happens. The subject only knows the listener interface, never the concrete classes. Here StockLevel is the subject and StockListener is the observer interface.

import java.util.*;
interface StockListener { void lowStock(String sku, int onHand, int reorderPoint); }   // the observer
class StockLevel {                                                  // the subject
    final String sku;  final int reorderPoint;  private int onHand;  private boolean alerted;
    private final List<StockListener> listeners = new ArrayList<>();
    StockLevel(String sku, int onHand, int reorderPoint) {
        this.sku = sku;  this.onHand = onHand;  this.reorderPoint = reorderPoint; }
    void subscribe(StockListener l) { listeners.add(l); }
    synchronized void stockOut(int q) {
        if (q > onHand) throw new IllegalStateException(sku + ": only " + onHand + " left, asked " + q);
        onHand -= q;
        if (onHand <= reorderPoint && !alerted) {                    // alert ONCE per dip
            alerted = true;
            for (StockListener l : listeners) l.lowStock(sku, onHand, reorderPoint); } }
    synchronized void stockIn(int q) { onHand += q;  if (onHand > reorderPoint) alerted = false; }
    synchronized int onHand() { return onHand; } }
public class Main { public static void main(String[] args) {
    int perDay = 4, leadDays = 2, safety = 2;                       // sells 4 a day, supplier takes 2 days
    StockLevel s = new StockLevel("NDL-70G", 20, perDay * leadDays + safety);   // reorder point = 10
    s.subscribe((sku, left, rp) -> System.out.println("  Buyer: reorder " + sku + " (" + left + " left)"));
    s.subscribe((sku, left, rp) -> System.out.println("  Dashboard: " + sku + " hit reorder point " + rp));
    for (int day = 1; day <= 4; day++) {
        s.stockOut(perDay);  System.out.println("day " + day + ": " + s.onHand() + " left"); }
    s.stockIn(40);  System.out.println("supplier delivers 40: " + s.onHand());
    s.stockOut(50); } }

Real output:

day 1: 16 left
day 2: 12 left
  Buyer: reorder NDL-70G (8 left)
  Dashboard: NDL-70G hit reorder point 10
day 3: 8 left
day 4: 4 left
supplier delivers 40: 44
Exception in thread "main" java.lang.IllegalStateException: NDL-70G: only 44 left, asked 50
    at StockLevel.stockOut(Main.java:10)
    at Main.main(Main.java:25)

What happened:

  • The reorder point is computed in code: perDay * leadDays + safety = 4 × 2 + 2 = 10.
  • The buyer and the dashboard subscribe as lambdas (short unnamed functions). StockListener has exactly one abstract method, so a lambda with three parameters (sku, left, rp) -> ... can stand for it.
  • Day 1: 20 → 16. Day 2: 16 → 12. Day 3: 12 → 8, at or below 10: both listeners are told, once. The alert lines print before day 3: 8 left because they are printed inside stockOut, before main prints the day line.
  • Day 4: 8 → 4. Still below the point, but alerted is already true, so no repeat.
  • The supplier delivers 40: 4 + 40 = 44, and stockIn resets alerted because 44 is above 10.
  • stockOut(50) is refused: stock may never go below zero. The IllegalStateException (Java's exception for "this call is not allowed in the object's current state") carries the message NDL-70G: only 44 left, asked 50. The stack trace lines say where: stockOut at line 10 of Main.java, called from main at line 25.

One design point: subscribe adds to a plain ArrayList without a lock. That's fine here because everyone subscribes at startup on one thread. If listeners can join while stock is moving on other threads, use a CopyOnWriteArrayList (a list that's safe to read while another thread adds to it), as the mini project does.

7. The audit trail

Last problem. The count says 30, but the manager expected 35. Where did 5 packets go? A single number can't tell you: it has no memory.

The fix is an audit trail: every movement (every change to on hand) becomes a record: when it happened, which SKU, how many (the delta, + for in and − for out), why, who did it, and the stock after. It is append-only: you add records, but you never edit or delete one, just like a bank statement. A mistake is fixed by adding a new correcting movement, not by changing an old one.

And there's a free check, called a replay: add up every movement from the start, and you must get the number on hand. If you don't, something changed the stock without a record.

import java.time.LocalTime;  import java.util.*;
record Movement(int seq, LocalTime at, String sku, int delta, String reason, String by, int after) {}
class AuditedStock {
    private final Map<String, Integer> onHand = new HashMap<>();
    private final List<Movement> log = new ArrayList<>();       // audit trail: append only
    synchronized void move(String sku, int delta, String reason, String by, LocalTime at) {
        int now = onHand.getOrDefault(sku, 0) + delta;
        if (now < 0) throw new IllegalStateException(sku + " would go to " + now);
        onHand.put(sku, now);                                   // the number AND the reason, together
        log.add(new Movement(log.size() + 1, at, sku, delta, reason, by, now)); }
    int onHand(String sku) { return onHand.getOrDefault(sku, 0); }
    List<Movement> trail() { return Collections.unmodifiableList(log); } }   // read-only view
public class Main { public static void main(String[] args) {
    AuditedStock st = new AuditedStock();
    st.move("NDL-70G", +40, "purchase order PO-17", "Asha", LocalTime.of(9, 0));
    st.move("NDL-70G", -3, "order #5521", "app", LocalTime.of(11, 20));
    st.move("NDL-70G", -5, "damaged in rain", "Ravi", LocalTime.of(14, 5));
    st.move("NDL-70G", -2, "order #5530", "app", LocalTime.of(18, 45));
    for (Movement m : st.trail())
        System.out.printf("#%d %s %+4d %-22s by %-5s -> %d%n",
                          m.seq(), m.at(), m.delta(), m.reason(), m.by(), m.after());
    int replay = st.trail().stream().mapToInt(Movement::delta).sum();
    System.out.println("on hand " + st.onHand("NDL-70G") + ", replaying the trail gives " + replay);
    st.trail().remove(2);                                       // try to hide the damaged packets
} }

Real output:

#1 09:00  +40 purchase order PO-17   by Asha  -> 40
#2 11:20   -3 order #5521            by app   -> 37
#3 14:05   -5 damaged in rain        by Ravi  -> 32
#4 18:45   -2 order #5530            by app   -> 30
on hand 30, replaying the trail gives 30
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableList.remove(Collections.java:1510)
    at Main.main(Main.java:24)

What the run shows:

  • Movement #3 answers the manager: at 14:05, Ravi wrote off 5 packets, damaged in rain. (A write-off is stock removed because it can't be sold.)
  • on hand 30, replaying the trail gives 30: 40 − 3 − 5 − 2 = 30. The number and the history agree.
  • move changes the number and appends the record inside one synchronized method, so one never happens without the other.
  • trail() returns Collections.unmodifiableList(log): a read-only view of the real list. Reading works; remove(2) (index 2, the third record) throws UnsupportedOperationException, Java's exception for "this object doesn't support that operation". The history can't be quietly changed from outside.
  • printf with %+4d prints the sign (+40, -3) in 4 characters; %-22s pads the reason to 22 characters, left-aligned, so the columns line up.

In a real system the trail lives in a database table that the application may only INSERT into, and the replay check runs every night.

8. The class diagram

Product("Masala noodles") ─ sold as ─▶ Sku("NDL-70G", size)      one SKU = one exact shelf item
Warehouse(city) ─ has ─▶ StockLevel per SKU:  onHand · reserved · available = onHand − reserved
reserve (cart) ─▶ commit (paid: stock out)  or  release (payment failed: back on sale)
StockLevel methods are synchronized: read + check + write in one step
reorderPoint = daily sales × lead time + safety stock → low-stock alert ONCE per dip
StockListener (Observer) ◁─ Buyer · Dashboard · ...   subscribe(), notified by StockLevel
Movement(seq, time, sku, delta, reason, by, after) → append-only audit trail; replay = on hand

Read it top to bottom: a product is sold as SKUs; a warehouse has one stock level per SKU; a cart reserves and payment commits or releases; every stock method is synchronized; the stock level is the Observer subject for low-stock alerts; and every change to on hand becomes a movement in the append-only trail.

9. Interview follow-ups

Question Answer
Many warehouses? Pick the nearest warehouse that has the SKU available (on hand − reserved), not just on hand. The mini project does this with a distance map.
Many servers? synchronized protects one JVM (one running Java program). With many servers, let the database do the check and the write in one statement: UPDATE stock SET reserved = reserved + 1 WHERE sku = ? AND on_hand - reserved >= 1, then look at how many rows changed: 1 means reserved, 0 means not enough.
Carts that are never paid? Reservations expire: each hold has an expiry time, and a background job releases expired holds, like the seat holds in episode 75. A late payment for an expired hold must be refused.
Moving stock between cities? A transfer is a stock out in one warehouse and a stock in at the other, both written to the audit trail. In a database, do both in one transaction.
Food with expiry dates? Store stock in batches (one batch per expiry date) and sell the oldest batch first (FIFO, first in, first out).
Where do alerts go if the SMS service is slow? Don't call slow listeners while holding the stock lock; put the alert on a queue and let another thread send it.
How do you know the count is right? Replay the audit trail and compare with on hand; also do a physical count (a stock take) and record the difference as an adjustment movement with a reason.

10. Common mistakes

Every "what you see" below is real output or a real compiler error from a program we ran (the episode programs above, or a small variant of them).

Mistake What you see (real) Fix
Read, check, write without a lock 5 packets, orders accepted: 20, stock now says: 4 synchronized methods on StockLevel
"ConcurrentHashMap is thread-safe, so I'm fine" ConcurrentHashMap, orders accepted: 20, stock now says: 4 The three steps must be one step; a safe map only makes each single call safe
Subtract stock when an item goes into a cart nobody paid; shelf has 5 packets, app says available: 0 Reserve, then commit or release
release without a check, called twice on hand 5, reserved -2, available 7 Refuse a release bigger than reserved (the mini project throws)
Alert on every sale below the reorder point SMS to buyer: NDL-70G low (10 left), then (9 left), (8 left), (7 left) An alerted flag: once per dip, reset on stock in
Calling each alert target by name StockLevel edited for every new target Observer: subscribe(StockListener)
A lambda with the wrong number of parameters for the listener error: incompatible types: incompatible parameter types in lambda expression Match the interface: (sku, left, rp) -> ...
Stock allowed below zero a negative count on the dashboard Throw: IllegalStateException: NDL-70G: only 44 left, asked 50
Storing only the number "where did 5 packets go?" Append-only audit trail
Returning the real list from trail() on hand 30, trail [40, -3, -2], replay gives 35 Collections.unmodifiableList(log) or List.copyOf(log): UnsupportedOperationException on remove

Mini project: a multi-warehouse inventory service

One Inventory class that puts everything together, plus homework items from the episode. Two warehouses (Pune, Mumbai), each with a StockLevel per SKU and a reorder point of 10. Reservations with an id and an expiry time: a fake clock (now, in minutes) replaces real waiting, so the demo runs instantly. commit refuses an expired or already-used hold, and every change refuses on hand below 0, reserved below 0, or reserved above on hand. Low-stock alerts go to StockListener observers once per dip (kept in a CopyOnWriteArrayList). An append-only audit trail with a replay per warehouse and SKU; trail() returns a read-only copy. transfer(sku, from, to, qty) writes two movements, and nearestWith(sku, qty, distances) picks a warehouse. And a concurrency test: 100 customers race for 30 packets on a pool of 8 threads.

Every change goes through one private method, change, which takes the stock level's lock (synchronized (l)), checks, writes, appends the movement and fires the alert in one step. AtomicInteger gives each hold a unique number without a lock; volatile makes a change to now visible to all threads.

import java.util.*;  import java.util.concurrent.*;  import java.util.concurrent.atomic.*;

record Product(String name) {}
record Sku(String code, Product product, String size) {}
record Movement(int seq, String warehouse, String sku, int delta, String reason, String by, int after) {}
record Reservation(String id, String warehouse, String sku, int qty, int expiresAt) {}
interface StockListener { void lowStock(String warehouse, String sku, int onHand, int reorderPoint); }

class StockLevel {                                   // one SKU in one warehouse; guarded by its own lock
    int onHand, reserved;  final int reorderPoint;  boolean alerted;
    StockLevel(int reorderPoint) { this.reorderPoint = reorderPoint; }
    int available() { return onHand - reserved; } }

class Inventory {
    private final Map<String, Map<String, StockLevel>> stock = new ConcurrentHashMap<>();   // warehouse -> sku -> level
    private final Map<String, Reservation> holds = new ConcurrentHashMap<>();
    private final List<Movement> log = new ArrayList<>();                                   // append only
    private final List<StockListener> listeners = new CopyOnWriteArrayList<>();
    private final AtomicInteger nextHold = new AtomicInteger(1);
    volatile int now = 0;                                       // a fake clock in minutes: no sleeping needed

    void addWarehouse(String w) { stock.put(w, new ConcurrentHashMap<>()); }
    void track(String w, Sku s, int reorderPoint) { stock.get(w).put(s.code(), new StockLevel(reorderPoint)); }
    void subscribe(StockListener l) { listeners.add(l); }
    private StockLevel level(String w, String sku) {
        StockLevel l = stock.getOrDefault(w, Map.of()).get(sku);
        if (l == null) throw new IllegalArgumentException("unknown SKU " + sku + " in " + w);
        return l; }

    private void change(String w, String sku, int dOnHand, int dReserved, String reason, String by) {
        StockLevel l = level(w, sku);
        synchronized (l) {                                      // read + check + write: one step
            int on = l.onHand + dOnHand, res = l.reserved + dReserved;
            if (on < 0 || res < 0 || res > on)
                throw new IllegalStateException(sku + " in " + w + ": on hand " + on + ", reserved " + res + " is not allowed");
            l.onHand = on;  l.reserved = res;
            if (dOnHand != 0) synchronized (log) { log.add(new Movement(log.size() + 1, w, sku, dOnHand, reason, by, on)); }
            if (on > l.reorderPoint) l.alerted = false;         // refilled: the next dip may alert again
            else if (!l.alerted) { l.alerted = true;            // once per dip
                for (StockListener x : listeners) x.lowStock(w, sku, on, l.reorderPoint); } } }

    void stockIn(String w, String sku, int q, String reason, String by) { change(w, sku, +q, 0, reason, by); }
    void writeOff(String w, String sku, int q, String reason, String by) { change(w, sku, -q, 0, reason, by); }

    String reserve(String w, String sku, int q, int minutes) {           // null = not enough available
        StockLevel l = level(w, sku);
        synchronized (l) { if (l.available() < q) return null;  l.reserved += q; }
        String id = "H" + nextHold.getAndIncrement();
        holds.put(id, new Reservation(id, w, sku, q, now + minutes));
        return id; }
    void commit(String holdId) {                                         // paid: stock really goes out
        Reservation r = holds.remove(holdId);
        if (r == null) throw new IllegalStateException("hold " + holdId + " not found (expired or already used)");
        change(r.warehouse(), r.sku(), -r.qty(), -r.qty(), "order " + holdId, "app"); }
    void release(String holdId) {                                        // payment failed: back on sale
        Reservation r = holds.remove(holdId);
        if (r != null) change(r.warehouse(), r.sku(), 0, -r.qty(), null, null); }
    int expireHolds() {
        int n = 0;
        for (Reservation r : holds.values())
            if (r.expiresAt() <= now && holds.remove(r.id(), r)) { change(r.warehouse(), r.sku(), 0, -r.qty(), null, null);  n++; }
        return n; }
    void transfer(String sku, String from, String to, int q, String by) {   // two movements, both in the trail
        change(from, sku, -q, 0, "transfer to " + to, by);
        change(to, sku, +q, 0, "transfer from " + from, by); }
    Optional<String> nearestWith(String sku, int q, Map<String, Integer> km) {
        return km.keySet().stream()
                 .filter(w -> { StockLevel l = level(w, sku);  synchronized (l) { return l.available() >= q; } })
                 .min(Comparator.comparing(km::get)); }
    String show(String w, String sku) {
        StockLevel l = level(w, sku);
        synchronized (l) { return w + " " + sku + ": on hand " + l.onHand + ", reserved " + l.reserved + ", available " + l.available(); } }
    List<Movement> trail() { synchronized (log) { return List.copyOf(log); } }          // a read-only copy
    int replay(String w, String sku) {
        return trail().stream().filter(m -> m.warehouse().equals(w) && m.sku().equals(sku)).mapToInt(Movement::delta).sum(); } }

public class Main { public static void main(String[] args) throws Exception {
    Sku small = new Sku("NDL-70G", new Product("Masala noodles"), "70 g");
    Inventory inv = new Inventory();
    for (String w : List.of("Pune", "Mumbai")) { inv.addWarehouse(w);  inv.track(w, small, 10); }
    inv.subscribe((w, sku, left, rp) -> System.out.println("  ALERT buyer: " + sku + " in " + w + " at " + left + " (reorder point " + rp + ")"));
    inv.stockIn("Pune", "NDL-70G", 30, "purchase order PO-17", "Asha");
    inv.stockIn("Mumbai", "NDL-70G", 12, "purchase order PO-18", "Imran");

    ExecutorService pool = Executors.newFixedThreadPool(8);                 // 100 customers, 30 packets
    List<Callable<String>> tries = new ArrayList<>();
    for (int i = 0; i < 100; i++) tries.add(() -> inv.reserve("Pune", "NDL-70G", 1, 10));
    List<String> got = new ArrayList<>();
    for (Future<String> f : pool.invokeAll(tries)) if (f.get() != null) got.add(f.get());
    pool.shutdown();
    got.sort(Comparator.comparingInt(id -> Integer.parseInt(id.substring(1))));   // H1, H2, ... H30
    System.out.println("100 customers -> holds: " + got.size() + " | " + inv.show("Pune", "NDL-70G"));

    for (String id : got.subList(0, 25)) inv.commit(id);                   // 25 pay
    for (String id : got.subList(25, 27)) inv.release(id);                 // 2 payments fail
    System.out.println("25 paid, 2 failed -> " + inv.show("Pune", "NDL-70G"));
    inv.now = 15;                                                          // 3 carts left open for 15 minutes
    System.out.println("minute 15, expired holds: " + inv.expireHolds() + " | " + inv.show("Pune", "NDL-70G"));
    try { inv.commit(got.get(29)); } catch (IllegalStateException e) { System.out.println("late payment: " + e.getMessage()); }

    Map<String, Integer> kmFromCustomer = Map.of("Pune", 3, "Mumbai", 150);
    System.out.println("nearest with 4: " + inv.nearestWith("NDL-70G", 4, kmFromCustomer).orElse("none")
                       + " | nearest with 8: " + inv.nearestWith("NDL-70G", 8, kmFromCustomer).orElse("none")
                       + " | nearest with 20: " + inv.nearestWith("NDL-70G", 20, kmFromCustomer).orElse("none"));
    inv.transfer("NDL-70G", "Mumbai", "Pune", 6, "Imran");
    System.out.println("after transfer: " + inv.show("Pune", "NDL-70G") + " | " + inv.show("Mumbai", "NDL-70G"));
    try { inv.writeOff("Pune", "NDL-70G", 20, "damaged in rain", "Ravi"); }
    catch (IllegalStateException e) { System.out.println("write-off refused: " + e.getMessage()); }
    inv.writeOff("Pune", "NDL-70G", 2, "damaged in rain", "Ravi");

    List<Movement> trail = inv.trail();
    System.out.println("audit trail: " + trail.size() + " movements, " + trail.stream().filter(m -> m.reason().startsWith("order")).count()
                       + " of them orders of -1 (not printed); the rest:");
    for (Movement m : trail) if (!m.reason().startsWith("order"))
        System.out.printf("  #%d %-6s %+4d %-22s by %-5s -> %d%n", m.seq(), m.warehouse(), m.delta(), m.reason(), m.by(), m.after());
    for (String w : List.of("Pune", "Mumbai"))
        System.out.println(inv.show(w, "NDL-70G") + " | replay " + inv.replay(w, "NDL-70G"));
} }

Real output (we ran it six times; the output was identical every time, because the hold ids are sorted before use):

100 customers -> holds: 30 | Pune NDL-70G: on hand 30, reserved 30, available 0
  ALERT buyer: NDL-70G in Pune at 10 (reorder point 10)
25 paid, 2 failed -> Pune NDL-70G: on hand 5, reserved 3, available 2
minute 15, expired holds: 3 | Pune NDL-70G: on hand 5, reserved 0, available 5
late payment: hold H30 not found (expired or already used)
nearest with 4: Pune | nearest with 8: Mumbai | nearest with 20: none
  ALERT buyer: NDL-70G in Mumbai at 6 (reorder point 10)
after transfer: Pune NDL-70G: on hand 11, reserved 0, available 11 | Mumbai NDL-70G: on hand 6, reserved 0, available 6
write-off refused: NDL-70G in Pune: on hand -9, reserved 0 is not allowed
  ALERT buyer: NDL-70G in Pune at 9 (reorder point 10)
audit trail: 30 movements, 25 of them orders of -1 (not printed); the rest:
  #1 Pune    +30 purchase order PO-17   by Asha  -> 30
  #2 Mumbai  +12 purchase order PO-18   by Imran -> 12
  #28 Mumbai   -6 transfer to Pune       by Imran -> 6
  #29 Pune     +6 transfer from Mumbai   by Imran -> 11
  #30 Pune     -2 damaged in rain        by Ravi  -> 9
Pune NDL-70G: on hand 9, reserved 0, available 9 | replay 9
Mumbai NDL-70G: on hand 6, reserved 0, available 6 | replay 6

What the run shows:

  • 100 customers, 30 packets, 8 threads: exactly 30 holds, and available is 0. Never oversold.
  • 25 holds are committed one by one; when on hand reaches 10, the buyer is alerted once. 2 holds are released (payment failed), 3 stay open: on hand 5, reserved 3, available 2.
  • At minute 15 the 3 open holds (10-minute expiry) are released: available 5. A late payment for hold H30 is refused: hold H30 not found (expired or already used).
  • The nearest warehouse with 4 packets is Pune (3 km); with 8 it's Mumbai, because Pune has only 5 available; nobody has 20.
  • The transfer of 6 takes Mumbai from 12 to 6, which alerts for Mumbai (first dip there), and takes Pune from 5 to 11, above the point, so Pune's alert resets.
  • A write-off of 20 from Pune's 11 is refused (on hand -9 ... is not allowed); the write-off of 2 goes through, 11 → 9, and Pune alerts again because this is a new dip.
  • The trail has 30 movements; the 25 order lines are counted, not printed. Replay equals on hand in both warehouses: 9 and 6.
  • Caution: the listeners run while the stock lock is held. That's fine for a println; a slow SMS call should go on a queue instead (see the follow-ups). And transfer takes the two locks one after the other, not together, so for a moment the packets are in neither warehouse; a database transaction fixes that in a real system.

Practice

1. Pune has NDL-70G with on hand 40 and reserved 12. A customer wants 30. Can they reserve? What about 28?

Answer

Available = 40 − 12 = 28. 30 is refused (reserve returns false), 28 succeeds and leaves available 0, reserved 40, on hand 40. On hand doesn't change until the customers pay (commit).

2. A shop sells 6 packets a day. The supplier takes 3 days, and the owner wants 4 spare packets. What is the reorder point?

Answer

6 × 3 + 4 = 22. Order when 22 are left: 18 will be sold during the 3 days of lead time, and 4 stay as safety stock.

3. Add an SmsListener as a third observer to the alerts program. What has to change in StockLevel?

Answer

Nothing. Write class SmsListener implements StockListener { public void lowStock(String sku, int onHand, int rp) { /* send SMS */ } } (or a lambda) and call s.subscribe(new SmsListener()). That is the point of Observer: StockLevel only knows the StockListener interface.

4. Make release in the LEVELS program safe against being called twice.

Answer
synchronized void release(int q) {
    if (q > reserved) throw new IllegalStateException("release " + q + " but only " + reserved + " reserved");
    reserved -= q; }

Better still, release by reservation id as in the mini project: holds.remove(id) returns the reservation only the first time, so a second release with the same id does nothing.

5. Why does replay have to equal on hand, and what would you do if it doesn't?

Answer

On hand starts at 0 and only changes through movements, each of which is recorded with its delta. So the sum of the deltas must be on hand. If it isn't, some code changed stock without recording it (or a record was deleted). Find the code path that skips the trail; meanwhile record the difference as an "adjustment" movement with a reason, never by editing old rows.

6. Ten threads call stockIn(1) on a StockLevel whose stockIn is not synchronized, 1000 times each. Will on hand always end at 10000?

Answer

No. onHand += q is a read, an add and a write: three steps. Two threads can read the same value and both write value + 1, so increments get lost. We ran exactly this (a StockLevel with a plain onHand += q, 10 tasks of 1000 calls on a 10-thread pool, joined with invokeAll).

Five real runs on a 2-CPU machine (yours will differ; that is the point):

on hand 10000
on hand 9255
on hand 10000
on hand 10000
on hand 10000

Four runs happened to give 10000 and one lost 745 increments. A bug that shows up "sometimes" is still a bug, and tests that pass once prove nothing. Make stockIn synchronized (or use an AtomicInteger and addAndGet).

Quick quiz

SKU TEA-250G in Delhi has on hand 12 and reserved 5. A new customer wants 8 packets. What happens? (a) Sold: 12 ≥ 8 (b) Refused: only 7 available (c) Sold, reserved becomes 13 (d) Sold, on hand becomes 4

Answer

(b) Refused: only 7 available. Available = on hand − reserved = 12 − 5 = 7. The 5 reserved packets are promised to other carts, so 8 can't be reserved, even though 12 are on the shelf. (c) would promise 13 packets out of 12; (d) mixes up reserving with committing.

Interview questions

  1. What classes do you start with? Product, Sku, Warehouse, StockLevel, a Reservation (hold), StockListener, Movement, and a service class that ties them together.
  2. What's the difference between a product and a SKU? A product is what the customer thinks of; a SKU is one exact countable item. You count SKUs.
  3. How do you prevent overselling? Make check + reserve one atomic step: synchronized in one JVM, a conditional UPDATE ... WHERE on_hand - reserved >= q with many servers.
  4. Why reserve instead of subtracting at checkout? Paying takes time; reserving takes the stock off sale without pretending it left. Commit on payment, release on failure or expiry.
  5. What is available stock? On hand minus reserved.
  6. How do you pick the reorder point? Daily sales × lead time + safety stock.
  7. How do you stop alert spam? Alert once per dip: an alerted flag set on the alert and cleared when stock goes back above the point.
  8. Why Observer for alerts? New alert targets subscribe without changing StockLevel; the subject only knows the interface.
  9. What goes in an audit record? Sequence, time, SKU, warehouse, delta, reason, who, and the stock after.
  10. Why append-only? History must be trustworthy; corrections are new records. And the trail can be replayed to check on hand.
  11. What does synchronized not protect? Anything outside one JVM, and anything that reads or writes the fields without going through the synchronized methods.

Glossary

Term Meaning, with an example
Inventory management system Software that tracks how much of every item is in stock, where, and why it changed
Inventory requirements What the system must do: stock in/out, never oversell, hold for carts, alert early, audit every change
Kirana store A small neighbourhood grocery shop; our made-up example
Product What the customer thinks of: Product("Masala noodles")
SKU (stock keeping unit) One exact countable item: NDL-70G (70 g pack) vs NDL-280G (280 g pack) of the same product
Warehouse A building that holds stock: the Pune warehouse
StockLevel How many of one SKU are in one warehouse: Pune's NDL-70G
On hand The number physically in the building: 5
Stock in A movement that raises on hand: the supplier delivers 40
Stock out A movement that lowers on hand: an order ships 3, or 5 are written off
Movement One change to on hand, with its delta and reason
Delta The change in a movement: +40 in, -3 out
Overselling Accepting more orders than there is stock: 20 orders for 5 packets
Reservation (hold) A promise of stock to a customer who is paying: hold H7 for 1 packet, expires in 10 minutes
Reserved stock Stock promised to carts, still in the building: reserved 5
Committed stock Reserved stock whose payment succeeded; it really goes out: commit(3)
Reserve / commit / release Promise stock / make the sale final / give the promise back
Available What a new customer can order: on hand − reserved; 12 − 5 = 7
Reservation expiry A hold that isn't paid in time is released automatically
Lead time Days the supplier takes to deliver after an order: 2
Safety stock Extra stock kept for a bad day: 2 packets
Reorder point The level at which to order again: daily sales × lead time + safety stock = 4 × 2 + 2 = 10
Low-stock alert A message sent when stock reaches the reorder point: Buyer: reorder NDL-70G (8 left)
Once per dip Alert the first time stock reaches the point, not again until it has been refilled above it
Observer pattern A subject keeps a list of observers and notifies all of them when something happens
Observer for alerts StockLevel (subject) notifies every StockListener (observer) on low stock
Subject The object being watched: StockLevel
Observer / listener An object that wants to be told: the buyer, the dashboard
Subscribe Add yourself to the subject's list: s.subscribe(listener)
Tight coupling One class knowing too much about others, so changing them means changing it
Concurrency Many things running at the same time, like 20 orders on 20 threads
Concurrency on stock updates Making sure stock changes stay correct when many threads change it at once
Thread One line of work running in a program; each customer's order ran on its own thread
Thread pool / ExecutorService A set of reusable threads you hand tasks to: Executors.newFixedThreadPool(20)
Future A handle to a result that arrives later; f.get() waits for it
CountDownLatch A starting gun: threads wait on await() until countDown() reaches 0
Race condition A bug where the result depends on which thread runs first
Lost update Two threads write over each other's change: 20 sales, stock only dropped by 1
Read, check, write The three steps of a stock update; they must be one step
synchronized Java keyword: only one thread at a time may run the synchronized methods of an object
Lock What a thread holds while inside synchronized code; others wait for it
Atomic Can't be split: no other thread can act in the middle
ConcurrentHashMap A map many threads can use at once; each call is safe, a sequence of calls is not
computeIfAbsent Create and store a value only if the key is missing; atomic in ConcurrentHashMap
CopyOnWriteArrayList A list that is safe to read while another thread adds to it; good for listener lists
AtomicInteger A thread-safe counter: nextHold.getAndIncrement()
volatile Makes a field's latest value visible to all threads: the fake clock now
JVM The Java Virtual Machine: one running Java program; synchronized works only inside one
Conditional update A database UPDATE ... WHERE on_hand - reserved >= 1 that checks and writes in one statement
Database transaction Several database changes that all happen or none do
Record (Java) A short class for plain data: record Sku(String code, Product product, String size)
Lambda A short unnamed function: (sku, left, rp) -> System.out.println(...)
Optional A box that holds a value or nothing: nearestWith(...) returns Optional<String>
IllegalStateException Java's exception for "not allowed in the current state": NDL-70G: only 44 left, asked 50
UnsupportedOperationException Java's exception for "this object doesn't support that": remove on a read-only list
Audit trail A record of every movement: when, which SKU, how many, why, who, stock after
Append-only You may add records but never edit or delete them, like a bank statement
Replay Adding up every movement from the start; must equal on hand: 40 − 3 − 5 − 2 = 30
Read-only view A wrapper that lets you read a list but not change it: Collections.unmodifiableList(log)
Write-off Stock removed because it can't be sold: 5 packets damaged in rain
Purchase order (PO) An order the shop sends to a supplier: PO-17 for 40 packets
Transfer Moving stock between warehouses: a stock out in one plus a stock in at the other
Batch Stock with the same expiry date, stored and counted together
FIFO First in, first out: sell the oldest batch first
Stock take Counting the shelves by hand to check the system's numbers

Summary

  • Inventory requirements: stock in and out, never oversell, hold stock for paying customers, alert before running out, audit every change.
  • A Product is sold as SKUs; each Warehouse keeps one StockLevel per SKU.
  • One number with read, check, write and 20 real threads: 5 packets, orders accepted: 20, stock now says: 4. A race condition; ConcurrentHashMap alone gave the same result.
  • synchronized StockLevel methods make each stock update one atomic step: exactly 5 of 20 reserved.
  • Reserved vs committed: available = on hand − reserved; reserve, then commit (paid) or release (failed or expired).
  • Reorder point = daily sales × lead time + safety stock = 10; a low-stock alert fires once per dip, and stock never goes below zero (only 44 left, asked 50).
  • The Observer pattern lets the buyer, a dashboard or an SMS service subscribe without touching StockLevel.
  • An append-only audit trail answers "where did 5 packets go?", replays to on hand (30 and 30), and can't be edited (UnsupportedOperationException).
  • Next episode: design an online shopping cart and checkout: carts, orders and their states, coupons, a pricing pipeline, payment providers and an idempotent checkout.