Multi-Warehouse Container Tracking, Dock Scheduling, and Fleet Routing

Medium · System Design · Software Engineer · Technical Screen

Prompt

Design the backend platform for a multi-warehouse e-commerce logistics and fulfillment network that coordinates inter-facility trailer routes, dock-door appointments, and physical container movement inside and across warehouses.

Here, a container (pallet or tote) holds merchandise and moves physically across dock bays, staging zones, and storage racks:

  • Inbound trailers deliver containers into a warehouse, while outbound trailers pick up containers bound for peer warehouses or last-mile sort hubs.
  • Floor associates scan container barcodes at every physical handoff, producing a high-rate, bursty event stream.
  • Dispatchers reserve dock-door time windows, compute and adjust multi-stop truck routes, and monitor container progress and schedule exceptions.

Functional requirements:

  1. Trailer loads: Create and track inbound and outbound loads, each carrying a container manifest and planned arrival/departure windows.
  2. Dock appointment scheduling: Assign trailers to compatible dock doors and time intervals while preventing or resolving overlapping bookings.
  3. Route planning and dynamic re-planning: Given facility stops with arrival windows, compute a feasible stop sequence and re-plan cleanly when field conditions shift (traffic delays, cancelled loads, missing containers).
  4. End-to-end container tracking: Track every container's active facility and floor zone, its summary of carried items, and its current lifecycle stage (created, staged, loaded, in-transit, received).
  5. Allocation and state integrity: Prevent any container from being double-assigned across active outbound loads, and reconcile conflicting, delayed, or out-of-order barcode scans.
  6. Operator and dispatcher interfaces: Expose APIs and live operational views for barcode scan submission, dock calendars, route schedules, and container statuses.

Illustrative floor edge cases:

Suppose at warehouse wh-dal2, pallet plt-18 has a PUTAWAY scan buffered offline on handheld hh-dal-04 at 09:40 that uploads after its 10:02 STAGE scan and 10:08 LOAD scan onto trailer trl-510 at bay-07: replaying that late 09:40 scan must not roll plt-18 backward off trl-510, and if a second associate at bay-08 scans plt-18 onto trl-511 in the same second, the double-assignment must be blocked immediately.

Scale & operational assumptions (state explicit boundaries where unspecified):

  • Footprint & event volume: Dozens to a couple hundred warehouses and several thousand dock doors overall, peaking at several hundred to a few thousand barcode scans per second across all hubs (with sharp per-warehouse surges).
  • Route size: Each truck trip covers just a handful of stops (typically 2 to ~15), while hundreds of trips run in parallel network-wide.
  • Latency: Floor scans show up on tracking dashboards within a few seconds, whereas booking a dock slot returns a synchronous confirmation to the dispatcher.
  • Offline resilience & availability: WAN partitions occur; handhelds buffer and replay scans, and an isolated warehouse must continue scanning and operating locally (~99.9%+ availability for scan ingest and dock scheduling, while global analytics views may be eventually consistent).
  • Access control: Multi-warehouse role-based permissions covering dispatchers, floor operators, and read-only viewers.

Scope & Expectations

  • Clarify system ownership boundaries (external carrier/TMS and SKU-level WMS integrations), decompose the platform into cleanly decoupled services, and choose appropriate data stores and messaging channels.
  • Define core schemas, APIs, and consistency mechanisms for idempotent scan deduplication, out-of-order replay reconciliation, race-free container allocation, and conflict-free dock reservations.
  • Justify your stop-sequencing optimization approach (exact versus heuristic trade-offs and primary business objective) and how in-flight routes re-plan safely during disruptions.
  • Detail how a warehouse continues operating during WAN partitions, alongside staleness observability and failure recovery.

Step-by-step walkthrough

  1. Clarify requirements, decompose the system, and scope an MVP

    A multi-warehouse logistics platform looks sprawling until we settle the core ownership questions up front and draw crisp boundaries around what our services own:

    • Carrier dispatch & live traffic: An external TMS (Transportation Management System) manages carrier contracts, driver assignments, HOS (Hours of Service) legal driving limits, and live GPS/ETA telemetry. Our platform owns transport planning: which containers ride which trailer load, dock-door appointments, and stop sequencing. Travel-time matrices come from a commercial routing/traffic provider with historical time-of-day curves as a fallback.
    • Container contents vs. SKU inventory: An existing WMS (Warehouse Management System) owns item-level SKU balances and customer order allocation. Our platform tracks physical containers (totes and pallets), storing a compact summary (sku_count, unit_count, weight_kg, volume_m3, hazmat, temp_class) plus a wms_ref pointer. Preventing double-allocation here means guaranteeing one physical container is never assigned to two active outbound loads simultaneously (extending to SKU-level reservation is covered in the follow-ups).
    • Scanner behavior: Operators carry rugged Wi-Fi handhelds with local flash storage. Every scan generates a client-side UUID (event_id) and a monotonically increasing per-device counter (device_seq). Device clocks sync via NTP when online and drift slightly while offline.
    • Single primary routing objective: Maximize on-time arrival within dock appointment windows first, then minimize total drive time (fuel/labor cost), then minimize truck count—subject to hard trailer capacity, driver HOS, pickup-before-drop order, and dock compatibility (e.g., refrigerated doors).
    • Target scale: 150 warehouses and ~6,000 dock doors today (~2,000 peak scans/s network-wide), engineered for 3x growth over 3 years; scan-to-dashboard p99 < 5 s; >= 99.9% availability for scanning and dock booking; local facility survival during cloud network partitions.

    Architectural decomposition (two subsystems, different physics):

    Subsystem A: Container & Inventory Tracking
      - Workload : Write-heavy, bursty scan stream; offline replays, duplicates, out-of-order clocks
      - Pattern  : Append-only event log + deterministic state fold (eventual read views, strict audit)
    
    Subsystem B: Transport Planning & Execution
      - B1 Dock & Load Allocation : Low write QPS, zero tolerance for double-booking -> ACID SQL constraints
      - B2 Vehicle Route Planner  : CPU-heavy optimization -> stateless workers writing immutable plans
    

    Keeping Subsystem A and Subsystem B decoupled via asynchronous events guarantees a heavy route-optimization burst never slows barcode scanning, and an offline scan replay never blocks a dispatcher booking a dock door.

    MVP scope: (1) Inbound/outbound load creation and single-active container allocation, (2) conflict-free dock-door reservations, (3) event-sourced scan ingestion with container state projection, and (4) exact single-truck stop sequencing with time windows. Regional multi-truck load consolidation and predictive ETA re-planning follow in Phase 2.

  2. Back-of-the-envelope capacity planning

    Network footprint       150 facilities x ~40 dock doors/facility  = 6,000 dock doors
    Daily truck loads       6,000 doors x ~8 turns/day                = 48,000 loads/day
    Container legs/day      48,000 loads x ~50 pallets/totes per load = 2.4 million container legs/day
    Scan throughput         2.4M legs x ~10 scans/leg                 = 24 million scans/day
                            24M / 86,400 s = ~280 scans/s average     -> ~2,000 scans/s peak (~200/s in 1 hub)
    Scan bandwidth & disk   2,000/s x 500 B = 1 MB/s peak ingress;  12 GB/day (~4.4 TB/year raw)
    
    Active working set      2.4M legs/day x ~3 days in transit x 1 KB = ~7.2 GB active container state
    Dock & load writes      48,000 reservations/day + edits           = ~2-20 writes/s (tiny!)
    Route optimization      ~10,000 multi-stop routes/day x 5 replans = ~50,000 solves/day (~1-10 solves/s)
    Single-route size       k <= 15 stops: 16 x 16 travel matrix (256 floats)
                            Exact DP states = k x 2^(k-1) = 15 x 2^14 = 245,760 states (~1.72M transitions)
    Offline partition       1 hub @ 200 scans/s x 3,600 s (1 hour)    = 720,000 buffered scans (~360 MB)
    

    Three crucial insights jump out from this math:

    1. Raw data volume is modest (1 MB/s peak, 7.2 GB active state). A single Kafka cluster and a primary-standby PostgreSQL setup easily handle the byte rate; the real engineering challenge is correctness under duplicates, out-of-order replays, and concurrent operator scans.
    2. One truck's route (<= 15 stops) has only 245,760 dynamic-programming states—small enough to solve provably optimally in under half a second! Only regional multi-truck consolidation (assigning hundreds of loads across dozens of trucks) requires heuristics.
    3. One hour of hub disconnection is just 360 MB—small enough for two local edge servers in each warehouse to buffer on SSD and keep local floor operations running smoothly.
  3. APIs and event streams

    1. Operator Handheld API (via Facility Edge Gateway)

    POST /v1/scans:batch
    {
      "device_id": "hh-dal-04",
      "device_clock_ms_at_send": 1764518400120,
      "events": [
        {
          "event_id": "7a3c9100-e29b-41d4-a716-446655440018",   # UUID generated on device at scan moment
          "device_seq": 18405,
          "container_id": "plt-4092",
          "scan_type": "LOAD",      # RECEIVE | PUTAWAY | STAGE | LOAD | UNLOAD | AUDIT
          "facility_id": "wh-dal2",
          "zone_id": "bay-07",
          "load_id": "trl-510",
          "device_time_ms": 1764518399800,
          "operator_id": "op-419"
        }
      ]
    }
    -> 200 OK:
    {
      "results": [
        {"event_id": "7a3c9100...", "status": "ACCEPTED", "verdict": "OK", "message": "Loaded onto trl-510"}
      ]
    }
    
    • Every batch is idempotent on event_id (DUPLICATE returns the prior verdict without re-applying). verdict (OK | WARN | STOP) drives an instant green chime or red buzzer on the operator's scanner. (DEPART events are generated automatically for every loaded container when a sealed trailer leaves the gate.)

    2. Dispatcher & Planning APIs (HTTPS + Role-Based Facility Scopes)

    POST   /v1/loads                         Create inbound/outbound load with window & capacity
    POST   /v1/loads/{id}/allocations        Claim {container_ids} -> per-container OK | CONFLICT(other_load)
    POST   /v1/loads/{id}:seal               Verify manifest == physical LOADED state; block if exceptions open
    POST   /v1/door-reservations             {facility_id, door_id?, attrs, slot, load_id, idempotency_key}
                                             -> 201 Created | 409 Conflict {conflicts, suggested_slots}
    PATCH  /v1/door-reservations/{id}        Move/extend appointment using optimistic concurrency (If-Match)
    POST   /v1/routes/{id}/plans             Trigger route solve ({trigger, time_budget_ms}) -> 202 {version}
    POST   /v1/routes/{id}/plans/{v}:activate  Atomically swap active plan if If-Match version still current
    GET    /v1/containers/{id}               Current state, location, active load, scan history, as_of watermark
    WS     /v1/facilities/{f}/live           Real-time push of container, door, route & watermark updates
    

    3. Asynchronous Event Bus (Kafka topics partitioned to preserve entity order) - scan.raw & container.state_changed & allocation.changed (partition key: container_id) - load.changed (key: load_id), door.reservation_changed & exception.changed (key: facility_id) - route.plan_activated & eta.updated (key: route_id, bridged to external TMS).

  4. Data model and container state machine

    We use Event Sourcing (storing an immutable append-only log of scan events as the single source of truth and deriving current container state from it) paired with CQRS—Command Query Responsibility Segregation (separating strongly consistent write tables from fast, eventually consistent read dashboards):

    1. Tracking & Allocation Store (PostgreSQL):
       scan_event       (event_id, container_id, device_id, device_seq, scan_type, facility_id, zone_id,
                         load_id, device_time, corrected_time, received_at) -- Append-only, monthly partitions
       seen_event       (event_id PK, received_at)                          -- 30-day deduplication table
       container        (container_id PK, kind [TOTE|PALLET], wms_ref, contents_summary_json)
       container_state  (container_id PK, status, facility_id, zone_id, load_id,
                         last_order_key, state_version, flags)              -- Materialized projection!
       allocation       (allocation_id PK, container_id, load_id, status [ACTIVE|RELEASED], claimed_at)
                        -- Partial unique index: UNIQUE (container_id) WHERE status = 'ACTIVE'
       load             (load_id PK, facility_id, direction, window, capacity, used_positions, status, version)
       exception        (exception_id PK, kind, facility_id, container_id, load_id, status, evidence_json)
    
    2. Dock & Route Planning Store (PostgreSQL):
       door             (door_id PK, facility_id, kind [IN|OUT|BOTH], attrs_json)
       door_reservation (res_id PK, door_id, load_id, slot tstzrange, status [HELD|CONFIRMED|RELEASED],
                         hold_expires_at, version)  -- GiST exclusion constraint prevents overlapping slots!
       route            (route_id PK, carrier_ref, active_plan_version)
       route_plan       ((route_id, version) PK, based_on_versions_json, objective_json,
                         status [PROPOSED|ACTIVE|SUPERSEDED], stops_json)   -- Immutable, never edited!
    

    Expected container lifecycle transitions:

    CREATED ---> STAGED ---> LOADED ---> IN_TRANSIT ---> RECEIVED ---> STORED ---> STAGED ---> ...
                   ^           |                            |                        ^
                   +-(UNLOAD)--+                            +-----(cross-dock)-------+
    (AUDIT updates facility_id + zone_id without changing lifecycle status)
    

    Notice two strict separations: (1) Plan vs. physical truth—route_plan versions record what should happen, while scan_event records what physically happened; the route planner never writes container_state. (2) Log vs. projection—if a software bug ever corrupts container_state, we can recompute it cleanly from scan_event.

  5. High-level architecture

     WAREHOUSE FACILITY (x150)                     CLOUD REGION (3 Availability Zones)
    +--------------------------------+            +----------------------------------------------------+
    | Handheld Scanners              |            | API Gateway (OIDC Auth + Facility-Scoped RBAC)     |
    | - Generate UUID + device_seq   |            |                                                    |
    | - Local retry buffer           |            | Scan Ingest ---> Kafka: scan.raw (48 partitions,   |
    |              | Wi-Fi           |            |                    |    keyed by container_id)     |
    |              v                 |  batches   |                    v                               |
    | Facility Edge Pair (2 nodes)   |----------->| Tracking Workers (1 consumer per container_id):    |
    | - Mirrored SSD scan log        |            | - Dedup, clock-correct, deterministic fold         |
    | - 48h cache: loads, doors,     |<-----------| - Write Postgres (scan_event, state, outbox)       |
    |   on-site containers           |  streams + |                                                    |
    | - Lease-guarded offline mode   |  30s lease | Allocation & Load Service (ACID Postgres unique)   |
    +--------------------------------+            | Dock Scheduling Service   (ACID GiST exclusion)    |
                                                  | Route Planner API + Stateless Solver Worker Pool   |
     Dispatcher Web UI (HTTPS + WS) ------------->| Exception Workflow Service                         |
     External TMS (GPS/ETAs/HOS) <--------------->| CQRS Read Models (Facility Boards, Search, OLAP)   |
     External WMS (SKU summaries) --------------->+----------------------------------------------------+
    
  6. Deep dive 1: Scan correctness under duplicates, disorder, and concurrency

    Offline scanners, retries, and drifting device clocks create three distinct failure modes. Each requires its own independent mechanism:

    1. Duplicate scans -> Atomic deduplication on event_id. Never deduplicate by (container_id, timestamp): an operator can legitimately scan STAGE and LOAD in the same second, while a network retry might stamp a fresh send time. Instead, the scanner mints a UUID event_id at the moment the trigger is pulled. Inside one SQL transaction, the Tracking Worker runs: INSERT INTO seen_event (event_id, received_at) VALUES (:id, now()) ON CONFLICT DO NOTHING If 0 rows are inserted, the event was already processed and we skip straight to returning the stored verdict; otherwise we insert into scan_event, update container_state, and write an outbox event atomically.

    2. Out-of-order arrivals & clock drift -> Clock offset clamping + deterministic fold. When a handheld uploads a batch, the NTP-synced Edge Gateway measures offset = edge_now - device_clock_ms_at_send and computes corrected_time = device_time_ms + offset, clamped so timestamps never move backward across increasing device_seq on the same scanner. Even with Kafka partitioned by container_id, Scanner A returning from a 20-minute dead zone will deliver its 10:00 AM scans after Scanner B's 10:15 AM scans. Therefore, container_state is defined as a deterministic fold over all of that container's scans sorted by (corrected_time, device_id, device_seq):

    NEXT_STATUS = {
        "RECEIVE": "RECEIVED",
        "PUTAWAY": "STORED",
        "STAGE": "STAGED",
        "LOAD": "LOADED",
        "DEPART": "IN_TRANSIT",
        "UNLOAD": "STAGED",
    }
    
    EXPECTED_PREV_STATUSES = {
        "RECEIVE": {"CREATED", "IN_TRANSIT"},
        "PUTAWAY": {"RECEIVED", "STAGED"},
        "STAGE": {"CREATED", "RECEIVED", "STORED"},
        "LOAD": {"STAGED"},
        "DEPART": {"LOADED"},
        "UNLOAD": {"LOADED"},
    }
    
    
    def scan_sort_key(event):
        """Total chronological order across devices, preserving exact per-device sequence."""
        return (event["corrected_time"], event["device_id"], event["device_seq"])
    
    
    def fold_container_events(events):
        """Recompute a container's state from its scans regardless of network arrival order."""
        state = {
            "status": "CREATED",
            "facility_id": None,
            "zone_id": None,
            "load_id": None,
            "missing_step_gaps": [],
        }
    
        for event in sorted(events, key=scan_sort_key):
            scan_type = event["scan_type"]
            # Location audit updates physical position without altering lifecycle status.
            if scan_type == "AUDIT":
                state["facility_id"] = event["facility_id"]
                state["zone_id"] = event["zone_id"]
                continue
    
            # Record skipped transitions rather than dropping physical scan evidence.
            if state["status"] not in EXPECTED_PREV_STATUSES[scan_type]:
                gap = (state["status"], scan_type, event["event_id"])
                state["missing_step_gaps"].append(gap)
    
            state["status"] = NEXT_STATUS[scan_type]
            state["facility_id"] = event["facility_id"]
            state["zone_id"] = event["zone_id"]
    
            # Keep load_id while on a trailer (LOADED / IN_TRANSIT); clear it on the warehouse floor.
            if scan_type in ("LOAD", "DEPART"):
                state["load_id"] = event["load_id"]
            else:
                state["load_id"] = None
    
        return state
    
    • Fast path vs. late path: When an incoming event sorts after container_state.last_order_key (~98% of scans), we advance state in O(1) without reading old history. Only when scan_sort_key(event) < last_order_key do we read that container's 10–50 historical rows via (container_id, corrected_time) and re-run fold_container_events—healing any temporary missing_step_gaps automatically once an offline scanner uploads the missing intermediate step!

    3. Concurrent writes -> Partition serialization + optimistic version guard. Routing scan.raw by container_id assigns one consumer thread per container, and UPDATE container_state ... WHERE state_version = :v guards against consumer rebalancing races.

    What happens when a scan violates expected state? (Never drop, never blindly ignore): - Plausible skipped scan (e.g., RECEIVE at Hub B when last state was LOADED at Hub A because DEPART is delayed): Apply RECEIVED at Hub B (a physical barcode scan proves the tote is standing in Hub B!) and flag INFERRED_STEPS for a 2-minute grace window in case the delayed scan arrives. - Physical impossibility (scanned in Dallas and Memphis 4 minutes apart): Keep both events, flag NEEDS_REVIEW, freeze allocation changes, and alert an inventory lead (usually a duplicated barcode label). - Wrong-truck load (LOAD onto trl-511 while allocated to trl-510): Record the physical LOADED state, beep red STOP on the handheld immediately, open an exception on trl-511, and block sealing trl-511 until an UNLOAD scan removes the container or a dispatcher reassigns it.

  7. Deep dive 2: Race-free container allocation and dock-door scheduling

    Unlike high-volume scan tracking, container allocation (~30 claims/s) and dock scheduling (~2–20 writes/s) are low-rate decisions where strong ACID consistency eliminates race conditions completely.

    1. Preventing container double-allocation with a partial unique index: Application-side "SELECT if free, then INSERT" fails whenever two operators scan the same pallet in the same millisecond. Instead, we enforce uniqueness inside PostgreSQL using a partial unique index (a uniqueness rule enforced only on rows matching a WHERE filter—here, status = 'ACTIVE'):

    CREATE UNIQUE INDEX uniq_active_container_allocation
        ON allocation (container_id)
        WHERE status = 'ACTIVE';
    
    -- Atomic claim inside one READ COMMITTED transaction:
    BEGIN;
    SAVEPOINT claim_attempt;
    
    -- Step 1: Lock the load row and verify capacity before claiming the container.
    UPDATE load
       SET used_positions = used_positions + 1
     WHERE load_id = :target_load
       AND status IN ('PLANNED', 'LOADING')
       AND used_positions < capacity;
    -- (If 0 rows updated -> ROLLBACK; return LOAD_FULL_OR_CLOSED)
    
    -- Step 2: Claim the container; concurrent claims on the same container serialize on the index.
    INSERT INTO allocation (container_id, load_id, status, claimed_at)
    VALUES (:container_id, :target_load, 'ACTIVE', now())
    ON CONFLICT (container_id) WHERE status = 'ACTIVE' DO NOTHING;
    
    -- If 0 rows inserted, undo Step 1's capacity increment via the savepoint and inspect the winner:
    -- ROLLBACK TO SAVEPOINT claim_attempt;
    -- SELECT load_id FROM allocation WHERE container_id = :container_id AND status = 'ACTIVE';
    --   -> same :target_load : return OK (idempotent retry!)
    --   -> other load_id     : return CONFLICT(other_load) so scanner beeps red STOP!
    COMMIT;
    

    (When transferring a container from L1 to L2, lock the two load rows in sorted load_id order first so concurrent cross-transfers L1 -> L2 and L2 -> L1 can never deadlock.) Before any outbound trailer can :seal and depart, the Load Service waits until the facility's scan watermark passes seal time and verifies a two-way set match: every container ACTIVE-allocated to L has container_state.status = 'LOADED' on L, every container physically LOADED on L is ACTIVE-allocated to L, and zero exceptions remain open.

    2. Preventing overlapping dock-door appointments with an exclusion constraint: A dock reservation is a time interval slot (including a 15-minute yard turnover buffer) on door_id. PostgreSQL's GiST exclusion constraint enforces at the storage engine level that no two non-released intervals on the same door can ever overlap—even by one second under concurrent requests:

    CREATE EXTENSION IF NOT EXISTS btree_gist;
    
    ALTER TABLE door_reservation
      ADD CONSTRAINT no_overlapping_door_slots
      EXCLUDE USING gist (door_id WITH =, slot WITH &&)
      WHERE (status <> 'RELEASED');
    

    When a dispatcher requests "any compatible refrigerated door at Dallas (wh-dal2) between 14:00 and 15:30", the service queries compatible doors ordered by tightest gap after the prior appointment, tries INSERT under a savepoint across the ~40 doors in Dallas, and returns 201 Created on the first open door—or 409 Conflict with nearest alternative time slots. Multi-stop route activations place 2-minute HELD reservations across facilities first, then flip them to CONFIRMED once the route plan activates. Live eta.updated delays that push a truck into the next appointment raise a predicted conflict early so dispatchers (or auto-reassignment policy) can move the truck to a free door before it arrives.

  8. Deep dive 3: Vehicle route optimization and versioned re-planning

    Finding stop orders under arrival windows, trailer capacity, and a travel-time matrix is the VRPTW (Vehicle Routing Problem with Time Windows). Because general VRPTW is NP-hard, we split optimization by scale:

    1. Single-truck sequencing (k <= 15 stops): Exact Held-Karp Dynamic Programming. Why is an exact DP both fast and valid here? When a truck arrives before a dock's window_open, it simply waits in the yard until window_open. Because max(depart + travel, window_open) + service never decreases when depart increases, finishing a subset of stops earlier can never make a future window infeasible or delay the final finish time. Thus, for each (visited_bitmask, last_stop) pair, we only need to store the single earliest departure time (15 × 2^14 = 245,760 reachable states for 15 stops—under 0.5 seconds in Python and < 10 ms in C++/Rust):

    def optimal_stop_sequence(travel_mins, service_mins, windows, start_time):
        """Find the exact feasible stop order (1..n-1) from stop 0 that finishes earliest."""
        num_nodes = len(travel_mins)
        if num_nodes <= 1:
            return start_time, []
    
        all_visited_mask = (1 << num_nodes) - 1
        # dp[(visited_mask, current_stop)] = (earliest_departure_time, previous_stop)
        current_layer = {(1, 0): (start_time, None)}
        parent_trace = dict(current_layer)
    
        # Expand layer by layer so we only visit reachable (visited_mask, last_stop) states.
        for _step in range(1, num_nodes):
            next_layer = {}
            for (visited_mask, last_stop), (depart_time, _prev) in current_layer.items():
                for next_stop in range(1, num_nodes):
                    if visited_mask & (1 << next_stop):
                        continue
                    earliest_open, latest_close = windows[next_stop]
                    arrival_time = max(depart_time + travel_mins[last_stop][next_stop], earliest_open)
                    # Hard time-window constraint: arriving after latest_close is infeasible.
                    if arrival_time > latest_close:
                        continue
    
                    leave_time = arrival_time + service_mins[next_stop]
                    next_state = (visited_mask | (1 << next_stop), next_stop)
                    if next_state not in next_layer or leave_time < next_layer[next_state][0]:
                        next_layer[next_state] = (leave_time, last_stop)
    
            if not next_layer:
                return None  # No feasible route satisfies all dock windows
            parent_trace.update(next_layer)
            current_layer = next_layer
    
        # Pick the final stop with the earliest overall completion time.
        best_finish, best_last = min(
            (depart_time, stop) for (_mask, stop), (depart_time, _prev) in current_layer.items()
        )
    
        # Reconstruct stop order backwards from best_last to stop 0.
        route_order = []
        mask, curr = all_visited_mask, best_last
        while curr != 0:
            route_order.append(curr)
            prev_stop = parent_trace[(mask, curr)][1]
            mask ^= 1 << curr
            curr = prev_stop
        route_order.reverse()
        return best_finish, route_order
    

    (Pickup-before-drop rules add a 1-line bitmask check; if we also want to minimize driving fuel when trucks wait at early windows, each state stores a small list of Pareto-optimal (departure_time, drive_mins) pairs.)

    2. Regional multi-truck consolidation: Anytime heuristics. Assigning 500 loads across 80 trucks uses cheapest insertion followed by Large Neighborhood Search (LNS) (repeatedly removing 10–20% of stops and re-inserting them in lower-cost slots) inside a fixed 10-second time budget, always keeping the best feasible solution found so far.

    3. Safe re-planning without floor churn: - Coalesce & freeze: Disruptions within 30 seconds on one route merge into one solve. Completed stops, the next immediate stop en route, containers physically LOADED on the trailer, and dock slots starting within 2 hours (unless directly conflicted) are frozen; remaining stops optimize with a stability penalty per changed dock or stop order. - Optimistic saga activation: route_plan (route_id, v+1) records its input versions and activates via a small saga (a multi-step workflow with clean rollback compensations): hold new dock slots -> atomically set active_plan_version = v+1 (If-Match: v) -> confirm new dock slots -> release old slots -> notify TMS.

  9. Deep dive 4: Keeping facilities operating through network partitions

    Each warehouse runs a redundant 2-node Edge Gateway over local Wi-Fi. When a backhoe cuts a warehouse's internet fiber, operators must keep scanning and loading trailers without splitting brain with cloud dispatchers.

    We prevent split-brain container allocation using a time-bounded lease (a temporary authority ticket renewed every 10 seconds that expires automatically if heartbeats stop):

    Normal operation: Edge renews lease every 10 s; Cloud grants lease valid for 30 s.
    
    Fiber cut at t = 0:
      t = 0..30 s  : Cloud still considers Edge online; Edge fails synchronous cloud calls.
      t = 30 s     : Cloud lease expires! Cloud immediately REFUSES remote allocation edits for
                     containers at Facility F (dispatchers see "Facility offline - edits queued").
      t = 45 s     : Edge waits 30 s + 15 s clock-rate safety margin after its last received reply,
                     then enters LOCAL AUTHORITY MODE: confirms local container allocations on its
                     mirrored SSD using the exact same partial-unique-index rule!
    

    Because 45 s > 30 s (plus clock-drift margin), Cloud and Edge are never simultaneously authoritative for Facility F's containers—even for a single millisecond! Meanwhile, dock-door scheduling stays cloud-authoritative (since remote dispatchers book doors across facilities) while the warehouse gate works off its cached 48-hour schedule and reconciles emergency yard overrides as exceptions upon reconnect. When fiber heals, the Edge drains its buffered scans and local allocations in a rate-limited background lane before handing lease authority back to the Cloud.

  10. Scaling, failure handling, and observability

    Scaling bottlenecks & evolution to 3x load: - Kafka & Tracking DB: 48 partitions on scan.raw give 48-way parallel fold processing. At 6,000 scans/s (3x growth), shard scan_event, seen_event, and container_state across PostgreSQL instances by hash(container_id) (each container's fold stays single-shard!), while keeping allocation and load together on one dedicated unsharded primary (~90 claims/s at 3x) so cross-table load-capacity + container-claim transactions stay single-node. Partition scan_event monthly and archive > 90-day partitions to columnar S3 storage. - CQRS read projections: Facility boards and search indexes consume outbox events asynchronously and display an explicit as_of freshness watermark per facility.

    Failure modes & observability: - Consumer or DB failover: Kafka commits offsets after SQL transactions commit (event_id deduplication makes replays no-ops); PostgreSQL fails over to a synchronous cross-AZ standby in < 30–60 s while warehouse edges buffer seamlessly. - Solver crash or infeasibility: Existing ACTIVE route plan stays untouched; infeasible windows return a diagnostic conflict report for human dispatchers. - Key metrics: End-to-end scan-to-visible p99 latency, consumer lag in seconds (now - kafka_append_time), edge lease state & buffer depth, INFERRED_STEPS / NEEDS_REVIEW exception counts, seals blocked by manifest mismatch, and route plan churn vs. actual on-time arrival %.

  11. Summary of design trade-offs

    • Event-sourced scan fold vs. in-place row overwrites: Makes duplicate retries, 20-minute offline replays, and full historical audits completely safe, trading ~4.4 TB/year of event storage and occasional 10–50 row refolds on late scans.
    • ACID SQL constraints for allocations & doors vs. pure event streaming: Partial unique indexes and GiST exclusion constraints eliminate race conditions without distributed locks, requiring edge lease fallback when a warehouse loses internet.
    • Lease-guarded Edge offline authority vs. cloud-only dependence: Keeps warehouse docks loading trailers during WAN outages, trading a 45-second transition pause when internet first drops.
    • Exact Held-Karp DP per truck (<= 15 stops) vs. anytime LNS heuristics per region: Gives provably optimal stop sequences where problem size permits, and time-bounded feasible routes where NP-hard fleet size demands heuristics.
    • Immutable versioned route_plans + stability penalties vs. mutating plans on every ping: Preserves plan-vs-actual auditability and prevents chaotic floor churn at the cost of a slightly sub-optimal pure drive distance.

Intuition & how it works

Think of running this fulfillment platform like operating an airport baggage-tracking ledger alongside an air-traffic gate controller. Out on the warehouse floor, handheld scanners read tote and pallet barcodes in concrete trailers and Wi-Fi dead zones, uploading buffered scans minutes later and occasionally twice. If we simply overwrote a container's database row in arrival order, an offline scanner uploading a 20-minute-old PUTAWAY scan would falsely teleport a pallet off a departing highway truck back onto a warehouse shelf! Instead, we use event sourcing: we record every scan in an immutable log and compute each container's current state by sorting its events chronologically ((corrected_time, device_id, device_seq)) and folding them forward from start to finish. Meanwhile, promising a container to one outbound truck (allocation) and promising a dock door to one truck (door_reservation) are low-rate decisions where double-booking is disastrous, so those tables use strict PostgreSQL uniqueness and non-overlap constraints—and we keep the route planner's proposed schedule (route_plan) strictly separate from physical scan truth (container_state).

Why do simpler one-size-fits-all designs fail here? Putting scan tracking, dock reservations, and route optimization inside one tightly coupled service with in-place row UPDATEs causes offline scan replays to corrupt container locations and lets CPU-heavy routing queries stall live dock operations. Checking "is this container free?" in application code (SELECT then INSERT) fails under concurrency because two operators scanning the same pallet in the same second both see it free and double-allocate it to two trucks. Finally, trying to solve multi-truck regional routing to mathematical perfection in real time times out because the general VRPTW (Vehicle Routing Problem with Time Windows) is NP-hard—whereas sequencing a single truck's <= 15 stops has only 15 × 2^14 = 245,760 dynamic-programming states and solves exactly in milliseconds.

Let us trace two concrete mini-scenarios—an out-of-order offline scan replay and a same-second double-scan race—for pallet plt-18 at warehouse wh-dal2:

Scenario 1: Out-of-order & duplicate scan arrivals for pallet plt-18
  - 10:02 (arrives 10:02): event e2 (STAGE at bay-07)          -> status = STAGED,   load = None
  - 10:08 (arrives 10:08): event e3 (LOAD onto trl-510)        -> status = LOADED,   load = trl-510
  - 10:09 (arrives 10:09): event e3 arrives AGAIN (retry)      -> seen_event hit! Ignored (DUPLICATE)
  - 09:40 (arrives 10:21): event e1 (PUTAWAY) buffered offline -> sorts BEFORE 10:02!
    Tracking worker refolds [09:40 PUTAWAY -> 10:02 STAGE -> 10:08 LOAD]:
    -> Final state stays (LOADED, trl-510) with full history healed (never rolls backward to STORED!)

Scenario 2: Two operators scan plt-18 onto trl-510 and trl-511 in the same millisecond
  - Both edge calls run: UPDATE load (check capacity) + INSERT INTO allocation ... WHERE status='ACTIVE'
  - Postgres partial unique index lets trl-510 commit first; trl-511's INSERT hits conflict,
    rolls back its capacity increment via savepoint, and reads winner = trl-510.
  - Operator 1's scanner chimes GREEN ("OK: trl-510"); Operator 2's buzzes RED ("STOP: belongs to trl-510").

Key trade-offs

  • Decomposing into event-sourced tracking + ACID scheduling + stateless optimization vs. one shared model. Scan tracking prioritizes write availability, idempotent replay, and disorder tolerance; container allocation and dock scheduling prioritize zero race conditions on low-volume writes; route solving prioritizes bounded CPU budgets. Separating their databases and connecting them through CQRS (Command Query Responsibility Segregation) read models prevents failures or bursts in one subsystem from taking down the others.
  • Event sourcing with deterministic refold vs. in-place state mutation. Keeping every raw scan and deriving container_state over sorted (corrected_time, device_id, device_seq) makes duplicates, late offline uploads, and audit reconstruction effortless. The cost is ~4.4 TB/year of raw event storage and re-folding 10–50 rows whenever a scan arrives out of chronological order.
  • Database-enforced invariants vs. distributed application locks. A partial unique index (UNIQUE (container_id) WHERE status = 'ACTIVE') for container allocation and a PostgreSQL GiST exclusion constraint (EXCLUDE USING gist (door_id WITH =, slot WITH &&)) for non-overlapping dock appointments eliminate check-then-act races inside the storage engine. The trade-off is requiring reachable ACID authority—handled during warehouse internet cuts via an edge lease.
  • Lease-guarded warehouse edge authority vs. cloud-only operations. Granting each warehouse's local 2-node Edge Gateway a 30-second renewable lease (with a 45-second edge wait before taking offline authority) lets operators keep scanning and allocating on-site containers during fiber cuts with zero split-brain overlap. The cost is edge hardware management and a brief 45-second pause for new claims right when a WAN link drops.
  • Exact Held-Karp dynamic programming (single truck) vs. anytime heuristics (regional fleet). Sequencing one truck's <= 15 stops visits 245,760 states and finds the exact earliest-finishing schedule quickly because arriving early and waiting never hurts later windows. Consolidating hundreds of loads across dozens of trucks explodes combinatorially, so trading mathematical optimality for Large Neighborhood Search (LNS) inside a 10-second time budget guarantees dispatchers always get a valid answer on time.
  • Plan stability penalties & immutable route_plan versions vs. continuous pure re-optimization. Freezing completed stops, active legs, loaded pallets, and imminent (< 2 h) dock appointments while penalizing changes against the active plan sacrifices a few minutes of theoretical drive time to keep dock crews and drivers calm and auditable.
  • Explicit staleness watermarks (as_of) vs. blocking dashboards. Read boards stay fast under burst lag by displaying per-facility processed watermarks, while safety-critical actions (trailer :seal verification) wait until the watermark catches up.

Common mistakes

  • Overwriting container location/status in message arrival order, so an offline scanner replaying 30-minute-old scans moves departed containers backward into the warehouse.
  • Deduplicating scans by (container_id, timestamp) instead of a client-generated event_id UUID, which falsely drops two rapid real scans or double-applies a retry whose upload timestamp changed.
  • Either silently dropping unexpected scans or blindly forcing state transitions: Dropping an out-of-sequence RECEIVE throws away physical proof of where the pallet actually sits, while forcing contradictory scans (two hubs 300 km apart in 5 minutes) corrupts inventory without raising a NEEDS_REVIEW exception—or forgetting to clear load_id when a floor scan follows a missed UNLOAD.
  • Checking double-allocation or dock overlap in application code (SELECT then INSERT) without a database unique/exclusion constraint, allowing concurrent requests in the same millisecond to double-book.
  • Allowing the route planner to mutate container_state or load truth directly, turning a speculative route proposal into fake physical inventory movement.
  • Claiming an exact solver handles network-wide multi-truck VRPTW in real time (or conversely using sloppy heuristics without noticing <= 15 single-truck stops can be solved exactly), or failing to name the single primary optimization objective.
  • Triggering missing-container exceptions off wall-clock timers during ingest lag, flooding operations teams with thousands of false alarms whenever a warehouse reconnects after an outage.
  • Ignoring split-brain during warehouse network partitions, letting cloud dispatchers and offline dock operators allocate the same physical pallet to two different trailers simultaneously.

Follow-up questions

  • Suppose a sudden scan surge pushes ingestion lag to several minutes. How do you measure that lag, surface data staleness clearly to dispatchers, and ensure delayed processing never corrupts container states? We measure lag per partition and per warehouse via now - kafka_append_time of the oldest uncommitted message (using broker append time rather than device_time so an old offline replay is distinguished from live pipeline delay), alongside edge buffer depth, alerting once lag crosses 30 seconds. Every UI query and WebSocket feed carries that warehouse's as_of processed watermark, rendering an explicit "Data delayed by ~3m" banner on stale facility views. Processing lag never corrupts container states because fold_container_events orders strictly by (corrected_time, device_id, device_seq) rather than arrival time; synchronous allocation claims hit the ACID allocation index directly instead of lagging read models; trailer :seal waits until the facility watermark passes seal time; and missing-scan exception timers advance on processed event time rather than wall-clock time so lag never sets off false exception storms.
  • If two dock workers scan the same pallet onto two separate outbound trailers inside the same second, how does your system block double-assignment and what feedback appears on each handheld? Both handhelds submit their LOAD scans to the Edge Gateway, which synchronously calls the Allocation Service for (plt-18, trl-510) and (plt-18, trl-511). Each transaction increments its own load row (used_positions + 1 <= capacity) under a savepoint and executes INSERT INTO allocation ... VALUES ('plt-18', :load, 'ACTIVE') ON CONFLICT (container_id) WHERE status = 'ACTIVE' DO NOTHING; PostgreSQL's partial unique index serializes the two claims, letting trl-510 commit first while trl-511 inserts zero rows, rolls back to its savepoint (undoing trl-511's capacity increment), and queries the active winner (trl-510). Associate 1 sees a green OK within tens of milliseconds, while Associate 2 hears a red STOP buzzer reading "Assigned to trl-510 at bay-07 — do not load". Both physical scans still append to scan_event; if Associate 2 already placed the pallet inside trailer trl-511, the mismatch opens an exception on trl-511 and blocks trl-511:seal until an UNLOAD scan removes it or a dispatcher transfers the allocation.
  • While a driver is already mid-route, an upstream warehouse cancels half of its scheduled outbound pallets. Which parts of the route remain locked versus re-optimized, and how do you handle freight already sitting on the trailer? The re-planner locks completed stops, the stop the driver is currently heading toward, driving hours already spent, dock appointments starting within ~2 hours (unless conflicted), and every pallet physically LOADED on the trailer according to container_state. When the cancelled pallets sit at a future pickup stop not yet visited, their allocations are released, dwell time at that stop shrinks (or the stop drops out if zero pickups or deliveries remain), and freed trailer capacity can absorb compatible pending freight if appointment windows permit. When cancelled pallets are already physically aboard the trailer, the planner cannot pretend they vanished: it keeps their weight and cube occupied, marks their status DIVERT_OR_RETURN, and schedules their unload at an upcoming hub on the route for cross-dock restock. Activating route_plan version v + 1 never edits physical state directly; at each downstream bay, physical UNLOAD scans reconcile against v + 1's expected drop list and flag discrepancies as explicit exceptions.
  • How would you expand this platform to reserve SKU-level inventory—rather than only tracking physical totes and pallets—without coupling scan operations to cross-service two-phase commits with the WMS or OMS? Keep single-service ownership per invariant instead of running distributed two-phase commit (2PC): the WMS stays authoritative for SKU-level available-to-promise balances, while our platform stays authoritative for physical container placement and trailer manifests. For asynchronous order fulfillment, cross-system reservation executes as an outbox-driven saga: our service marks a request RESERVATION_PENDING and sends an idempotent ReserveInventory(idempotency_key, sku, qty, facility_id) command to the WMS, flipping to RESERVED upon confirmation or issuing a compensating ReleaseInventory on rejection or timeout. Where floor workflows require sub-50 ms synchronous SKU reservation at scan time (even across brief WAN blips), the WMS grants each warehouse pre-allocated escrow blocks of fast-moving SKUs that local PostgreSQL deducts atomically in one local transaction and replenishes asynchronously in the background, backed by periodic ledger reconciliation between WMS counts and container summaries.

Follow-up questions

Similar questions

More Axon interview questions

All 17 Axon questions →