Real-Time Multi-Vendor Price Comparison Platform
System DesignModel answerLast updated
Build a service aggregating product offers from 30+ external APIs, balancing freshness, latency, and quota limits through hybrid caching.
Problem
You're building a product price comparison platform that aggregates listings from multiple online retailers. Users search for items by identifier (like ISBN for books) or keywords, and your service returns a unified view of available offers sorted by total cost.
Context
Your platform needs to query 30+ external merchant APIs and web sources. Each merchant has different response times, rate limits, and reliability characteristics. Some provide bulk endpoints, others only support single-item lookups. Rate limits typically range from 10-100 requests per second per merchant.
System Requirements
Functional
- Search capability: Support lookups by unique identifier or keyword query
- Offer aggregation: Collect price, shipping, condition, and seller rating from all sources
- Ranking: Sort results by total cost (item price + shipping)
- Graceful degradation: Return available results even when some sources fail or timeout
Scale & Performance
- Query load: 5,000 requests/second at peak
- Catalog size: 50 million unique items
- Response time: 99th percentile under 800ms
- External timeouts: Cap at 1.5 seconds per merchant
- Data freshness: Price data should typically be under 4 hours old
Your Task
Design the architecture for this system. Address:
- API design: What endpoints do you expose? What does the response structure look like?
- Data modeling: How do you store item metadata, offers, and pricing history?
- Fetching strategy: When do you query external merchants—on demand, background refresh, or both?
- Reliability patterns: How do you handle slow or failing merchants without impacting overall availability?
- Rate limiting: How do you stay within merchant quotas while serving high query volume?
- Cache strategy: What do you cache, where, and how do you keep it fresh?
Consider the trade-offs between freshness, latency, and cost (quota consumption).
Hints
Hint 1
Calculate the refresh rate needed to keep all 50M items fresh—it won't fit merchant quotas. You need a hybrid approach.
Hint 2
Stale-while-revalidate lets you return cached data immediately while triggering background refresh.
Hint 3
Use a popularity-based tiering system: refresh bestsellers frequently, long-tail items only on access.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is reconciling conflicting constraints: users expect fast, fresh prices, but merchant quotas make exhaustive real-time fetching impossible. The solution is a hybrid push-pull architecture with intelligent caching.
1. Sizing the Problem
First, validate whether pure push or pull is feasible:
- Pure push (refresh everything periodically): 50M items × 30 merchants = 1.5B offer pairs. Refreshing every 4 hours means 1.5B / 14,400 seconds ≈ 104,000 requests/second—far exceeding typical merchant quotas.
- Pure pull (fetch on every query): 5,000 QPS × 30 merchants = 150,000 outbound requests/second—again, impossible.
Observation: Most traffic concentrates on popular items. If the top 1M items (representing ~85% of queries) are refreshed every 4 hours, that's only 1M × 30 / 14,400 ≈ 2,100 req/s total, or about 70 req/s per merchant—manageable.
2. Architecture Components
Data Stores:
- Item catalog (PostgreSQL + Elasticsearch): Store identifiers, titles, authors, metadata. Elasticsearch handles keyword search.
- Offer database (Cassandra/DynamoDB): Partition by item ID. Each partition contains all offers for one item with fields: merchant, condition, price, shipping, currency, rating, URL, fetch timestamp.
- Offer cache (Redis): Pre-aggregated, sorted offer lists per item. TTL: 4 hours soft, 24 hours hard.
- Price history (time-series DB): Track price changes for trend analysis.
Services:
- Query Service: Handles user requests, checks cache, orchestrates fetching.
- Fetch Orchestrator: Coordinates parallel calls to merchants, enforces timeouts and single-flight deduplication.
- Refresh Scheduler: Maintains priority queue of items to refresh based on popularity scores.
- Merchant Adapters: Per-merchant clients with circuit breakers, rate limiters, and connection pools.
3. Request Flow
For GET /items/{id}/offers:
- Check Redis for
offers:{id}. - Cache hit, fresh data (< 4 hours old): Return immediately (~2ms latency). This serves 80%+ of requests.
- Cache hit, stale data (4-24 hours old): Return cached data marked with age, then enqueue async refresh (stale-while-revalidate). User sees instant response.
- Cache miss (cold item): Fan out to all healthy merchants in parallel with 1.5s timeout per call. Wait only
max_wait_ms(e.g., 600ms), return partial results flagged as incomplete. Remaining responses populate cache in background.
This keeps p99 latency under 800ms even when merchants are slow, because we don't wait for all responses.
4. Tiered Refresh Strategy
Assign items to tiers based on access frequency (exponentially decayed count from logs):
| Tier | Size | Refresh Interval |
|---|---|---|
| Hot | Top 1M items | Every 2-4 hours (proactive) |
| Warm | Next 5M items | Daily, or on first access |
| Cold | Remaining 44M | On-demand only |
Hot tier uses background workers that continuously poll a priority queue. This ensures popular items always have fresh prices without user-facing latency.
5. Reliability Patterns
Circuit Breakers: Each merchant adapter tracks error/timeout rates. If failure rate exceeds 50% over 10 seconds (min 20 samples), open the circuit for 30 seconds. Serve cached offers for that merchant instead of making failing calls.
Bulkheads: Separate connection pools and concurrency limits per merchant. A slow or hanging merchant exhausts only its own pool, not the entire system.
Single-Flight Fetching: When multiple concurrent requests need the same item, coalesce them into one fetch operation per merchant. Use local in-flight tracking plus distributed locks (Redis SETNX with TTL) to prevent thundering herds across instances.
Partial Results: Return whatever data is available within the deadline. Flag response as partial: true with list of pending merchants. Users can optionally poll for updates.
6. Rate Limiting
Split each merchant's quota into user lane (40%) and background lane (60%). User requests can borrow unused background tokens but not vice versa. Use token bucket algorithm per merchant, coordinated via Redis.
When quota is exhausted, skip that merchant for user queries and serve cached data. Background refresh backs off with exponential delay.
Batch APIs: Where merchants support bulk lookups, pack 50-100 items per request. This makes quota math 50× better.
7. Cache Invalidation
Probabilistic early refresh (XFetch): Refresh slightly before TTL expires with probability proportional to age. This spreads load and prevents synchronized expiration.
Price change events: When a refresh detects significant price delta (>5%), publish to event stream for real-time alerts.
New releases: Pre-warm cache for anticipated high-demand items before launch.
8. API Design
GET /v1/search?q=keywords&limit=20
→ [{id, title, author, ...}]
GET /v1/items/{id}/offers?condition=new|used¤cy=USD&max_wait_ms=600
→ {
id,
offers: [{
merchant, condition, price, shipping, total, rating, url, fetched_at
}],
partial: boolean,
pending_merchants: [...]
}
The partial flag and pending_merchants list make degraded state explicit to clients.
9. Trade-Offs
Freshness vs. Cost: 4-hour staleness is the price of feasibility. Stricter SLAs would require higher quotas or selective coverage (fewer merchants).
Latency vs. Completeness: Returning partial results keeps latency low at the cost of sometimes incomplete data. For price-sensitive users, this is acceptable.
Complexity: Hybrid architecture is more complex than pure push or pull, but neither extreme meets requirements.
Scraping vs. APIs: Web scraping is fragile and slower. Use APIs where available; scrape only as fallback, with separate worker pools for isolation.
Complexity
- Latency: p50 ~5ms (cache hit), p99 ~700ms (partial fetch)
- Throughput: 5,000 QPS with horizontal scaling of stateless services
- Storage: ~60GB for active offers (cacheable in memory), ~5TB for full offer history
Common Mistakes
- Waiting for all merchants: This causes p99 latency to track the slowest merchant. Use timeouts and partial results.
- No circuit breakers: One failing merchant can cascade and exhaust connection pools or trigger retries that amplify load.
- Cache stampede: Popular items expiring simultaneously cause thundering herds. Use single-flight and jittered refresh.
- Ignoring quotas: Naive fanout exceeds rate limits instantly. Model quota consumption before building.