Design a Freight Yard Platform for Dock Slots, Routes and Totes
System DesignModel answerLast updated
Design a multi-warehouse platform that books dock doors, plans and replans truck routes, and tracks containers from noisy scan events while keeping inventory consistent.
Context
A retail logistics company runs a network of warehouses and wants one platform to coordinate trucks, dock doors and containers (totes or pallets). Containers move between dock doors, staging areas and storage, and travel between facilities on trucks.
People and devices that use the system:
- Inbound trucks deliver containers to a warehouse.
- Outbound trucks collect containers for other warehouses or last-mile hubs.
- Floor operators scan containers at every physical hand-off, producing a heavy stream of events.
- Dispatchers book door time slots, plan and replan routes, and watch container status and delays.
What the platform must do
- Loads: create and manage inbound and outbound loads, each with a container list and planned arrival or departure windows.
- Dock-door scheduling: assign trucks to doors and time slots, and detect and resolve conflicts.
- Route planning: given stops with time windows, produce a feasible stop sequence, and replan on delays, cancellations or missing containers.
- Container tracking: follow each container's location (facility and zone), lifecycle status (created, staged, loaded, in transit, received) and a summary of contents.
- Inventory correctness: never double-allocate a container or its inventory, and reconcile when scans conflict or arrive late or out of order.
- APIs and UI: dispatchers see routes, the door schedule and container status; operators submit scans.
Assumptions you may start from (change them and say so)
- Tens to low hundreds of facilities, thousands of dock doors in total.
- Hundreds to low thousands of scan events per second at peak, bursty per facility.
- A route usually has up to about 15 stops, with many routes active at once.
- Scan-to-visible latency in seconds; door-booking confirmation must be synchronous.
- Networks can partition. Scanners buffer and replay, and a facility must keep scanning and serving last-known state while cut off.
- Door scheduling and scan ingest target 99.9%+ availability; global analytics may be eventually consistent.
- Multiple warehouses with role-based access (dispatcher, dock operator, viewer).
What to deliver
- A high-level architecture: services, data stores, messaging.
- A core data model.
- Key APIs and events.
- A consistency strategy: idempotency, ordering, deduplication.
- A routing approach: exact or heuristic, and which objective you optimize.
- An observability and failure-handling plan.
You may ask clarifying questions (for example whether an external transport system owns dispatch and ETAs, or whether another system owns SKU-level contents), but keep that pass short and spend most of your time on depth.
Hints
Hint 1
Spend a minute scoping: state an MVP and what is out of scope, then go deep on the hard parts (event correctness, door booking, routing) rather than reciting generic requirements.
Hint 2
Treat scans as an append-only event log keyed by a unique event ID and a per-container sequence or version, and derive current container state from it. Decide what to do with events that do not fit the current state.
Hint 3
For doors, prevent overlapping reservations with a transactional check per door (or per facility partition) so the consistency boundary is small. For routes, recognize a vehicle routing problem with time windows and choose a heuristic with local repair for replanning.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions (brief)
MVP: load management, synchronous dock-door booking, container state tracking from scans, a routing service that returns a feasible, good sequence, and dispatcher/operator APIs.
Out of scope or integrated:
- Driver tendering and live traffic ETAs come from an external transport system.
- SKU-level contents and order allocation belong to the warehouse/order system. We store a contents summary plus a reference, not the full detail.
- We own physical container location and state, and we enforce that a container is committed to only one load at a time.
Primary routing objective: on-time delivery within windows first, then minimize total travel time. Hard constraints are time windows and container capacity. I would confirm this with the interviewer in one question.
2. Architecture
- Load Service: loads, container manifests, planned windows. Relational store.
- Dock Scheduler: door reservations. Strongly consistent, partitioned by facility.
- Scan Ingest: a thin, highly available HTTP/gRPC endpoint that validates the device and writes to a log (Kafka or similar), partitioned by
container_id. It acknowledges only after durable append. - Container State Processor: stream consumers that apply events to a per-container state store and publish state-change events.
- Routing Service: stateless solver workers fed by a job queue.
- Read/Query layer: materialized views (door board, route view, container status) in a read-optimized store with a cache, plus push updates (WebSocket or SSE) to dispatcher screens.
- Edge component per facility: a local buffer and cache so scanning and last-known state continue during a partition.
Sync vs async: door booking and load creation are synchronous (the dispatcher needs an answer). Scans, state projection, notifications and replan triggers are asynchronous via the log.
3. Data model (core)
Facility(id, zones…),DockDoor(id, facility_id, capabilities)Load(id, direction, origin, destination, window_start, window_end, status)Container(id, type, current_facility, current_zone, status, version, contents_summary, contents_ref, load_id NULL)DoorReservation(id, door_id, load_id, start, end, status)Route(id, vehicle_id, status)andRouteStop(route_id, seq, facility_id, window, eta)ScanEvent(event_id, container_id, device_id, type, device_ts, server_ts, facility, zone, seq/version)– append-only, the source for history and audits.
Current container state is a projection of its events; history is never overwritten.
4. Key APIs and events
POST /loads,POST /loads/{id}/containersPOST /doors/{id}/reservations(synchronous; returns 409 with alternative slots on conflict)POST /routes:plan,POST /routes/{id}:replanPOST /scans(batch accepted, as devices replay buffers)GET /containers/{id},GET /facilities/{id}/door-schedule- Events:
ContainerScanned,ContainerStateChanged,ReservationConfirmed,RouteReplanned,DiscrepancyRaised.
5. Consistency strategy
Idempotency and dedup: each scan carries a unique event_id (device ID + monotonic counter, synthesized if the device lacks one). The processor stores a dedup key (unique constraint or short-TTL set); replays are no-ops.
Ordering: partitioning by container_id gives per-container order in the log, but device clocks and replays break real-world order. So the state machine uses the event's logical sequence and device timestamp, not arrival order. The processor applies:
- Valid transition: apply it.
- Late but older than current state: store in history, do not regress state.
- Impossible transition (e.g. "received" before "loaded"): park it in a short holding buffer for a bounded time in case the missing event arrives, then raise a
Discrepancyfor human or automated reconciliation.
No double allocation: assigning a container to a load is a conditional write (UPDATE … SET load_id = ? WHERE id = ? AND load_id IS NULL, or compare-and-set on version). Concurrent attempts see exactly one winner.
Reconciliation: physical scans are the evidence of truth. If a scan places a container somewhere the system does not expect, record the scan, flag the discrepancy, and trigger a cycle count or manifest correction rather than silently overwriting.
6. Dock scheduling correctness
The invariant is "no two active reservations overlap on the same door." Keep reservations for a door in one partition and enforce it in one transaction:
- In a relational store with range support, use an exclusion constraint on
(door_id, time_range), or lock the door row and check overlap before insert. - Otherwise use slot-granular rows (e.g. 15-minute slots) with a unique key
(door_id, slot)inserted atomically.
On conflict, return the nearest free slots on compatible doors. Rebooking after a truck delay is a transaction that releases the old slot and takes a new one. Add a hold timeout so abandoned tentative bookings expire. Because the consistency boundary is a single door, throughput scales by facility and contention stays low.
7. Routing
This is a vehicle routing problem with time windows (VRPTW), NP-hard, but a route has ≤ ~15 stops.
- For a single route with ≤ ~12–15 stops, exact methods (DP over subsets, or a MIP/CP-SAT solver) are feasible within seconds.
- For multi-truck assignment across many loads, use a heuristic: constructive insertion followed by local search (2-opt, relocate, swap) or a solver library such as OR-Tools, with a time budget.
- Travel times come from a cached matrix (external service), with dock service times added.
Replanning: do not resolve from scratch on every event. On a delay or cancellation, mark affected stops, then run local repair (reinsert or reorder only impacted stops), warm-started from the current plan. Penalize churn so drivers and dock bookings are not reshuffled needlessly. Trigger a full resolve only if repair fails feasibility. If a replan moves an arrival, it must also re-request the door slot, and that can fail, so surface it to the dispatcher.
8. Scale and availability
At ~2k events/s, one partitioned log handles this easily; partition by container_id (or facility+container) for parallel consumers. Read models are denormalized per query, cached, and updated by the projector. During a partition, the edge component accepts scans, keeps local state, and replays on reconnect; dedup and sequencing make replay safe. Door booking during a partition is limited to that facility's own authoritative partition, so local bookings still work.
9. Observability and failure modes
Metrics: scan-to-visible latency (p50/p99), consumer lag, dedup rate, discrepancy count and age, reservation conflict rate, solver latency and infeasible rate, replan frequency, edge buffer depth.
| Failure | Mitigation |
|---|---|
| Consumer lag after a burst | Autoscale consumers, alert on lag, backpressure at ingest |
| Duplicate or replayed scans | Event-ID dedup |
| Clock skew on devices | Logical sequence, server timestamp as tiebreaker |
| Poison event | Dead-letter queue with alerting |
| Solver timeout | Return best-so-far or the previous feasible plan |
| Lost door booking on failover | Synchronous replication for the reservation store |
Common mistakes
- Spending most of the time on generic functional/non-functional lists instead of the hard problems.
- Trusting arrival order and overwriting state with late events.
- Putting the door-overlap check in application code without a transactional guarantee.
- Claiming an exact solver for the whole network, or fully re-optimizing on every delay.
- Storing full SKU contents here when another system owns them.