"Design an inventory system" sounds like a map from product to count. A weak answer keeps one quantity per product, or stock-keeping unit (SKU), lowers it when an order arrives and raises it when a delivery comes in. That answer cannot say how many units are on the shelf and how many are promised. It cannot say which warehouse should send an order, or what happens when two orders want the last unit at the same moment.
The interviewer is checking three things. First, whether "in stock" is modelled honestly: units on the shelf, units promised to orders, and units free to sell are three different numbers. Second, whether the shared counts stay right when many orders arrive at once, and when a truck carries stock from one warehouse to another. Third, whether the rule for choosing a warehouse can change without editing the core.
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
The cart and checkout are designed in Shopping Cart, and taking a restaurant's stock at checkout is in Food Delivery. This page starts where those stop: the order exists, and the warehouses must now set its units aside, send them, and keep count.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| What does "in stock" mean? | On hand minus what is already promised to orders | Two counts per warehouse: on hand and reserved |
| Which warehouse sends an order? | A rule the business will change: nearest, most stock, or split | An AllocationStrategy interface |
| May one line ship from two warehouses? | Only if the rule allows it | SplitNearestFirst is one of the rules |
| How long is stock held for an order? | 30 minutes, then it goes back on sale | A hold time and a timer |
| When is it too late to cancel? | Once the order has shipped. A picked order can still be cancelled | A status on each reservation, and the moves each status allows |
| Can stock move between warehouses? | Yes, by truck, and some units may arrive broken | A Transfer and an in-transit count |
| Who reorders when stock runs low? | The buyers. We tell them when a reorder point is reached | A StockAlertListener |
| Do we keep history? | Yes. Every change to on hand is recorded, so counts can be rebuilt | A Ledger |
| How many orders arrive at once? | Many, from many threads | Locks, and where they go |
| Can the order service send the same request twice? | Yes, it retries after a timeout | The order id makes reserve safe to repeat |
The first question matters most. If the design keeps one number, a cancelled order and a shipped order look the same, and a transfer cannot tell units it may send from units it has promised. Every later part of this design builds on keeping on hand and reserved apart.
Requirements
Functional:
- A delivery from a supplier adds units to one warehouse.
- An order reserves all its lines or none. The allocation rule decides which warehouses hold the units. If any line is short, the order is refused and the refusal names every short SKU.
- A reservation is picked and then shipped. Shipping removes the units from on hand. A reservation can be cancelled until it ships, and a reservation that is not picked within its hold time expires. Both give the units back.
- Stock can be sent from one warehouse to another. On the truck it belongs to neither. On arrival, the units that arrive are added, and the rest are written off.
- When a SKU's free stock in a warehouse falls to its reorder point, the buyers are told once.
- Every change to on hand is recorded, and on hand can be rebuilt from the records.
Out of scope: bins and shelves inside a warehouse, returns, stock counts that correct a wrong number, batches with expiry dates, and choosing one warehouse for a whole order. We come back to these at the end, because each is a likely follow-up.
Everything lives in memory, as is normal for a low-level design interview. Storing the counts and the ledger in a database is a separate discussion.
What the code itself must handle:
- Many callers at once. Orders, pickers, docks and the timer call in from different threads, often for the same SKU.
- A rule that changes. The way a warehouse is chosen will change, and that should not mean editing the core class.
- Testable time. Holds expire, so a test must be able to move the clock.
Finding the classes
We start from the nouns in the requirements. Most become classes or records. Some are dropped, and dropping them is part of the design.
Should Order be a class here?
An Order class with lines, an address and a status
An Order class is tempting, because "order" is in the question. But the order already lives in the order service, with its customer, payment and address. A second Order here would copy those fields, and the two copies would drift apart.
No. A Reservation keyed by the order idOur pick
Inventory only needs to know what is set aside for an order, where, and until when. A Reservation holds exactly that, and the order id ties it back to the order service. The cost is that inventory cannot answer "what did the customer buy?", which is not its question to answer.
Data or behaviour?
Some types only carry values that never change: a warehouse, a location, an order line, a hold, a transfer, a ledger movement. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString without writing them. A stock level is a record too. When a count changes, the code builds a new StockLevel and replaces the old one.
The class diagram
The classes fall into three groups:
- Data:
StockLevel,Warehouse,Location,OrderLine,Hold,Transfer,Candidate,Pick,MovementandLowStockAlertare records.ReservationStatusandMovementTypeare enums. - The core:
InventoryService,SkuStockandReservationhold the state that changes, and keep it right under many threads.Ledgerkeeps the history. - Rules and outside systems:
AllocationStrategyandStockAlertListenerare interfaces, so a new rule or a new listener never changes the core.
Building it
On hand, reserved, available
A warehouse has units on its shelves. Some of them are promised to orders that have not shipped yet. The rest are free to sell. We store the first two and work out the third:
public record StockLevel(int onHand, int reserved) { public static final StockLevel EMPTY = new StockLevel(0, 0); public StockLevel { if (onHand < 0 || reserved < 0) { throw new IllegalArgumentException("Counts cannot be negative: " + onHand + " on hand, " + reserved + " reserved"); } if (reserved > onHand) { throw new IllegalArgumentException("Cannot reserve " + reserved + " with only " + onHand + " on hand"); } } public int available() { return onHand - reserved; }available() is onHand - reserved, so it can never disagree with the other two. The constructor refuses a level with more reserved than on hand, so a bug that tries to promise units the shelf does not have fails at once, where it happens.
Each event moves the numbers in its own way. A reservation raises reserved and leaves onHand alone, because the units are still on the shelf. Shipping lowers both by the same amount, so available does not change. Cancelling or expiring lowers reserved only.
What does a warehouse count?
One quantity, lowered when an order arrives
This is the shortest answer. But nobody can tell how many units are physically on the shelf, a cancelled order cannot be told apart from a shipped one, and a stock take has nothing to compare against.
On hand, reserved and available, all three stored
Each read is a field read. But three stored numbers can disagree, and every change must update the right two of them.
On hand and reserved stored, available worked outOur pick
The two stored numbers each mean one physical thing: units on the shelf, and units promised. available() is one subtraction, so it is always right. The record checks that reserved never exceeds on hand.
One SkuStock per SKU
The next question is where these levels live. The obvious place is the warehouse: each Warehouse keeps a map from SKU to level. But the questions this design answers most often are about one SKU across every warehouse. An order for 5 lamps must see the lamp count in Newark, Chicago and Dallas at the same moment, to choose between them.
So the counts are grouped by SKU. A SkuStock holds one SKU's level in every warehouse, the units of it on trucks, and its reorder points:
final class SkuStock { private final String sku; private final Ledger ledger; private final ReentrantLock lock = new ReentrantLock(); private final Map<String, StockLevel> levels = new HashMap<>(); private final Map<String, Integer> reorderPoints = new HashMap<>(); private final List<LowStockAlert> pendingAlerts = new ArrayList<>(); private int inTransit;Every method on SkuStock is package-private. Apart from lock and unlock, each one expects the caller to hold its lock. Here is how a reservation, a release and a shipment change the level:
void reserve(String warehouseId, int quantity) { StockLevel level = level(warehouseId); change(warehouseId, new StockLevel(level.onHand(), level.reserved() + quantity)); } void release(String warehouseId, int quantity) { StockLevel level = level(warehouseId); change(warehouseId, new StockLevel(level.onHand(), level.reserved() - quantity)); } void ship(String warehouseId, int quantity, Instant at, String orderId) { StockLevel level = level(warehouseId); StockLevel next = new StockLevel(level.onHand() - quantity, level.reserved() - quantity); ledger.append(at, sku, warehouseId, MovementType.SHIPPED, quantity, orderId); change(warehouseId, next); }Notice the order inside ship. It builds the new StockLevel first, which checks the numbers. Then it writes the ledger line, and only then does it store the level. If the numbers are wrong, nothing has been written anywhere.
Where do a SKU's counts live?
On each Warehouse, a map from SKU to level
This matches the physical world. But choosing a warehouse for one order reads every warehouse, so it would need every warehouse's lock, and two orders for different SKUs would still wait for each other.
In one SkuStock per SKU, holding every warehouse's levelOur pick
All the numbers an order for one SKU needs sit in one object, under one lock. Orders for different SKUs never touch the same SkuStock. The cost is that "everything in Newark" means reading every SkuStock, which is a report, not an order.
Choosing the warehouse
An order for 5 lamps for a customer in Philadelphia could come from several places. There is more than one good answer, and the business will change its mind. This is the first place the design needs a pattern.
A rule is given the quantity for one line and a list of Candidate records. Each candidate is a warehouse id, its distance from the customer and how many units it has free. The rule returns Pick records that add up to the quantity, or empty if it cannot place them all. A rule sees only these values, in its own copy of the list. It cannot change a count, and it cannot change the numbers its answer is later checked against.
We wrote three rules. NearestFullLine takes the nearest warehouse that can send the whole line. MostStockFirst takes the warehouse with the most free. SplitNearestFirst takes what the nearest has, then the next nearest:
public Optional<List<Pick>> allocate(int quantity, List<Candidate> candidates) { List<Candidate> nearestFirst = candidates.stream() .filter(candidate -> candidate.available() > 0) .sorted(Candidate.NEAREST_FIRST) .toList(); List<Pick> picks = new ArrayList<>(); int remaining = quantity; for (Candidate candidate : nearestFirst) { if (remaining == 0) { break; } int take = Math.min(remaining, candidate.available()); picks.add(new Pick(candidate.warehouseId(), take)); remaining -= take; } if (remaining > 0) { return Optional.empty(); } return Optional.of(List.copyOf(picks)); }None of these rules is right in general. Splitting gets units to the customer sooner, but every extra parcel costs postage. Taking from the warehouse with the most stock keeps small warehouses from running dry, but it ships from far away. That is a business choice, so it sits behind an interface.
Is an interface worth it for the allocation rule?
Write the loop inside InventoryService
There are fewer files. But the next change of mind ("split only for premium customers", "never ship from Dallas in winter") edits the class that also holds the locks and the reservations.
AllocationStrategy, with three implementationsOur pick
A new rule that needs only distances and free counts is a new class, and InventoryService does not change. Three real rules prove the interface is useful. The cost is that a rule which needs more, such as the whole order at once, needs a wider interface.
The rule is code that InventoryService does not control. A rule could return picks that add up to 4 instead of 5, or take 6 from a warehouse with 3 free. So plan hands the rule a copy of the candidates, and checks the answer against the original before any count changes:
private List<Hold> plan(Location destination, List<OrderLine> lines) { List<Hold> holds = new ArrayList<>(); List<String> shortSkus = new ArrayList<>(); for (OrderLine line : lines) { List<Candidate> candidates = candidatesFor(line.sku(), destination); Optional<List<Pick>> picks = allocation.allocate(line.quantity(), new ArrayList<>(candidates)); if (picks.isEmpty()) { shortSkus.add(line.sku()); } else { requireValidPlan(line, picks.get(), candidates); for (Pick pick : picks.get()) { holds.add(new Hold(line.sku(), pick.warehouseId(), pick.quantity())); } } } if (!shortSkus.isEmpty()) { throw new InsufficientStockException("Not enough stock for " + String.join(", ", shortSkus)); } return holds; }plan goes through every line and only collects holds. It changes nothing. If a line is short, its SKU goes on a list, and after the loop one InsufficientStockException names every short SKU, so the customer can fix the order in one go. If the rule's answer is wrong, requireValidPlan throws an IllegalStateException. The design uses three kinds of error. InsufficientStockException is a message for a customer. IllegalStateException says a move is not allowed right now, to a calling system such as a picker's scanner or a dock, or that a rule broke its promise. IllegalArgumentException, NullPointerException and ArithmeticException (a count too big for an int) mean a programmer sent bad input.
Reserving an order
With the plan in hand, reserving is short:
public Reservation reserve(String orderId, Location destination, List<OrderLine> lines) { requireOrderId(orderId); Objects.requireNonNull(destination, "destination"); List<OrderLine> order = List.copyOf(lines); if (order.isEmpty()) { throw new IllegalArgumentException("Order " + orderId + " has no lines"); } Set<String> skus = new LinkedHashSet<>(); for (OrderLine line : order) { if (!skus.add(line.sku())) { throw new IllegalArgumentException("SKU " + line.sku() + " appears twice in order " + orderId); } } return withLocks(skus, () -> { Reservation existing = reservations.get(orderId); if (existing != null) { return existing; } List<Hold> holds = plan(destination, order); Reservation reservation = new Reservation(orderId, holds, clock.instant().plus(holdFor)); Reservation raced = reservations.putIfAbsent(orderId, reservation); if (raced != null) { // The same order id arrived with other SKUs, under other locks, and won. return raced; } for (Hold hold : holds) { stocks.get(hold.sku()).reserve(hold.warehouseId(), hold.quantity()); } return reservation; }); }reserve checks its inputs first: an order id, a destination, at least one line, and no SKU twice. Then withLocks takes the lock of every SKU in the order, and the rest runs under those locks. It plans, claims the order id with putIfAbsent, then reserves each hold. Because the plan already proved every hold fits, under the same locks, none of the reserve calls on SkuStock can fail halfway. The order is held whole or not at all, and the claimed order id never needs taking back.
Look at the first lines inside the lock. The order service may time out, and then send the same request again. If reserve made a second reservation, the order would hold its units twice. So the order id is the key. A second call finds the first reservation and returns it, even if stock has since run out.
What happens when reserve is called twice for one order?
Reserve again, and let the caller avoid repeats
This keeps reserve simple. But a caller that timed out cannot know whether the first call worked, and every retry holds the units again, until the hold expires.
The order id is the key. A second call gets the first reservationOur pick
A retry is always safe. The check runs under the same locks as the reservation, so two copies of one request cannot both get past it. The cost is that a retry with different lines also gets the first reservation, and a new attempt needs a new order id.
One case slips past that check. Two calls for the same order id whose SKUs do not overlap take different locks, so both can pass it. putIfAbsent catches this. It runs before any count changes, so the losing call has changed nothing, and it returns the winner's reservation.
Pick, ship, cancel, expire
A reservation moves through five statuses. HELD means the units are set aside. PICKED means they are in a tote on the packing table. SHIPPED, CANCELLED and EXPIRED are the three endings.
| Status | pick | ship | cancel | timer |
|---|---|---|---|---|
HELD | becomes PICKED, or EXPIRED if its time is up | refused | CANCELLED, units back | EXPIRED once its time is up |
PICKED | refused | SHIPPED, units leave | CANCELLED, units back | stays PICKED |
SHIPPED | refused | refused | refused | stays |
CANCELLED | refused | refused | does nothing | stays |
EXPIRED | refused | refused | does nothing | stays |
Each method checks the status under the SKU locks, then changes the counts and the status in the same locked step. Here is pick:
public void pick(String orderId) { Reservation reservation = find(orderId); withLocks(reservation.skus(), () -> { requireStatus(reservation, ReservationStatus.HELD, "picked"); if (reservation.expiresBy(clock.instant())) { release(reservation, ReservationStatus.EXPIRED); throw new IllegalStateException("Order " + orderId + " expired at " + reservation.expiresAt()); } reservation.moveTo(ReservationStatus.PICKED); }); }pick checks the clock itself. If the hold's time is up, it expires the reservation, gives the units back and refuses the pick. The timer does not have to have run first. The time check lives in one method on Reservation:
/** Only a held reservation can run out of time. Picked units are already in a tote. */ boolean expiresBy(Instant now) { return status == ReservationStatus.HELD && !now.isBefore(expiresAt); }expiresBy is true only for a HELD reservation, and only once now has reached expiresAt. A hold that runs out at 09:30 has expired at exactly 09:30. A picked order never expires, because its units are no longer on the shelf to sell.
The timer calls releaseExpired, which walks the reservations and expires each one that is due:
public int releaseExpired() { Instant now = clock.instant(); int released = 0; for (Reservation reservation : reservations.values()) { if (reservation.expiresBy(now) && expire(reservation, now)) { released++; } } return released; }expire takes the reservation's locks and asks expiresBy again. A picker may have picked the order between the first look and the lock. The second look, under the lock, is the one that counts. So a late pick and the timer can race, and the units still come back exactly once.
When does a hold run out?
When the timer runs
This is simple to write. But a hold is then as long as its time plus the timer's delay. If the timer stalls, a picker can take units that should have gone back on sale.
At its time. pick checks the clock, and the timer only returns units soonerOur pick
The hold time means what it says, whatever the timer does. The timer is still needed, because a hold that nobody picks would otherwise keep its units off sale for ever. The cost is that one rule lives in two places, so both call the same expiresBy.
Two orders, the last mug
Two customers order the last mug at the same moment. Both calls run on different threads. If reading "available: 1" and writing "reserved: 1" are two separate steps, both orders can read 1 before either writes.
Every call that reads or changes a SKU's counts goes through one helper, withLocks:
/** * Locks the SKUs in name order, runs the work, then unlocks and sends any * low-stock alerts. One order for every caller means two calls never wait * for each other in a circle. */ private <T> T withLocks(Collection<String> skus, Supplier<T> work) { List<SkuStock> locked = new ArrayList<>(); List<LowStockAlert> alerts = new ArrayList<>(); T result; try { for (String sku : new TreeSet<>(skus)) { SkuStock stock = stocks.computeIfAbsent(sku, key -> new SkuStock(key, ledger)); stock.lock(); locked.add(stock); } result = work.get(); } finally { for (int i = locked.size() - 1; i >= 0; i--) { alerts.addAll(locked.get(i).takeAlerts()); locked.get(i).unlock(); } } for (LowStockAlert alert : alerts) { notifyQuietly(alert); } return result; }withLocks puts the SKUs in a TreeSet, so they are locked in name order. Then it runs the work, and in the finally block it collects any low-stock alerts and unlocks, in reverse order. The alerts are sent only after every lock is released.
The name order matters when an order has two SKUs. Order 1 asks for a lamp and a mug, and order 2 asks for a mug and a lamp. If each locked its SKUs in its own order, order 1 could hold the lamp lock while waiting for the mug lock, and order 2 could hold the mug while waiting for the lamp. Both would wait for ever. With one order for every caller, both lock LAMP-01 first, so one of them waits.
The project includes demo/RaceCheck.java. Its first half sends 1,000 one-unit orders for 100 mugs through 16 threads. Its second half dispatches 300 one-unit transfers, then lets two threads unload each one at the same moment:
Orders reserved 100, refused 900. The counters say 100 reserved of 100 Transfers unloaded 300 of 600 tries. WEST on hand 300, in transit 0, ledger agrees: true
Exactly 100 orders were told yes, and the counters agree. Every transfer was counted once, and the ledger matches. We also ran the check once more with lock() and unlock() in SkuStock emptied. More than 100 orders were told yes while the counters still said 100 reserved, and a few orders failed with an error instead of either answer. In the transfer half, some transfers were unloaded twice, in transit went below zero, and the counters no longer matched the ledger. The exact numbers change from run to run.
Where do the locks go?
One lock for the whole inventory
This is correct and easy to explain. But every order, pick, delivery and truck waits for every other one, across all SKUs and all warehouses.
A lock per warehouse
This sounds natural. But choosing a warehouse reads them all, so one order takes every warehouse lock, and two orders for different products still wait for each other.
A lock per SKU, taken in name orderOur pick
The race is over one SKU's units, and that SKU's counts all sit in its SkuStock. Orders for different SKUs never wait for each other. The cost is that an order with many SKUs takes many locks, so they must always be taken in the same order.
Moving stock by truck
A transfer has two moments. When the truck leaves Dallas, the units are no longer on Dallas's shelves. When it reaches Newark, they are on Newark's. In between they are on the road, and the design must count them exactly once all the way.
void sendInTransit(String warehouseId, int quantity, Instant at, String transferId) { StockLevel level = level(warehouseId); if (level.available() < quantity) { throw new InsufficientStockException("Only " + level.available() + " " + sku + " free at " + warehouseId + ", cannot send " + quantity); } StockLevel next = new StockLevel(level.onHand() - quantity, level.reserved()); int nextInTransit = Math.addExact(inTransit, quantity); ledger.append(at, sku, warehouseId, MovementType.TRANSFER_OUT, quantity, transferId); change(warehouseId, next); inTransit = nextInTransit; } void arriveFromTransit(String warehouseId, int sent, int arrived, Instant at, String transferId) { StockLevel level = level(warehouseId); StockLevel next = new StockLevel(Math.addExact(level.onHand(), arrived), level.reserved()); if (arrived > 0) { ledger.append(at, sku, warehouseId, MovementType.TRANSFER_IN, arrived, transferId); } if (arrived < sent) { ledger.append(at, sku, warehouseId, MovementType.TRANSFER_LOST, sent - arrived, transferId); } change(warehouseId, next); inTransit -= sent; }sendInTransit refuses to send units that are promised to orders, because it checks available(), not onHand. It lowers Dallas's on hand and raises inTransit in the same locked step, and Math.addExact refuses a total too big for an int before anything is written. arriveFromTransit adds what arrived to Newark and lowers inTransit by what was sent. If fewer arrive, a TRANSFER_LOST line records the difference, so no unit vanishes.
The other danger is unloading one truck twice. receiveTransfer checks, under the SKU's lock, that the transfer is still in the in-transit map. It changes the counts, and only then removes the transfer:
public void receiveTransfer(String transferId, int quantityArrived) { Transfer transfer = inTransit.get(transferId); if (transfer == null) { throw new IllegalStateException("Transfer " + transferId + " is not in transit"); } if (quantityArrived < 0 || quantityArrived > transfer.quantity()) { throw new IllegalArgumentException("Between 0 and " + transfer.quantity() + " can arrive, got " + quantityArrived); } withLocks(List.of(transfer.sku()), () -> { if (!inTransit.containsKey(transferId)) { throw new IllegalStateException("Transfer " + transferId + " is not in transit"); } stocks.get(transfer.sku()).arriveFromTransit(transfer.toWarehouse(), transfer.quantity(), quantityArrived, clock.instant(), transferId); inTransit.remove(transferId); }); }A second dock finds the transfer gone, before or after taking the lock, and is refused, so nothing is counted twice. If arriveFromTransit throws, the transfer is still in the map and can be unloaded again, because nothing is removed before the work succeeds.
Where are units while they are on the truck?
Still in the sending warehouse until they arrive
The sender's count stays put. But the sender could then sell units that are on a truck, and a report of the network would count them in Dallas while Newark is waiting for them.
In the receiving warehouse from the moment they leave
Newark can sell them at once. But it then promises units that are hours away, and a lost unit is already counted on its shelf.
In a separate in-transit count that belongs to neitherOur pick
Neither warehouse can sell units on the road, and the total across the network stays the same until a loss is written off. The cost is a third place to look when asking "how many do we have?".
The ledger
Every change to on hand writes one Movement to the Ledger: a sequence number, the time, the SKU, the warehouse, the type, the quantity and the order, transfer or delivery that caused it. Each type knows what it does to on hand and to in transit:
public enum MovementType { RECEIVED(1, 0), SHIPPED(-1, 0), TRANSFER_OUT(-1, 1), TRANSFER_IN(1, -1), TRANSFER_LOST(0, -1);That lets the ledger work out on hand again from nothing but its lines:
/** On hand, worked out again from nothing but the movements. */ public synchronized int onHandFromHistory(String warehouseId, String sku) { int onHand = 0; for (Movement movement : movements) { if (movement.sku().equals(sku) && movement.warehouseId().equals(warehouseId)) { onHand += movement.type().onHandChange(movement.quantity()); } } return onHand; }A reservation does not write a line, because it does not move a unit. The open reservations themselves say what is reserved.
Counters, a ledger, or both?
Counters only
Reads are fast. But when a count looks wrong, there is nothing to explain how it got there.
A ledger only, summed on every read
There is one source of truth. But every reservation would sum the history of that SKU, and the history only grows.
Both, changed in the same method under the same lockOur pick
Reads use the counters. The ledger explains them, and onHandFromHistory can rebuild any count to check it. They cannot drift, because SkuStock writes the line and the count in one method, under the SKU's lock. The cost is two writes for each movement.
Low-stock alerts
The buyers want to hear when Chicago is down to 5 lamps, so they can order more. Inventory should not know who the buyers are, how many systems listen, or how they place orders.
The check sits in SkuStock.change, the one method every count change goes through:
private void change(String warehouseId, StockLevel next) { StockLevel before = level(warehouseId); levels.put(warehouseId, next); Integer point = reorderPoints.get(warehouseId); if (point != null && before.available() > point && next.available() <= point) { pendingAlerts.add(new LowStockAlert(warehouseId, sku, next.available(), point)); } }An alert fires only when available() was above the reorder point before the change and is at or below it after. Falling further does not alert again. Rising above the point and falling again does. Shipping never alerts, because it leaves available() unchanged. The alert fired earlier, when the order reserved the units.
The alerts wait in pendingAlerts until withLocks releases the locks, and then each listener is called through notifyQuietly:
private void notifyQuietly(LowStockAlert alert) { for (StockAlertListener listener : listeners) { try { listener.onLowStock(alert); } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "Stock alert listener failed", e); } } }A listener is outside code. If it throws, the reservation has already happened and must not be undone, so the failure is logged and the next listener still runs. Because no lock is held while it runs, a listener can call back into the inventory, for example to order a transfer from another warehouse.
When does a low-stock alert fire?
On every change that leaves on hand below the point
This is the simplest check. But every order after the point is reached sends another alert, and on hand still counts units that are promised to orders.
When available first falls to the reorder pointOur pick
The buyers hear once for each time stock runs low, and they hear when the free units run low, not when the shelf empties after shipping. The cost is that a listener that was down when the alert fired misses it until the next crossing.
The final design
InventoryService is the core. It owns one SkuStock per SKU and a Reservation per order, writes history through the Ledger, and reaches the allocation rule and the buyers only through interfaces. It reads the time from a Clock it is given, so a test can move a hold past its time in one line. Every count changes under the lock of its SKU, and nothing outside the code runs while a lock is held, apart from the allocation rule.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should Order be a class here? | No. A Reservation keyed by the order id | The order service already owns the order. |
| 2 | What does a warehouse count? | On hand and reserved stored, available worked out | Available can never disagree with the other two. |
| 3 | Where do a SKU's counts live? | In one SkuStock per SKU, holding every warehouse's level | One order reads one object under one lock. |
| 4 | Is an interface worth it for the allocation rule? | AllocationStrategy, with three implementations | A new rule is a new class. |
| 5 | What happens when reserve is called twice for one order? | The order id is the key. A second call gets the first reservation | A retry is always safe. |
| 6 | When does a hold run out? | At its time. pick checks the clock, and the timer only returns units sooner | The hold time means what it says. |
| 7 | Where do the locks go? | A lock per SKU, taken in name order | Different SKUs never wait, and no two orders wait in a circle. |
| 8 | Where are units while they are on the truck? | In a separate in-transit count that belongs to neither | Nobody sells units on the road. |
| 9 | Counters, a ledger, or both? | Both, changed in the same method under the same lock | Fast reads, and every count can be explained. |
| 10 | When does a low-stock alert fire? | When available first falls to the reorder point | The buyers hear once, about free units. |
Here is order A-100 from the demo, end to end:
- The order service calls
reserve("A-100", philadelphia, lines). The inputs are checked first, with no lock held. ThenwithLockstakes theLAMP-01lock, the only SKU in the order. - Under the lock,
reservelooks for an earlier reservation for A-100 and finds none, so this is not a retry.planbuilds oneCandidatefor each warehouse, with its distance from the customer and its free units. AllocationStrategy.allocateis the outside call, and it runs under the lock so the free counts cannot change while it decides.SplitNearestFirstreturns Newark 3 and Chicago 2, andrequireValidPlanchecks that the answer adds up and fits.putIfAbsentputs the newReservation, held until 09:30, into the map. ThenSkuStock.reserveraisesreservedin both warehouses. Newark drops to 0 free, below its reorder point of 1, sochangequeues an alert.withLockscollects the alert and releases the lock. Only then doesnotifyQuietlytell eachStockAlertListener, so a slow buyers' system never holds up the next lamp order.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search.
package inventory; import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.TreeSet;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.atomic.AtomicLong;import java.util.function.Supplier; import alert.LowStockAlert;import alert.StockAlertListener;import allocation.AllocationStrategy;import allocation.Candidate;import allocation.Pick;import ledger.Ledger;import warehouse.Location;import warehouse.StockLevel;import warehouse.Warehouse; public final class InventoryService { private static final System.Logger LOG = System.getLogger(InventoryService.class.getName()); private final Map<String, Warehouse> warehouses; private final AllocationStrategy allocation; private final Ledger ledger; private final Clock clock; private final Duration holdFor; private final Map<String, SkuStock> stocks = new ConcurrentHashMap<>(); private final Map<String, Reservation> reservations = new ConcurrentHashMap<>(); private final Map<String, Transfer> inTransit = new ConcurrentHashMap<>(); private final AtomicLong transferNumbers = new AtomicLong(); private final List<StockAlertListener> listeners = new CopyOnWriteArrayList<>(); public InventoryService(List<Warehouse> warehouses, AllocationStrategy allocation, Ledger ledger, Clock clock, Duration holdFor) { Objects.requireNonNull(warehouses, "warehouses"); if (warehouses.isEmpty()) { throw new IllegalArgumentException("Inventory needs at least one warehouse"); } Map<String, Warehouse> byId = new LinkedHashMap<>(); for (Warehouse warehouse : warehouses) { if (byId.putIfAbsent(warehouse.id(), warehouse) != null) { throw new IllegalArgumentException("Two warehouses have the id " + warehouse.id()); } } Objects.requireNonNull(holdFor, "holdFor"); if (holdFor.isZero() || holdFor.isNegative()) { throw new IllegalArgumentException("A hold must last some time, got " + holdFor); } this.warehouses = Collections.unmodifiableMap(byId); this.allocation = Objects.requireNonNull(allocation, "allocation"); this.ledger = Objects.requireNonNull(ledger, "ledger"); this.clock = Objects.requireNonNull(clock, "clock"); this.holdFor = holdFor; } public void addAlertListener(StockAlertListener listener) { listeners.add(Objects.requireNonNull(listener, "listener")); } public void setReorderPoint(String warehouseId, String sku, int units) { requireWarehouse(warehouseId); requireSku(sku); if (units < 0) { throw new IllegalArgumentException("A reorder point cannot be negative, got " + units); } withLocks(List.of(sku), () -> stocks.get(sku).setReorderPoint(warehouseId, units)); } /** A delivery from a supplier has been counted onto the shelves. */ public void receive(String warehouseId, String sku, int quantity, String deliveryRef) { requireWarehouse(warehouseId); requireSku(sku); requirePositive(quantity); Objects.requireNonNull(deliveryRef, "deliveryRef"); withLocks(List.of(sku), () -> stocks.get(sku).receive(warehouseId, quantity, clock.instant(), deliveryRef)); } // ---------------------------------------------------------------- orders public Reservation reserve(String orderId, Location destination, List<OrderLine> lines) { requireOrderId(orderId); Objects.requireNonNull(destination, "destination"); List<OrderLine> order = List.copyOf(lines); if (order.isEmpty()) { throw new IllegalArgumentException("Order " + orderId + " has no lines"); } Set<String> skus = new LinkedHashSet<>(); for (OrderLine line : order) { if (!skus.add(line.sku())) { throw new IllegalArgumentException("SKU " + line.sku() + " appears twice in order " + orderId); } } return withLocks(skus, () -> { Reservation existing = reservations.get(orderId); if (existing != null) { return existing; } List<Hold> holds = plan(destination, order); Reservation reservation = new Reservation(orderId, holds, clock.instant().plus(holdFor)); Reservation raced = reservations.putIfAbsent(orderId, reservation); if (raced != null) { // The same order id arrived with other SKUs, under other locks, and won. return raced; } for (Hold hold : holds) { stocks.get(hold.sku()).reserve(hold.warehouseId(), hold.quantity()); } return reservation; }); } public void pick(String orderId) { Reservation reservation = find(orderId); withLocks(reservation.skus(), () -> { requireStatus(reservation, ReservationStatus.HELD, "picked"); if (reservation.expiresBy(clock.instant())) { release(reservation, ReservationStatus.EXPIRED); throw new IllegalStateException("Order " + orderId + " expired at " + reservation.expiresAt()); } reservation.moveTo(ReservationStatus.PICKED); }); } public void ship(String orderId) { Reservation reservation = find(orderId); withLocks(reservation.skus(), () -> { requireStatus(reservation, ReservationStatus.PICKED, "shipped"); Instant now = clock.instant(); for (Hold hold : reservation.holds()) { stocks.get(hold.sku()).ship(hold.warehouseId(), hold.quantity(), now, orderId); } reservation.moveTo(ReservationStatus.SHIPPED); }); } /** Gives the units back. Cancelling twice, or after expiry, does nothing. */ public void cancel(String orderId) { Reservation reservation = find(orderId); withLocks(reservation.skus(), () -> { if (reservation.status() == ReservationStatus.SHIPPED) { throw new IllegalStateException("Order " + orderId + " has already shipped"); } if (reservation.status().holdsStock()) { release(reservation, ReservationStatus.CANCELLED); } }); } /** Called by a timer. Returns how many reservations ran out of time. */ public int releaseExpired() { Instant now = clock.instant(); int released = 0; for (Reservation reservation : reservations.values()) { if (reservation.expiresBy(now) && expire(reservation, now)) { released++; } } return released; } public Optional<Reservation> reservation(String orderId) { return Optional.ofNullable(reservations.get(orderId)); } // ---------------------------------------------------------------- transfers public Transfer dispatchTransfer(String sku, String fromId, String toId, int quantity) { requireSku(sku); requireWarehouse(fromId); requireWarehouse(toId); requirePositive(quantity); if (fromId.equals(toId)) { throw new IllegalArgumentException("A transfer needs two different warehouses"); } return withLocks(List.of(sku), () -> { String id = "TR-" + transferNumbers.incrementAndGet(); Transfer transfer = new Transfer(id, sku, fromId, toId, quantity, clock.instant()); stocks.get(sku).sendInTransit(fromId, quantity, transfer.dispatchedAt(), id); inTransit.put(id, transfer); return transfer; }); } /** The truck has been unloaded. Fewer units than were sent means some were lost or damaged. */ public void receiveTransfer(String transferId, int quantityArrived) { Transfer transfer = inTransit.get(transferId); if (transfer == null) { throw new IllegalStateException("Transfer " + transferId + " is not in transit"); } if (quantityArrived < 0 || quantityArrived > transfer.quantity()) { throw new IllegalArgumentException("Between 0 and " + transfer.quantity() + " can arrive, got " + quantityArrived); } withLocks(List.of(transfer.sku()), () -> { if (!inTransit.containsKey(transferId)) { throw new IllegalStateException("Transfer " + transferId + " is not in transit"); } stocks.get(transfer.sku()).arriveFromTransit(transfer.toWarehouse(), transfer.quantity(), quantityArrived, clock.instant(), transferId); inTransit.remove(transferId); }); } // ---------------------------------------------------------------- reads public StockLevel stockLevel(String warehouseId, String sku) { requireWarehouse(warehouseId); requireSku(sku); if (!stocks.containsKey(sku)) { return StockLevel.EMPTY; } return withLocks(List.of(sku), () -> stocks.get(sku).level(warehouseId)); } public int inTransit(String sku) { requireSku(sku); if (!stocks.containsKey(sku)) { return 0; } return withLocks(List.of(sku), () -> stocks.get(sku).inTransit()); } // ---------------------------------------------------------------- allocation private List<Hold> plan(Location destination, List<OrderLine> lines) { List<Hold> holds = new ArrayList<>(); List<String> shortSkus = new ArrayList<>(); for (OrderLine line : lines) { List<Candidate> candidates = candidatesFor(line.sku(), destination); Optional<List<Pick>> picks = allocation.allocate(line.quantity(), new ArrayList<>(candidates)); if (picks.isEmpty()) { shortSkus.add(line.sku()); } else { requireValidPlan(line, picks.get(), candidates); for (Pick pick : picks.get()) { holds.add(new Hold(line.sku(), pick.warehouseId(), pick.quantity())); } } } if (!shortSkus.isEmpty()) { throw new InsufficientStockException("Not enough stock for " + String.join(", ", shortSkus)); } return holds; } private List<Candidate> candidatesFor(String sku, Location destination) { SkuStock stock = stocks.get(sku); List<Candidate> candidates = new ArrayList<>(); for (Warehouse warehouse : warehouses.values()) { int available = stock.level(warehouse.id()).available(); candidates.add(new Candidate(warehouse.id(), warehouse.location().distanceKmTo(destination), available)); } return candidates; } /** The rule is outside code: check its answer before any count changes. */ private static void requireValidPlan(OrderLine line, List<Pick> picks, List<Candidate> candidates) { Map<String, Integer> left = new HashMap<>(); for (Candidate candidate : candidates) { left.put(candidate.warehouseId(), candidate.available()); } int total = 0; for (Pick pick : picks) { int remaining = left.getOrDefault(pick.warehouseId(), 0) - pick.quantity(); if (remaining < 0) { throw new IllegalStateException("The allocation rule took more " + line.sku() + " from " + pick.warehouseId() + " than it has free"); } left.put(pick.warehouseId(), remaining); total += pick.quantity(); } if (total != line.quantity()) { throw new IllegalStateException("The allocation rule placed " + total + " of " + line.quantity() + " " + line.sku()); } } // ---------------------------------------------------------------- helpers private boolean expire(Reservation reservation, Instant now) { return withLocks(reservation.skus(), () -> { if (!reservation.expiresBy(now)) { return false; } release(reservation, ReservationStatus.EXPIRED); return true; }); } private void release(Reservation reservation, ReservationStatus next) { for (Hold hold : reservation.holds()) { stocks.get(hold.sku()).release(hold.warehouseId(), hold.quantity()); } reservation.moveTo(next); } private void withLocks(Collection<String> skus, Runnable work) { withLocks(skus, () -> { work.run(); return null; }); } /** * Locks the SKUs in name order, runs the work, then unlocks and sends any * low-stock alerts. One order for every caller means two calls never wait * for each other in a circle. */ private <T> T withLocks(Collection<String> skus, Supplier<T> work) { List<SkuStock> locked = new ArrayList<>(); List<LowStockAlert> alerts = new ArrayList<>(); T result; try { for (String sku : new TreeSet<>(skus)) { SkuStock stock = stocks.computeIfAbsent(sku, key -> new SkuStock(key, ledger)); stock.lock(); locked.add(stock); } result = work.get(); } finally { for (int i = locked.size() - 1; i >= 0; i--) { alerts.addAll(locked.get(i).takeAlerts()); locked.get(i).unlock(); } } for (LowStockAlert alert : alerts) { notifyQuietly(alert); } return result; } private void notifyQuietly(LowStockAlert alert) { for (StockAlertListener listener : listeners) { try { listener.onLowStock(alert); } catch (RuntimeException e) { LOG.log(System.Logger.Level.WARNING, "Stock alert listener failed", e); } } } private Reservation find(String orderId) { requireOrderId(orderId); Reservation reservation = reservations.get(orderId); if (reservation == null) { throw new IllegalArgumentException("No reservation for order " + orderId); } return reservation; } private static void requireStatus(Reservation reservation, ReservationStatus expected, String action) { if (reservation.status() != expected) { throw new IllegalStateException("Order " + reservation.orderId() + " is " + reservation.status() + " and cannot be " + action); } } private void requireWarehouse(String warehouseId) { Objects.requireNonNull(warehouseId, "warehouseId"); if (!warehouses.containsKey(warehouseId)) { throw new IllegalArgumentException("No warehouse " + warehouseId); } } private static void requireSku(String sku) { Objects.requireNonNull(sku, "sku"); if (sku.isBlank()) { throw new IllegalArgumentException("A SKU cannot be blank"); } } private static void requireOrderId(String orderId) { Objects.requireNonNull(orderId, "orderId"); if (orderId.isBlank()) { throw new IllegalArgumentException("An order id cannot be blank"); } } private static void requirePositive(int quantity) { if (quantity <= 0) { throw new IllegalArgumentException("A quantity must be at least 1, got " + quantity); } }}demo/Main.java stocks three warehouses with lamps, shows what each rule would do with one order, then runs orders through holds, a ship, an expiry and a cancel. It ends with a transfer that loses one unit and the ledger that records it all:
Received LAMP-01: NJ 3, IL 8, TX 12 5 x LAMP-01 for Philadelphia under each rule: NJ is 128 km away IL is 1082 km away TX is 2090 km away NearestFullLine IL 5 MostStockFirst TX 5 SplitNearestFirst NJ 3 + IL 2 ALERT NJ LAMP-01: 0 available, reorder point 1 A-100 reserved NJ 3 + IL 2, held until 09:30 NJ on hand 3, reserved 3, available 0 A-101 for 30 refused: Not enough stock for LAMP-01 A-100 sent again: the same reservation, NJ 3 + IL 2 ALERT IL LAMP-01: 2 available, reorder point 5 A-102 reserved IL 4 A-100 picked and shipped. NJ 0, IL 6, TX 12 IL on hand 6, reserved 4, available 2 09:31 timer: 1 released, A-102 is EXPIRED, IL on hand 6, reserved 0, available 6 ALERT IL LAMP-01: 4 available, reorder point 5 A-103 reserved IL 2 A-103 cancelled, IL on hand 6, reserved 0, available 6 TR-1: 6 from TX to NJ. NJ 0, IL 6, TX 6, in transit 6 TR-1 arrived with 5 of 6. NJ 5, IL 6, TX 6, in transit 0 TR-1 unloaded again: Transfer TR-1 is not in transit Ledger for LAMP-01: 1 09:00 RECEIVED NJ 3 PO-881 2 09:00 RECEIVED IL 8 PO-882 3 09:00 RECEIVED TX 12 PO-883 4 09:00 SHIPPED NJ 3 A-100 5 09:00 SHIPPED IL 2 A-100 6 09:31 TRANSFER_OUT TX 6 TR-1 7 09:31 TRANSFER_IN NJ 5 TR-1 8 09:31 TRANSFER_LOST NJ 1 TR-1 On hand from the ledger: NJ 5, IL 6, TX 6. Matches the counters: true
Notice three things in the output. The alert for Newark prints before the line that reports A-100, because it fires inside reserve, just after the lock is released. Chicago alerts twice: once when A-102 takes it to 2 free, and again after the expired hold lifted it to 6 and A-103 took it to 4. And the eight ledger lines rebuild Newark 5, Chicago 6 and Dallas 6, which match the counters, with the lost unit as its own line.
Follow-up questions
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Send a whole order from one warehouse when you can." | AllocationStrategy takes every line at once, so its signature and plan change. | Counts, locks, ledger, transfers. |
| "Stock counts find 2 lamps missing." | A new ADJUSTED movement type and an adjust method that writes it. If on hand would fall below reserved, it refuses or a person decides. | Reservations, allocation, transfers. |
| "Customers return items." | A RETURNED movement adds units back, perhaps to a separate damaged count first. | Reservations and allocation. |
| "Track bins and shelves inside a warehouse." | StockLevel becomes a level per bin, and picking names a bin. SkuStock sums the bins for allocation. | The allocation rule, the ledger's idea, the locks per SKU. |
| "Some products expire, so ship the oldest first." | Units carry a batch and a date, and holds name the batch. | The order flow, the statuses, the alerts. |
| "Reorder automatically." | A listener that dispatches a transfer or raises a purchase order. It can call back in, because no lock is held. | The inventory classes. |
| "Old reservations fill memory." | Finished reservations move to an archive after a while. A retry after that is treated as new. | Everything that handles live orders. |
| "Each warehouse ships its part separately." | ship takes a warehouse id and ships only that warehouse's holds. The status needs a partly shipped value. | Counts, ledger and allocation. |
| "Run this as a service with a database." | The counts and the ledger line are written in one database transaction, with a row lock per SKU. | The classes and the rules about each count. |
In most rows the change lands in a new movement type, a new rule or a new listener, and InventoryService changes little. The first row is the exception: a rule that sees the whole order changes the interface. When you answer a follow-up, say which classes change and which do not.
What the interviewer looks for
Mid-level
A mid-level candidate shows a working reserve, ship and cancel with sensible classes and enums. They keep reserved apart from on hand, and they say that two orders for the last unit need a lock, even if the lock is wider than it needs to be.
Senior
A senior candidate gives the reasons. They explain why available is worked out and never stored, why the allocation rule is an interface, and why the lock sits on the SKU. They make a whole order reserve all or nothing, make a retried reserve safe, and handle the hold that runs out while a picker is on the way.
Staff+
A staff candidate raises the hard cases before being asked. They count units on a truck exactly once, record losses instead of letting units vanish, take several locks in one fixed order, and keep a history that can rebuild every count. They can say how each part maps to a real database, and where the in-memory design would have to change.
Common mistakes
- One quantity per product. It cannot tell promised units from free ones, so cancelling, shipping and transfers all go wrong.
- Checking available, then reserving, in two steps without a lock. Two orders both see 1 free and both get the unit.
- Locking SKUs in the order the customer listed them. Two orders with the same SKUs in opposite orders can wait for each other for ever.
- Counting units on a truck in either warehouse. One of the two counts is then wrong for the whole journey.
- Trusting the allocation rule's answer. A rule that takes more than a warehouse has can fail halfway through and leave an order half held.
- Relying only on the timer to expire holds. A stalled timer then lets an expired hold be picked.
- Calling listeners while holding the lock. A slow buyers' system then holds up every order for that SKU.
Summary
- Store on hand and reserved, and work out available from them.
- Group the counts by SKU, so one order reads one object under one lock.
- Put the warehouse choice behind
AllocationStrategy, and check its answer before any count changes. - Reserve a whole order or nothing, and key it by order id so a retry is safe.
- Lock SKUs in name order, and call listeners only after the locks are released.
- Keep units on a truck in their own count, claim each transfer once, and write losses down.
- Write a ledger line in the same step as every on-hand change, so any count can be rebuilt.