Multi-Vendor Order Fulfillment System
System DesignModel answerLast updated
Design a service that queries multiple vendor APIs concurrently, selects the best offer within constraints, and coordinates payment with order placement.
You're building a service that helps customers find and complete purchases across multiple third-party vendors. When a customer wants to buy a product, your system checks which vendors have it in stock, compares prices, and completes the transaction with the vendor offering the best deal.
Your Task
Design an order fulfillment broker that:
- Queries multiple vendors concurrently to find availability and pricing for a requested product
- Selects and purchases from the optimal vendor based on price constraints and a time window
- Coordinates payment authorization and capture to ensure money moves only when the vendor confirms the order
- Handles failures gracefully: network timeouts, vendor outages, partial responses, and ambiguous states
Functional Scope
Your API should accept:
- Product identifier, quantity, maximum acceptable price per unit, and request timeout
- Return an order identifier immediately and process asynchronously
Your system must:
- Support status queries for in-flight orders
- Prevent duplicate purchases if a vendor request times out and retries
- Maintain an audit trail of vendor responses and state transitions
Constraints
- 10–15 vendor integrations, each with different response times and reliability
- Peak load: hundreds of purchase requests per second
- Timeout window: 5 seconds to 5 minutes
- A purchase at one vendor must never result in charging the customer twice or buying from two vendors
What to Cover
- API contracts and workflow orchestration
- State management and transitions
- How you ensure exactly-once purchase semantics
- Database schema and storage strategy
- Failure modes and recovery mechanisms
Hints
Hint 1
Think about the difference between attempting a vendor API call and knowing its outcome—timeouts create ambiguity
Hint 2
Payment authorization before purchase and capture after confirmation creates a two-phase commit across systems
Hint 3
An outbox pattern ensures state changes and their side effects (notifications, vendor calls) stay consistent
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Multi-Vendor Order Fulfillment: Model Answer
This problem tests distributed transaction orchestration across systems you don't control. A strong solution centers on a durable state machine, idempotent operations at every boundary, and a choreography that sequences payment steps so funds move only after the vendor commits.
1. Clarifying Questions and Assumptions
Start by establishing scale and semantics:
- Volume: ~300 orders/sec peak, 12 vendors average → ~3,600 vendor queries/sec. With retries and polling during the timeout window, provision for 8–10k outbound requests/sec.
- Fulfillment: one vendor fulfills the entire quantity (not split across multiple). Mention order splitting as a future enhancement.
- Payment flow: assume authorize/capture/void model. Authorization holds funds; capture completes the charge; void releases an unused hold.
- Price constraint: maximum price is per-unit, single currency.
- Audit requirements: ~12k events/sec × 1 KB ≈ 12 MB/sec sustained, roughly 1 TB/day. Store append-only in a log system, not the primary database.
2. API Design
POST /v1/orders
Headers: Idempotency-Key: <uuid>
Body: {
"product_id": "ISBN-9780262046305",
"quantity": 2,
"max_unit_price": 4500,
"currency": "USD",
"timeout_ms": 30000,
"payment_method": "pm_xyz",
"webhook_url": "https://client.example/webhooks"
}
→ 202 Accepted
{
"order_id": "ord_abc123",
"status": "PENDING",
"expires_at": "2026-11-04T10:15:30Z"
}
GET /v1/orders/{order_id}
→ {
"order_id": "ord_abc123",
"status": "COMPLETED",
"vendor": "vendor_b",
"unit_price": 4199,
"total": 8398,
"timeline": [...]
}
POST /v1/orders/{order_id}/cancel
(only valid while status is PENDING or POLLING)
- Idempotency-Key ensures repeated submissions with identical parameters return the same order.
- Webhooks deliver status changes; clients can also poll GET.
- Status updates include enough detail to debug without exposing raw vendor responses.
3. Data Schema
orders (PostgreSQL primary store)
| Column | Purpose |
|---|---|
| order_id (PK) | derived from idempotency key |
| customer_id, product_id, quantity | request parameters |
| max_unit_price, currency, expires_at | constraints |
| status, version | state machine + optimistic lock |
| selected_vendor_id, quote_id | winning bid |
| final_unit_price, payment_auth_id | fulfillment details |
| vendor_order_ref | vendor's confirmation ID |
| created_at, updated_at |
vendor_requests
Tracks every purchase attempt per vendor to enforce exactly-once:
| Column | Notes |
|---|---|
| order_id, vendor_id (composite key) | one purchase attempt per vendor |
| idempotency_token | unique token for vendor API |
| status | INITIATED, SUCCESS, FAILED, UNKNOWN |
| request_at, response_at | timing |
| vendor_order_ref | returned by vendor |
Unique constraint (order_id, vendor_id) prevents double-purchasing.
event_outbox
Transactional outbox for async tasks:
| Column | Notes |
|---|---|
| id (PK), order_id | event identity |
| event_type | VENDOR_QUERY, PAYMENT_AUTH, etc. |
| payload (JSONB) | parameters for worker |
| published | null until consumed |
audit_log (Kafka → S3 / data warehouse)
All vendor interactions, latencies, request/response bodies, state transitions. Keyed by order_id, partitioned by date.
4. Architecture
Client
↓
Load Balancer
↓
API Service (stateless, multi-AZ)
↓ writes order + outbox events atomically
PostgreSQL (primary + replicas)
↓ outbox relay process
Message Queue (SQS / Kafka)
↓
Orchestrator Workers
├→ Vendor Adapters (connection pools, circuit breakers)
├→ Payment Service (auth/capture/void)
└→ Notification Service (webhooks)
↓
Audit Stream → S3 / ClickHouse
- API tier validates input, writes to database, returns 202. Never calls vendors synchronously.
- Orchestrator drives the saga. Options: managed workflow engine (Temporal, Step Functions) or custom workers with DB-backed state.
- Vendor adapters normalize heterogeneous APIs, enforce per-vendor timeouts (e.g., 500ms), rate limits, and bulkheads so one slow vendor doesn't exhaust threads.
- Outbox relay polls the outbox table and publishes events, ensuring state changes and their side effects commit together.
5. State Machine and Workflow
PENDING → POLLING → AUTHORIZED → PURCHASING → CONFIRMED → COMPLETED
↓ ↓ ↓ ↓ ↓
└─────────┴──────────┴─────────────┴────→ FAILED
↓
COMPENSATING → REFUNDED
Step-by-step flow:
-
PENDING: Order persisted. Schedule deadline timer. Transition to POLLING.
-
POLLING: Fan out quote requests to all vendors concurrently with short timeouts (500ms).
- Collect responses: price, availability, estimated delivery.
- Select the vendor with the lowest price ≤ max_unit_price. Tie-break by vendor reliability score.
- If no vendor qualifies yet and time remains before
expires_at, retry with exponential backoff. - If deadline passes without a valid quote → FAILED (EXPIRED).
-
AUTHORIZED: Place a payment authorization hold for
quantity × selected_price.- If authorization fails (insufficient funds, card declined) → FAILED (PAYMENT_DECLINED).
- Authorization is fast to void and guarantees we can pay when the vendor ships.
-
PURCHASING: Submit purchase order to the selected vendor with a deterministic idempotency token
hash(order_id || vendor_id).- Insert row into
vendor_requestsfirst. Unique constraint prevents duplicate calls. - If vendor confirms → CONFIRMED.
- If vendor rejects (out of stock, price changed) → void the auth, pick next-best quote if time allows, else FAILED.
- If timeout or network error → COMPENSATING (ambiguous state).
- Insert row into
-
CONFIRMED: Vendor has committed. Capture the payment authorization.
- If capture succeeds → COMPLETED.
- If capture fails → COMPENSATING (must cancel vendor order and refund/void).
-
COMPENSATING: Entered on capture failure or ambiguous purchase timeout.
- Cancel the vendor order.
- Void or refund the payment.
- End in REFUNDED or FAILED with detailed reason.
All transitions use optimistic locking (UPDATE orders SET status = ?, version = version + 1 WHERE order_id = ? AND version = ?), ensuring duplicate queue messages become no-ops.
6. Handling the Ambiguous Timeout
This is the crux of idempotency. If the purchase call to vendor_b times out, we do not know if it succeeded.
- Never fail over to another vendor. That's how you buy twice.
- Move to COMPENSATING and retry the same vendor with the same idempotency token. A well-behaved vendor returns the original result.
- If the vendor doesn't support idempotency tokens, query its order status API using our reference.
- If still unresolved, mark UNKNOWN and schedule a reconciliation job that checks again in 5 minutes, then cross-references settlement reports.
- The timeout window (
timeout_ms) governs the polling phase, not resolution of an in-flight purchase.
7. Key Design Decisions and Trade-offs
Authorize-then-buy-then-capture vs. charge-then-buy:
- Auth-then-buy prevents "ordered but can't pay." The cost is higher payment processing fees and one extra round trip. For high-value items, the safety is worth it.
Saga orchestration: managed workflow vs. custom:
- Temporal or Step Functions provide durable timers, retries, and visibility out of the box but add operational complexity.
- Custom implementation uses database state, message queues, and worker pools—more code, but fewer dependencies.
Synchronous fan-out vs. async polling:
- Async keeps the API fast and decouples request acceptance from vendor latency. Clients must handle webhooks or poll.
- For low-latency use cases (timeout < 2s), consider synchronous fan-out with aggressive timeouts and fallback to async if any vendor is slow.
Audit log storage:
- Writing audit events through Kafka keeps the transactional database fast and isolates analytics load.
- Trade-off: small risk of losing an audit event if the process crashes between DB commit and Kafka publish. Mitigate by also writing audit events to the outbox.
Vendor reliability scoring:
- Track historical success rate, p95 latency, and stock-out frequency per vendor.
- Use scores to tie-break when prices are equal and to deprioritize flaky vendors in retry logic.
8. Failure Modes and Mitigations
| Failure | Impact | Mitigation |
|---|---|---|
| Vendor API down | Can't get quotes | Circuit breaker; exclude from this request; alert ops if multiple vendors fail |
| Slow vendor | Blocks workers | Per-vendor timeout (500ms); bulkhead thread pools |
| Database unavailable | Can't accept orders | Multi-AZ replicas; fail open with cached status for reads |
| Payment service timeout | Can't authorize | Retry with exponential backoff; if still failing, fail the order |
| Duplicate queue message | Double-purchase risk | Idempotent handlers with optimistic locking and unique constraints |
| Webhook delivery fails | Client misses update | Retry with exponential backoff for 24 hours; client can poll |
9. Scaling Considerations
- Vendor query fan-out: Use connection pools per vendor with concurrency limits. Provision worker capacity for peak load × average vendor count × retry factor (~3×).
- Database hot spots: Partition orders by creation time or hash of order_id if write throughput exceeds single-instance capacity.
- Read replicas: Serve GET /orders/{id} from replicas with 1–2 second lag tolerance.
- Audit log: Stream to Kafka, batch write to S3 in Parquet, load into warehouse for analytics.
Common Mistakes
- Failing over to another vendor after a timeout during PURCHASING → double-buy.
- Capturing payment before vendor confirmation → customer charged for an order that fails.
- Storing audit logs in the primary database → write amplification and query interference.
- No idempotency tokens → retries create duplicate vendor orders.
- Ignoring partial failures (2 of 10 vendors respond) → system appears slow instead of making a decision with available data.
This design ensures correctness through idempotency and a two-phase payment flow, resilience through isolated vendor calls and circuit breakers, and observability through a complete audit trail.