Prompt
How do I build a shipping service that supports multiple carriers?
Latest observation
To build a shipping service that supports multiple carriers, design it as an abstraction layer over carrier-specific APIs so your app can work with a common shipping model while each carrier is handled by an adapter.
1) Define your core shipping workflow
At minimum, support:
- Rate shopping: get shipping options and prices
- Label purchase: create shipment and buy label
- Tracking: poll or receive tracking updates
- Void/cancel: cancel labels when possible
- Address validation: optional but very useful
- Pickup / manifesting: optional depending on carrier
- Returns: if you need reverse logistics
2) Create a canonical data model
Normalize all carrier data into your own internal structures.
Example core objects:
AddressPackageShipmentRateQuoteLabelTrackingEventCarrierAccount
Your model should include common fields like:
- shipper/recipient address
- package weight and dimensions
- service level
- declared value / insurance
- shipping date
- signature required
- tracking number
- label format (PDF/ZPL/EPL)
Keep carrier-specific fields in a separate metadata map so you don’t lose data.
3) Use a provider/adapter pattern
Implement one adapter per carrier:
FedExAdapterUPSAdapterUSPSAdapterDHLAdapter- etc.
Each adapter implements the same interface, for example:
interface ShippingCarrier {
getRates(request: RateRequest): Promise<RateQuote[]>;
createShipment(request: ShipmentRequest): Promise<ShipmentResult>;
getTracking(trackingNumber: string): Promise<TrackingInfo>;
voidShipment(shipmentId: string): Promise<void>;
validateAddress(address: Address): Promise<AddressValidationResult>;
}
Your application calls the interface, not the carrier directly.
4) Build a carrier selection layer
Add logic to decide which carrier/service to use based on:
- cheapest rate
- fastest delivery
- destination country/zone
- package weight/size limits
- service reliability
- business rules
- negotiated account rates
- customer preferences
A “rating engine” can rank options and choose one automatically.
5) Normalize rate responses
Carriers return rates differently. Convert them into a common format:
- carrier name
- service code
- service display name
- transit time estimate
- cost
- currency
- delivery promise/date
- surcharges/fuel fees
- special restrictions
Example normalized rate:
{
"carrier": "UPS",
"serviceCode": "GROUND",
"serviceName": "UPS Ground",
"price": 12.45,
"currency": "USD",
"estimatedDays": 3,
"deliveryDate": "2026-01-08"
}
6) Handle label generation carefully
Different carriers support different label formats and APIs. Your system should:
- request the label format you need
- store both the raw carrier response and normalized result
- support reprinting
- support multiple label sizes if needed
- handle async label creation if carrier processing is delayed
Store:
- label URL or blob
- tracking number
- shipment ID
- raw response payload
- print format metadata
7) Tracking architecture
Tracking can be implemented by:
- polling carrier APIs on a schedule
- webhooks/events if the carrier supports them
- a hybrid approach
Best practice:
- store current tracking state
- keep event history
- deduplicate updates
- map carrier statuses into internal statuses like:
createdin_transitout_for_deliverydeliveredexceptionreturnedvoided
8) Make the integration resilient
Carrier APIs can be unreliable. Use:
- retries with exponential backoff
- timeouts
- circuit breakers
- idempotency keys
- request logging and correlation IDs
- dead-letter queues for failed async jobs
Also cache:
- rate results briefly
- service availability
- address validation results if allowed
9) Support asynchronous processing
Shipping operations often don’t need to be fully synchronous.
Use jobs/queues for:
- label generation
- tracking refresh
- manifests
- webhook processing
- reconciliation
This improves reliability and helps with carrier downtime.
10) Account and credential management
Each carrier usually needs:
- API key / OAuth credentials
- account number
- sandbox vs production config
- billing or meter number
- ship-from locations
Store credentials securely:
- encrypted at rest
- secret manager or vault
- per-tenant isolation if multi-tenant
- role-based access control
11) Add error normalization
Each carrier has its own error schema. Convert errors into standardized categories:
- invalid address
- service unavailable
- account issue
- package exceeds limits
- authentication failure
- rate limited
- label creation failed
This makes your frontend and business logic much simpler.
12) Testing strategy
You’ll want:
- unit tests for your normalization logic
- contract tests per carrier adapter
- integration tests against sandbox accounts
- mocked responses for edge cases
- regression tests for label formats and tracking status mapping
13) Consider using a shipping aggregator
If you want to move faster, use an aggregator like:
- Shippo
- EasyPost
- ShipEngine
These provide one API for multiple carriers, which reduces integration effort. You can still keep your own abstraction so you can swap providers later.
14) Suggested architecture
A simple layout:
- API layer: your app endpoints
- Shipping domain service: business rules and orchestration
- Carrier adapters: one per carrier or aggregator
- Rate engine: chooses best option
- Job queue: background tasks
- Database: shipments, rates, labels, tracking events
- Webhook service: carrier callbacks
- Admin tools: debugging, re-sync, label reprint
15) Practical implementation tips
- Start with 1–2 carriers and a small feature set
- Build the canonical model before writing adapters
- Keep raw carrier payloads for debugging
- Make service codes configurable, not hardcoded
- Track every label lifecycle state
- Design for partial failures and retries
- Document carrier-specific quirks in code comments or runbooks
Minimal interface example
type CarrierName = "UPS" | "FedEx" | "USPS";
interface ShippingService {
getRates(request: RateRequest): Promise<RateQuote[]>;
purchaseLabel(request: ShipmentRequest): Promise<ShipmentResult>;
track(trackingNumber: string): Promise<TrackingInfo>;
cancel(shipmentId: string): Promise<void>;
}
Recommended build order
- Define canonical shipment and rate models
- Implement one carrier adapter end-to-end
- Add rate shopping
- Add label purchase
- Add tracking updates
- Add error handling and retries
- Add more carriers
- Add automation and optimization rules
If you want, I can also sketch:
- a database schema,
- a REST API design,
- or a sample implementation in Node.js, Python, or Java.