Ocean Freight Container Packing Service with Hazmat Segregation
Hard · System Design · Software Engineer · Onsite
Prompt
In ocean freight consolidation, logistics providers combine cargo bookings from multiple shippers into standardized shipping containers—such as 20ft and 40ft dry vans, 40ft high-cubes, and temperature-controlled reefers. Cargo units differ in dimensions, mass, stackability, and dangerous-goods classifications (such as IMDG hazard classes, where corrosive acids or oxidizers cannot share a box with flammables or food-grade freight).
Design a backend container-planning service that assigns manifest items into containers at minimum total equipment cost while strictly enforcing physical and regulatory compatibility rules and supporting human review, manual adjustments, and final sign-off.
Your system must satisfy the following functional and operational constraints:
- Cost-Optimal Legal Packing: Assign manifest cargo across offered container types while honoring volume, payload weight, geometry/stackability, and pairwise or tag-level segregation rules.
- Asynchronous Execution & Determinism: Run solver jobs asynchronously (exposing status polling and webhooks) and produce byte-identical assignments whenever cargo revisions, container offers, rule-set versions, and configuration seeds match.
- Actionable Infeasibility Diagnostics: Whenever a manifest cannot be legally or physically packed, pinpoint the conflicting cargo items, segregation rules, or container supply caps.
- Editable Drafts, Concurrency Guards & Auditability: Persist solver outputs as drafts where planners can manually move items across containers (validated against physical and safety rules), block approval if underlying cargo attributes mutated during solving or review, prevent double-booking cargo or containers under concurrent approvals, and record an append-only audit trail of all revisions, runs, edits, and approvals.
- Scale & Latency Targets: Handle 15,000 planning jobs per day with bursts up to 100 concurrent runs; finish typical manifests (50–500 items) in under 30 seconds at p95 and large consolidations (up to 5,000 items) in under 2 minutes, with strict transactional consistency on approvals and inventory locks.
Scope & Expectations
- Asynchronous APIs & Versioned Contracts: Endpoints for manifest updates, async job creation, progress tracking/webhooks, conflict diagnostics, validated manual moves, and optimistic-concurrency approvals.
- Schema & Immutable Audit Trail: Data models covering versioned cargo attributes, container specs, versioned segregation rules, draft plans, strict allocation locks, and append-only audit logs.
- Solver Architecture, Scale & Explainability: Queue isolation, worker pools, constraint modeling up to
5,000items within latency SLAs, deterministic execution, and minimal conflict-set extraction for infeasible runs. - Concurrency & Stale-Input Protection: Preventing race conditions across simultaneous planner edits, upstream cargo updates, and competing plan approvals.
Step-by-step walkthrough
Clarify domain rules, requirements, and scope
In ocean freight consolidation—combining cargo bookings from several shippers into shared standardized ocean containers—a bad packing plan either wastes thousands of dollars on half-empty boxes or gets rejected at the port gate for breaking physical or hazardous-goods laws. Pinning down exact invariants up front keeps our solver, database schema, and concurrency protocol aligned.
Domain vocabulary in plain English
- Manifest: The list of cargo items scheduled for a specific origin port, destination port, and vessel sailing.
- Container types: Standard dry boxes (
20GP,40GP), taller high-cube boxes (40HC), and temperature-controlled refrigerated containers called reefers (40RF). - IMDG segregation rules: International Maritime Dangerous Goods safety regulations specifying which hazard tags (such as
IMDG_8corrosive acids,IMDG_5.1oxidizers, orFOODfood-grade freight) are forbidden from sharing the same container.
Functional requirements
- Cost-optimal valid packing: Assign every cargo item in a manifest to an available container to minimize total container cost while strictly enforcing physical fit (door opening, inner dimensions, allowed rotations, stackability), payload weight, volume, reefer needs, and tag-based incompatibility rules.
- Asynchronous execution: Return immediately on submission and expose progress and completion via polling and signed webhooks.
- Byte-identical determinism: Submitting the exact same item revisions, container offers, rule-set version, solver version, and seed must produce the exact same container assignment every time.
- Actionable infeasibility: When a manifest cannot be packed, return the specific conflicting items, rules, and container caps alongside a maximum-packed partial draft.
- Drafts, validated manual moves, and strict approval: Save solver outputs as editable drafts, validate every manual operator move against physical and safety rules, reject approval if any cargo attribute or rule changed since computation, and guarantee no item or scarce container is ever double-allocated across two approved plans.
- Immutable auditability: Preserve an append-only history of every input revision, solver snapshot, manual move, and approval.
Non-functional requirements and scale
- Throughput: 15,000 planning requests per day, spiking to 100 concurrent runs ahead of port vessel cutoffs.
- Latency: End-to-end p95 under 30 seconds for standard manifests (50–500 items) and under 2 minutes for large consolidations (up to 5,000 items), including queue wait time.
- Consistency: Strict transactional consistency on approvals and inventory reservations; eventual consistency (< 2 seconds) is acceptable for UI progress bars and "stale draft" warning banners.
Estimate scale and pinpoint the real bottleneck
1. Traffic & burstiness Daily jobs = 15,000 / 86,400 s = ~0.174 jobs/s average Assumed job mix = 98% standard (~300 items, ~15 s on 4 vCPUs) 2% large (~3,000 items, ~90 s on 16 vCPUs) Daily compute = (14,700 * 15 * 4) + (300 * 90 * 16) = 0.88M + 0.43M = 1.31M vCPU-s/day Average busy compute = 1,310,000 / 86,400 = ~15 vCPUs (~3 concurrent jobs on average) Vessel-cutoff peak = 100 concurrent jobs (e.g., 90 standard * 4 + 10 large * 16 = 520 vCPUs) -> ~33 worker hosts of 16 vCPUs (~34x peak-to-average burst!) 2. Combinatorial solver size (binary variables x[item, container_slot]) Standard (500 items * ~36 candidate slots across 3 container types) = ~18,000 binaries -> Fits comfortably in a single integer-programming model (< 20 s). Large (5,000 items * ~300 candidate slots across 3 container types) = ~1,500,000 binaries -> Too large for one monolithic exact model inside 2 minutes; requires decomposition! 3. Transactional database load Assignment rows/day = (14,700 * 300) + (300 * 3,000) = ~5.3M rows/day (~61 inserts/s avg) Storage growth = ~5.3M * ~1 KB (revisions + assignments + audit) = ~5.5 GB/day -> Fits easily on a single PostgreSQL primary + synchronous standby!Three design lessons from the math: 1. The database is lightweight, while solver CPU is spiky: ~60 inserts/s means a single relational database handles all metadata, approvals, and inventory locks in simple ACID transactions—no distributed database sagas needed. 2. Queue lane isolation is mandatory: Because peak concurrency is 34x average and large jobs run 6x longer, putting 5,000-item jobs in the same queue as 50-item jobs would blow the 30-second standard SLA during cutoff bursts. 3. 5,000-item manifests cannot use a single giant solver call: We must partition along hard domain boundaries and refine iteratively.
Design the asynchronous API and concurrency headers
Long-running optimization never belongs inside a synchronous HTTP request (which times out across load balancers and proxies). Instead,
POST /v1/plan-jobssnapshots the inputs and immediately returns202 Acceptedwith ajob_id.To prevent lost updates without holding pessimistic locks while an operator studies a screen for half an hour, every mutating endpoint uses Optimistic Concurrency Control (OCC) via HTTP
ETagandIf-Matchheaders—each read returns the resource's current version number, and each write passes that version back so the server rejects stale edits with409 Conflict.1. Cargo Manifests (immutable item revisions) POST /v1/manifests -> 201 { manifest_id, manifest_hash } PUT /v1/manifests/{manifest_id}/items/{item_id} Header: If-Match: "rev-3" Body: { l_mm, w_mm, h_mm, weight_kg, stackable, tags: ["IMDG_8"], pod: "SGSIN" } -> 200 { item_id, revision: 4, manifest_hash: "sha256:7d3e..." } | 409 REVISION_CONFLICT 2. Async Planning Jobs POST /v1/plan-jobs Header: Idempotency-Key: <uuid> Body: { manifest_id, container_offers: [ { type: "40HC", max_count: 30, cost_usd: 2900 }, { type: "40RF", max_count: 2, cost_usd: 4800 } ], rule_set_version: "2026-11-01.3", -- optional; defaults to current active set config: { seed: 7, budget_tier: "standard" }, webhook_url: "https://..." } -> 202 { job_id, input_hash: "sha256:6c8a...", status: "QUEUED" } GET /v1/plan-jobs/{job_id} -> 200 { status: "QUEUED" | "RUNNING" | "SUCCEEDED" | "INFEASIBLE" | "FAILED", progress: { best_cost_usd: 17400, lower_bound_usd: 16800, gap_pct: 3.4 }, plan_id: "plan_512" } 3. Draft Inspection, Validated Overrides, Rebase, and Approval GET /v1/plans/{plan_id} Returns Header: ETag: "v3" GET /v1/plans/{plan_id}/explanation Minimal conflict sets + suggested fixes GET /v1/plans/{plan_id}/history Immutable timeline of versions & edits POST /v1/plans/{plan_id}/moves Header: If-Match: "v3" Body: { moves: [ { item_id: "K-305", to_container: "B4" } ], reason: "keep shipper together" } -> 200 { version: 4 } | 409 VERSION_CONFLICT | 422 RULE_VIOLATION { violations: [...] } POST /v1/plans/{plan_id}/rebase Header: If-Match: "v4" Re-validates a STALE or RULES_CHANGED draft against latest item revisions & active rules. POST /v1/plans/{plan_id}/approve Header: If-Match: "v4" -> 200 { status: "APPROVED", version: 5 } -> 409 STALE_INPUT | RULES_CHANGED | ALREADY_ALLOCATED | CONTAINERS_UNAVAILABLERelational data model and immutable audit trail
Keeping cargo revisions, draft plans, item allocations, and sailing container caps in one PostgreSQL database lets database constraints (
PRIMARY KEYandCHECK) mathematically rule out double-allocation and overbooking:1. Reference Specs & Versioned Rules (published rows are immutable) container_types type_code PK ('20GP','40GP','40HC','40RF'), inner_l_mm, inner_w_mm, inner_h_mm, door_w_mm, door_h_mm, max_payload_kg, usable_vol_pct, is_reefer rule_sets rule_set_version PK, status ('DRAFT'|'ACTIVE'|'RETIRED'), content_hash rules (rule_set_version, rule_id) PK, kind ('FORBID_PAIR'|'MAX_TAG_KG'|...), tag_a, tag_b, limit_value, regulation_ref 2. Manifests & Immutable Cargo Revisions manifests manifest_id PK, sailing_id, origin_port, manifest_hash, updated_at cargo_items item_id PK, manifest_id FK, booking_id, current_revision INT item_revisions (item_id, revision) PK -- NEVER UPDATED IN PLACE: l_mm, w_mm, h_mm, weight_kg, stackable, rotations_mask, tags TEXT[], pod TEXT, created_by, created_at 3. Jobs, Drafts, Assignments, and Edit Deltas plan_jobs job_id PK, idempotency_key UNIQUE, manifest_id, input_hash, snapshot_uri, rule_set_version, solver_version, config_json, status, attempts, lease_owner, lease_until plans plan_id PK, job_id UNIQUE, manifest_id, input_hash, manifest_hash, rule_set_version, status ('DRAFT'|'STALE'|'RULES_CHANGED'|'APPROVED'| 'AMENDMENT_REQUIRED'|'INFEASIBLE'), version INT, total_cost_usd, lower_bound_usd plan_containers (plan_id, container_ref) PK, type_code assignments (plan_id, item_id) PK, item_revision INT, container_ref (INDEX on item_id) plan_edits (plan_id, version) PK, actor, moves_json, reason, created_at -- append-only! explanations (job_id, conflict_seq) PK, item_ids[], rule_ids[], limits_json, summary 4. Strict Allocation Locks & Tamper-Evident Audit allocations item_id PK, plan_id FK, plan_version, approved_at -- PK on item_id makes assigning one item to two approved plans impossible! container_inventory (sailing_id, type_code) PK, total_count INT, reserved_count INT, CHECK (reserved_count <= total_count) audit_events (entity_type, entity_id, seq) PK, actor, action, payload_json, prev_hash, row_hash, created_at -- DB role has INSERT + SELECT only outbox event_id PK, topic, payload_json, created_at, published_atNotice two clean storage patterns: - Edit deltas instead of full-table copies: The raw solver output is stored once in immutable object storage (
snapshot_uri),assignmentsholds the current draft view, and each manual move appends one compact delta row toplan_editsinstead of duplicating 5,000 rows on every drag-and-drop. - Transactional outbox: Writing a row tooutboxinside the same SQL transaction as a job finish or plan approval ensures our webhook relay always delivers the notification, even if the API process crashes 1 ms afterCOMMIT.High-level decoupled architecture
Operator UI Booking / Upstream Systems | | v v +-----------------------------------------+ +------------------------------------+ | Stateless Plan API |------->| PostgreSQL (Primary + Sync Standby)| | - freeze canonical snapshot & hash | ACID | manifests, item_revisions, rules, | | - enqueue job / check determinism cache| txns | jobs, plans, allocations, outbox | | - validate moves & run approval txn | +------------------------------------+ +-----------------------------------------+ ^ | publish job_id | idempotent result write v | +---------------------------------+ claim lease +------------------------------------+ | Two-Lane Message Queue |--------------->| Autoscaled Solver Worker Pools | | - Standard lane (<= 500 items) | | 1. O(N) physical pre-checks | | - Large lane (> 500 items) | | 2. Hard partition (POD, reefer) | +---------------------------------+ | 3. CP-SAT (std) / Greedy+LNS (lg) | | 4. 3D layer placement check | +---------------------------------+ progress | 5. MUC shrinker if infeasible | | Redis (ephemeral job progress: |<---------------+------------------------------------+ | best_cost, gap_pct for polling)| | +---------------------------------+ v +------------------------------------+ Outbox Relay ---> Signed Webhooks (with retry) | Immutable Object Storage (S3/GCS) | Stale Marker <--- Cargo revision events | canonical snapshots & solver logs | (flags open drafts STALE) | indexed by input_hash | +------------------------------------+Deep dive 1: Constraint optimization, tag modeling, and scaling to 5,000 items
We formulate container packing using CP-SAT (Constraint Programming with Boolean Satisfiability)—an integer optimization engine (such as OR-Tools CP-SAT) that combines linear capacity inequalities with fast Boolean clause learning over
0/1decision variables. All measurements are converted to exact integers (mm,kg,cm^3) before solving.Core mathematical formulation (for one compatible sub-problem)
Suppose a fast greedy pass needs
Kcontainers, giving usScandidate container slots across the offered types. We create binary variablex[i, k] in {0, 1}only if itemiphysically fits through slotk's door and inside its inner dimensions under at least one allowed rotation (and matches dry/reefer requirements):Decision Variables: x[i, k] in {0, 1} : 1 if item i is placed in container slot k open[k] in {0, 1} : 1 if container slot k is used has[k, g] in {0, 1} : 1 if container slot k contains ANY item carrying regulatory tag g Hard Constraints: 1. Pack every item once: sum_k x[i, k] = 1 for all items i 2. Weight limit: sum_i weight_i * x[i, k] <= max_payload(k) * open[k] for all slots k 3. Usable volume limit: sum_i vol_i * x[i, k] <= usable_vol(k) * open[k] for all slots k 4. Dedicated floor limit: sum_{i in floor_only} area_i * x[i, k] <= floor_area(k) * open[k] (where floor_only = non-stackable items OR items taller than inner_h / 2) 5. Tag indicator link: x[i, k] <= has[k, g] for every item i, slot k, tag g on item i 6. Tag incompatibility: has[k, g] + has[k, h] <= 1 for every rule forbidding (tag g, tag h) 7. Symmetry breaking: open[type, j] >= open[type, j + 1] (fill slot #1 before opening slot #2!) Objective: Minimize sum_k cost(k) * open[k] + epsilon * (count of bookings split across multiple containers)Look closely at three critical modeling tricks here: - Tag-level indicators (
has[k, g]) instead of item-pair constraints: If 500 hazardous items have 50% pairwise conflicts, writingx[a, k] + x[b, k] <= 1for every conflicting item pair creates62,375 pairs * 36 slots = 2.24 millionconstraints (and ~300 million at 5,000 items!). Routing rules throughhas[k, g]("does slotkcontain tagg?") needs only30 rules * 36 slots = 1,080incompatibility constraints, regardless of how many items share a tag! - Symmetry breaking (open[type, j] >= open[type, j + 1]): Without ordering identical40HCslots, swapping the contents of40HC #1and40HC #2looks like a "new" solution to the branch-and-bound tree, wasting exponential search time onK!permutations. - Aggregate bounds + post-solve 3D verification: Weight, 85% usable volume, and floor-area bounds keep the assignment model fast, while catching 99% of geometric limits. Once CP-SAT outputs an assignment, a fast deterministic 3D layer-building heuristic verifies physical placement inside each container; if an awkward combination of long crates fails 3D packing in containerk, we add a no-good cut (sum_{i in C_k} x[i, k] <= |C_k| - 1, forbidding that exact subset in that container type) and locally re-solve those containers.How we scale to 5,000 items inside 2 minutes
Instead of feeding 1.5 million binary variables into one monolithic solve: 1. Decompose on hard domain boundaries: Items heading to Singapore (
SGSIN) and Yokohama (JPYOK), or reefer vs. dry cargo, can never share a container. Splitting by(pod, is_reefer)immediately breaks a 5,000-item manifest into smaller independent sub-problems solved in parallel. 2. Construct an instant feasible baseline (< 1 s): Sort items by decreasing volume (placing hazmat-constrained items first on ties) and run deterministic First-Fit Decreasing to get an immediate legal plan and tight slot count. 3. Improve via Large Neighborhood Search (LNS)—an iterative metaheuristic that freezes most containers, unpacks 4–6 related or under-utilized containers (only ~150–300 items), re-solves that small sub-problem optimally with CP-SAT in 1–2 seconds, and keeps any cost reduction for a fixed number of deterministic iterations. 4. Report an explicit optimality gap: Solve a tiny continuous linear program (allowing fractional containersy_t >= 0covering total weight and volume) in< 10 msto obtain a mathematicallower_bound_usd, displayinggap_pct = (total_cost - lower_bound) / total_costso operators see"$87,000 (within 2.9% of theoretical minimum)".Deep dive 2: Guaranteeing byte-identical determinism
Why do optimization services accidentally return different answers on Tuesday than on Monday for the exact same cargo? Four culprits sneak in unless explicitly eliminated:
Nondeterminism Culprit Engineering Fix ---------------------------------------------- ---------------------------------------------------- 1. Hash-map iteration order or float rounding Build a canonical snapshot: sort items by item_id, varies across serialization or machines. sort tags alphabetically, store integer mm/kg/cm^3. 2. Wall-clock timeout ("stop at 20.0 seconds") Stop on deterministic work units (CP-SAT's explores fewer nodes when CPU cache is busy. max_deterministic_time; fixed LNS step count). 3. Multi-threaded solver workers race to share Run CP-SAT in deterministic mode with pinned seed; learned clauses in unpredictable order. parallelize across independent (pod, reefer) splits and merge results in sorted partition-key order. 4. Solver binary or rule set changes silently. Pin rule_set_version and solver_version inside the job record and keep immutable solver images.We hash the canonical inputs before enqueuing:
input_hash = SHA-256( canonical_items_bytes || canonical_offers_bytes || rule_set_content_hash || config_json || solver_version )If an operator clicks "Plan" twice on unchanged cargo,
input_hashhits our object-storage cache and creates a fresh editable draft in milliseconds without burning solver CPU. Meanwhile, a separate wall-clock watchdog (set at 2x the expected runtime on standardized worker hardware) catches hung hosts: if triggered, it fails the attempt and retries on a healthy worker rather than returning whatever partial solution happened to exist at timeout—preserving strict determinism.Deep dive 3: Optimistic concurrency, stale-input protection, and atomic approval
While a plan sits in
DRAFTfor 40 minutes of human review, dimensions may be edited by warehouse staff, a colleague may drag items on the same draft, another planner may allocate one of the items to an earlier vessel, or a competing draft may grab the sailing's last40RFreefer.We combine manifest/revision checks with plan version checks inside one atomic PostgreSQL approval transaction—and lock rows in deterministic primary-key order so two concurrent approvals can never deadlock each other:
BEGIN; -- 1. Optimistic version & rule check on the draft row (acquires row lock on plans). UPDATE plans SET status = 'APPROVED', version = version + 1, approved_by = :actor, approved_at = now() WHERE plan_id = :plan_id AND version = :if_match_version AND status = 'DRAFT' AND rule_set_version = (SELECT rule_set_version FROM rule_sets WHERE status = 'ACTIVE'); -- If 0 rows updated -> ROLLBACK and return 409 (VERSION_CONFLICT, STALE_INPUT, or RULES_CHANGED). -- 2. Stale-input check: lock every cargo_items row in sorted item_id order (prevents deadlocks -- and blocks any concurrent PUT /items update until this approval transaction finishes!). SELECT c.item_id, c.current_revision, a.item_revision FROM cargo_items c JOIN assignments a USING (item_id) WHERE a.plan_id = :plan_id ORDER BY c.item_id FOR SHARE OF c; -- Fast check: compare plans.manifest_hash; detailed check: if ANY c.current_revision <> a.item_revision, -- ROLLBACK and return 409 STALE_INPUT listing the exact changed item_ids! -- 3. Prevent cargo double-allocation across plans (allocations PK is item_id). INSERT INTO allocations (item_id, plan_id, plan_version, approved_at) SELECT item_id, :plan_id, :if_match_version + 1, now() FROM assignments WHERE plan_id = :plan_id; -- Unique violation on item_id -> ROLLBACK and return 409 ALREADY_ALLOCATED. -- 4. Lock scarce sailing container rows in sorted type_code order (prevents multi-type deadlocks!) -- and reserve counts; CHECK (reserved_count <= total_count) blocks reefer overbooking. SELECT type_code FROM container_inventory WHERE sailing_id = :sailing_id AND type_code IN (SELECT DISTINCT type_code FROM plan_containers WHERE plan_id = :plan_id) ORDER BY type_code FOR UPDATE; UPDATE container_inventory ci SET reserved_count = ci.reserved_count + req.cnt FROM (SELECT type_code, COUNT(*) AS cnt FROM plan_containers WHERE plan_id = :plan_id GROUP BY type_code) req WHERE ci.sailing_id = :sailing_id AND ci.type_code = req.type_code; -- CHECK violation -> ROLLBACK and return 409 CONTAINERS_UNAVAILABLE. -- 5. Append tamper-evident audit row and transactional outbox event. INSERT INTO audit_events (...); INSERT INTO outbox (...); COMMIT;How edits and background stale banners interact cleanly with this transaction: - Immediate UI feedback: Whenever
PUT /manifests/{id}/items/{item_id}createsrevision + 1, an async consumer queriesassignments(item_id)and flips open drafts containing that item toSTALEso operators see a banner right away. Even if that async event lags by 5 seconds, step 2 of the approval transaction catches the revision mismatch with 100% certainty! - Post-approval cargo edits: Updatingcargo_itemsacquires a row lock (waiting if an approval is mid-flight) and then checksallocations(item_id). If the item is already approved, the system marks the planAMENDMENT_REQUIREDinstead of silently mutating an approved manifest. - Validated batch moves:POST /movesaccepts a list of moves (so swapping two items between full containers validates the end state rather than failing mid-swap) using the exact same constraint + 3D placement library as the solver. Safety rules can never be bypassed; if an item was misclassified asIMDG_8, the user fixes the item's tag (creating a new auditeditem_revision) and callsrebase.Deep dive 4: Explainable infeasibility via Minimal Unsatisfiable Cores (MUC)
Returning
"Error: INFEASIBLE"on a 1,200-item manifest leaves an operator blind. Instead, we want a Minimal Unsatisfiable Core (MUC)—a small subset of items, safety rules, and container caps that are mutually impossible together, such that relaxing any single element makes that subset packable.We run a three-stage diagnostic funnel, catching easy physical errors in milliseconds before invoking solver-based core shrinking:
- Stage 1 —
O(N)single-item physical pre-checks (no solver needed): Check whether any single item exceeds every offered container's door opening, inner length/width/height across all allowed rotations, or max payload, or requires40RFwhen zero reefers were offered. In practice, most real-world failures are typos (e.g.,14,000 mmentered instead of1,400 mm) caught right here in< 5 ms. - Stage 2 — Aggregate capacity and mutual-exclusion cliques: Check total manifest weight/volume against total offered capacity, and check pairwise-incompatible tag cliques (for example, 3 items carrying 3 mutually incompatible hazmat classes that all require reefers when
max_count(40RF) = 2). - Stage 3 — Assumption-literal MUC extraction and deterministic deletion shrinking: In CP-SAT, we guard each relaxable constraint with a Boolean assumption literal
a(an on/off switch:a_item_i => sum_k x[i, k] = 1,a_rule_r => has[k, g] + has[k, h] <= 1,a_cap_t => sum open[t, j] <= max_count(t)). When the solve is infeasible, CP-SAT returns a sufficient subset of assumptions that caused the conflict, and we shrink it deterministically to a minimal core:
def shrink_to_minimal_core(solver_runner, initial_core: list[str]) -> list[str]: """Deterministically shrink an infeasible assumption set into a Minimal Unsatisfiable Core.""" # Sort assumption IDs so iteration order—and the resulting explanation—is 100% deterministic. core = sorted(set(initial_core)) for candidate in list(core): # An earlier successful shrink may have already dropped this assumption literal. if candidate not in core: continue # Test whether the model is STILL infeasible if we relax `candidate`. trial_assumptions = [lit for lit in core if lit != candidate] is_feasible, smaller_core = solver_runner.solve_with_assumptions(trial_assumptions) if not is_feasible: # `candidate` was redundant! Replace `core` with the solver's new, smaller witness. core = sorted(set(smaller_core)) # Otherwise (`is_feasible` is True), `candidate` is strictly necessary; keep it in `core`. return coreFinally, we run one pass with
sum_k x[i, k] <= 1maximizing packed priority weight so the operator gets both a crisp diagnosis and a ready-to-use partial plan:Example Explanation Returned by GET /v1/plans/{plan_id}/explanation: Conflict #1 (Single-Item Geometry): Item K-77 ("Turbine Rotor", length 12,350 mm) exceeds longest offered container 40HC (12,032 mm). Suggested fix: Offer a 45HC / flat-rack container or split item K-77 off this manifest. Conflict #2 (Minimal Unsatisfiable Core of 4 elements): { Item K-19 [REEFER, IMDG_8], Item K-54 [REEFER, FOOD], Rule R-22 ("IMDG_8 forbidden with FOOD"), Offer Cap ("40RF max_count = 1") } Why: Both items require a reefer, Rule R-22 forbids co-loading them, and only 1 40RF is offered. Suggested fix: Increase 40RF max_count to 2, or move either K-19 or K-54 to the next sailing. Best Partial Plan: 497 of 500 items packed into 11x 40HC + 1x 40RF ($36,700); 3 items unassigned.- Stage 1 —
Scaling, failure recovery, and key trade-offs
Scaling and operational resilience
- Two-lane autoscaling with warm pool: Standard workers (4 vCPU) and large workers (16 vCPU) pull from separate queues so 5,000-item runs never delay
< 30 sstandard plans. Because booting new cloud VMs takes 45–90 seconds, keep a warm floor (~20 standard slots) and pre-scale 2 hours before scheduled port cutoffs. - Cheap progress polling: Workers write
{best_cost_usd, lower_bound_usd, gap_pct}to Redis every 2 seconds; 100 UIs polling every 2 seconds is just 50 reads/s from Redis and zero load on PostgreSQL. - Worker crash recovery: Each worker renews a 15-second lease on
plan_jobs. If a worker crashes mid-solve, the lease expires, another worker picks up the canonical snapshot, computes the exact same deterministic assignment, and writes the result withINSERT INTO plans ... ON CONFLICT (job_id) DO NOTHING. After 3 crashes, the job transitions toFAILEDand pages on-call rather than poison-looping.
Summary of key trade-offs
- Single CP-SAT model (<= 500 items) vs. Partition + LNS (5,000 items): Exact models find tighter packings on small manifests, while hard-boundary decomposition + LNS finishes 5,000 items inside 2 minutes and quantifies any remaining sub-optimality via the LP lower-bound gap.
- Aggregate capacity + 3D verification vs. full 3D MIP: Keeps the assignment model orders of magnitude faster while guaranteeing every container can physically be loaded, at the cost of an occasional local no-good-cut repair.
- Deterministic work budgets vs. wall-clock cutoffs: Guarantees byte-identical audit replay and safe retries, requiring uniform worker CPU families and calibrated work-unit budgets to hold the 30 s / 2 min p95 targets.
- Optimistic locking (
If-Match+item_revision+ single ACID approval) vs. pessimistic cargo locks: Operators can review drafts for hours without blocking upstream booking edits, accepting a fastrebasestep whenever cargo changes underneath an open draft. - Deletion-shrunk minimal core (MUC) vs. minimum-cardinality core: Gives operators a clean, irreducible conflict explanation in at most
|core|tiny solver calls rather than solving an NP-hard minimum-hitting-set problem just to shave one element off an error message.
- Two-lane autoscaling with warm pool: Standard workers (4 vCPU) and large workers (16 vCPU) pull from separate queues so 5,000-item runs never delay
Intuition & how it works
Think of ocean container planning like seating guests at wedding tables with strict size limits and "do not seat together" rules—while guests are still updating their dietary needs right up to the dinner bell. Solving the seating chart takes intense math, so you never make the receptionist freeze on the phone while computing it: instead, you take a frozen photograph of the guest list, hand it to a back-room puzzle solver that runs on a fixed step count so the same photograph always gives the exact same chart, and then—right when the host clicks "Approve"—you check in one instant transaction that nobody changed their RSVP and nobody was promised two seats.
A naive design—running a brute-force 3D packing solver synchronously inside an HTTP endpoint, writing one incompatibility constraint for every pair of hazardous items, stopping at a 30-second wall-clock timer, and saving operator edits with "last write wins"—fails on every requirement. Synchronous HTTP requests time out on 90-second 5,000-item consolidations; pairwise item constraints explode quadratically into hundreds of millions of inequalities; stopping on wall-clock seconds returns different plans whenever a server CPU is slightly busier; and approving without re-checking item versions lets a shipment sail after a warehouse clerk updated a crate's weight or hazard class.
Walk through a tiny 3-item manifest (K-1: 9,500 kg corrosive acid IMDG_8, K-2: 6,500 kg food-grade cocoa FOOD, K-3: 11,000 kg industrial pumps) with 20GP containers (max_payload = 28,000 kg, $1,800 each):
1. Canonical snapshot & async solve (rev 1): By weight alone, 9,500 + 6,500 + 11,000 = 27,000 kg <= 28,000 kg fits in one box, but tag rule R-22 forbids IMDG_8 with FOOD (has[k, IMDG_8] + has[k, FOOD] <= 1). A background worker runs CP-SAT (an integer constraint solver combining linear bounds with Boolean logic search) on a fixed deterministic work budget and saves Draft v1: Container B1 = [K-1, K-3] (20,500 kg), Container B2 = [K-2] (6,500 kg), recording item_revision = 1 for all three items.
2. Concurrent cargo edit: While an operator inspects Draft v1, warehouse staff re-weigh K-3 at 20,000 kg, creating immutable item_revision = 2 (20,500 kg -> 29,500 kg, which would overload B1!).
3. Protected approval: When the operator clicks "Approve" with If-Match: "v1", the PostgreSQL approval transaction locks K-1, K-2, K-3, spots K-3's current_revision (2) != plan item_revision (1), rolls back with 409 STALE_INPUT naming K-3, and prevents an overloaded container from ever reaching the port.
Key trade-offs
- Monolithic CP-SAT (<= 500 items) vs. Decomposition + Large Neighborhood Search (5,000 items). A single CP-SAT model (~18,000 binary variables) finds near-optimal packings for standard manifests inside 20 seconds, whereas 5,000 items (~1.5 million binaries) stalls if solved all at once. Splitting by destination port and dry/reefer first, building a 1-second greedy baseline, and refining 4–6 containers at a time via Large Neighborhood Search (LNS) (an iterative loop that repeatedly unpacks and re-optimizes small subsets of containers) meets the 2-minute target while a continuous linear-programming lower bound tells operators the exact optimality gap (e.g.,
"within 2.9% of minimum possible cost"). - Aggregate capacity + 3D verification vs. full 3D coordinates inside the optimizer. Enforcing weight, 85% usable volume, door clearance, and floor area for non-stackable/tall crates inside CP-SAT keeps the assignment model fast, followed by a deterministic 3D layer-placement check per container (adding a local "no-good cut" if awkward shapes collide). Embedding continuous 3D
(x, y, z)coordinates for 5,000 items directly inside one global model would miss latency targets by orders of magnitude. - Deterministic work budgets vs. wall-clock timeouts and racing threads. Stopping on solver-internal deterministic work units, canonical integer inputs (
mm,kg), and pinned seeds guarantees byte-identical assignments and safe crash retries, at the price of slightly less search throughput per second than unrestricted parallel thread racing and the need to standardize worker CPU types. - Optimistic Concurrency Control (
If-Match+item_revision) vs. pessimistic locks. Checking plan versions and immutable item revisions inside a millisecond approval transaction lets human planners review drafts for hours without blocking upstream booking updates, trading away guaranteed approval when cargo changes mid-review (handled cleanly viarebaseor re-planning). - Tag-level indicator variables (
has[k, g]) vs. pairwise item constraints. Linking items to tag flags (x[i, k] <= has[k, g]) keeps incompatibility constraints proportional tonum_rules * num_slots(~1,000–9,000 rows) rather thannum_items^2 * num_slots(millions of rows), requiring only a dedicated synthetic tag if a one-off contract forbids two specific bookings from co-loading. - Deletion-shrunk Minimal Unsatisfiable Core (MUC) vs. smallest-possible core. Shrinking solver assumption literals (Boolean switches attached to each item, rule, and container cap) one by one yields an irreducible conflict set in at most
|core|tiny solves, whereas searching for the globally smallest cardinality conflict set is NP-hard and rarely adds clarity for an operator.
Common mistakes
- Running optimization synchronously inside the API request, causing gateway timeouts, dropped connections, and lost compute on 30-to-120-second runs.
- Promising determinism while stopping on wall-clock timers (
timeout = 25s), iterating over unsorted hash sets, or using multi-threaded non-deterministic search, so identical inputs produce different assignments depending on background CPU load. - Generating pairwise
x[i, k] + x[j, k] <= 1constraints for every conflicting pair of items, blowing up memory and presolve time quadratically on hazmat-heavy manifests. - Checking only total cubic volume and weight, ignoring door dimensions, allowed rotations, and floor-area exhaustion from non-stackable crates.
- Validating cargo freshness only at job submission, allowing stale drafts to be approved after weights, dimensions, or hazard tags changed during solver execution or human review.
- Allowing double-allocation or container overbooking across concurrent drafts, or locking
container_inventoryrows in arbitraryGROUP BYorder during approval (which causes PostgreSQL row-lock deadlocks when two plans reserve both20GPand40HCsimultaneously). - Putting 5,000-item jobs and 50-item jobs in a single FIFO queue, allowing a burst of 10 large consolidations to push every standard job past its 30-second p95 SLA.
- Returning a bare
"INFEASIBLE"status instead of running fast single-item pre-checks, extracting a Minimal Unsatisfiable Core, and providing a best partial plan.
Follow-up questions
- How can the optimization pipeline incorporate 3D physical balance constraints—specifically center-of-gravity bounds and chassis axle load limits—without losing safety guarantees? Keep the fast container-assignment stage intact and upgrade the per-container 3D verification stage into a small per-container CP-SAT placement solve (each container holds only ~10–60 items). Group compatible stackable items into vertical columns respecting top-load limits (heaviest on bottom), enforce 2D non-overlapping rectangle constraints on the container floor (
AddNoOverlap2D), and constrain the lengthwise and widthwise center of gravity within a safe tolerancedaround the midpointL / 2: since total container cargo weightWis fixed for that container,(L / 2 - d) * W <= sum_j weight_j * center_x_j <= (L / 2 + d) * Wis purely linear in the integer coordinatescenter_x_j(and chassis front/rear axle limits reduce directly to bounds ondby static moment balance). If a container's assigned items cannot be balanced (for instance, one ultra-dense machine with nothing to counterbalance it), emit a no-good cut back to the LNS loop to swap items with an adjacent container. - When a cargo manifest cannot fit onto a single vessel sailing, how would you partition bookings across multiple departure dates to balance cost and delay? Model sailing selection at the booking level (
z[b, s] in {0, 1}assigning bookingbto sailings, allowed only whencargo_ready_date(b) <= cutoff(s)) so customer bookings stay intact unless explicitly allowed to split, adding a weighted lateness penalty (days_delayed * priority_weight) alongside container costs and per-sailing container inventory limits. Solve hierarchically: first run an aggregate multi-sailing assignment model (seeded by keeping items from our best partial plan on the earliest sailing and pushing items involved in Minimal Unsatisfiable Cores to later sailings where reefers or capacity exist), and then validate each sailing with our standard deterministic container solver, shifting the lowest-priority conflicting booking forward if any sailing fails detailed packing. Present 2–3 Pareto trade-off drafts to the operator (lowest total cost, minimum delayed bookings, zero split bookings) as linked draft plans that approve atomically. - How would you roll out live updates to hazardous-goods segregation rules with zero downtime while protecting active solver runs and unapproved drafts? Store every regulatory update as a new immutable
rule_setsversion ("2026-12-01.1") rather than mutating rule rows in place, and flip the active-version pointer atomically; workers load rule sets by explicitrule_set_version(and cache them safely forever since versions never mutate), so in-flight solver jobs finish cleanly without restarts. Next, run an asynchronous background sweep that re-validates every openDRAFTagainst the newly activated rule set using our fast constraint checker (milliseconds per plan, no re-solving needed): drafts that still pass every rule automatically advance theirrule_set_versionwith an audit entry, while drafts with newly forbidden combinations transition toRULES_CHANGEDwith exact violation details so operators can move the offending item or click Re-plan. Finally, step 1 of the approval transaction checksrule_set_version = active_version_for_sailing_date, guaranteeing zero chance of approving a draft under retired safety rules (409 RULES_CHANGED), while pre-publish shadow runs over recent manifests let compliance teams preview breakage impact before flipping the pointer.
Follow-up questions
- How can the optimization pipeline incorporate 3D physical balance constraints—specifically center-of-gravity bounds and chassis axle load limits—without losing safety guarantees?
- When a cargo manifest cannot fit onto a single vessel sailing, how would you partition bookings across multiple departure dates to balance cost and delay?
- How would you roll out live updates to hazardous-goods segregation rules with zero downtime while protecting active solver runs and unapproved drafts?
Similar questions
- Select Minimax Word Guesses from Tile Feedback
- Total Busy Duration and Peak Concurrent Rooms
- Maximize Non-Adjacent Totals on Lines and Trees
- Verify and Reconstruct IPv4 Strings
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor