Order Fulfillment Engine with Backorder Queue
Data Structure DesignModel answerLast updated
Process a stream of orders and restocks against live inventory, fulfilling backorders in arrival order before replenishing on-hand stock.
Order Fulfillment Engine with Backorder Queue
You are building the core of a warehouse fulfillment system for an online marketplace. The system receives a time-ordered stream of events and must track inventory in real time.
Inputs
initial_stock — a list of (sku: str, qty: int) pairs representing on-hand inventory at startup.
events — a list already sorted by timestamp. Each event is one of:
("order", order_id: str, items: list[(sku, qty)])— a customer order requesting one or more SKUs.("restock", items: list[(sku, qty)])— a warehouse replenishment adding stock.
Processing rules
On an Order event:
- For each SKU in the order, allocate as many units as currently available.
- If supply is short, fulfill what you can and record the remainder as a backorder attached to that order.
- An order for a SKU with zero on-hand inventory is fully backordered.
On a Restock event:
- Before adding anything to on-hand inventory, use the incoming stock to satisfy outstanding backorders in FIFO order (oldest order first) for each SKU.
- Only after all backorders for a SKU are cleared does surplus stock go to on-hand inventory.
- FIFO priority is per SKU: a restock of SKU
Aserves the oldest backorder waiting forA, regardless of other SKUs on that same order.
Output
Return a tuple (order_report, final_inventory):
order_report: a dict keyed byorder_id, each value containing:"items": a dict keyed by SKU with{"fulfilled": int, "backordered": int}"fully_fulfilled":Trueif no quantity remains backordered after all events
final_inventory: a dict of{sku: qty}for all SKUs, sorted by SKU
Constraints
- Up to 10⁵ events and 10⁵ distinct SKUs.
- Target time complexity: O(L + S log S) where L is total line items across all events and S is the number of distinct SKUs.
- Target space complexity: O(S + B) where B is the number of outstanding backorder lines.
- The same SKU appearing more than once in a single order should be merged.
- Non-positive quantities should be ignored.
- Order IDs are unique.
What is expected
Describe the data structures you would choose and why, implement the solution, analyze time and space complexity, and walk through at least two edge cases. As a follow-up: how would you extend the design to support order cancellation without degrading throughput?
Hints
Hint 1
For O(1) allocation per line item, you need direct SKU lookup — think about what structure gives you that, and what structure lets you drain backorders in arrival order without scanning the whole queue.
Hint 2
A heap is tempting for FIFO but it's overkill here: events are already time-ordered, so insertion order is priority order. What does that let you simplify?
Hint 3
For cancellation, deleting from the middle of a queue is O(n). Think about how garbage collection patterns like lazy deletion can let you mark an entry as void and skip it at pop time, keeping dequeue cost amortized O(1).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarifying assumptions
Before writing anything, confirm these with the interviewer:
- Events arrive pre-sorted by timestamp — no need to sort them.
- FIFO is per SKU, not per order. A restock of SKU
Adoesn't unblock SKUBon the same order. - A SKU not present at startup that appears in a restock is simply created.
- Duplicate SKU lines within one order are merged; non-positive quantities are dropped.
Data structures
Three structures carry the whole design:
on_hand: dict[str, int]— O(1) reads and writes for current stock levels.ledger: dict[str, dict[str, [int, int]]]— maps eachorder_idto a per-SKU pair[fulfilled, outstanding]. Mutable in place so restocks update it without rebuilding anything.backlog: dict[str, deque[str]]— one FIFO queue per SKU holding theorder_ids that still have outstanding demand for that SKU.dequegives O(1) append and popleft.
A heap would add unnecessary log-factor overhead. Because events are already in timestamp order, appending to a deque preserves arrival priority automatically.
Core invariants
These two invariants guarantee correctness:
- No hoarding: if
on_hand[sku] > 0thenbacklog[sku]is empty. Restocks drain the queue before touchingon_hand; orders only enqueue whenon_handhits zero. Stock is never held while a backorder waits. - FIFO integrity: each SKU queue is append-only at the tail and consumed only from the head. A partially filled head order stays at the front until its outstanding quantity reaches zero.
Together they mean every unit flows to the highest-priority destination, and no unit is double-counted.
Complexity
Let L = total (sku, qty) line items across all events.
Time:
- Each order line: O(1) lookup + possible O(1) enqueue → O(L) total.
- Each queue entry is enqueued once and popped at most once → O(L) amortized across all restocks.
- Each restock line does at most one partial fill (the head stays) plus zero or more full pops; total pops are bounded by total enqueues.
- Sorting the final inventory: O(S log S).
- Total: O(L + S log S).
Space: O(S) for on_hand, O(B) for the backlog queues where B ≤ total backorder lines, plus the ledger which the output requires regardless. Meets O(S + B).
Implementation
from collections import defaultdict, deque
def process_events(initial_stock, events):
"""
initial_stock : list[(sku: str, qty: int)]
events : list of ("order", order_id, [(sku, qty), ...])
or ("restock", [(sku, qty), ...])
already sorted by timestamp
Returns
-------
order_report : {order_id: {"items": {sku: {"fulfilled": int,
"backordered": int}},
"fully_fulfilled": bool}}
final_inventory : {sku: qty} — sorted by sku
"""
on_hand = defaultdict(int)
for sku, qty in initial_stock:
if qty > 0:
on_hand[sku] += qty
ledger = {} # order_id -> {sku: [fulfilled, outstanding]}
backlog = defaultdict(deque) # sku -> FIFO of order_ids
order_seq = [] # preserves arrival order for output
for event in events:
kind = event[0]
if kind == "order":
_, order_id, items = event
# Merge duplicate SKUs, drop non-positive quantities
requested = defaultdict(int)
for sku, qty in items:
if qty > 0:
requested[sku] += qty
lines = {}
for sku, qty in requested.items():
give = min(qty, on_hand[sku])
if give:
on_hand[sku] -= give
short = qty - give
lines[sku] = [give, short]
if short:
backlog[sku].append(order_id)
ledger[order_id] = lines
order_seq.append(order_id)
elif kind == "restock":
_, items = event
for sku, qty in items:
if qty <= 0:
continue
queue = backlog[sku]
# Drain backorders FIFO before adding to on-hand
while qty and queue:
line = ledger[queue[0]][sku] # [fulfilled, outstanding]
give = min(qty, line[1])
line[0] += give
line[1] -= give
qty -= give
if line[1] == 0:
queue.popleft()
if qty:
on_hand[sku] += qty
# Build output
report = {
order_id: {
"items": {
sku: {"fulfilled": f, "backordered": b}
for sku, (f, b) in ledger[order_id].items()
},
"fully_fulfilled": all(b == 0 for _, b in ledger[order_id].values()),
}
for order_id in order_seq
}
final_inventory = dict(sorted(on_hand.items()))
return report, final_inventory
Edge cases
- Restock with no waiting backorders: the
whileloop exits immediately and the full quantity lands inon_hand. - Restock smaller than the head backorder: the head order gets a partial fill and stays at the front; the queue is not corrupted.
- Order for an unknown SKU:
on_hand[sku]is 0, sogive = 0and the full quantity is backordered. - Empty event list: returns the initial inventory unchanged with an empty report.
- Order with zero net fulfillment: still recorded,
fully_fulfilled = False.
Extension: order cancellation in amortized O(1)
Adding a ("cancel", order_id) event without degrading throughput rules out scanning queues. The cleanest approach is lazy deletion:
- Keep a
cancelled: set[str]of voided order IDs. - On a cancel event, mark the order in the set and zero out its outstanding quantities in the ledger (so future restocks don't accidentally allocate to it).
- In the restock loop, after
popleft(), check whether the popped order is incancelledand skip it if so.
Each entry is still enqueued once and popped once, so the amortized cost remains O(1) per queue operation. The cancelled set adds O(1) lookup. No queue scanning required.
A common mistake here is trying to remove entries eagerly from the middle of the deque — that's O(n) and breaks throughput at scale.