Design a Multi-Vendor Book Aggregator & Automated Ordering Service
System DesignModel answerLast updated
Design an asynchronous system that aggregates quotes across hundreds of vendor APIs to find the best price for an ISBN, places an order within a target bid, and manages payment consistency.
You are tasked with designing the system backend for an automated book procurement platform.
When a user submits a search request containing an ISBN, a maximum bid price, and a payment token, the system must:
- Query hundreds of third-party vendor endpoints to retrieve current price quotes.
- Identify the vendor offering the lowest price.
- If the lowest price is less than or equal to the maximum bid price, immediately place the order and process payment.
- If the lowest price exceeds the maximum bid price, notify the user of the lowest price found.
- If no vendors have stock, inform the user that the item is currently out of stock.
Context & Constraints
- Asynchronous & High Latency Vendors: Downstream vendors respond asynchronously (either via webhook callbacks or non-blocking polling/HTTP streaming), and their latencies vary wildly.
- Scale: High query volume for popular titles.
- Consistency: The system must guarantee that money is never captured without a confirmed vendor order, and books are never ordered without valid payment authorization.
Key Areas to Cover
- Core Architecture & Request Lifecycle: Define client APIs, background workers, event flows, state machine, and data models.
- Downstream Fault Tolerance & Partial Results: Describe timeout handling, circuit breakers, fan-out strategy, and how partial/incomplete quotes affect decision-making.
- Caching & Load Mitigation: Address request coalescing (thundering herd), caching strategies for price quotes, and safe TTL invalidation.
- Transaction Consistency & Idempotency: Detail the step-by-step workflow for charging the payment source and placing downstream vendor orders, including compensation logic for failure scenarios.
Hints
Hint 1
Use an explicit state machine for request lifecycles to handle asynchronous callbacks safely.
Hint 2
Separate payment authorization (hold) from payment capture to eliminate financial risks if downstream fulfillment fails.
Hint 3
Use single-flight request coalescing (e.g., Redis locks or Go singleflight) to prevent thundering herd calls on downstream vendors for popular ISBNs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level System Architecture & Request Flow
+-------------------+
| API Gateway |
+---------+---------+
|
v
+-------------------+
| Procurement Svc |<-------> [ Redis (Cache/Locks) ]
+----+--------+-----+
| |
+------------------+ +------------------+
| |
v v
+---------------+ +---------------+
| Task Dispatcher| | Vendor Router |
+-------+-------+ +-------+-------+
| |
v v
[ Kafka Topic ] [ Vendor APIs 1..N ]
(Fan-Out Jobs) (Async Callback/Poll)
| |
v v
+---------------+ +---------------+
| Quote Aggregator | Callback Svc |
+-------+-------+ +-------+-------+
| |
+------------------+ +------------------+
| |
v v
+-------------------+
| Request Database | (PostgreSQL / DynamoDB)
+-------------------+
API Contracts
Client Request Endpoint
POST /v1/procurement-requests
Content-Type: application/json
{
"isbn": "9780134685991",
"max_bid_cents": 4500,
"currency": "USD",
"payment_method_token": "pm_tok_99218a"
}
Response: 202 Accepted
{
"request_id": "req_88a91bc4",
"status": "PROCESSING",
"poll_interval_ms": 1000
}
Status Polling Endpoint (or Webhook / WebSocket)
GET /v1/procurement-requests/req_88a91bc4
Response (Order Placed):
{
"request_id": "req_88a91bc4",
"status": "COMPLETED",
"outcome": "ORDER_PLACED",
"final_price_cents": 3899,
"vendor_id": "vend_book_depot",
"tracking_reference": "trk_abc123"
}
Request State Machine
+-------------------+
| CREATED |
+---------+---------+
|
v
+-------------------+
| AGGREGATING |
+----+---------+----+
| |
+---------------+ +---------------+
| (Deadline or | (No stock found)
| All Quotes In) v
v +-------------------+
+-------------------+ | OUT_OF_STOCK |
| QUOTES_READY | +-------------------+
+---------+---------+
|
+------+------+
| |
| Lowest > Bid| Lowest <= Bid
v v
+------+ +-------------------+
| BID_ | | RESERVING_PAYMENT|
|EXCEE-| +---------+---------+
| DED | |
+------+ v
+-------------------+
| PLACING_ORDER |
+----+---------+----+
| |
Success | | Failure (Compensation)
v v
+--------+ +-------------------+
|ORDER_ | | PAYMENT_REFUNDED |
|PLACED | | / ORDER_FAILED |
+--------+ +-------------------+
- CREATED: Request recorded; payment token validated.
- AGGREGATING: Fan-out queries sent to vendor adapters.
- QUOTES_READY: Gathering window closed (via strict deadline or receiving quotes from all healthy vendors).
- BID_EXCEEDED: Lowest price exceeds
max_bid_cents. Process terminates; lowest price returned to client. - RESERVING_PAYMENT: Payment authorization (hold) acquired for
lowest_price. - PLACING_ORDER: Call to the chosen vendor's purchase endpoint with idempotency keys.
- ORDER_PLACED: Order confirmed, payment captured.
- ORDER_FAILED / PAYMENT_REFUNDED: Vendor failed to place the order after payment hold; authorization released.
2. Downstream Fan-Out & Fault Tolerance
Fan-Out Strategy & Gathering Window
- Querying 500+ vendors in real-time over HTTP causes high tail latencies.
- We establish a strict deadline window $T_{\text{max}} = 2500\text{ ms}$.
- A dispatcher publishes an event
QuoteQueryRequested{request_id, isbn}to a high-throughput message bus (e.g., Kafka/RabbitMQ). - Vendor worker tasks execute HTTP requests to individual vendors.
Total Vendors (500)
├── Active Circuit Breakers (50 skipped) ──> Ignored immediately
└── Healthy Vendors (450 queried)
├── Responses within T_max (410 received) ──> Used in Aggregation
└── Timeout / Unresponsive (40 dropped) ──> Logged as NO_QUOTE
Circuit Breakers per Vendor
To prevent catastrophic resource exhaustion, each vendor integration is wrapped in a Circuit Breaker pattern (e.g., Resilience4j/Hystrix semantics):
- Closed State: Normal operation.
- Open State: Triggered if error rate > 50% or P95 latency > $3000\text{ ms}$ over a 1-minute sliding window. Requests to this vendor immediately return a cached failure status without network I/O.
- Half-Open State: Periodically allows 1% of probe requests through to evaluate health recovery.
Partial Results & Out-of-Stock Qualifications
- Acceptable Decision Threshold: An aggregation decision is valid if:
- $T_{\text{max}}$ elapses OR all open vendor queries complete.
- At least $M%$ (e.g., 80%) of healthy vendors respond OR at least 1 valid quote $\le \text{bid_price}$ is returned.
- Out-of-Stock Determination:
- If zero vendors report stock, but 30% of vendors timed out or erred, the final status is marked as:
OUT_OF_STOCK_UNCONFIRMED(indicating that not all channels responded). - If $\ge 95%$ of all active vendors return
NO_STOCK, status isOUT_OF_STOCK_CONFIRMED.
- If zero vendors report stock, but 30% of vendors timed out or erred, the final status is marked as:
3. Caching & Load Mitigation
Multi-Level Caching Architecture
Querying downstream vendors for every single request creates severe load and rate-limiting issues. We utilize two caching layers:
+--------------------------+
| Incoming ISBN Quote Req |
+------------+-------------+
|
v
+--------------------------+
| Read Redis Price Cache |
+------------+-------------+
|
+------------------+------------------+
| Cache Hit | Cache Miss
v v
+-----------------------+ +-----------------------+
| Return Cached Quotes | | Singleflight Lock |
| (Validate against TTL)| | (Consolidate Queries) |
+-----------------------+ +-----------+-----------+
|
v
+-----------------------+
| Fan-Out to Vendors |
+-----------------------+
-
Global Redis Price Cache:
- Key:
quote:{isbn}:{vendor_id} - Value:
{ price_cents: 3800, stock: true, timestamp: 1711900800 } - TTL Strategy: Short TTLs (e.g., 60–300 seconds). Prices change frequently, but sub-minute real-time quotes across 500 APIs for identical requests are wasteful.
- Key:
-
Singleflight / Request Coalescing (Thundering Herd Mitigation):
- If 1,000 users query a newly released bestseller simultaneously, the cache miss should not trigger $1,000 \times 500 = 500,000$ vendor HTTP calls.
- We implement Distributed Request Coalescing using Redis Locks or in-memory Go
singleflight. - Only the first request for a missing ISBN executes the fan-out query. Subsequent concurrent requests await the outcome of the primary request's execution and read from the newly populated cache.
Price Validity Rule
Safety Guard: A cached price can be used to filter out vendors or evaluate feasibility, but never to execute a financial transaction without explicit re-verification if the cached quote is older than 30 seconds. If a transaction is triggered from a cached quote, the vendor placement call includes the expected price constraint (
expected_price: 3899). If the vendor rejects due to price drift, the system falls back to re-quoting.
4. Transaction Consistency & Order Execution
Placing an order with a vendor and charging a customer are two independent distributed side-effects.
Payment & Ordering Pattern: Two-Phase Authorization & Capture
We use a two-phase payment approach (Authorize $\rightarrow$ Order $\rightarrow$ Capture) to ensure zero risk of charging a customer for an unfulfillable order.
Procurement Svc Payment Gateway Vendor API
| | |
|--- 1. Auth (Hold Funds) ---->| |
|<-- Auth Success (Token) -----| |
| | |
|------------------- 2. Place Order (Idempotent) ---------->|
| |--- (Succeeds)
|<------------------ 3. Order Confirmed --------------------|
| | |
|--- 4. Capture Payment ------>| |
|<-- Capture Confirmed --------| |
Detailed Transaction Steps:
- Authorize Payment: Create an authorization hold on the customer's payment method for
lowest_quoted_price. Money is locked, but not transferred. - Execute Vendor Purchase: Send request to vendor API with an Idempotency Key (
idempotency_key = {request_id}:{vendor_id}). - Process Vendor Response:
- Case A: Vendor Order Confirmed: Call Payment Gateway to Capture the authorized funds. Transaction complete.
- Case B: Vendor Fails / Out of Stock / Price Changed: Send Void Authorization request to Payment Gateway. Customer hold is released immediately. Evaluate second-lowest vendor if remaining time permits.
- Case C: Network Timeout / Unknown Vendor State: Do NOT capture payment yet. Mark state as
PENDING_VERIFICATION. Initiate a background worker to query the vendor'sGET /orders/{idempotency_key}status endpoint.
Idempotency Matrix
To prevent double-charging or double-ordering during retries:
| Target System | Key Pattern | Purpose |
|---|---|---|
| Payment Gateway | auth_{request_id} | Ensures authorization is executed at most once per user procurement request. |
| Vendor Endpoint | order_{request_id}_{vendor_id} | Prevents duplicate vendor orders if network timeouts force a retry. |
| Payment Capture | cap_{request_id} | Guarantees funds are captured exactly once upon confirmed vendor fulfillment. |
System Recovery & Failure Modes Matrix
| Failure Mode | Point of Failure | System Resolution |
|---|---|---|
| Vendor network drops mid-quote aggregation | Query Step | Gathering window times out at $T_{\text{max}}$. Aggregates remaining received quotes. |
| Procurement Svc crashes after Payment Auth | Step 1 | Background worker identifies stale RESERVING_PAYMENT records older than 5 minutes and issues payment hold release calls. |
| Procurement Svc crashes during Vendor Order | Step 2 | Reconciler worker reads PLACING_ORDER state, queries Vendor Status API with order_{request_id}_{vendor_id}. If order exists $\rightarrow$ proceed to capture. If not $\rightarrow$ void auth. |
| Payment Capture API returns 500 error | Step 4 | Retried automatically with exponential backoff using idempotency key cap_{request_id} until successful. |
5. Non-Functional Requirements & Scaling Metrics
- Latency SLA: P95 overall response time $\le 3000\text{ ms}$.
- Throughput: Designed for $10,000$ concurrent active aggregation workflows.
- Storage Sizing:
- Requests DB: $\sim 1\text{ KB}$ per record. At 1,000,000 requests/day $\approx 1\text{ GB/day}$. PostgreSQL or DynamoDB with TTL-based archiving to S3/Parquet for analytical queries.
- Observability:
- PromEx metrics for downstream vendor error rates, quote latency heatmaps, circuit-breaker trips, and price-drift failure frequencies.