Fresh Food Stock and Fleet Tracking Platform Design
System DesignModel answerLast updated
Design a backend that follows perishable stock across warehouses and trucks, answers nearest-and-soonest-expiring queries, prevents overselling, and raises expiry warnings.
Scenario
A national grocery retailer wants a single platform that knows where its short-shelf-life stock is (dairy, produce, chilled goods) at any moment. Stock moves between distribution centers, stores, and delivery trucks. Design the backend.
What the platform must do
- Report the current position of every stock unit in near real time.
- Capture each unit's expiry date when it is received.
- Answer: "Give me the N closest units of product X that expire within the next T hours/days."
- Notify the right people when stock approaches its expiry date.
Quality attributes
- Accepting position updates must stay highly available.
- Inventory lookups must be fast.
- Stock counts must be exact so the same unit is never sold twice.
- The system must scale to millions of tracked units and thousands of updates per second.
What to cover in your answer
- The API for reporting positions and for querying and reserving stock.
- A data model for products, items, containers, and warehouse or vehicle locations.
- Which storage you would choose for geospatial tracking versus authoritative stock state, and why.
- How you absorb a high rate of position updates without overloading your main inventory database.
- Any trade-offs, failure modes, and follow-up scaling concerns you would raise.
State your assumptions about scale before you start designing.
Hints
Hint 1
Ask who actually moves. Cartons sit in cases, cases on pallets, pallets in a zone or on a truck. If only containers and vehicles report positions, the write volume drops sharply.
Hint 2
Split data by the consistency it needs: positions can be slightly stale but must always be writable, while stock counts and reservations need strong consistency. Put a stream between ingestion and the inventory database.
Hint 3
For nearest-N queries, index the thousands of locations (warehouses, stores, vehicles) rather than millions of items, then read per-location stock buckets keyed by SKU and expiry day. For overselling, think conditional updates plus idempotency keys.
Hint 4
Expiry alerts can be driven by an index on expiry time bucketed by hour, scanned ahead of time by idempotent, partitioned workers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions
State numbers first, since they justify each component:
| Dimension | Assumption |
|---|---|
| Tracked units (case or lot level) | ~50M |
| Warehouses and stores | ~1,000 |
| Vehicles | ~20,000, GPS every 10s, so about 2K writes/s |
| Warehouse scan events | 5-10K/s average, around 5x at peak on receiving docks |
| Inventory queries | ~5K QPS, p99 under 100 ms |
| Location history | 90 days hot, 2+ years cold |
Consistency splits cleanly in two. Location is eventually consistent (seconds of lag is fine) but must always accept writes. Stock and reservations must be strongly consistent. This split drives the design.
Key insight: model location as containment. Items rarely move by themselves. An item sits in a case, the case on a pallet, the pallet in a zone or on a truck. Only containers and vehicles emit position events; items inherit location from their parent. Track at case or lot granularity (also how perishables are rotated, earliest-expiry-first). Item-level RFID would multiply write volume roughly 100x.
2. API
POST /v1/locations:batch
{ device_id, events: [{entity_id, entity_type, lat, lng | node_id, zone, ts, seq}] }
-> 202 Accepted
POST /v1/receipts
{ node_id, items: [{item_id, sku, lot_id, qty, expiry_ts, container_id}] }
-> 201 (synchronous, transactional)
GET /v1/inventory/nearby?sku=..&lat=..&lng=..&n=20&expires_within=72h
POST /v1/reservations { sku, node_id, qty, order_id, idempotency_key } -> 201 | 409
POST /v1/alert-rules { sku|category, threshold_hours, channel }
Location writes return 202 because they go to a stream. Receipts and reservations are synchronous because they change stock.
3. Data model
Inventory store (strong consistency):
Product(sku, category, shelf_life_days, temp_class)Item(item_id, sku, lot_id, qty, expiry_ts, container_id, node_id, status)with status AVAILABLE, RESERVED, EXPIRED, DISPOSEDContainer(container_id, type, parent_id, node_id)Node(node_id, type[warehouse|store|vehicle], lat, lng, geohash)Stock(sku, node_id, expiry_day, available, reserved, version): the aggregate used for fast queries and oversell protection
Current location store: key-value entity_id -> {lat, lng, node_id, zone, ts, seq} in Redis or DynamoDB, plus a geo index of vehicles and nodes.
History: append-only (entity_id, ts, lat, lng, node_id) in object storage (Parquet) or a time-series/wide-column store.
4. Architecture
Scanners / RFID / GPS -> API gateway -> Kafka (partitioned by entity_id)
-> Location processor (dedupe, last-write-wins by seq) -> current-location store
-> History sink (batched) -> object storage / time-series DB
-> Transition detector (did the node change?) -> Inventory DB
Inventory DB --CDC--> geo/query index, expiry scheduler -> alerts
The inventory database never sees raw pings. The stream processor coalesces updates and writes to the inventory DB only when an entity changes node (pallet leaves dock, enters Truck 17). Thousands of writes per second become tens.
Use sequence numbers per entity so out-of-order or replayed messages are ignored (last-write-wins by seq).
5. Deep dives
Nearest N units expiring within T
Do not geo-index 50M items. Index the ~21K nodes.
- Convert the query point to a geohash and search its cell and neighbors, widening the ring if needed. Static sites come from a precomputed index; vehicles from Redis
GEOSEARCH. - Order candidate nodes by distance. For each, do one range read on
Stockwith key(sku, node_id, expiry_day)for buckets inside the window withavailable > 0. - Accumulate until N is reached, then stop. Cache hot
(sku, geohash)results for a few seconds.
A quadtree also works; geohash is simpler to shard and store in key-value systems.
Preventing overselling
Use a conditional decrement on the stock row:
UPDATE stock
SET available = available - :q, reserved = reserved + :q, version = version + 1
WHERE sku = :sku AND node_id = :node AND expiry_day = :d AND available >= :q;
Zero rows affected means 409. Shard by node_id so a reservation touches one partition and needs no distributed transaction. Reservations carry an idempotency key and a TTL; a sweeper releases abandoned ones. On DynamoDB use a ConditionExpression.
Expiry alerts
Maintain an index on (expiry_hour_bucket, item_id). Partitioned workers with leases scan buckets ahead of time:
- Within the threshold: emit
EXPIRING_SOON. - Past expiry: mark
EXPIREDand decrement the stock aggregate.
Processing is idempotent, with a per-partition watermark so restarts neither skip nor duplicate work.
6. Trade-offs
- Granularity: case or lot tracking is cheaper; item-level tracking gives precision at much higher cost.
- Freshness vs. cost: vehicles ping every 10-30s; inside buildings use zone-level scan events rather than coordinates.
- SQL vs. NoSQL: Postgres offers easy transactions and rich queries; DynamoDB scales horizontally with little effort. Either works if sharded by node with conditional writes.
7. Failure modes and follow-ups
- Hot dock: partition the stream by
entity_id, notnode_id; batch scans at the edge (one request per pallet); coalesce to latest-per-entity per window; shard hot counters with key suffixes and sum on read. - Processor lag: location views go stale but reservations still work, because they use the inventory DB directly.
- Duplicate scans: handled by
seqand idempotency keys. - Clock skew on devices: prefer server receive time for ordering ties.
Common mistakes
- Writing every GPS ping to the primary database.
- Geo-indexing every item instead of nodes.
- Saying "use transactions" without a concrete mechanism such as a conditional update.
- Treating location and stock with the same consistency level.
- Forgetting to decrement stock when items expire.