Unified Shipping Platform Across Several Courier Services
System DesignModel answerLast updated
Design a backend that lets a retailer rate, buy labels, and track parcels across multiple couriers behind a single internal API, with safe retries and fault isolation.
Problem
An online retailer ships millions of parcels a day from many warehouses and wants one internal shipping platform that sits in front of several external couriers (think national postal services and large private express companies). Each courier has its own API style, authentication, address rules, service names, and tracking codes.
Design the platform so that order-management systems and warehouse tooling interact with a single, consistent interface.
Capabilities required
- Register a shipment for an order, including origin and destination addresses and one or more packages (weight, dimensions, declared value).
- Pick a courier and service level, either explicitly or automatically based on a rule such as "cheapest option that still meets the promised delivery date".
- Buy postage and produce a printable label with a tracking number.
- Follow the parcel from creation to final delivery, including failure and exception outcomes.
- Cancel a label before the parcel is picked up.
- Hide courier-specific differences behind a uniform API and a normalized status model.
What to cover in your answer
- Assumptions, scope clarifications, and a rough capacity estimate.
- The main internal APIs.
- The data model and your storage choices.
- The main components and how courier integrations are structured.
- Reliability and scalability: retries, duplicate prevention, courier outages, rate limits, and high-volume tracking updates.
- Key trade-offs and what you would do differently as the system grows.
Assume peak load of several hundred label purchases per second and thousands of tracking updates per second.
Hints
Hint 1
Label purchase costs real money, so think about what happens when a courier call times out after charging you. How do you avoid buying twice?
Hint 2
Define a common adapter interface per courier (rate, purchase, void, track, parse webhook) and a canonical status enum so the rest of the system never sees courier-specific codes.
Hint 3
Separate the write path that must stay available (label purchase) from the high-volume ingest path (tracking events), and decide where queues, caches, and circuit breakers belong.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions
Functional: create a shipment, get rates from several couriers, select one (manually or by strategy), buy a label, track to delivery, void before pickup, and publish status changes to downstream systems.
Non-functional:
- No duplicate purchases. A label is a paid resource.
- High availability for label creation. Packing lines stop if labels cannot print.
- Fault isolation. One slow courier must not degrade the others.
- Extensibility. A new courier is a new plug-in, not a redesign.
Rough scale: about 5M shipments/day (about 15M at peak season), so around 60 purchases/s on average and roughly 600/s at peak. With about 3 couriers quoted per shipment, that is around 2k outbound courier calls/s at peak. With roughly 8 tracking events per parcel, that is 40-120M events/day and a peak near 5k/s. Labels at about 50 KB each add up to several hundred GB/day in object storage. Tracking ingest dominates volume; label purchase dominates correctness risk.
2. Internal API
POST /v1/shipments(withIdempotency-Key): order id, addresses, packages, service preference, ship-by date. Returnsshipment_idand statusCREATED.GET /v1/shipments/{id}/rates: list of{rate_id, carrier, service, cost, est_delivery, expires_at}.POST /v1/shipments/{id}/purchase(withIdempotency-Key): body is either arate_idor a strategy such asCHEAPEST_MEETING_SLA. Returns tracking number, label URL, cost.POST /v1/shipments/{id}/void.GET /v1/shipments/{id}andGET /v1/tracking/{tracking_number}.POST /v1/carriers/{carrier}/webhookfor inbound courier pushes.
Downstream systems subscribe to a shipment.status_changed topic instead of polling.
3. Data model and storage
- Shipment: id, order id, addresses, status, carrier, service, tracking number, label URL, cost, idempotency key (unique),
versionfor optimistic locking, timestamps. - Package: weight, dimensions, declared value.
- RateQuote: carrier, service, amount, estimated delivery, expiry. Short TTL.
- TrackingEvent: dedupe key
(tracking_number, event_time, carrier_event_id), normalized status, raw code, location, raw payload. - CarrierConfig: vault-referenced credentials, account numbers, enabled services, rate limits, status-code mapping.
Storage:
- Shipments in a relational database sharded by
shipment_id, because state transitions are transactional and need unique constraints. - Tracking events in a write-optimized wide-column or time-series store partitioned by tracking number.
- Label files in object storage, served through signed URLs.
4. Architecture
Requests enter through an API gateway to a Shipment Service that owns the state machine: CREATED -> RATED -> PURCHASING -> LABEL_PURCHASED -> IN_TRANSIT -> OUT_FOR_DELIVERY -> DELIVERED, with EXCEPTION, RETURNED, LOST, VOIDED, and PURCHASE_UNKNOWN as side states.
- Rating Service: fans out to eligible couriers in parallel with a tight deadline (1-2 s), returns what arrived in time, and caches quotes for identical lane/weight/service combinations for a few minutes. A rules layer applies business constraints such as contract allocations, hazmat limits, PO-box restrictions, and delivery-date promises.
- Label Service: executes purchases and stores documents.
- Carrier Gateway: one adapter per courier implementing a shared interface (
rate,purchase,void,track,parseWebhook). Adapters own authentication, protocol (REST or SOAP), unit and address conversion, and mapping courier codes to the canonical status enum. This is where heterogeneity is contained. - Tracking Service: ingests pushes and polls, normalizes, dedupes, updates shipment state, and emits events.
5. Deep dives
Idempotent purchase
The classic failure is a timeout after the courier already charged you, followed by a retry that buys a second label.
- The client supplies an idempotency key; a unique constraint returns the stored result on repeats.
- Move the shipment
RATED -> PURCHASINGusing a version check so only one worker proceeds. - Send a deterministic customer reference (the shipment id) to the courier so the purchase can be looked up later.
- On timeout or 5xx, do not retry blindly. Mark
PURCHASE_UNKNOWNand let a reconciler query the courier by reference: adopt the label if it exists, otherwise retry. - A nightly job compares courier invoices with the database and voids orphaned labels.
Tracking ingestion
- Webhook endpoints verify signatures, write the raw payload to a log (Kafka), and return 200 immediately. A normalizer consumes the raw topic, maps codes, dedupes on the event key, writes to the event store, and publishes a status-changed event.
- For couriers without push, a scheduler polls active shipments with adaptive frequency (less often in transit, more often near delivery, stop a few days after delivery) and batches where the courier allows it.
- Handle out-of-order events by comparing event time and only moving status forward along the lifecycle, while still storing every event.
Courier isolation and rate limits
- Per-courier circuit breakers, timeouts, bulkheaded thread pools or queues, and token-bucket rate limiters sized to each contract.
- If a courier is degraded, the rules layer drops it from selection and uses the next best option; purchases already assigned to that courier queue with backoff.
- Label purchase is the only synchronous critical path. Everything else (notifications, analytics, invoices) hangs off events.
Scalability
- Stateless services scale horizontally; the database is sharded by shipment id; Kafka is partitioned by tracking number so per-parcel ordering is preserved.
- Cache rates and address validation results; keep labels out of the database.
- Run active-active across regions for the purchase path, with the idempotency store being the single source of truth per shard.
6. Trade-offs and common mistakes
- Synchronous vs queued purchase: synchronous is simpler and fits the packing-line workflow; fall back to async with a "label pending" state when a courier is slow.
- Webhooks vs polling: webhooks are cheaper and faster but unreliable; keep a slow polling safety net for lost pushes.
- Mistakes to avoid: retrying purchases without a reference lookup, leaking courier status codes into the public API, using one shared client pool for all couriers, ignoring quote expiry, and storing label binaries in the transactional database.
7. Follow-ups worth preparing
Multi-package shipments, returns labels, international customs documents, address validation, cost allocation and invoice reconciliation, and adding a courier without redeploying (config-driven mapping tables plus a versioned adapter).