Design a Contextual Pricing Service for a High-Volume Retail Platform
System DesignModel answerLast updated
Design a pricing API that handles batch lookups, personalized context, explicit freshness guarantees, and partial failure at one million item evaluations per second.
Scenario
You are a senior engineer at a large e-commerce platform that sells digital and physical goods across 30 regional markets worldwide. The platform's frontend surfaces prices in three distinct places: product detail pages, search result grids, and a checkout funnel. A third-party partner network also queries your pricing data in bulk.
A single search grid can render up to 100 items simultaneously, and pricing for each item depends on who is asking: their loyalty tier, where they are shipping to, what promotional code they've applied, and whether a time-limited sale is currently running. Your job is to design the core Pricing Service that powers all of these surfaces.
Requirements
Functional
- Single and batch retrieval: The API must support fetching a price for one item or up to 250 items in a single request.
- Pricing context: Each request carries contextual inputs — customer loyalty level, destination country, active promo codes, and preferred currency — which affect the final computed price.
- Freshness metadata: Every price in the response must include when it was calculated, how long it is valid, and whether it was computed fresh or retrieved from a cache.
- Per-item fault isolation: If one item in a batch fails to resolve (for example, due to a downstream tax service timeout or an unrecognized item ID), that item returns an error while all other items in the batch succeed normally.
Non-Functional
- Throughput: 100,000 requests per second at peak, with an average of 10 items per request — roughly 1 million item evaluations per second.
- Latency: Single-item p99 under 25 ms; 100-item batch p99 under 75 ms.
- Scale: 50 million active items across 30 regional markets.
- Availability: 99.99% uptime for pricing evaluations.
What You Are Expected to Cover
1. API protocol and schema
Compare GET with query parameters versus a read-only POST for batch requests. Consider URL length limits, proxy caching behavior, and whether idempotency is affected. Define the JSON request and response schema, including how per-item errors are represented alongside successes.
2. Batch orchestration and fan-out
Walk through how the service handles a batch internally: deduplicating repeated item IDs within a single request, decomposing the batch for downstream calls, enforcing bounded concurrency, and propagating request deadlines so that slow downstream services don't blow your p99 budget.
3. Contextual caching strategy
Pricing depends on user-specific inputs, which can destroy cache hit ratios if handled naively. Describe a caching topology — potentially multi-tier — that preserves high hit rates despite personalization. Cover how you key the cache, how you handle cache stampedes, and how stale-while-revalidate applies here.
4. Overload handling and graceful degradation
Explain how the service protects itself and its downstream dependencies under load. Cover backpressure mechanisms, circuit breakers, and differentiated staleness policies: for example, a search page may tolerate a slightly stale price, while the checkout flow must not.
Hints
Hint 1
A single price is really a composition of layers with very different volatility: base price (slow-changing, high-cardinality), promotion rules (fast-changing, low-cardinality), tax tables (stable, tiny), and FX rates (ticking, tiny). Each layer has a different optimal caching strategy. Decomposing the price this way is the key insight that makes both latency and hit-rate targets achievable.
Hint 2
For batch fan-out, the number of downstream network calls should be proportional to the number of distinct cache shards or DB partitions hit — not proportional to the number of items in the batch. Group L2 misses by shard and issue one multi-get per shard, not one call per item. A bounded worker pool and a global per-node concurrency semaphore prevent a large batch from monopolizing all downstream…
Hint 3
Cache keys for personalized prices must include a rule-version token, not the full promo token list. When a flash sale starts, bumping the rule version implicitly invalidates all segment-level cache entries without requiring explicit key enumeration. User-specific promo tokens are applied as a pure in-memory overlay after the segment price is retrieved — they never appear in the cache key.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scale and Turn Numbers into Constraints
Before touching any design decision, convert the requirements into hard constraints.
Throughput math: 100K RPS × 10 items = 1M item evaluations/sec. At a p99 batch latency of 75 ms, there is no room for a synchronous remote call per item. Nearly all per-item work must be in-memory CPU time — microseconds, not milliseconds.
Data volume:
- 50M titles × 30 markets = 1.5B base-price rows. At roughly 100 bytes each, that is about 150 GB. This fits in a sharded distributed cache like Redis or Aerospike but not in a single process's heap.
- Promotion rule sets and tax tables are tiny by comparison — thousands of rules and ~30 country tax schedules. These fit entirely in every pricing node's process memory.
Context cardinality: loyalty tier (~4 values) × country (30) × currency (~10) × promo tokens (unbounded). You cannot cache a complete price per user — the key space explodes and hit rates collapse. This is the central design challenge.
Key insight — price decomposition:
final_price = FX( tax( promo( base(item, market), segment, tokens ), country ), currency )
base(item, market)is high-cardinality but slow-changing → cache in a shared distributed tier.- Promo rules, tax tables, and FX rates are low-cardinality rule sets → replicate to every pricing node and evaluate as pure in-memory functions.
Caller differentiation: browse/search surfaces tolerate a price that is a minute old. The checkout funnel requires an authoritative price. Confirm this early — it drives the freshness contract and the staleness fallback policy.
2. API Contract
GET vs read-only POST
| Factor | GET | POST |
|---|---|---|
| CDN/proxy caching | Yes, naturally | No |
| URL length | Hits limits at ~250 IDs + context | No constraint |
| Promo tokens in logs/URLs | Yes — a leak risk | Stays in body |
| Idempotency | Semantically clear | Must be documented |
Recommendation:
GET /v1/prices/{itemId}for single items. CDN-cacheable when context is anonymous or segment-only. Canonicalize and sort query parameters so cache keys are stable.POST /v1/prices:batchFetchfor batches, documented explicitly as safe and idempotent. Caching at the item level inside the service is more effective than caching whole-batch responses anyway, since batch compositions rarely repeat.
Request schema
{
"items": [{"itemId": "SKU-123"}, {"itemId": "SKU-456"}],
"context": {
"loyaltyTier": "GOLD",
"country": "DE",
"currency": "EUR",
"promoTokens": ["SUMMER20"]
},
"consistency": "BROWSE",
"maxStalenessMs": 60000
}
consistency: CHECKOUT tells the service to block on a fresh computation and never serve stale.
Response schema
HTTP 200 whenever the batch itself was processed. Per-item status lives in the envelope:
{
"results": [
{
"itemId": "SKU-123",
"status": "OK",
"price": {
"amount": "17.99", "currency": "EUR",
"listAmount": "22.99",
"appliedPromotions": ["SUMMER20"],
"taxIncluded": true
},
"freshness": {
"computedAt": "2025-06-01T09:00:00.120Z",
"validUntil": "2025-06-01T09:01:00Z",
"source": "CACHE",
"verified": true
}
},
{
"itemId": "SKU-456",
"status": "ERROR",
"error": {"code": "TAX_TIMEOUT", "retryable": true}
}
]
}
Use 4xx/5xx only for request-level failures: malformed input, auth error, batch over 250 items, or global overload (429 with Retry-After). Never let one bad item poison the HTTP status for the whole batch.
3. Architecture Overview
Client → API Gateway → Pricing Service (stateless, per-region)
|
┌─────────┴──────────┐
L1 cache Rule snapshot
(in-process) (promo + tax + FX, in-memory,
versioned, pushed via event stream)
|
L2 cache
(Redis cluster,
sharded by itemId)
|
┌─────────┴──────────┐
Base Price DB Promo/Tax engines
(partitioned by (called only on
market + itemId) cache miss or
complex rules)
Rule snapshot delivery: when a flash sale activates or a tax rule changes, an event triggers a new snapshot version. Each pricing node atomically swaps in the new snapshot and increments ruleVer. This version token appears in all segment-level cache keys, so invalidation is implicit — no key enumeration needed.
4. Batch Orchestration
- Validate and deduplicate. Normalize item IDs, strip duplicates, and map each unique ID to one or more response slots. Duplicates share one evaluation, fill all their slots on completion.
- L1 lookup (in-process LRU) for all items in the batch.
- Group L1 misses by L2 shard. Issue one
MGETper shard in parallel — ~3–5 network round trips for a 100-item batch, not 100. - Group L2 misses by DB partition. Fan out through a bounded worker pool (e.g., max 8 concurrent downstream calls per request, enforced by a per-node semaphore). This prevents a large batch from monopolizing connections.
- In-memory rule application. Apply promotions, tax, and FX as pure functions. Call the Promotion or Tax engine only for items whose rules exceed what the local snapshot covers, batched per engine call.
- Assemble in original order. Any item not resolved by the request deadline gets
DEADLINE_EXCEEDED, or a stale value if the caller's consistency policy allows it.
Deadline propagation: the gateway stamps an absolute deadline (e.g., now + 70 ms) in a header. Each downstream hop computes remaining = deadline - now - safetyMargin and passes it along via gRPC deadline or a custom header. Work that has already expired is abandoned rather than completed uselessly.
5. Caching and Stampede Protection
Cache key design:
- Base layer:
base:{market}:{itemId}— TTL in hours, invalidated on catalog change via CDC. - Segment layer:
px:{market}:{itemId}:{tier}:{currency}:{ruleVer}— TTL ~60s. BumpingruleVeron a rule change invalidates all affected entries without enumeration. - Promo tokens never appear in the key. They are applied as a pure in-memory overlay after the segment price is fetched.
stale-while-revalidate: each entry carries a softTTL (e.g., 45s) and a hardTTL (e.g., 90s). Between the two, serve the stale value and trigger an async background refresh. For browse traffic, the entry reports verified: true if age is within the caller's maxStalenessMs. Checkout requests block until a fresh computation completes.
Single-flight: within a node, concurrent misses for the same key share one in-flight future (sync.Map + promise pattern). Across nodes, a short Redis lock (SET NX PX 200) ensures only one node recomputes. Losers serve stale or wait briefly, preventing thundering-herd spikes on popular titles.
Probabilistic early refresh (XFetch): slightly randomized early expiry prevents synchronized stampedes on hot keys that all got cached at the same moment.
6. Overload Control and Fault Tolerance
Backpressure: the API gateway enforces per-client token-bucket rate limits. The pricing service tracks its own queue depth and returns 429 with Retry-After before latency degrades, rather than after.
Circuit breakers: wrap each downstream dependency (Base Price DB, Promo Engine, Tax Engine) in a circuit breaker with a half-open probe interval. A tripped Tax Engine does not take down pricing for all items — it surfaces TAX_TIMEOUT per item.
Differentiated degradation:
- Browse/search: serve stale prices up to
maxStalenessMs, markedverified: falseif beyond the soft TTL. Users see prices; the platform avoids hard failures. - Checkout: staleness is never acceptable. If a fresh price cannot be computed within the deadline, return an error and surface a "prices may have changed — retry" message to the user. Better a brief friction than a mispriced order.
Retry amplification: document that clients must not retry on 503 without Retry-After. Jitter is mandatory. Retry storms from hundreds of clients all backing off at the same second can be as damaging as the original overload.
Common Mistakes to Avoid
- Caching at the user level. Cache hit rates approach zero and memory usage explodes. Decompose into shared base + in-memory overlay instead.
- One downstream call per item. Violates latency targets immediately. Always batch by shard/partition.
- Returning HTTP 500 for partial item failures. Forces the client to retry the entire batch. Use item-level status envelopes.
- Ignoring the browse vs. checkout distinction. A uniform staleness policy either over-protects browse (hurting hit rates) or under-protects checkout (causing pricing errors).
- No deadline propagation. A slow Tax Engine response causes the entire batch to timeout, rather than just the affected items.