Design a Container Assignment System with Compatibility Constraints
System DesignModel answerLast updated
Design an automated container packing platform that optimizes cargo placement under weight, volume, and hazmat rules, supporting async runs, plan overrides, and strict determinism.
Context
In ocean logistics, freight consolidators combine shipments from different cargo owners into standardized sea containers (20ft, 40ft, High Cube, Refrigerated). Cargo items differ by dimensions, weight limits, stacking rules, temperature requirements, and dangerous goods classifications (e.g., IMDG classes). Specific combinations of goods are strictly prohibited from sharing a container (e.g., volatile organic liquids cannot be stored with strong oxidizers or human foodstuffs).
Design an automated planning service that assigns cargo items to available container types to minimize container procurement costs while adhering to all physical, temperature, and hazmat compatibility rules. The platform must also support asynchronous processing, operator reviews, and manual overrides.
Requirements
Functional Requirements
- Optimization Engine: Given a list of cargo items and supported container types, compute assignments that satisfy volume, mass payload, temperature, and material incompatibility constraints while minimizing cost.
- Asynchronous Execution: Planning tasks must run asynchronously, allowing clients to track job status via polling or webhooks.
- Strict Determinism: Re-running the solver on identical inputs (cargo manifest revision, container specs, rule version, configuration, and random seed) must produce identical output every time.
- Actionable Infeasibility Explanations: If a cargo set cannot be fully loaded legally or physically, return the minimal conflicting item subset and the specific rules breached.
- Drafting, Overrides, & Manual Approvals: Generated plans are stored as drafts. Human dispatchers can manually move items between containers (validated on-the-fly against constraints) and approve the final plan.
- Stale Input & Double-Allocation Prevention: Prevent a plan from being approved if the underlying cargo manifest changes during calculation or review, or if any cargo item has already been assigned in another approved plan.
- Audit Trails: Maintain an immutable, tamper-evident log of manifest revisions, solver outputs, manual user modifications, and final plan approvals.
Non-Functional Requirements & Scale
- Traffic: ~15,000 planning requests per day, with peak concurrency reaching 100 simultaneous optimization executions.
- Payload Volume: Typical manifest size ranges between 50 and 500 items; large consolidation runs contain up to 5,000 items.
- Latency Budget: 95th percentile under 30 seconds for typical plans (≤500 items); under 120 seconds for large plans (5,000 items).
- Consistency: Strong transactional consistency for final plan approvals and inventory allocation locks.
What Your Design Should Cover
- API Contracts: REST/gRPC interfaces for job creation, progress tracking, conflict inspection, manual item migration, and plan approval.
- Data Model & Schema: Tables for Cargo Items, Incompatibility Rules, Container Catalogs, Draft Plans, Assignments, and Audit Records.
- System Architecture: Storage layout, worker queues, job lifecycle, and solver execution isolation.
- Concurrency & Race Condition Handling: Strategies (e.g., Optimistic Concurrency Control, input hashes, database locks) to avoid double allocation and stale approvals.
- Explainability Strategy: Algorithmic approach to isolate Minimal Unsatisfiable Subsets (MUS) when a plan is infeasible.
Hints
Hint 1
Divide solver workers into separate queues based on manifest size to prevent small jobs from being starved by massive 5,000-item optimization runs.
Hint 2
Achieve solver determinism by bounding execution using deterministic solver time units rather than wall-clock time, and fixing the thread count and random seed.
Hint 3
Use a canonical input hash (covering items, rules, and seeds) combined with database locks to ensure that stale manifest revisions cannot be approved.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Scale & Operational Capacity
Throughput & Calculation Demands
- Request Volume: $15,000 \text{ requests/day} \approx 0.175 \text{ requests/sec (average)}$.
- Peak Surge: Assuming a 10x multiplier during end-of-day cutoffs, the API must handle $\approx 1.8 \text{ incoming job submissions/sec}$.
- Compute Footprint: Assuming an average solve duration of 20 seconds, steady state consumes ~3.5 continuous worker cores. Sizing for 100 concurrent burst runs requires an autoscaling pool of up to 100 dedicated worker instances.
- Payload Footprint: Each cargo item record averages ~1 KB. Standard manifests (500 items) total ~0.5 MB; large manifests (5,000 items) total ~5 MB.
- Storage Tiering: Raw manifest payloads and output assignment trees are stored in Object Storage (S3). Relational metadata, status flags, state hashes, and locking tables live in PostgreSQL.
2. API Design
Endpoints
Submit Planning Request
POST /v1/plans
Content-Type: application/json
Idempotency-Key: 9f8a3c81-1200-4b2a-b0e2-8812c3dfa102
{
"manifest_id": "man_8839102",
"manifest_revision": 3,
"container_catalog_version": "2024.2",
"rule_set_version": "v1.8.4",
"config": {
"seed": 42,
"objective": "MINIMIZE_COST",
"max_deterministic_time": 1000.0
},
"webhook_url": "https://logistics.example.com/hooks/plans"
}
--> 202 Accepted
{
"plan_id": "pln_01J8A2",
"job_id": "job_99812A",
"status": "QUEUED"
}
Poll Execution Progress
GET /v1/jobs/job_99812A
--> 200 OK
{
"job_id": "job_99812A",
"plan_id": "pln_01J8A2",
"status": "RUNNING",
"progress_percentage": 65,
"current_best_cost_usd": 14200.00
}
Fetch Plan Assignments
GET /v1/plans/pln_01J8A2
--> 200 OK
{
"plan_id": "pln_01J8A2",
"version": 1,
"input_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"status": "DRAFT",
"containers": [
{
"container_id": "cnt_slot_1",
"type_id": "40FT_HC",
"volume_utilization": 0.92,
"weight_utilization": 0.81,
"items": ["itm_101", "itm_102"]
}
]
}
Inspect Infeasibility Conflicts
GET /v1/plans/pln_01J8A2/explanation
--> 200 OK
{
"status": "INFEASIBLE",
"conflicts": [
{
"rule_id": "RULE_IMDG_3_5_1",
"description": "Class 3 Flammable Liquids cannot share a container with Class 5.1 Oxidizing Substances",
"conflicting_item_ids": ["itm_402", "itm_911"]
}
],
"unassigned_items": ["itm_402", "itm_911"]
}
Manual Item Override (Dispatcher Action)
POST /v1/plans/pln_01J8A2/moves
If-Match: "version-1"
Content-Type: application/json
{
"item_id": "itm_101",
"source_container_id": "cnt_slot_1",
"destination_container_id": "cnt_slot_2"
}
--> 200 OK (Plan updated to version 2)
--> 409 Conflict (If-Match tag mismatch)
--> 422 Unprocessable Entity (Violation: "Container slot 2 exceeds payload limit by 420kg")
Approve Final Plan
POST /v1/plans/pln_01J8A2/approve
If-Match: "version-2"
Content-Type: application/json
{
"expected_input_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
--> 200 OK { "status": "APPROVED" }
--> 409 Conflict { "code": "STALE_MANIFEST", "message": "Manifest updated from revision 3 to revision 4" }
--> 409 Conflict { "code": "CARGO_ALREADY_ALLOCATED", "allocated_items": ["itm_101"] }
3. Data Schema
+-----------------------+
| manifest_revision |
+-----------------------+
| manifest_id (PK) |
| revision (PK) |
| content_hash |
+-----------+-----------+
|
| 1:N
v
+-----------------------+ +---------+-------------+
| incompatibility_rule | | cargo_item |
+-----------------------+ +-----------------------+
| rule_id (PK) | | item_id (PK) |
| rule_set_version (PK) | | manifest_id |
| selector_a (JSON) | | revision |
| selector_b (JSON) | | weight, volume |
| scope (CONTAINER/ADJ) | | imdg_class, is_reefer |
+-----------------------+ +-----------+-----------+
|
| 1:N
v
+-----------------------+ +-----------+-----------+
| container_spec | | plan_assignment |
+-----------------------+ +-----------------------+
| type_id (PK) | | plan_id (PK) |
| catalog_version (PK) | | plan_version (PK) |
| max_vol, max_weight | | item_id (PK) |
| is_reefer, unit_cost | | container_slot_id |
+-----------------------+ +-----------+-----------+
^
| N:1
+-----------------------+ |
| audit_event | +-----------+-----------+
+-----------------------+ | plan |
| seq (PK) | +-----------------------+
| plan_id | | plan_id (PK) |
| actor, event_type |---| manifest_id |
| payload_hash | | manifest_revision |
| prev_sig, signature | | input_hash |
+-----------------------+ | version (OCC) |
+-----------------------+
PostgreSQL DDL Strategy
-- Manifest Revisions (Immutable)
CREATE TABLE manifest_revision (
manifest_id VARCHAR(64) NOT NULL,
revision INT NOT NULL,
content_hash VARCHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (manifest_id, revision)
);
-- Plans (State Tracking & OCC)
CREATE TABLE plan (
plan_id VARCHAR(64) PRIMARY KEY,
manifest_id VARCHAR(64) NOT NULL,
manifest_revision INT NOT NULL,
input_hash VARCHAR(64) NOT NULL,
version INT NOT NULL DEFAULT 1,
status VARCHAR(32) NOT NULL CHECK (status IN ('DRAFT', 'APPROVED', 'SUPERSEDED', 'INFEASIBLE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
FOREIGN KEY (manifest_id, manifest_revision) REFERENCES manifest_revision(manifest_id, revision)
);
-- Active Cargo Commitments (Double-Allocation Guard)
CREATE TABLE item_allocation (
item_id VARCHAR(64) PRIMARY KEY,
approved_plan_id VARCHAR(64) NOT NULL,
allocated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
FOREIGN KEY (approved_plan_id) REFERENCES plan(plan_id)
);
4. System Architecture
+----------------------+
| Client / UI |
+----------+-----------+
|
v
+----------------------+
| API Gateway |
+----------+-----------+
|
v
+----------------------+
| Plan Core Service | <---> [ PostgreSQL ]
+----------+-----------+
|
+----------------+----------------+
| (Transactional Outbox Pattern) |
v v
+---------------------------+ +---------------------------+
| Standard Queue (SQS) | | Heavy Jobs Queue (SQS) |
| (Manifests <= 500 items) | | (Manifests > 500 items) |
+-------------+-------------+ +-------------+-------------+
| |
v v
+---------------------------+ +---------------------------+
| Standard Worker Pool | | High-Memory Worker Pool |
| (CP-SAT Solver) | | (CP-SAT Solver) |
+-------------+-------------+ +-------------+-------------+
| |
+----------------+----------------+
| Writes Results & Plans
v
+-------------------+
| AWS S3 Blob Store |
+-------------------+
Async Task Processing
- Outbox Pattern: Creation of a plan persists a record to PostgreSQL and emits an Outbox message in a single database transaction, ensuring zero job loss.
- Queue Separation: Standard workloads ($\le 500$ items) execute on high-throughput queue lanes; large batch jobs (up to 5,000 items) execute on isolated lanes to prevent head-of-line blocking.
- Execution Caching: The API computes
input_hash= SHA-256(manifest_items+rules_version+container_catalog+seed+solver_version). Duplicate requests hit the PostgreSQL metadata cache and immediately return stored solution blueprints.
5. Solver Engine & Constraint Formulation
The underlying packing engine models bin packing with incompatibility graphs using Constraint Programming (Google OR-Tools CP-SAT).
Mathematical Formulation
- Sets: Items $I$, Container Types $K$, Container Slots $J$.
- Variables:
- $x_{i,j} \in {0, 1}$: Item $i$ assigned to slot $j$.
- $u_j \in {0, 1}$: Slot $j$ is activated.
- Objective: $$\min \sum_{j \in J} \text{Cost}(type(j)) \cdot u_j$$
- Constraints:
- Full Assignment: $\sum_{j} x_{i,j} = 1 \quad \forall i \in I$.
- Volume Limit: $\sum_{i} \text{Vol}i \cdot x{i,j} \le \text{MaxVol}(type(j)) \cdot u_j \quad \forall j$.
- Mass Limit: $\sum_{i} \text{Mass}i \cdot x{i,j} \le \text{MaxMass}(type(j)) \cdot u_j \quad \forall j$.
- Material Incompatibility: For any conflicting item pair $(a, b) \in \text{Conflicts}$: $$x_{a,j} + x_{b,j} \le 1 \quad \forall j$$
- Reefer Requirement: If $\text{NeedsReefer}(i) = \text{true}$, then $x_{i,j} = 0$ for non-reefer slots $j$.
Ensuring Absolute Determinism
- Deterministic Time Limit: Configure CP-SAT with
max_deterministic_time(ticks based on solver work units), avoiding non-deterministic wall-clock timers. - Fixed Thread Allocation: Lock search worker thread counts (e.g.,
num_search_workers: 8in deterministic mode). - Canonical Sorting: Sort all input vectors lexicographically by UUID before constructing the model.
6. Concurrency, Race Conditions & Stale Approvals
Dispatcher Action Database Transaction (Plan Approval)
|
v
+---------------------------+
| POST /plans/{id}/approve |
| If-Match: "version-2" |
+-------------+-------------+
|
v
+---------------------------------------------------------------------------------------+
| BEGIN TRANSACTION; |
| |
| 1. SELECT current revision FROM manifest WHERE manifest_id = plan.manifest_id; |
| IF current_revision != plan.manifest_revision THEN |
| ROLLBACK; Return 409 STALE_MANIFEST; |
| END IF; |
| |
| 2. SELECT item_id FROM item_allocation WHERE item_id IN (...plan_items...) |
| FOR UPDATE; |
| IF any items found THEN |
| ROLLBACK; Return 409 CARGO_ALREADY_ALLOCATED; |
| END IF; |
| |
| 3. INSERT INTO item_allocation (item_id, approved_plan_id) VALUES (...); |
| 4. UPDATE plan SET status = 'APPROVED', version = version + 1 WHERE plan_id = ... ; |
| |
| COMMIT; |
+---------------------------------------------------------------------------------------+
Handling Modifications and Race Conditions
- Manual Edits (Optimistic Concurrency Control): Updates pass an
If-Match: "version-N"header. The update checksWHERE version = Nand increments to $N+1$. If another operator committed an edit first, a409 Conflicterror is returned. - Stale Manifest Prevention: During plan approval, the transactional block validates that the
manifest_revisiontied to the plan matches the latestmanifest_revisionrecorded for that manifest ID. - Double Allocation Prevention: The database table
item_allocationholds a Primary Key constraint onitem_id. During approval, inserting already-allocated items triggers a primary key collision, aborting the transaction and preventing double allocation.
7. Actionable Infeasibility Strategy
When a solver run determines a manifest cannot be legally loaded, returning a generic error is insufficient for human dispatchers.
+--------------------------------------------------------------------+
| Solver Returns INFEASIBLE |
+--------------------------------------------------------------------+
|
v
+--------------------------------------------------------------------+
| Activate Slack / Assumption Variables |
| - Add slack binary variable s_i to assignment constraint for |
| item i: sum(x_i,j) + s_i = 1 |
| - Add penalty term to objective: MIN sum(cost) + M * sum(s_i) |
+--------------------------------------------------------------------+
|
v
+--------------------------------------------------------------------+
| Solve Relaxation Model |
| - Determines unplaceable items (where s_i = 1) |
+--------------------------------------------------------------------+
|
v
+--------------------------------------------------------------------+
| Compute Minimal Unsatisfiable Subset (MUS) |
| - Extract conflict graph induced by unplaceable items |
| - Map items to specific rule IDs (e.g. IMDG_3_5_1) |
+--------------------------------------------------------------------+
|
v
+--------------------------------------------------------------------+
| Return Conflict JSON to User |
+--------------------------------------------------------------------+
Explanatory Feedback Loop
- Relaxation Solve: Introduce slack variables $s_i \in {0, 1}$ for each item's mandatory placement constraint. Assign a high penalty cost $M$ to non-zero slack variables.
- Conflict Subgraph Extraction: Run an iterative QuickXPlain or Minimal Unsatisfiable Subset (MUS) extraction routine over the relaxed model to find the smallest set of conflicting constraints.
- Structured Explanation: Map the resulting minimal subset back to specific business and regulatory rules (e.g., "Item A and Item B conflict under Rule IMDG 3.2"), allowing the user to remove or reclassify specific cargo.