Prompt
How do I build a carrier-agnostic shipping layer for our app?
Latest observation
A good carrier-agnostic shipping layer is basically an internal shipping domain model + adapter layer that hides UPS/FedEx/DHL/etc. differences from the rest of your app.
1) Start with a canonical model
Define your own internal objects and workflows first. Don’t let carrier APIs drive your app design.
Common core entities:
- Shipment: who/where/what is being shipped
- Package: weight, dimensions, contents, hazmat flags, etc.
- Service level: ground, express, overnight, economy
- Rate quote: price, transit time, surcharges, delivery estimate
- Label: shipping label artifact + tracking number
- Tracking event: scan updates and status history
- Pickup / manifest / return shipment if you need them
Example canonical shipment:
{
"shipment_id": "shp_123",
"shipper": { "name": "Acme", "address": { "country": "US", "postal_code": "94107" } },
"recipient": { "name": "Jane", "address": { "country": "US", "postal_code": "10001" } },
"packages": [
{ "weight": 2.4, "weight_unit": "lb", "dimensions": { "l": 10, "w": 8, "h": 4, "unit": "in" } }
],
"service_level": "GROUND",
"options": { "signature_required": true, "insurance_value": 100 }
}
2) Put a provider interface in front of carriers
Create a common interface with the operations your app needs. For example:
getRates(shipment)purchaseLabel(shipment, selectedRate)voidLabel(labelId)track(trackingNumber)createPickup(...)validateAddress(address)(optional)
The app should call only this interface; each carrier implementation translates to/from the carrier’s API.
3) Use adapters for each carrier
Build one adapter per carrier:
UpsAdapterFedexAdapterDhlAdapterUspsAdapter
Each adapter handles:
- auth / token refresh
- carrier-specific field mapping
- API quirks
- error translation
- retries / idempotency nuances
Keep carrier-specific logic isolated so adding a new carrier doesn’t touch the whole app.
4) Normalize rates and services
Carriers use different names and structures for similar services. Normalize them into your own service taxonomy.
Example:
- Carrier:
UPS Ground/FedEx Ground→ Canonical:GROUND - Carrier:
2Day AM/Express Saver→ Canonical:EXPRESS_2DAY
Store both:
- canonical service code for your app
- raw carrier service code for execution
5) Design for incomplete parity
Not every carrier supports every feature.
Plan for:
- optional capabilities per carrier
- graceful degradation
- feature flags
Example:
- Carrier A supports Sunday delivery, Carrier B doesn’t
- Carrier C supports label voiding within 24h, Carrier D doesn’t
Expose capabilities like:
{
"carrier": "UPS",
"supports": {
"rates": true,
"labels": true,
"voids": true,
"pickup": false,
"returns": true
}
}
6) Standardize errors
Translate carrier-specific error responses into your own error types:
INVALID_ADDRESSRATE_UNAVAILABLESERVICE_NOT_SUPPORTEDAUTH_FAILEDLABEL_PURCHASE_FAILEDTRACKING_NOT_FOUNDCARRIER_TIMEOUT
This makes UI and business logic much simpler.
7) Keep carrier raw payloads for auditing
Even if you normalize everything, persist:
- raw request payload
- raw response payload
- correlation IDs
- timestamps
- chosen carrier and service
This helps with debugging, compliance, and chargeback disputes.
8) Build idempotency in from the start
Label purchases and shipment creation should be idempotent:
- use a request id / idempotency key
- dedupe retries
- ensure you don’t buy duplicate labels if a timeout happens
This is especially important for carrier APIs that may succeed even when your app times out.
9) Make rate shopping a separate service
If you compare multiple carriers, create a dedicated “rate shopping” step:
- Normalize shipment
- Query eligible carriers in parallel
- Normalize results
- Rank by cost, ETA, service constraints, business rules
- Present best options or auto-select
You can rank by:
- cheapest
- fastest
- cheapest within SLA
- preferred carrier
- historical reliability
10) Consider a provider-agnostic shipping abstraction library vs. SaaS
You have two paths:
Build it yourself
Pros:
- full control
- custom workflows
- lower per-label vendor dependence
Cons:
- more engineering effort
- ongoing carrier API maintenance
Use an aggregator
Examples: Shippo, EasyPost, Sendcloud, etc.
Pros:
- faster time to market
- one API for many carriers
- less carrier maintenance
Cons:
- vendor lock-in to aggregator
- less control over edge cases/costs
- sometimes limited feature parity
Many teams start with an aggregator, then later carve out a thinner internal abstraction so the rest of the app stays portable.
11) Suggested architecture
A practical layering:
UI / API → Shipping domain service → Carrier selection / rules engine → Provider adapter interface → Carrier-specific adapters → Carrier APIs
Supporting components:
- rate cache
- label store
- tracking event processor
- webhook receiver
- observability/logging
12) Example TypeScript-style interface
interface ShippingProvider {
getRates(shipment: Shipment): Promise<RateQuote[]>;
createLabel(shipment: Shipment, rateId: string): Promise<LabelResult>;
voidLabel(labelId: string): Promise<void>;
track(trackingNumber: string): Promise<TrackingStatus>;
getCapabilities(): ProviderCapabilities;
}
13) Common pitfalls
- Designing directly around one carrier’s API
- Not separating rate shopping from label purchase
- Ignoring timezone/measurement unit differences
- No idempotency for label creation
- Not persisting raw carrier payloads
- Assuming all carriers support the same options
- Weak webhook retry handling for tracking updates
14) Practical implementation plan
- Define canonical shipment/rate/label/tracking models
- Define provider interface + error model
- Build one carrier adapter end-to-end
- Add normalization and capability detection
- Add idempotency + audit logging
- Add rate shopping and ranking
- Add more carriers behind the same interface
- Build tests with recorded carrier responses and contract tests
If you want, I can also provide:
- a concrete DB schema for this layer,
- a TypeScript or Python reference implementation,
- or a carrier capability matrix template.