Skip to content

Design Amazon Sales Rank by Category

Advanced 97 min read Part 17 of 18

Rank 10 million products by last week's sales in each of 1,000 categories, refresh hourly, and serve 40,000 rank lookups per second from cache.

The Problem#

Open almost any product page on Amazon and scroll to the product details. Near the bottom there is usually a line such as "Best Sellers Rank: #3 in Kitchen Scales, #412 in Home & Kitchen". Click a category and you get a best sellers list: the top 100 products in that category, ordered by how well they are selling right now. We will design these two features: "what is this product's rank?" and "what are the best sellers in this category?".

Wikipedia's article on Amazon describes the Amazon sales rank as a relative measure of popularity that is updated hourly. It also says the rank decides which products appear on the best sellers lists, and that products making large jumps up or down can appear on a separate "movers and shakers" list. Amazon does not publish its sales figures or the details of its ranking formula. That gives us a useful starting point. The rank is relative: it compares products and is not a count shown to anyone. It is recomputed on a schedule, hourly rather than on every sale. And the exact formula is a business choice that we are free to design.

The version usually asked in interviews is narrower and more concrete: compute the past week's most popular products in each category, and let users view them. A product can belong to several categories. The ranking must be refreshed every hour. There are about 10 million products, 1,000 categories and 1 billion sales a month, and there are 100 times more reads than writes.

At first glance this is a sorting problem, and a small one. The interesting parts are the problems around it:

  1. Where do the sales come from, and which ones count? A sale is an order line in the order system. Orders get cancelled, returned and refunded, and some turn out to be fraud. The ranking pipeline must ingest these events reliably. It must never count an order twice, and it must never slow down checkout.
  2. "The past week" keeps moving. Every hour, the oldest hour of sales leaves the window and a new hour enters. Recomputing a full week of data every hour is simple but wasteful. Updating the window incrementally is efficient but needs care.
  3. One product, many categories. A kitchen scale may sit in "Kitchen Scales", "Baking Tools" and "Home & Kitchen". Each sale must count in every one of its categories. This multiplies the data and creates skew: a huge category such as "Books" holds millions of products.
  4. Reads dominate. Every product page view asks for that product's ranks, and best sellers pages are visited all day. That is 40,000 reads per second on average, and many more at peak, for an answer that changes only once an hour. This is the textbook case for caching and precomputation.
  5. Ranks are a public signal with money behind them. Sellers watch their rank, and buyers trust "#1 Best Seller" badges. Some sellers try to game the rank with fake orders or by buying their own products. The pipeline must withstand bad data and publish one consistent snapshot every hour.

An analogy. Think of the weekly chart at a radio station. Record shops send in their sales slips all week. Once an hour, a clerk adds up the slips from the last seven days for each genre (pop, jazz, classical; one album can be in two genres), sorts each genre's list and pins the new chart on the noticeboard. Thousands of listeners read the noticeboard, but nobody ever reads the pile of slips. The design questions are the clerk's questions:

  • How do you collect the slips without losing or double-counting any?
  • How do you total a moving seven-day window without re-reading every slip each hour?
  • How do you handle albums that belong to several genres?
  • How do you swap in the new chart all at once, so that nobody reads half of the old chart and half of the new one?

Background: a few terms used in this design#

  • Sales rank. A product's position in a category when products are ordered by a sales score; #1 is the best seller. Ranks are relative: a product's rank can drop even if its own sales stay the same, because other products sold more.

  • Category (browse node). A node in the store's product taxonomy, such as "Kitchen Scales". Amazon calls these browse nodes. In the base problem, categories are flat (there are no subcategories). A variant in the deep dives covers category trees.

  • Order line (sale). One product in one order, with a quantity and a price. This is our unit of input. An order with three products produces three order lines.

  • Window. The period of sales that counts, for example the last 7 days.

    • A rolling (sliding) window moves forward every hour.
    • A calendar window resets at a fixed time, for example every Monday at 00:00.
  • Tumbling window. Fixed buckets that do not overlap, such as one bucket per clock hour. Summing the last 168 hourly buckets gives a rolling 7-day window.

  • MapReduce. A programming model for batch processing on a cluster, described by Jeffrey Dean and Sanjay Ghemawat in "MapReduce: Simplified Data Processing on Large Clusters" (OSDI 2004). It works in three steps:

    1. A map function turns each input record into key-value pairs.
    2. The framework shuffles the pairs so that all pairs with the same key reach one machine.
    3. A reduce function combines the values for each key.

    Apache Hadoop is the best-known open-source implementation. Apache Spark does the same work faster, in memory. See Batch vs Stream Processing.

  • Stream processing. Processing events continuously as they arrive while keeping running state (such as counts per hour), instead of processing them in periodic batches. Apache Flink and Kafka Streams are common engines. See Apache Flink and Stream Processing.

  • Snapshot. One complete, versioned result of a ranking run ("ranks as of 14:00"). Readers always see exactly one snapshot, never a mix of two.

  • Cache-aside. The reader checks the cache first. On a miss, it reads the database, stores the result in the cache and returns it. See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.

  • TTL (time to live). How long a cache entry may live before it expires.

  • Read replica. A copy of a database that follows the primary and serves reads. See Database Replication.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
What does "popular" mean: units sold, number of orders, revenue, or something else?Decides what we sumUnits sold (quantity) by default, with a cap per order to resist bulk-buy manipulation; revenue is a variant
Over what period?Decides the window and how much data each run readsThe past 7 days, rolling, recomputed hourly
Should recent sales count more than older ones?With a flat window, ranks jump when old sales fall outThe base design uses a flat 7-day window; a decayed score is covered in a deep dive
How fresh must ranks be?Batch vs streamingUpdated at least hourly; the most popular products may need fresher ranks
Can a product be in several categories?Each sale fans out to several countsYes, typically 1 to 5; products do not change categories in the base problem
Are there subcategories?A parent's rank must include its children's salesNo in the base problem; a deep dive covers category trees
Do cancellations and returns reduce the count?Correctness and abuseCancellations before shipping are removed; returns are removed while the sale is still in the window; orders flagged as fraud never count
Do we show a rank for every product, or only the top N?A full rank needs a full sort of every categoryEvery product with at least one sale in the window gets a rank in each of its categories; best sellers pages show the top 100
How many products, categories and sales?Sizing10 million products, 1,000 categories, 1 billion sales a month
How many reads?Size of the caching and serving tiers100 billion reads a month, about 100 reads per write
One marketplace or many?Separate rankings per countryOne marketplace in the base design; per-marketplace ranks are a variant
Is the rest of the store in scope (catalogue, checkout, search)?Scope controlNo; we build only the ranking pipeline and the read path, and we consume events from the order system

Requirements#

Functional requirements#

  1. Ingest sales. Receive every order line (product, quantity, price, time) from the order system, plus cancellations and returns, without losing or double-counting any of them.
  2. Compute rankings per category. Every hour, compute each product's sales score over the past 7 days in every category it belongs to, and rank the products within each category.
  3. View best sellers. A user can view the top products in a category for the past week, in rank order, with paging (top 100 by default).
  4. Look up a product's rank. A product page shows the product's rank in each of its categories ("#3 in Kitchen Scales").
  5. Show freshness. Every response says which snapshot it comes from ("as of 14:00 UTC").

Out of scope:

  • The general e-commerce site: catalogue, cart, checkout and payments.
  • Search ranking, recommendations and personalised best sellers.
  • Seller-facing sales analytics.

The deep dives mention movers and shakers and per-marketplace ranks as variants.

Non-functional requirements#

  • High availability. Rank lookups and best sellers pages must stay up (99.99%) even when the ranking pipeline is late or down. In that case, serve the last good snapshot.
  • Low read latency.
    • Rank lookups: p99 under 10 ms inside the data centre, so they add nothing noticeable to the product page.
    • Best sellers pages: p99 under 100 ms end to end, mostly served from a CDN.
  • Freshness. A new snapshot every hour, published within 15 minutes of the hour closing. Very popular products may be refreshed every few minutes.
  • Consistency of a snapshot. A user sees ranks from only one snapshot at a time. Within a snapshot, the best sellers list and the rank shown on a product page agree.
  • Eventual consistency is fine. A sale may take up to about an hour to affect the rank. Nobody needs a rank that reflects the last second.
  • Correctness. Every sale in the window that is not cancelled or fraudulent is counted exactly once in each of its product's categories. Batch reprocessing can correct any mistake.
  • No impact on checkout. The ranking system must never slow down or block placing an order.
  • Robustness to manipulation. One buyer or one bulk order must not be able to push a product to #1.
  • Scalability. Room for 10 times more sales and reads (more marketplaces, peak shopping days) without a redesign.

Capacity Estimation#

We start from the stated numbers and derive everything else. A month has about 2.5 million seconds, which gives handy conversions: 1 request per second is about 2.5 million a month, 40 per second is about 100 million a month, and 400 per second is about 1 billion a month. See Back-of-the-Envelope Estimation.

Sales (writes).

  • 1 billion order lines a month ÷ 2.5 million seconds ≈ 400 sales per second on average.
  • Traffic is uneven. Evenings are busier than nights, and big shopping days are much busier than normal days. Assume a normal daily peak of about 3 times the average (1,200 per second) and a peak-day burst of 10 to 20 times (4,000 to 8,000 per second). These multipliers are assumptions to design against, not published figures.
  • Cancellations, returns and fraud flags add events. Assume they add about 10% on top: roughly 440 events per second on average.

Size of a sale. A compact record of one sale needs only a few fields:

FieldBytes
created_at (timestamp)5
product_id8
category_id4
seller_id8
buyer_id8
quantity4
total_price5
Totalabout 40
  • 40 bytes × 1 billion = 40 GB of new sales data a month, or about 1.44 TB over three years. Almost all of it is new rows rather than updates.
  • In practice the event on the wire is bigger. It carries an event id, an order id, a line id, a currency, a marketplace and a schema version, so it takes perhaps 150 to 250 bytes in a binary format such as Avro or Protobuf. That is still only 150 to 250 GB a month on the event stream, and about 100 KB per second on average. Ingest bandwidth is not a concern at this scale.

The 7-day window.

  • Sales in one week ≈ 1 billion × 7 / 30 ≈ 233 million order lines, about 9 GB in the compact format.
  • Sales in one hour ≈ 1.4 million order lines.
  • Each product is in about 3 categories on average (an assumption). Every sale therefore contributes to about 3 category counts: roughly 700 million (category, product) contributions per week.

How many products have a rank? Sales follow a long tail: a few products sell thousands of units a week, and millions sell a handful or none. Assume that 4 million of the 10 million products sell at least once in a given week.

  • Ranked entries: 4 million products × 3 categories ≈ 12 million (category, product, rank) rows per snapshot.
  • At about 24 bytes each (category id, product id, score, rank), that is about 300 MB of raw data per snapshot. Even with the overhead of an in-memory store, 1 to 3 GB holds a whole snapshot.
  • The top 100 of every category: 1,000 × 100 = 100,000 entries. With display fields (title, image URL, price), at about 200 bytes each, that is about 20 MB.

Hourly buckets (for incremental windows).

  • Distinct products sold in one hour: assume about 600,000.
  • One bucket row per (hour, product) with a 16-byte count is about 10 MB per hour. All 168 hours of a week take about 1.7 GB. That is small enough to keep in a stream processor's state or in a key-value store.

Reads.

  • 100 billion reads a month ÷ 2.5 million seconds ≈ 40,000 reads per second on average, with a daily peak of about 120,000 per second and more on peak days.
  • Assume 90% are product-page rank lookups (about 36,000 per second) and 10% are best sellers pages (about 4,000 per second).
  • Read to write ratio ≈ 40,000 / 400 = 100 : 1.

Bandwidth for reads.

  • A rank lookup response (2 to 5 categories with ranks) is about 200 to 500 bytes, so 36,000 per second × 500 bytes ≈ 18 MB/s.
  • A best sellers page response for 100 products with titles and image URLs is about 20 KB. 4,000 per second × 20 KB ≈ 80 MB/s, most of which a CDN can serve because the page is the same for everyone.

Compute for one ranking run.

  • Full recompute. Read 233 million rows (9 GB compact, perhaps 3 to 5 GB as compressed columnar files), join each with its 3 categories, sum and sort. A Spark cluster of 20 to 50 cores does this in a few minutes. A single large machine could do it in under an hour. The data is small; the challenge is doing it reliably every hour.
  • Incremental update. Read only the newest hour (1.4 million rows), add it to the window and subtract the hour that falls out. This takes seconds.

Summary.

QuantityValue
Sales400 per second average, 1,200 daily peak, 4,000 to 8,000 on peak days
Sales data40 GB a month (compact), 1.44 TB over 3 years
Window233 million sales per week, 1.4 million per hour
Ranked rows per snapshotabout 12 million (4 million products × 3 categories)
Snapshot sizeabout 300 MB raw, 1 to 3 GB in memory
Top-100 lists100,000 entries, about 20 MB
Reads40,000 per second average, 120,000 daily peak
Read to write ratio100 : 1

The takeaway: the computation is small, and the reads are large and repetitive. Each snapshot is read millions of times before it is replaced. That shapes the whole design. We precompute everything once an hour and serve reads only from precomputed, cached results.

Core Entities#

  • Product. id, title, seller, image. It is owned by the catalogue; we only reference it.
  • Category. id, name and (in the tree variant) a parent id.
  • ProductCategory. The many-to-many link between products and categories. A product typically has 1 to 5 links.
  • SaleEvent. One event per order-line change: event id, type (placed, cancelled, returned, fraud flagged), order id, line id, product id, quantity, unit price, buyer id, seller id and the time it happened. This is the input, and it is immutable.
  • HourlyProductSales. The units sold per product per clock hour (after removing cancellations and applying caps). This is the building block of windows.
  • Snapshot. One ranking run: version (for example 2026-12-04T14), window start and end, status (building, validated, published, retired) and the time it was published.
  • CategoryRanking. For one snapshot and one category, the ordered list of products, each with a rank and a score.
  • ProductRank. For one snapshot and one product, its rank in each of its categories. This is the same data as CategoryRanking, indexed the other way round.

API Design#

The public read API is small and cacheable. Writes do not come through a public API at all: they arrive as events from the order system.

GET /v1/categories/{category_id}/best-sellers?limit=100&cursor={c}
  200 OK
  Cache-Control: public, max-age=300, stale-while-revalidate=600
  {
    "category_id": 1234,
    "snapshot": "2026-12-04T14:00Z",
    "window": "7d",
    "items": [
      { "rank": 1, "product_id": "B0ABC12345", "title": "...", "image_url": "..." },
      { "rank": 2, "product_id": "B0XYZ67890", "title": "...", "image_url": "..." }
    ],
    "next_cursor": "rank:101"
  }
 
GET /v1/products/{product_id}/sales-rank
  200 OK
  { "product_id": "B0ABC12345", "snapshot": "2026-12-04T14:00Z",
    "ranks": [ { "category_id": 1234, "category_name": "Kitchen Scales", "rank": 3 },
               { "category_id": 77, "category_name": "Home & Kitchen", "rank": 412 } ] }
 
GET /v1/products/sales-rank?ids=B0ABC12345,B0XYZ67890,...   (batch, up to 50)
 
Internal event (topic: order-line-events, key: product_id)
  { "event_id": "uuid", "type": "PLACED | CANCELLED | RETURNED | FRAUD_FLAGGED",
    "order_id": "...", "line_id": 3, "product_id": "B0ABC12345", "quantity": 2,
    "unit_price": 1999, "currency": "USD", "buyer_id": "hashed", "seller_id": "...",
    "occurred_at": "2026-12-04T13:42:10Z" }
 
Internal RPC (gRPC): RankService.GetRanks(product_ids, snapshot?)
                     RankService.GetCategoryPage(category_id, from_rank, limit, snapshot?)

Design notes:

  • Do not expose sales counts. The simplest version of this API returns total_sold with each product. Amazon keeps its sales figures private, and Wikipedia's article quotes Amazon's help pages calling the rank "a guide of general interest" rather than definitive sales information. So the public API returns ranks only. Internal callers that need scores (for example seller analytics) use a separate, authenticated API.
  • Every response names its snapshot. Clients and caches can tell which run they are looking at, and support staff can answer "why did my rank change at 14:00?".
  • Cursor paging by rank, not by offset. cursor=rank:101 means "start at rank 101 in this snapshot". The cursor should also encode the snapshot version, so that page 2 comes from the same run as page 1 even if a new snapshot is published in between.
  • Batch lookups. Search results and listing pages show ranks for up to 50 products. One batched call (a multi-get in the cache) replaces 50 round trips.
  • Cache headers. Best sellers pages are the same for every user, so they are publicly cacheable for a few minutes. stale-while-revalidate lets the CDN keep serving the old page while it fetches the new one. The rank lookup is usually embedded in the product page, which has its own caching.
  • REST outside, RPC inside. External clients use plain HTTP with JSON. Internal services (the product page renderer, search) call the Rank Service over gRPC for lower overhead and typed contracts. See API Styles: REST, gRPC, GraphQL and More.
  • Events keyed by product id. Keying the topic by product keeps all events for one product in order on one partition, which simplifies matching a cancellation to its sale.

High-Level Design#

We build the design one requirement at a time, starting with the simplest thing that works, then put the pieces together.

1) Sales flow in from the order system without touching checkout#

The order system is the source of truth for sales. We must not add work to the checkout path: no synchronous call to a "ranking service" while the customer waits. Instead, the order system publishes an event for every order-line change, and the ranking system consumes those events at its own pace.

The safe way to publish is the transactional outbox. When the order service writes an order, it writes one outbox row per order line in the same database transaction. A relay (a change-data-capture tool such as Debezium reading the database log, or a small poller) copies outbox rows to a Kafka topic, order-line-events. If the order commits, the event will eventually be published. If the order rolls back, no event exists. This avoids the dual-write problem, where the order is saved but the event is lost, or the event is sent for an order that never committed. See Change Data Capture and the Outbox Pattern.

Two consumers read the topic:

  • An archiver writes every event, unchanged, to an object store (Amazon S3 or Google Cloud Storage) as hourly files: sales/date=2026-12-04/hour=13/part-0001.parquet. This is the permanent, replayable log of sales, and it is the input to batch jobs. An object store comfortably handles 40 GB to 250 GB of new data a month, and we do not have to run our own distributed file system.
  • The ranking pipeline (step 2 onwards).

Kafka keeps about 7 days of events (about 250 million events × 250 bytes ≈ 60 GB, or about 180 GB with three replicas, which is small for a Kafka cluster). A consumer that falls behind, or a new job, can therefore re-read a full week without touching the order database. See Apache Kafka in Practice.

2) Compute the past week's ranking per category: the simple batch version#

The simplest correct design is a batch job that runs every hour over the last 7 days of the sales log:

  1. Read all sale events with occurred_at in the window.
  2. Remove cancelled, returned and fraud-flagged lines (match them to their sale by order_id and line_id).
  3. Look up each product's categories and emit one record per (category, product) with the quantity.
  4. Sum the quantity per (category, product).
  5. Sort each category by the total, highest first, and assign ranks.
  6. Write the result to a sales_rank table and the serving store.

This is exactly a MapReduce shape. The map step turns a sale into ((category, product), quantity) pairs. The shuffle groups pairs by key. The reduce step sums them. A second map-reduce step re-keys by category and sorts by total. Deep dive 2 walks through the job in detail, including how it handles products in several categories.

At our scale, this job reads about 9 GB and finishes in minutes, so it does meet the hourly requirement. It is the right first answer in an interview. Its weakness is that every run re-reads 167 hours that it already summed in the previous run.

3) Make the window incremental with hourly buckets#

A 7-day rolling window is the sum of the last 168 hourly buckets. So we keep, per product, the units sold in each clock hour:

  • When an hour closes, a job (or a stream processor) sums that hour's events per product into HourlyProductSales. That is about 1.4 million events reduced to about 600,000 rows.
  • The window total for each product is updated with a sliding sum: new total = old total + units in the newest hour − units in the hour that just fell out of the window.
  • Only products that changed in either of those two hours need a new total. That is about 1 million products, not 10 million.

The incremental run takes seconds, and the full batch run becomes a daily correctness check that recomputes everything from the log and corrects any drift. Deep dive 3 covers windows in detail, including late events, decayed scores and why ranks jump when a big sale falls out of a flat window.

4) Serve rank lookups and best sellers pages#

Ranks are read 100 times more often than they are written, and they change only once an hour. So the read path never computes anything. It only looks up precomputed results:

  • Best sellers page: key bs:{snapshot}:{category}:{page} holds the ordered list of 100 products for that page, already joined with display fields.
  • Product rank lookup: key pr:{snapshot}:{product} holds the product's ranks in all its categories.

A Rank Service answers both queries from an in-memory serving store (Redis, or a key-value store such as DynamoDB with a cache in front). Best sellers pages are the same for every user, so a CDN caches them at the edge. Product-page rank lookups are part of the product page, which the page renderer caches, and the Rank Service keeps the hottest keys in process memory.

5) Publish one consistent snapshot every hour#

If the pipeline overwrote ranks in place, one at a time, a reader could see product A ranked by the 14:00 run and product B by the 13:00 run. Two products could then both claim "#1 in Kitchen Scales". Instead, every run writes a new, versioned snapshot next to the old one:

  1. Build. Write all keys for snapshot 2026-12-04T14 (old keys for T13 are untouched).
  2. Validate. Run automatic checks: row counts, the number of categories, the size of rank changes compared with the previous hour, and spot checks against the batch totals. Deep dive 11 lists them.
  3. Publish. Atomically change one pointer, current_snapshot = 2026-12-04T14, in a small configuration store.
  4. Warm and retire. Pre-load the hottest keys of the new snapshot into caches, and delete snapshots older than a few hours.

Readers read the pointer (cached for a few seconds), then read keys of that version only. Publishing is instant and rollback is just moving the pointer back.

6) Fresher ranks for the hottest products#

Requirement: "more popular products might need to be updated more frequently." A product that goes viral at 14:05 should not wait until 15:00 to show up in the top 10. A stream processor (Apache Flink) also consumes order-line-events and keeps, per category, running totals for the current partial hour. Every 5 minutes it combines them with the last published snapshot and recomputes only the top 100 of each category. That is a small sort, because only products already near the top, or selling fast right now, can enter the top 100. It publishes those lists as a fast overlay. The hourly batch snapshot remains the authority, and the overlay is discarded when the next hourly snapshot is published.

This is the Lambda architecture: an accurate, complete batch layer plus a fast, approximate speed layer, merged at serving time. Deep dive 5 compares it with a pure streaming (Kappa) design.

The full high-level design#

Components:

ComponentResponsibilityTechnology choices
Order Service and outboxSource of truth for sales; writes an outbox row per order line in the order transactionExisting order system; PostgreSQL, MySQL or DynamoDB
CDC relayPublishes outbox rows to Kafka at least once, in commit orderDebezium, DynamoDB Streams, AWS DMS
Event streamDurable, replayable log of order-line events for 7 daysKafka, Amazon Kinesis
ArchiverWrites events unchanged to hourly files in the object storeKafka Connect S3 sink, Flink file sink
Sales logPermanent, cheap, replayable history of all salesS3 or GCS with Parquet files, partitioned by date and hour
Product-category tableThe many-to-many product-to-category mapping, with a daily snapshot for jobsCatalogue database; exported to Parquet
Hourly bucketerSums units per product per clock hour, applies cancellations and capsFlink job with keyed state, or an hourly Spark job
Incremental rankerSlides the 7-day window by one hour, re-ranks changed categoriesSpark job or a service over the KV store
Full batch rankerRecomputes the window from the raw log; daily correctness check and backfillsSpark (or Hadoop MapReduce) on a managed cluster such as EMR or Dataproc
Snapshot validatorChecks each snapshot before it goes live; refuses bad onesPart of the ranking workflow (Airflow, Step Functions)
Serving storeVersioned keys for best sellers pages and product ranksRedis cluster, or DynamoDB or Cassandra with a cache
sales_rank tableDurable, queryable copy of each snapshot for rebuilds, audits and internal toolsPostgreSQL or MySQL with read replicas
Speed layerTop 100 per category refreshed every few minutes for hot productsFlink, Kafka Streams
Rank ServiceAnswers rank lookups and page requests; merges overlay and snapshotStateless service with an in-process cache
CDNServes best sellers pages at the edgeCloudFront, Akamai, Fastly
Analytics warehouseLong-term sales analysis, seller reports, model trainingAmazon Redshift, Google BigQuery, Snowflake

Key Flows#

Flow 1: A sale is placed and reaches the hourly bucket#

  1. Kai buys two kitchen scales and a book at 13:42. The order service writes the order, its three lines and three outbox rows in one transaction, and checkout finishes. Nothing in the ranking system is on this path.
  2. The CDC relay reads the database log a few hundred milliseconds later and publishes one PLACED event per order line to order-line-events, keyed by product id.
  3. The hourly bucketer (a Flink job) receives the events. It checks the event id against a short-lived set of recently seen ids, because the relay delivers at least once and could send a duplicate after a restart.
  4. It adds the line's quantity, after applying the per-order cap (deep dive 11), to the bucket for (product, hour 13). The hour is taken from occurred_at (event time), not from the time the event arrived.
  5. Every 30 seconds, and when the hour closes, it writes the bucket totals to the bucket store. Kafka offsets are committed together with Flink's state checkpoint, so a crash replays events into a state that has not yet counted them. That gives effectively-once counting.

Flow 2: The hourly snapshot is built, validated and published#

  1. At 15:00 the hour 14:00 to 15:00 closes. The scheduler waits a short grace period (5 minutes) so that events delayed in the relay or in Kafka still land in the right hour.
  2. The incremental ranker reads two buckets: the newest hour (14:00) and the hour that leaves the 7-day window (14:00 seven days ago). For each product in either bucket, the new window total is the old total plus the new hour minus the expired hour.
  3. For each category that contains a changed product, it re-ranks the category and writes the new keys under version T14: the best sellers pages and the per-product rank records. Products whose total and position did not change keep their old values; Deep dive 7 explains how to write only what changed while still producing a complete version.
  4. The validator compares T14 with T13: number of ranked products, number of categories, the largest rank movements and spot checks against independently computed totals. If a check fails, the pointer stays on T13 and someone is paged. The site keeps working with ranks that are one hour older.
  5. On success, the pointer moves to T14 in one atomic write. Within seconds, all Rank Service instances see the new pointer and start reading T14 keys.
  6. The workflow pre-loads the hottest keys of T14 into caches and deletes versions older than a few hours.

Flow 3: A shopper opens a product page#

  1. The product page renderer calls the Rank Service over gRPC, in parallel with its other calls (price, reviews, availability), with a tight timeout of about 20 ms.
  2. The Rank Service knows the current snapshot from the pointer, which it refreshes every few seconds.
  3. It checks its in-process cache first (hot products are requested many times a second on every instance), then Redis. Because the key includes the snapshot version, a cached value can never be stale within its snapshot. It just stops being used when the pointer moves.
  4. On a Redis miss (after a Redis node failure, for example), it reads the sales_rank table from a read replica and writes the result back to Redis: classic cache-aside.
  5. If the Rank Service does not answer within the timeout, the page renders without the rank line. A missing rank is a cosmetic loss; a slow product page loses sales.

Flow 4: A shopper views the best sellers in a category#

  1. The shopper clicks "Best Sellers in Kitchen Scales". The request goes to the CDN with a URL such as /v1/categories/1234/best-sellers?limit=100.
  2. The CDN usually has the page (it is the same for every shopper in the marketplace) and returns it in 10 to 40 ms.
  3. On a miss, the CDN asks the web tier, which asks the Rank Service for bs:T14:1234:1. That key already holds the 100 products in order, joined with titles and image URLs at build time, so the response needs one key read.
  4. The page's max-age is a few minutes and it carries the snapshot version, so a new snapshot reaches shoppers within minutes of publication. After a publish, the workflow can also send a purge for the top categories, so the most visited pages switch immediately.
  5. The speed-layer overlay (step 6 of the high-level design) can replace the top of the list between hourly runs. The Rank Service merges the overlay before responding and marks the response as "updated 14:25".

Flow 5: An order is cancelled, or a product is returned#

  1. Kai cancels the book an hour later. The order service writes the cancellation and an outbox row in one transaction, and a CANCELLED event for that order line is published, keyed by the book's product id.
  2. The hourly bucketer subtracts the line's capped quantity from the bucket of the hour of the original sale (13:00), not from the current hour, because the sale belongs to that hour of the window. Since the event carries the original occurred_at of the order line, the bucketer knows which bucket to adjust.
  3. If hour 13 has already been ranked and published, the bucket's correction appears in the next incremental run: the ranker re-reads buckets that changed since its last run (they carry a version number), not just the newest hour.
  4. A return two weeks later falls outside the 7-day window, so it has no effect on the current rank. It is still recorded in the sales log for audits and longer windows.
  5. A fraud flag works like a cancellation, and it also puts the buyer on a watch list for the anti-manipulation checks (deep dive 11).

Data Model#

The simplest version of the result table has one row per (category, product) with an auto-increment id and the total sold, plus indexes on id, category_id and product_id. We keep its spirit but make two changes: every row belongs to a snapshot, and the primary key is ordered for the two queries we serve. In PostgreSQL syntax:

CREATE TABLE sales_rank (
  snapshot_id  text   NOT NULL,     -- '2026-12-04T14'
  category_id  int    NOT NULL,
  rank         int    NOT NULL,     -- 1 = best seller
  product_id   text   NOT NULL,
  units        bigint NOT NULL,     -- score; internal only
  PRIMARY KEY (snapshot_id, category_id, rank)
) PARTITION BY LIST (snapshot_id);
 
-- "What are product P's ranks?" in one index range
CREATE INDEX sales_rank_by_product
  ON sales_rank (snapshot_id, product_id) INCLUDE (category_id, rank);
 
-- One partition per snapshot; retiring a snapshot is a cheap DROP
CREATE TABLE sales_rank_2026_12_04_t14
  PARTITION OF sales_rank FOR VALUES IN ('2026-12-04T14');
  • (snapshot_id, category_id, rank) serves best sellers pages as one range scan: WHERE snapshot_id = $1 AND category_id = $2 AND rank BETWEEN 1 AND 100.
  • (snapshot_id, product_id) serves product rank lookups. INCLUDE makes the index covering, so the lookup never touches the table. See Database Indexing.
  • Partitioning by snapshot makes loading a new snapshot a bulk insert into a fresh partition (no row locks against readers), and retiring an old one a metadata operation.
  • Indexes keep lookups at log time instead of scans, and a hot working set (the current snapshot's indexes, a few GB) stays in memory. Reading 1 MB sequentially from memory takes about a quarter of a millisecond. From an SSD it takes a few times longer, and from a spinning disk tens of times longer. That is why the serving copy lives in memory.

The window buckets and the product-category mapping are small and keyed simply:

CREATE TABLE hourly_product_sales (
  product_id  text        NOT NULL,
  hour        timestamptz NOT NULL,   -- start of the clock hour, UTC
  units       int         NOT NULL,   -- after cancellations and caps
  version     int         NOT NULL,   -- bumped on every late correction
  PRIMARY KEY (product_id, hour)
);
 
CREATE TABLE product_category (
  product_id  text NOT NULL,
  category_id int  NOT NULL,
  PRIMARY KEY (product_id, category_id)
);

Where each piece of data lives.

DataStoreWhy
Sale events (raw)Kafka for 7 days; object store (Parquet) foreverReplayable input; cheap, durable history
Hourly bucketsFlink state plus a key-value store (DynamoDB, Cassandra, or the SQL table above)Small, keyed by product and hour, updated by late events
Product-category mappingCatalogue database; daily Parquet export for jobsOwned by the catalogue; jobs need a consistent copy
Window totals (running state)Ranker state, checkpointed to the object storeNeeded only by the incremental ranker
Snapshots for servingRedis cluster, versioned keysMicrosecond reads, simple key lookups
Snapshots for durability and toolssales_rank in PostgreSQL or MySQL, with read replicasRebuild Redis, audits, internal queries
Snapshot pointerStrongly consistent configuration store (etcd, ZooKeeper, DynamoDB with a conditional write)One atomic switch for the whole fleet
Long-term analyticsData warehouse (Redshift, BigQuery)Seller reports, trend analysis, model training

SQL or NoSQL? The result data is a few GB per snapshot, with two access patterns, both by key. A relational database is a fine durable home and makes ad-hoc checks easy. The serving copy wants a key-value store, because each request is "get one key" at very high rates. Sale events are append-only and huge over time, which fits an object store plus a warehouse rather than either kind of database. See Choosing a Database: A Decision Guide and SQL vs NoSQL: How to Choose.

Deep Dives#

1. Ingesting sales events: getting every sale exactly once, without slowing checkout#

Everything downstream is only as good as the input. If a sale is lost, a product ranks too low. If a sale is counted twice, it ranks too high. If ingestion is slow, it delays checkout, which costs real money. There are three common ways to get sales into the ranking pipeline.

a) Ship the order service's log files. The order (or "sales API") servers write a line to a local log for every sale. A log shipper (Fluent Bit, Vector or Filebeat) uploads the files to the object store every few minutes, and a batch job reads them. This is the simplest design and is often how such systems begin.

  • Good: nothing in the request path except an append to a local file, and it is trivially cheap.
  • Bad: a log line is written when the server thinks the order succeeded. If the database transaction later rolls back, the log still says "sold". If a server dies before its file is shipped, sales are lost. Logs are not a contract: a developer who changes the log format silently breaks ranking.

b) Dual write from the application. After committing the order, the service also sends an event to Kafka. Two separate writes cannot be atomic. If the process crashes between them, the order exists but the event does not. If it sends the event first and the commit then fails, the event describes a sale that never happened. Retrying in a loop does not fix this: it only narrows the window.

c) Transactional outbox with change data capture (the recommended design). The order service inserts an outbox row for each order line in the same transaction as the order itself. A relay reads committed outbox rows, or the database's write-ahead log directly (Debezium for PostgreSQL and MySQL, DynamoDB Streams for DynamoDB), and publishes them to Kafka.

  • Every committed sale produces an event, and no uncommitted sale does.
  • The relay delivers at least once. After a crash it may re-publish the last few events, so consumers must deduplicate by event_id (see Idempotency and Safe Retries).
  • Checkout pays only for one extra small row insert, a fraction of a millisecond inside a transaction it was already running.

What an event says. We publish facts about order lines, not "increment product X":

EventMeaningEffect on rank
PLACEDAn order line was created with a quantityAdds units in the hour of occurred_at
CANCELLEDThe line was cancelled before shippingSubtracts the same units from the same hour
RETURNEDSome or all units were returnedSubtracts the returned units from the original sale's hour, if it is still in the window
FRAUD_FLAGGEDRisk systems marked the order as fraudulentSubtracts all units; adds the buyer to a watch list
QUANTITY_CHANGEDThe buyer changed the quantity before shippingAdds the difference, positive or negative

Each later event carries the original sale time of the line, so the pipeline can adjust the right hourly bucket. Because events are facts, the same stream can feed other consumers (seller analytics, recommendations) that interpret them differently.

Should a sale count when it is placed, paid or shipped? Counting at placement makes ranks react fastest. Counting at shipment is the most robust against fraud and cancellations, but it lags by a day or more for some products, which hurts newly launched hits. The common compromise is to count at placement and subtract cancellations and fraud as they arrive. That is what we do. Pre-orders are a special case: they can count at placement (so a book climbs the chart before release day) or at release, and that is a product decision.

Ordering and partitioning. The topic is keyed by product_id, so all events for one product arrive in order on one partition. A cancellation therefore always arrives after its sale. With a hundred or more partitions, a single best-selling product sends at most a few hundred events per second to its partition, well within one partition's capacity of thousands of events per second. Keying by order id would spread load more evenly but would put a product's events on many partitions. That is harmless for summing, but it makes per-product deduplication and validation harder.

Deduplication. Every event has a globally unique event_id, for example a UUID created in the outbox row. The hourly bucketer keeps recently seen event ids in its keyed state with a TTL of a few hours. That is long enough to cover relay restarts, and the state stays small: about 1.6 million events an hour × 16 bytes ≈ 26 MB per hour of retention. Batch jobs deduplicate by event_id with a DISTINCT or a group-by.

Schema and contract. Events are defined in a schema registry (Avro or Protobuf) with compatibility rules, so the order team cannot silently break the ranking job. New fields are optional. Renaming or removing a field needs a new version of the topic.

Late and replayed data. Events usually arrive within a second of commit. During an incident (relay down, Kafka partition unavailable) they can arrive minutes or hours late. The pipeline uses event time (occurred_at) to choose the bucket, waits a short grace period before ranking an hour, and accepts corrections after that by bumping the bucket's version (deep dive 3). Because the raw log is kept forever in the object store, any period can be re-processed from scratch if a bug is found.

Back-pressure. If the ranking pipeline falls behind (a slow deploy, a Flink job restarting), events simply wait in Kafka. Checkout never notices, because the only coupling is the outbox row. That is the main reason to put a log between the two systems. See Asynchronous Processing and Message Queues.

2. The batch job: MapReduce over the sales log, step by step#

The batch job is the backbone of correctness. Even with the incremental and streaming paths in place, a full recomputation from the raw log runs regularly and is the reference everything else is checked against. It is also the clearest way to explain the computation.

Input. Hourly Parquet files of sale events for the last 7 days (about 233 million PLACED events plus a few million corrections), and a snapshot of the product-to-category mapping (about 30 million rows, 300 to 600 MB).

The computation in two map-reduce steps.

  1. Sum per (category, product). The map step reads one event, drops it if it is outside the window, turns it into a signed, capped number of units (positive for PLACED, negative for corrections), looks up the product's categories and emits one pair per category: ((category, product), units). The shuffle brings all pairs for one (category, product) to one reducer, which sums them.
  2. Sort within each category. The second step re-keys each total by category and orders products by total, highest first. Each category's ordered list becomes ranks 1, 2, 3 and so on.

A small worked example. Suppose the window holds these events, and products belong to these categories: P1 is in Scales and Kitchen, P2 in Kitchen, P3 in Scales and Kitchen, and P4 in Scales.

TimeEventProductUnits
Mon 09:12PLACEDP12
Mon 11:40PLACEDP25
Tue 08:03PLACEDP31
Tue 19:55PLACEDP13
Wed 10:10PLACEDP44
Wed 10:30CANCELLED (line from Tue 08:03)P31
Thu 14:00PLACEDP36

The map step emits, for example, ((Scales, P1), 2) and ((Kitchen, P1), 2) for the first event, and ((Scales, P3), -1) and ((Kitchen, P3), -1) for the cancellation. After the shuffle and sum:

CategoryProductUnits
ScalesP15
ScalesP36 (1 − 1 + 6)
ScalesP44
KitchenP15
KitchenP25
KitchenP36

After sorting within each category: Scales is P3 (#1), P1 (#2), P4 (#3). Kitchen is P3 (#1), then P1 and P2 tied on 5. A tie-break rule is needed, and deep dive 6 discusses it. Notice that P3's rank includes the cancellation: without it, P3 would have 7 units in both categories.

The job in code. A compact version in the style of Python's mrjob library:

class WeeklySalesRank(MRJob):
    def mapper_init(self):
        # Small side input shipped to every mapper: a map-side join
        self.cats = load_product_categories("product_category.parquet")
        self.start, self.end = window_bounds(self.options.run_hour, days=7)
 
    def mapper(self, _, line):
        ev = parse_event(line)   # event_id, type, product_id, qty, occurred_at
        if not (self.start <= ev.occurred_at < self.end):
            return
        sign = 1 if ev.type == "PLACED" else -1
        units = sign * min(ev.qty, MAX_UNITS_PER_LINE)
        for cat in self.cats.get(ev.product_id, ()):
            yield (cat, ev.product_id), units
 
    def combiner(self, key, units):
        yield key, sum(units)    # sums are associative, so pre-sum locally
 
    def reducer_sum(self, key, units):
        total = sum(units)
        if total > 0:
            cat, product = key
            yield cat, (total, product)
 
    def reducer_rank(self, cat, totals):
        ordered = sorted(totals, key=lambda t: (-t[0], t[1]))  # tie: product id
        for rank, (total, product) in enumerate(ordered, start=1):
            yield (cat, rank), (product, total)
 
    def steps(self):
        return [MRStep(mapper_init=self.mapper_init, mapper=self.mapper,
                       combiner=self.combiner, reducer=self.reducer_sum),
                MRStep(reducer=self.reducer_rank)]

(Deduplication by event_id is left out for brevity; in practice it is a first step that groups by event_id.)

Why each part is there.

  • Map-side join. The mapping table is small enough (a few hundred MB) to copy to every mapper, so the job never shuffles 233 million events just to join them with categories. A broadcast join in Spark is the same idea. If the mapping grew too big to copy around, we would instead do a reduce-side join: key both inputs by product_id, join in the reducer, then emit per category.
  • Combiner. Without it, every one of the roughly 700 million (category, product) contributions would cross the network. With it, each mapper sends one pre-summed pair per (category, product) it saw. Most best sellers appear in every mapper's input, so this cuts shuffle volume by a large factor. Wikipedia's MapReduce article notes that the shuffle can take longer than the computation itself, which is why reducing what mappers emit matters so much.
  • Filter early. Dropping events outside the window in the mapper, not the reducer, means they never reach the shuffle.
  • Drop non-positive totals. A product whose sales were all cancelled should not get a rank.

Two ways to sort within a category.

  1. In the reducer (as above). Each category's products go to one reducer, which sorts them in memory. The largest category might hold 2 to 3 million sold products, about 100 MB of (total, product) pairs, which a reducer sorts in about a second.
  2. Let the framework sort (secondary sort). Re-key each total as a composite key (category, total) with the product as the value, partition by category only, and let the shuffle's sort order the keys by category and then total. The output then arrives at each reducer already in rank order, and an identity reducer simply numbers the lines. This is the classic MapReduce trick for sorting more data than fits in a reducer's memory, because the framework's sort spills to disk. To get descending order, sort on the negated total or use a descending comparator.

Skew. Partitioning by category sends all of "Books" (millions of products) to one reducer, while "Kitchen Scales" (a few thousand) finishes instantly. The job's finish time becomes the time to process the biggest category. Fixes:

  • Split large categories into range partitions by score. Sample the totals, choose boundaries (rank 1 to 10,000 in partition A, 10,001 to 100,000 in B and so on), sort each range on its own reducer, then add each range's offset to its local ranks. This is the same sampling-based range partitioning that distributed sort benchmarks use.
  • Or compute only what is shown in full (the top 100 or top 10,000) exactly per category, and give the long tail a rank by counting (deep dive 6).

In Spark the same job is a few lines:

-- Spark SQL over the Parquet sales log and the mapping snapshot
WITH lines AS (
  SELECT product_id,
         SUM(CASE WHEN type = 'PLACED' THEN 1 ELSE -1 END
             * LEAST(qty, 20)) AS units
  FROM (SELECT DISTINCT * FROM sales
        WHERE occurred_at >= :start AND occurred_at < :end)
  GROUP BY product_id
),
per_cat AS (
  SELECT pc.category_id, l.product_id, l.units
  FROM lines l JOIN product_category pc ON pc.product_id = l.product_id
  WHERE l.units > 0
)
SELECT category_id, product_id, units,
       ROW_NUMBER() OVER (PARTITION BY category_id
                          ORDER BY units DESC, product_id) AS rank
FROM per_cat;

Notice one improvement over the plain MapReduce version: it sums per product first and joins with categories afterwards. A product in 3 categories is summed once, not three times, and the join input shrinks from 233 million events to about 4 million product totals. This is a general rule: aggregate before you fan out.

Cost and run time. 4 GB of compressed Parquet, 4 million product totals and 12 million ranked rows take a modest Spark cluster (say 10 executors with 4 cores each) about 2 to 5 minutes, including writing the output. Run daily as a reference job, this costs very little. See Data Pipelines, Warehouses and Lakes.

3. Time-windowed ranking: rolling windows, buckets, decay and late events#

"The past week's most popular products" sounds precise, but there are several reasonable definitions, and the choice changes both the user experience and the system.

Option A: a calendar week. Count sales from Monday 00:00 to now, and reset every Monday. It is simple to compute (a running sum that resets), but ranks are meaningless on Monday morning, when only a few hours of data exist and one early order can make a product #1. It also matches no shopper's idea of "best selling right now".

Option B: a rolling 7-day window (the base design). At each hour H, count sales in [H − 168 hours, H). Every hour the window slides forward by one hour.

  • Hourly buckets make this cheap. Keep units per (product, hour) for the last 168 hours. Window total = sum of the 168 buckets.
  • Incremental update. When hour H closes: total(p) = total(p) + bucket(p, H − 1) − bucket(p, H − 169). Only products present in either of those two buckets change, about 1 million of the 10 million.
  • Memory. 168 buckets × about 600,000 products per hour × 16 bytes ≈ 1.6 GB. A sparse layout (store only non-zero buckets) is what makes this small: most products sell in only a few hours of the week.

The cliff problem with flat windows. A flat window treats a sale from 6 days and 23 hours ago exactly like one from a minute ago. Then, one hour later, the old sale counts for nothing. Consider a kitchen scale that sold 5,000 units in one lightning-deal hour last Tuesday and about 50 units an hour since. Its window total is about 5,000 + 50 × 167 ≈ 13,350, which may make it #2. When last Tuesday's hour leaves the window, its total drops to about 8,400 in a single hour and it may fall to #40. Shoppers see wild jumps that do not reflect anything happening now.

Option C: time-decayed score. Give each sale a weight that shrinks smoothly with age, for example exponential decay with a half-life h:

score(p, t) = Σ over sales s of p: units(s) × 2^(−(t − time(s)) / h)

  • With h = 24 hours, a sale from one day ago counts half, from two days ago a quarter, and from seven days ago 1/128 (less than 1%). There is no cliff: old sales fade instead of vanishing.
  • The half-life is the product knob. A shorter half-life reacts faster to trends but is noisier. A longer one is steadier but slower. A half-life of 1 to 3 days is a sensible range for "best sellers". For a "movers and shakers" list, which ranks products by how much their rank improved recently, something like 6 to 12 hours fits better.
  • This is the same idea as exponential smoothing of a time series: each new period is blended with a decayed memory of the past.

Decay is cheaper to update than a flat window. With hourly updates, score(p, H) = score(p, H − 1) × 2^(−1/h) + units(p, H − 1). There is no subtraction and no need to keep 168 buckets: one number per product is enough.

There is an even better trick. Every score decays by the same factor each hour, and multiplying all scores by the same number does not change their order. So we never need to touch products that did not sell. Instead of decaying old scores, inflate new sales: add units × 2^((time(s) − T0) / h) for a fixed reference time T0. This is the idea of forward decay (Graham Cormode, Vladislav Shkapenyuk, Divesh Srivastava and Bojian Xu, "Forward Decay: A Practical Time Decay Model for Streaming Systems", ICDE 2009). The weights grow without bound, so every few weeks we pick a new T0 and rescale all stored scores once, or store logarithms.

Which to choose? The interview problem asks for "the past week", so the rolling 7-day sum is the honest base answer. Decay is the natural improvement once the cliff problem is noticed. Amazon does not publish its formula, so we should not claim to know which one it uses. A practical hybrid restricts decay to the 7-day window: sales older than 7 days count zero, and sales within it are decayed.

Event time, processing time and late events. An event belongs to the hour in which the sale happened (event time), not the hour in which our pipeline saw it (processing time). Usually the two are seconds apart. During incidents they can be hours apart. The standard tools, set out in Tyler Akidau and colleagues' "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing" (VLDB 2015), are:

  • A watermark: the pipeline's estimate that "all events up to time W have arrived". When the watermark passes 15:00, the 14:00 bucket is complete enough to rank.
  • A grace period (allowed lateness): we rank hour 14 at 15:05, not at 15:00, to catch most stragglers.
  • Late corrections: an event for hour 14 that arrives at 16:30 still updates the hour 14 bucket and bumps its version. The next hourly run re-reads buckets whose version changed and applies the difference to window totals. Nothing is lost; it just shows up an hour later.
  • A reference recomputation: the daily full batch job recomputes the window from the raw log and corrects any drift in the incremental totals.

Time zones and calendars. Buckets are in UTC, which has no daylight-saving jumps, so every bucket is exactly one hour long. A rolling window does not care about local time at all: "the last 168 hours" is the same everywhere. Local time matters only if the product wants a calendar window ("this week, Monday to Sunday, in Germany"). Most time zones are whole hours from UTC, so hourly UTC buckets line up with local midnight. A few (India at UTC+5:30, Nepal at UTC+5:45) are not, so a marketplace there would use 15-minute buckets, or accept that its "week" starts at the nearest UTC hour.

4. Streaming aggregation per category: the same sums, continuously#

The batch job recomputes from scratch, and the incremental ranker updates once an hour. A stream processor goes further: it keeps the running sums up to date continuously as events arrive, so totals are always current and the hourly "run" becomes a cheap read of state that already exists.

The Flink job.

  1. Source and watermarks. The source reads order-line-events and assigns each event its occurred_at as event time. The watermark trails the maximum event time seen by a few minutes, so the job knows when an hour is complete.
  2. Deduplicate. Keyed by event_id, the job keeps a "seen" flag with a TTL of a few hours. This removes duplicates from the at-least-once relay.
  3. Sign and cap. PLACED adds units, and the other event types subtract them. The per-order and per-buyer caps from deep dive 11 apply here.
  4. Per-product hourly buckets. Keyed by product_id, the job adds units to the bucket for the event's hour. When the watermark passes the end of an hour, it emits the final bucket. Late events after that emit a correction.
  5. Window totals per product. The same keyed operator keeps each product's 7-day total (sliding sum) or decayed score. Because state is keyed by product, each product's total is updated in one place.
  6. Fan out to categories. The product-to-category mapping is broadcast state: a copy on every parallel instance, updated from a compacted Kafka topic whenever the catalogue changes. Each total change for a product becomes one "score changed" message per category.
  7. Per-category state. Keyed by category_id, the job keeps the top of each category's list (say the top 1,000, in a sorted structure) and the counts it needs to assign long-tail ranks (deep dive 6). Every 5 minutes it emits the top 100 of each category to the fast overlay. Every hour it emits the full snapshot data.

Exactly-once state. Flink takes periodic checkpoints: consistent snapshots of all operator state plus the Kafka offsets that produced it, written to the object store. After a crash, the job restores the last checkpoint and re-reads Kafka from the saved offsets. So every event affects the state exactly once, even though some events are processed twice. Output to the serving store is written per snapshot version (idempotent overwrites of the same keys), so replays after a restart produce the same keys with the same values. See Apache Flink and Stream Processing.

State size. Per-product state is 10 million products × (168 buckets in sparse form, or 1 decayed score, plus a total) ≈ 2 GB for the sliding version or about 200 MB with decay. Per-category state (top 1,000 per category plus count structures) is under 100 MB. Dedupe state is a few hundred MB. Flink's RocksDB state backend handles this comfortably on a few machines.

Throughput. 400 events per second on average and 8,000 at peak is tiny for Flink, whose operators process tens of thousands to millions of events per second per core. Fan-out multiplies the category stage by about 3, still trivial. The job's size is driven by state and availability (several task managers, so one failure does not stop it), not by throughput.

Hot keys. A viral product sends all its events to one product-keyed instance, and a giant category such as "Books" sends all its score changes to one category-keyed instance. At hundreds of events per second this does not matter. At much larger scale the standard fix is two-phase aggregation: pre-aggregate per (category, random shard) for a few seconds, then merge the partial sums per category, which spreads one hot key's work over many instances.

When is streaming worth it here? At 400 sales per second, an hourly batch job is cheap, simple and easy to reason about. Streaming earns its complexity when:

  • freshness better than an hour matters (the hot-product requirement, or "movers and shakers"),
  • the hourly batch job's run time grows to a large share of the hour at higher scale, or
  • many consumers want the same continuously updated aggregates (seller dashboards, inventory forecasting, recommendations).

5. Batch, streaming, Lambda or Kappa: choosing the processing model#

Four designs can produce the same hourly ranks. Each places complexity and correctness in a different spot.

DesignHow it worksFreshnessComplexityCorrectness story
Hourly full batchSpark or MapReduce recomputes 7 days every hourAbout 1 hour plus job timeLowest: one job, statelessEvery run starts from the raw log; bugs fix themselves on the next run once the code is fixed
Incremental batchHourly buckets plus a sliding sumAbout 1 hourLow to medium: state between runsNeeds a periodic full run to correct drift
LambdaBatch layer for authority plus a streaming speed layer for recent data, merged at read timeMinutes for hot products, hourly for the restHighest: two code paths that must agreeBatch overwrites the speed layer's approximations every hour
Kappa (streaming only)One streaming job; reprocessing means replaying the log through a new version of the jobSeconds to minutesMedium: one code path, but stateful streaming in productionReplay from Kafka or the object store rebuilds state

Wikipedia's article on the Lambda architecture credits Nathan Marz with first describing it, in a blog post titled "How to beat the CAP theorem", and summarises the main criticism: the batch and streaming sides need two code bases that must produce the same results. The same article credits Jay Kreps with the Kappa architecture, which uses one streaming code path and handles reprocessing by replaying the log.

Our choice, and why.

  • The authority is an hourly incremental snapshot, corrected by a daily full batch. This is simple, cheap and easy to audit.
  • The speed layer exists only for one narrow job: refresh the top 100 of each category every 5 minutes. It does not need to rank 12 million entries, only to find products that would enter or move within the top 100.
  • To avoid the "two code bases" problem, both paths share one library for the scoring rules (signs, caps, dedupe, decay), and a nightly check compares the speed layer's last lists of the hour with the batch snapshot. Their differences must stay under a threshold.

How the speed layer finds hot products cheaply. A product can enter the top 100 of a category between hourly runs only if its score, plus its sales since the last snapshot, exceeds the score of the current #100. The speed layer keeps, per category:

  • the last snapshot's top 100 scores (the "bar" to beat), and
  • running totals since the snapshot for every product that sold since then.

Every 5 minutes it computes snapshot score + partial-hour units for products near the bar and re-sorts only the top of the list. With decay, recent units carry their full weight, so a product whose sales spike at 14:05 can move up within minutes.

Merging at read time. The Rank Service reads the overlay list for a category (if one exists and is newer than the snapshot) and serves it for ranks 1 to 100. Ranks below 100 come from the snapshot. A product page whose product is in the overlay uses the overlay's rank. When the next hourly snapshot is published, overlays older than it are ignored and later deleted.

One subtle problem: ranks that disagree. With the overlay, a product can be #3 on the best sellers page (overlay) while its product page still says #5 (snapshot) for a few minutes. Two rules keep this consistent: the Rank Service uses the overlay for both queries for products in the overlay, and every response carries the version it used (snapshot T14 + overlay 14:25).

6. Ranking within a category: full ranks, ties and the long tail#

The best sellers page needs the top 100 in order. A product page needs that product's rank, which may be #2 or #1,843,210. These are different problems.

The top of the list: a partial sort. Finding the top K of n items does not need a full sort.

  • Scan all n items and keep the K best in a min-heap of size K. Each item compares with the heap's minimum, and only larger ones enter. This costs O(n log K) time and O(K) memory. For n = 2 million and K = 100, that is a fraction of a second.
  • Quickselect finds the K-th largest in O(n) expected time, after which the K items are sorted.
  • In a streaming setting, a sorted structure (a balanced tree or a skip list) of the top 1,000 per category stays updated as scores change, with a margin below the visible 100 so that products falling out of the top 100 can be replaced without a full scan.

Every product's rank: three approaches.

  1. Full sort per category (batch). Sort every category completely and store the rank of every (category, product). That is 12 million rows per snapshot, a few hundred MB. Simple and exact. This is our default for the hourly snapshot.
  2. A sorted set per category (online). Redis sorted sets keep members ordered by score. ZADD updates a score in O(log n), ZREVRANK returns a member's rank in O(log n), and ZREVRANGE 0 99 returns the top 100. Redis implements sorted sets with a skip list whose nodes store span counts, which is why rank queries are logarithmic. Memory for 12 million members is roughly 1 to 1.5 GB (Redis sorted-set overhead is about 60 to 100 bytes per member). This gives always-current ranks, but updates must then be applied in place, which conflicts with versioned snapshots. A common compromise is one sorted set per (category, snapshot), built and then published by a pointer switch. See Redis in Practice.
  3. Rank by counting (approximate for the tail). A product's rank is 1 plus the number of products in the category with a higher score. For the top 10,000 we store exact ranks. For the tail, we keep a histogram of scores per category, for example the number of products with 1 unit, 2 units, 3 units and so on, with coarser bins for larger counts. Rank(p) = (number of products in higher bins) + (position within its bin). Products with the same small score share a bin. Showing the same rank for all of them is honest, because they are genuinely tied. The histogram for a category is a few KB, so it is cheap to store and update.

Ties. In the tail, ties are everywhere: tens of thousands of products in a category may have sold exactly 1 unit in the week. There are standard ways to rank ties:

MethodScores 9, 7, 7, 5Pros and cons
Ordinal (row number)1, 2, 3, 4Unique ranks; needs a deterministic tie-break, otherwise products swap ranks between runs for no reason
Standard competition ("1224")1, 2, 2, 4Honest about ties; total positions stay meaningful
Dense ("1223")1, 2, 2, 3Compact, but the number no longer means "how many products sell more"

The best sellers page needs a total order, so it uses ordinal ranks with a stable tie-break. The tie-break should be meaningful: the product that reached the score earlier (it sold its units sooner), or the one with more sales in the last 24 hours, or, as a last resort, the product id. Product pages in the tail can show competition ranks, which is what the histogram approach produces naturally.

Products with zero sales. A product that sold nothing in the window has no rank in that category, and its page shows no rank line. The alternative ("#2,431,877 of 2,431,877") is useless and costs storage. Products that sold in the last 30 days but not the last 7 can keep showing their last rank, marked as older, if the product team wants that. That is a presentation choice.

Why ranks in the tail jump. Suppose a category's tail has 400,000 products with exactly 1 sale, and 150,000 products have more. A product with 1 sale is ranked around #150,001 to #550,000. One more sale moves it past most of that group, up by perhaps 250,000 places. Sellers sometimes read this as a dramatic change. It is really the shape of a long-tailed distribution: in the tail, one sale moves you past huge numbers of products tied on almost nothing. The math deep dive at the end puts numbers on this.

Movers and shakers. Wikipedia's Amazon article mentions a list of products with large jumps in rank. With two snapshots, rank change = old rank − new rank is computed per (category, product). Ranking by percentage improvement favours tail products (from #400,000 to #4,000 is a 99% gain), so a useful list requires a minimum score, for example the top 10,000 only, and compares ranks over 24 hours rather than 1 hour, to filter noise. It is one more derived list per category in each snapshot, built and served like best sellers.

7. Serving rank lookups: versioned snapshots, bulk loading and atomic publishing#

The read side must answer about 36,000 rank lookups and 4,000 page requests per second on average, and far more at peak, in single-digit milliseconds. It must also switch from one snapshot to the next all at once.

Key design. Two families of keys per snapshot, both in a Redis cluster:

KeyValueSizeUsed by
pr:{ver}:{product_id}List of (category id, rank) for this product, about 2 to 5 entries30 to 80 bytesProduct page rank line
bs:{ver}:{category_id}:{page}100 entries of (rank, product id, title, image URL, price snapshot)about 20 KBBest sellers pages
cnt:{ver}:{category_id}Number of ranked products, histogram for the taila few KB"#X of Y", tail ranks
current (in a config store, not in Redis)The live version, for example T14a few bytesEvery request

The product id is the shard key for pr: keys and the category id for bs: keys, so load spreads across the cluster's hash slots. See Partitioning and Sharding.

Why versioned keys instead of overwriting in place.

  • Consistency. A reader resolves current once per request and reads only keys of that version, so the page and the product line never mix runs.
  • No invalidation. A key's value never changes after it is written. Caches anywhere can keep it until it expires, with no risk of serving a stale value for that version. When the pointer moves, readers simply ask for different keys. Cache invalidation, one of the hardest problems in caching, disappears.
  • Instant rollback. If a bad snapshot slips through validation, moving the pointer back to the previous version fixes the site within seconds.

The snapshot life cycle.

Writing a full version every hour, or only the changes? A full version is about 4 million pr: keys and about 1,000 to 3,000 bs: pages, around 300 MB. Redis accepts hundreds of thousands of writes per second per shard with pipelining, so a 10-shard cluster loads a full version in well under a minute. At our scale, write the full version every hour. It is the simplest correct choice.

At 10 to 100 times the scale, two optimisations help:

  • Write only changed keys and fall back to the previous version. The ranker writes keys only for products whose ranks changed, and records T14 inherits T13. A reader that misses pr:T14:P reads pr:T13:P. This is copy-on-write layering. It cuts writes by the share of unchanged products (often 50 to 70% of tail products keep the same rank hour to hour) but adds a second lookup on misses, and chains must be collapsed regularly.
  • Bulk-load files instead of individual writes. Build an immutable, sorted key-value file per shard (an SSTable or RocksDB file) in the batch job and ship it to the serving nodes, which open it read-only. LinkedIn's Voldemort read-only stores and HBase bulk loads work this way. It suits very large snapshots that change completely every run.

The pointer. current lives in a small, strongly consistent store: etcd, ZooKeeper, a DynamoDB item updated with a conditional write, or a row in the SQL database. Rank Service instances poll it every few seconds or watch it for changes, and cache it locally. A conditional update (set current = T14 if current = T13) prevents two runs that finish close together from publishing out of order. A late T13 can never overwrite T14.

Choice of serving store.

OptionRead latencyFitNotes
Redis cluster (in memory)Sub-millisecondBest for this size (a few GB per version)Keep 2 to 3 versions in memory; replicas per shard for availability
DynamoDB or Cassandra plus a cacheSingle-digit millisecondsGood if the data grows beyond memory, or for multi-region tablesWrites cost money per item; bulk loading 4 million items an hour is fine, 400 million is not
SQL read replicas only1 to 5 ms for indexed lookups, if hotFine for low traffic40,000 reads per second spread over several replicas is possible, but caching is cheaper
Static files on a CDN10 to 40 ms at the edgeExcellent for best sellers pagesPublish JSON pages per category to object storage; the CDN serves them

Redis is the serving store, the SQL table is the durable copy used to rebuild Redis, and best sellers pages are additionally pushed to the CDN.

Availability of the read path.

  • Every Redis shard has a replica in another zone, with automatic failover.
  • If Redis is unreachable, the Rank Service falls back to the SQL replicas for a limited rate (protected by a circuit breaker) and then to "no rank shown". It never lets rank lookups slow the product page.
  • The Rank Service runs in every zone, and each instance's in-process cache keeps serving hot keys for a while even if Redis is completely down.

8. Caching in depth: layers, patterns, stampedes and hot keys#

Caching is the core of this design: 40,000 reads per second against data that changes hourly. Done well, the database behind the cache sees almost nothing. Done badly, a single publish event can knock it over.

Is caching justified? Measure the problem first. Without a cache, 40,000 lookups per second on SQL read replicas at 1 to 3 ms each would need several large replicas running hot, and peaks of 120,000 or more per second would need many more. A best sellers page assembled from the database (a range scan plus a join with product details) might take 10 to 30 ms. A Redis read takes about 0.2 to 1 ms over the network, and an in-process cache read takes microseconds. Since the data changes only once an hour, almost every read is a repeat, so caching wins on every count.

The layers, from the shopper inwards.

LayerWhat it cachesHit rate (assumed)Notes
ClientBest sellers JSON for a few minutes; the product page has its own policyLow to mediumLeast control: we cannot invalidate a phone's cache, so keep TTLs short and responses versioned
CDNBest sellers pages for every category95 to 99%Same answer for every shopper in a marketplace; purge top categories on publish
Web or page cacheRendered product page fragments, including the rank lineMediumOwned by the product page team
In-processThe hottest few thousand pr: and bs: keys50 to 80% of Rank Service requestsMicrosecond reads; protects Redis from hot keys
RedisEvery key of the current and previous snapshotAbout 100% by designIt is the serving store, not an optional cache
SQLDurable copyRarely readIts buffer pool keeps recent partitions in memory

Which pattern?

  • Cache-aside is the default for the in-process layer and for refilling Redis from SQL: check the cache, on a miss read the source, store the value, return it. It keeps the cache lean, because only keys that are actually read are cached.
  • Write-through fits how snapshots reach Redis. The builder writes every key into the serving store as part of publishing, so nothing has to be loaded lazily. Strictly, Redis here is the primary serving store, with SQL as a backup, rather than a cache in front of SQL.
  • Write-behind (write to the cache and flush to the database later) has no place here: we never write ranks from the read path.
  • Read-through is how the CDN behaves: on a miss, the CDN itself fetches from the origin.
  • Refresh-ahead fits the hottest keys: shortly before the next snapshot is published, the builder pre-loads the new version's hottest keys into every cache layer (step 4 of Flow 2).

TTL and eviction. With versioned keys, TTL is about memory, not freshness. In-process entries live for 30 to 60 seconds, so a pointer change takes effect quickly, and use LFU or LRU eviction. Redis keys get a TTL of a few snapshot periods (for example 4 hours), so old versions expire automatically even if cleanup fails. LRU suits most workloads. LFU suits this one slightly better, because the popular products stay popular all day.

The publish-time stampede. Versioned keys have one sharp edge. At the moment the pointer moves from T13 to T14, every cached key becomes useless at once, because readers now ask for pr:T14:*. If the in-process caches and the CDN are cold for T14, the first few seconds send the full request rate to Redis, and for the CDN to the origin.

  • Warm before the switch. Pre-load the top N keys of T14 into Redis (they are there anyway) and into the in-process caches of every Rank Service instance (broadcast "warm these 5,000 keys"). Then move the pointer.
  • Request coalescing (single-flight). Inside each Rank Service instance, concurrent misses for the same key share one fetch, so 500 simultaneous requests for the top product in "Books" become one Redis read.
  • Staggered pointer adoption. Instances pick up the new pointer within a few seconds of each other (polling with jitter), which spreads the miss wave.
  • Stale-while-revalidate at the CDN. The CDN keeps serving the T13 page while it fetches the T14 page in the background, so shoppers never wait on a cold edge.

Hot keys. On a peak shopping day, the best sellers page of a top category, or the product page of a viral item, can receive tens of thousands of requests per second. With a 1-in-N shard layout, all of them land on one Redis shard.

  • In-process caching absorbs most of it: each Rank Service instance reads the key once per TTL.
  • Replicate hot keys. Write the hottest bs: pages under several suffixes (bs:T14:1234:1#0 to #7) on different shards, and let readers pick a suffix at random.
  • Read from Redis replicas for the hottest shards.
  • See Cache Failure Modes: Stampedes, Hot Keys and Penetration.

Cache failure. If Redis loses a shard, the in-process caches cover hot keys for a minute, the replica takes over within seconds, and misses fall back to SQL behind a circuit breaker that caps the rate at what the replicas can handle. Requests beyond that cap get "no rank" rather than a slow page. The database is never exposed to the full read rate.

Cache penetration. Requests for products that have no rank (most of the catalogue in any given week) would miss every layer and reach SQL each time. Store an explicit "no rank" value (pr:T14:P = []) for every catalogue product, or keep a Bloom filter of ranked products per snapshot. Either way the Rank Service answers "no rank" from memory. See Caching Fundamentals and Cache Eviction and Invalidation.

9. Products in many categories: fan-out, mapping changes, trees and skew#

"Items can be in multiple categories" is the assumption that most changes the shape of the computation.

Fan-out cost. If the average product is in c categories, every sale contributes to c category totals. With c = 3 that is 700 million contributions per week instead of 233 million. The fix from deep dive 2 is to aggregate per product first, then fan out. The expensive part (reading and summing events) happens once per product, and only the small per-product totals (4 million) are multiplied by c.

Where the mapping lives and how it is joined.

  • The catalogue owns product_category. Jobs never query the catalogue database directly. They read a daily snapshot (Parquet in the object store), plus a stream of changes (a compacted Kafka topic fed by CDC from the catalogue).
  • In batch, the mapping (30 million rows, a few hundred MB) is a broadcast join: every worker gets a copy.
  • In streaming, it is broadcast state, updated from the change topic.

Categories do change. The interview problem says items cannot change categories, which keeps it simple. In reality, sellers fix listings and the catalogue team reorganises the taxonomy. So when a product moves from "Baking Tools" to "Kitchen Scales" mid-week, which category should its past sales count in?

PolicyMeaningEffect
Category at time of saleEach sale stays in the category it was listed in when soldHistorically accurate; the product starts from zero in its new category, and its old category keeps its sales for up to 7 days
Category now (recommended)All window sales count in the product's current categoriesThe product's rank in the new category reflects its real popularity immediately; simple, because ranking uses the current mapping

We use the current mapping at each run. It matches what shoppers see: the product is listed in Kitchen Scales, so it should rank there with its real sales. Because we aggregate per product first, this costs nothing extra: the fan-out simply uses the current mapping.

Category trees. The base problem has no subcategories. Real taxonomies are trees: "Home & Kitchen" contains "Kitchen & Dining", which contains "Kitchen Utensils", which contains "Kitchen Scales". A product listed in a leaf also ranks in each ancestor, as in the "#3 in Kitchen Scales, #412 in Home & Kitchen" example.

  • Expand ancestors at fan-out. Precompute, for every leaf category, its ancestor list (a few levels deep). A product in 2 leaves with 4 ancestors each ranks in up to 8 categories, with duplicates removed where two leaves share an ancestor.
  • Avoid double-counting. A product in two leaves under the same parent must count once in the parent, not twice. Taking the union of ancestor sets before emitting guarantees this.
  • Display. The product page usually shows the leaf ranks and one top-level rank, not all eight, which is a presentation choice in the Rank Service.

Skew across categories. Category sizes follow a long tail. A few top-level categories hold millions of products, and many leaves hold a few hundred.

  • In batch, the per-category sort is skewed (deep dive 2's range partitioning fixes it).
  • In streaming, the category-keyed operator for "Books" receives far more updates than "Kitchen Scales". Two-phase aggregation or giving huge categories their own parallel operators fixes it.
  • In serving, the best sellers page of a giant category is a hot key (deep dive 8).

Many categories per product make the product page lookup slightly heavier, which is why the pr: key stores all of a product's ranks together in one value. One key read answers the whole "Best Sellers Rank" line, however many categories the product is in.

10. Scaling the databases: replicas, federation, sharding, denormalisation and NoSQL#

The simplest version of this design has one SQL database: a primary that takes writes (the raw transactions and the sales_rank table) and replicas that serve reads. It is worth walking through why that falls short, and which scaling technique fixes which part, because interviewers often probe exactly this.

Where a single SQL primary struggles.

  • Writes of raw sales. 400 inserts per second on average is easy for one primary, but peaks of 4,000 to 8,000, plus indexes, plus vacuum or purge work, plus 1.44 TB of growth over three years make one primary uncomfortable. And the ranking pipeline has no reason to store raw events in an OLTP database at all.
  • Reads. 40,000 reads per second on average, more at peak, would need many replicas. Replicas also lag the primary, so a freshly published snapshot may not yet exist on every replica.
  • Cache misses. Even behind a cache, if the cache fails, the replicas might not handle the misses. That is the reason for the circuit breaker in deep dive 8.

The techniques and where each helps.

TechniqueWhat it meansWhere it helps here
Move raw events out of the OLTP databaseEvents go to Kafka and the object store, never to a SQL tableRemoves the heaviest write load entirely; the object store absorbs 40 GB or more a month for very little cost
Read replicasCopies of the primary that serve readsServe the durable sales_rank copy for cache rebuilds and internal tools
Primary failoverA standby takes over when the primary failsKeeps the sales_rank table writable for the next snapshot load
Federation (functional partitioning)Different databases for different functionsThe ranking database is separate from the orders and catalogue databases, so a heavy snapshot load never competes with checkout
ShardingSplit one table across several databases by a keyShard sales_rank by category, or keep it whole: at a few GB per snapshot, sharding is not yet needed
DenormalisationStore data pre-joined for the read patternThe bs: pages contain titles and image URLs, so serving needs no join with the catalogue; pr: values hold all of a product's ranks together
SQL tuningIndexes, covering indexes, partitioning, bulk loadsThe covering index on (snapshot, product), one partition per snapshot, COPY for bulk inserts, no row-by-row updates
NoSQL for servingA key-value store for key lookups at high ratesRedis (or DynamoDB) answers rank lookups; SQL becomes the durable copy
Warehouse for analyticsA columnar database for large scansSeller reports and trend analysis run on Redshift or BigQuery over the sales log, not on the serving database
Tiered retentionKeep only recent data in fast storesRedis holds 2 to 3 snapshots; SQL keeps a few days of snapshots; the object store keeps everything

See Pattern: Scaling Writes, Pattern: Scaling Reads and Database Performance and SQL Tuning.

Loading a snapshot into SQL without hurting readers. Inserting 12 million rows an hour row by row would take minutes and would compete with reads. Instead:

  1. Create a new partition (or a staging table) for the snapshot.
  2. Bulk-load it with COPY (PostgreSQL) or LOAD DATA (MySQL). Millions of rows load in tens of seconds.
  3. Build its index after loading, which is faster than maintaining it during the load.
  4. Attach the partition. Readers of other snapshots never see a lock.
  5. Drop partitions older than the retention period. A drop is a metadata change, not a delete of millions of rows.

What changes at 10 to 100 times the scale? If sales grew to 10 or 100 billion a month (many marketplaces, a larger catalogue):

  • The batch layer stays the same in shape. Spark scales by adding executors, and the object store scales without limit.
  • The hourly buckets move from a SQL table to a wide-column or key-value store (Cassandra, DynamoDB, Bigtable) keyed by (product, hour).
  • The serving store may outgrow memory if we keep full ranks for hundreds of millions of products across dozens of marketplaces. A disk-based key-value store with a cache, or bulk-loaded read-only files (deep dive 7), takes over.
  • Approximation becomes attractive for the long tail. Exact counts are still cheap for the top of each category, but a count-min sketch (Graham Cormode and S. Muthukrishnan, "An Improved Data Stream Summary: The Count-Min Sketch and its Applications", 2005) can estimate tail counts in fixed memory. Its error is at most εN (N = total units in the window) with probability 1 − δ, using about e/ε × ln(1/δ) counters. The top-K and trending case study covers sketches and heavy-hitter algorithms such as Misra–Gries in depth. At our scale, with only 400 sales per second, exact counting is cheap, and we should not approximate.

11. Correctness, validation and resisting manipulation#

A sales rank is a public, money-moving signal. A product at #1 gets a badge and more visibility on the site, which leads to more sales. That creates two threats: our own bugs, and sellers who try to game the rank.

Making a snapshot trustworthy before it goes live. The validator runs before every pointer switch:

CheckExample ruleCatches
CompletenessNumber of ranked (category, product) entries within ±10% of the previous snapshotA job that read only part of the input
Category coverageEvery category ranked last hour is present, unless it has no salesA failed partition or a mapping bug
Score conservationSum of window units per product equals the batch reference within 0.1% (daily)Drift in incremental totals
MovementNo more than X% of the top 100 in large categories changed in one hour, unless a known event explains itDouble counting, a replay without dedupe
FreshnessThe newest bucket included is the hour just closedA stuck input
SanityUnits per product in the window never exceed the order system's own sales totals for that productBroken signs, caps or dedupe

A failing check keeps the previous snapshot live and pages the on-call engineer. Serving ranks that are one hour old is always better than serving wrong ranks.

Reconciling the paths. Three computations should agree: the speed layer, the incremental hourly snapshot and the daily full batch. Each night, the full batch result is compared with the incremental totals for the same window. Any difference above a tiny threshold means a bug, such as a missed late correction or a dedupe failure. The incremental state is then reset from the batch result, which makes the system self-healing.

Manipulation patterns and defences. Some sellers try to buy their way up the chart. Typical patterns and the counter-measures:

  • One huge order. A seller (or a friend) orders 500 units once. Defence: cap the units counted per order line and per buyer per product per window, for example at 20. Real bulk buyers (offices, schools) still buy what they want, but the rank counts them like a heavy household.
  • Many small orders from fake accounts. Defence: count only orders from accounts with some history (age, past purchases, verified payment), and weight new accounts lower. Risk systems flag clusters of accounts sharing payment instruments, devices or addresses, and their orders arrive as FRAUD_FLAGGED corrections.
  • Self-purchasing. The seller's own accounts buy their product. Defence: link buyer and seller identities through risk signals, and exclude or down-weight purchases from linked accounts.
  • Buy and return. Orders that inflate the rank and are later returned. Defence: subtract returns, and track return rates per product. A product with an unusual pattern of returns soon after purchase is reviewed, and its rank can be frozen.
  • Free or near-free sales. Units sold at a 100% discount through coupons. Defence: weight sales by price relative to the product's normal price, or exclude units below a minimum price.

Counting distinct buyers. A strong, simple defence is to rank by a score that grows with distinct buyers, not only units: score = Σ over buyers b of min(units by b, cap). Counting distinct buyers exactly per (product, window) needs a set of buyer ids. A HyperLogLog sketch estimates it with about 1 to 2% error in a few KB per product. At our scale, with 4 million products selling each week, exact sets are affordable for the tail and sketches cover the giant best sellers.

Anomaly detection on velocity. A product that goes from 0 to 300 sales an hour, all from new accounts in one region, at night, looks different from a product featured on television. The speed layer is the natural place for this check, because it sees spikes first. Suspicious spikes are held back from the fast overlay for review instead of being shown at once.

Auditability. Every snapshot is reproducible: given the raw log, the mapping snapshot, the code version and the configuration (caps, half-life), the batch job produces the same ranks. When a seller asks "why did my rank drop at 14:00?", support can see their product's buckets and the changes in its category, without exposing other sellers' sales figures.

12. Availability, failures, regions and operations#

The ranking system is not on the critical path of buying, but it is on the critical path of rendering pages. A product page that waits for a rank is a slow product page. The design principle is simple: the read path depends only on precomputed data, and every dependency can fail without breaking the page.

Failures in the pipeline.

FailureWhat the shopper seesRecovery
CDC relay downNothing; ranks freeze at the last snapshotThe relay resumes from its log position; events are late, not lost
Kafka partition unavailableNothing, if it heals within minutesReplication factor 3; producers retry; consumers resume from offsets
Flink job crashNothing; the speed layer pausesRestore from the last checkpoint and replay from Kafka
Hourly ranker failsRanks are an hour older ("as of 13:00")Retry; if the failure persists, page someone; the daily batch is the fallback
Validator rejects a snapshotRanks stay on the previous snapshotInvestigate; re-run after the fix
Bad snapshot publishedWrong ranks for minutesMove the pointer back; mark the snapshot rejected
Mapping snapshot missingThe job refuses to run (no silent empty join)Use the last good mapping, or wait

Freshness as an SLO. "A new snapshot is published within 15 minutes of each hour, 99% of the time" is the core pipeline objective. A dashboard tracks the age of the current snapshot, and an alert fires when it is more than 90 minutes old. That alarm catches stuck jobs, missing inputs and rejected snapshots. See Observability: Logs, Metrics and Traces.

Failures on the read path. Timeouts and fallbacks protect the product page. The Rank Service call has a hard timeout of about 20 ms, retries at most once to another instance, and returns "no rank" on failure. Circuit breakers protect SQL from cache-failure floods. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

Multiple regions. Shoppers are served from several regions. Two designs work:

  • Compute once, replicate everywhere. One region runs the pipeline for a marketplace and ships each snapshot to every serving region: bulk-copy files to each region's object store and load them into local Redis, or use a multi-region table such as DynamoDB global tables. The pointer is switched per region after its copy is loaded and validated, so a region never points at a snapshot it does not have.
  • Compute per region. Each region runs its own pipeline from a replicated event stream. This gives more independence, but the results may differ slightly between regions, which is bad for a public rank. We prefer computing once and replicating.

If the computing region fails, serving regions keep their last snapshot (ranks age gracefully), and a standby pipeline in another region takes over from the replicated sales log. See Multi-Region and Global Data and Disaster Recovery and Backups.

Peak days. Big shopping events multiply sales by 10 to 20 times and reads by more. Preparation:

  • Pre-scale the Rank Service and Redis replicas, and raise CDN TTLs slightly.
  • Shorten the speed layer's refresh interval for top categories, because deals change ranks quickly.
  • Load-test the publish path at peak read rates, because the publish-time stampede (deep dive 8) is worst exactly then.
  • Freeze risky deployments to the pipeline.

Backfills and changes to the formula. Changing the score (for example adding decay or new caps) is a product change with visible effects. Run the new formula in shadow for a week, writing snapshots that are never published. Compare them with the live ranks, review the biggest movers, and switch the pointer to the new formula's snapshots only after sign-off. Because snapshots are versioned and computed from the immutable log, this costs only compute.

Operating cost. At this scale, the whole system (a small Flink cluster, an hourly Spark job, a Redis cluster of about 10 shards with replicas, a small SQL database, Kafka topics shared with other consumers and CDN traffic for best sellers pages) is modest. The cost is dominated by the read path, which is why caching it well pays for itself.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Publish-time cache stampedeEvery versioned key misses at once; Redis or the origin gets the full read rateWarm hot keys before the switch, single-flight per key, jittered pointer adoption, stale-while-revalidate at the CDN
Hot best sellers page or viral productOne Redis shard overloaded on peak daysIn-process cache, hot-key replication with suffixes, CDN for pages, replica reads
Duplicate events after relay or job restartsRanks inflated; products jump wronglyUnique event ids, dedupe state with TTL, checkpointed offsets, validator movement checks
Lost sales from dual writes or log shippingRanks too low; silent errorsTransactional outbox with CDC; daily reconciliation against order totals
Late events after an incidentThe affected hours undercount until correctedEvent-time buckets, grace period, versioned bucket corrections, daily full recompute
Skewed giant categoriesBatch job finish time dominated by one reducer; hot operator in streamingAggregate per product before fan-out, range-partitioned sort, two-phase aggregation
Cliff when big sales leave a flat windowRanks drop sharply for no current reasonTime-decayed scores within the window, or a hybrid decay
Bad snapshot (bug, partial input)Wrong public ranks, seller complaintsValidator gate, versioned snapshots, instant rollback by pointer
Ranking pipeline down for hoursRanks go staleServe the last good snapshot with "as of" times; freshness alarms; standby pipeline in another region
Redis outageRank lookups fail or flood SQLReplicas with failover, in-process cache, circuit breaker to SQL, "no rank" fallback
Rank manipulation (bulk, fake or self-purchases)Untrustworthy best sellers listsPer-order and per-buyer caps, distinct-buyer scoring, fraud corrections, velocity anomaly holds
Cache penetration for unranked productsMisses for most of the catalogue reach SQLExplicit "no rank" entries or a Bloom filter of ranked products per snapshot

What Interviewers Expect#

Mid-level. Clarify the use cases (compute the past week's best sellers per category, let users view them) and state the numbers: 10 million products, 1,000 categories, 1 billion sales a month (400 per second), 100 billion reads a month (40,000 per second) and a 100 : 1 read ratio. Store sale logs in an object store and run a MapReduce or Spark job that sums units per (category, product) and sorts each category, writing to a sales_rank table with sensible indexes. Serve reads through a REST API, a load balancer and a memory cache, because reads vastly outnumber writes. Recognise that a product in several categories must be counted in each.

Senior. Ingest sales through a transactional outbox and Kafka instead of dual writes, with dedupe by event id and subtraction of cancellations and returns. Make the window incremental with hourly buckets and a sliding sum, and explain event time, grace periods and late corrections. Aggregate per product before fanning out to categories, and handle skew. Publish versioned snapshots with an atomic pointer switch, so readers never mix runs and caches need no invalidation. Layer the caches (CDN for pages, in-process for hot keys, Redis as the serving store, SQL as the durable copy), and handle the stampede at publish time and hot keys. Separate the ranking database from orders, use read replicas and bulk loads, and keep raw history in the object store and a warehouse.

Staff and above. Treat the rank as a product with business consequences. Discuss flat windows against time decay (the cliff problem, forward decay), tie-breaking and the long tail (histogram ranks, competition ranks), and movers and shakers. Choose between batch, incremental, Lambda and Kappa with a clear argument: an hourly incremental snapshot as the authority, a narrow speed layer for the top 100, shared scoring code, and nightly reconciliation that makes the system self-healing. Design against manipulation with caps, distinct-buyer scoring, fraud corrections and anomaly holds, and add a validation gate with rollback. Plan for multiple regions (compute once, replicate snapshots), freshness SLOs, shadow-testing formula changes and peak-day preparation. Know when not to use approximate counting: at 400 sales per second, exact counts are cheap.

Deep Dive: sizing the system, tier by tierShow

The capacity section gave totals. Here we turn them into machines, to show where the effort and the money actually go.

Event stream. About 440 events per second on average (sales plus corrections), 8,000 or more at peak, at about 250 bytes each. That is about 110 KB/s on average and 2 MB/s at peak. Seven days of retention hold about 60 GB, or about 180 GB with replication factor 3. A topic with 64 to 128 partitions on an existing shared Kafka cluster is plenty. The partition count is set for consumer parallelism and future growth, not current load.

Archiver and sales log. Parquet with compression shrinks events by perhaps 4 to 6 times, so about 10 to 15 GB per week and 50 GB per month land in the object store. Hourly files per partition are of a reasonable size (tens of MB); a daily compaction job merges small files so that batch reads stay fast.

Hourly bucketer (Flink). Throughput is trivial. State is the sizing driver: dedupe ids for a few hours (a few hundred MB), sparse hourly buckets for 7 days (about 1.6 GB) and window totals (about 200 MB). Three or four task managers with 4 cores and 16 GB each, using the RocksDB state backend with checkpoints every minute to the object store, give room for failover and peak days.

Incremental ranker. It reads about 1.2 million bucket rows per hour (newest hour, expired hour and late corrections), updates about 1 million product totals, fans out to about 3 million category entries and re-sorts the affected categories. Most categories need only a merge of a few changed entries into an already sorted list. This runs on a single machine with 8 to 16 cores in about a minute, or as a small Spark job.

Daily full batch. 10 executors with 4 cores each, about 5 minutes per run. It is cheap enough to run several times a day if needed, and to rerun for backfills.

Redis serving store.

  • One snapshot version: about 4 million pr: keys at roughly 100 to 150 bytes each including Redis overhead (about 0.5 GB), about 3,000 bs: pages at 20 KB (about 60 MB), plus count structures. Roughly 0.6 to 1 GB per version.
  • Three versions in memory (current, previous, and the one being built): about 3 GB.
  • Throughput after in-process caching (see the next deep dive): about 15,000 reads per second on average and perhaps 50,000 at peak. One Redis shard serves on the order of 100,000 simple operations per second.
  • So 6 shards with one replica each are chosen for availability and headroom, not for memory or throughput. That leaves room for hot-key replicas and peak days.

Rank Service. 40,000 requests per second on average and 120,000 at the daily peak, each a few microseconds of work plus at most one Redis call. A modest instance handles 5,000 to 10,000 gRPC requests per second, so 15 to 25 instances at peak, spread over 3 zones, with autoscaling.

SQL sales_rank. About 12 million rows per snapshot at about 60 to 80 bytes including indexes, so about 1 GB per snapshot. Keeping 48 hourly snapshots takes about 50 GB. One primary, one synchronous standby and two read replicas. It is a small database by modern standards.

CDN. 4,000 best sellers requests per second × 20 KB ≈ 80 MB/s (about 640 Mbit/s) at the edge, with origin traffic at 1 to 5% of that.

Summary.

TierSize
Kafka64 to 128 partitions on a shared cluster, about 180 GB retained
Object storeAbout 50 GB a month of Parquet
Flink3 to 4 task managers, a few GB of state
Incremental rankerOne 8 to 16 core machine, or a small Spark job
Daily batch10 executors × 4 cores, about 5 minutes
Redis6 shards plus replicas, about 3 GB used
Rank Service15 to 25 instances at peak
SQLOne primary, one standby, two replicas, about 50 GB
CDNAbout 640 Mbit/s at the edge

The lesson: the computation is small, and the engineering effort goes into the read path and into correctness. Most of the capacity exists for availability and peaks, not for steady load.

Deep Dive: the math of ranks, windows and cachesShow

How sales relate to rank. Sales across products are highly skewed. A simple model is a power law: the product at rank r sells about s(r) = C × r^(−α) units per week. Economists have used Amazon's public ranks to estimate sales with this kind of relationship, for example Judith Chevalier and Austan Goolsbee ("Measuring Prices and Price Competition Online: Amazon.com and BarnesandNoble.com", Quantitative Marketing and Economics, 2003) and Erik Brynjolfsson, Yu (Jeffrey) Hu and Michael D. Smith ("Consumer Surplus in the Digital Economy: Estimating the Value of Increased Product Variety at Online Booksellers", Management Science, 2003). The parameters vary by category and period, so the numbers below are only an illustration.

Take C = 10,000 units a week and α = 1:

RankWeekly units
110,000
101,000
100100
1,00010
10,0001

Below about rank 10,000, products sell around one unit a week, and many of them tie.

How sensitive is rank to one more sale? With α = 1, the rank for a product selling s units is about r = C / s.

  • At the top, a product with 1,000 units (rank 10) that sells one more moves to about rank 9.99. In practice it does not move at all.
  • In the tail, a product with 1 unit (rank about 10,000) that sells one more unit doubles its sales and moves to about rank 5,000.

So one sale is invisible at the top and dramatic in the tail. Explaining this to sellers avoids many support tickets, and it is why tail ranks shown to the public can safely be approximate (deep dive 6).

The cliff, in numbers. Using the kitchen-scale example from deep dive 3: 5,000 units in one deal hour plus 50 an hour otherwise gives a 7-day total of about 13,350. One hour after the deal hour leaves the window, the total is about 8,400, a 37% drop in an hour. If the category's #2 to #40 are spread between 13,000 and 8,500, the product falls from #2 to about #40 in one hour, although nothing about it changed.

With exponential decay and a 24-hour half-life, the deal hour's 5,000 units count 5,000 × 2^(−167/24) ≈ 40 units at the end of the week. The product's score has been falling smoothly all week, from about 5,000 just after the deal to about 1,700 by the time the deal leaves the window (1,700 is close to the steady-state score from 50 units an hour, which we compute next). There is no cliff.

What window does a half-life correspond to? A product selling a steady u units per hour has a decayed score of u × Σ 2^(−k/h) over k = 0, 1, 2, …, which is about u × h / ln 2 ≈ 1.44 × u × h. So a half-life of h hours "remembers" about 1.44 h hours of steady sales:

  • h = 24 hours remembers about 35 hours.
  • To give steady sellers the same score as a flat 7-day window (168 hours of sales), h ≈ 168 / 1.44 ≈ 117 hours, about 5 days.

This gives the product team a clear dial: the half-life sets how quickly ranks react, and 1.44 × h is its "equivalent window".

How well does caching work? Product page views are also skewed. Assume they follow a Zipf distribution with exponent 1 over 10 million products. The share of views going to the top k products is about H(k) / H(n), where H(k) ≈ ln k + 0.577 is the harmonic number.

Cached products (top k)Share of rank lookups
1,000(6.91 + 0.58) / (16.12 + 0.58) ≈ 45%
10,000(9.21 + 0.58) / 16.70 ≈ 59%
100,000(11.51 + 0.58) / 16.70 ≈ 72%
1,000,000(13.82 + 0.58) / 16.70 ≈ 86%

An in-process cache of 10,000 entries per Rank Service instance (a few MB) absorbs about 59% of lookups. The remaining 41% (about 15,000 per second on average) go to Redis, which holds everything. That is why Redis is sized as the full serving store rather than as a cache: the long tail is too long for any cache to absorb it.

CDN origin load. 1,000 categories × about 3 pages commonly viewed × 50 edge locations, each fetching a page at most once per 300-second TTL, is at most about 500 origin requests per second. Most pages are not requested in every location, so the real figure is lower. Compared with 4,000 page requests per second at the edge, the CDN absorbs well over 90%.

Why not a count-min sketch for the tail? A count-min sketch with width w = ⌈e/ε⌉ and depth d = ⌈ln(1/δ)⌉ overestimates each count by at most εN with probability 1 − δ, where N is the total count. Here N ≈ 300 million units per week. With ε = 10⁻⁴ (w ≈ 27,000 counters per row), the error bound is about 30,000 units, far larger than the counts of every product below the top few. To bound the error at 1 unit, ε would have to be about 1/N, which means hundreds of millions of counters per row: more memory than exact counts for 4 million products. So sketches are excellent for finding heavy hitters in a huge stream, but useless for ranking the long tail. At our scale, exact counts win.

Freshness math. With hourly snapshots published 5 to 15 minutes after the hour, a sale made just after the hour waits about 70 minutes to appear in a rank, and one made just before the hour about 10 minutes. On average the delay is about 40 minutes. The speed layer cuts this to about 5 to 10 minutes for the top 100 of each category, which is where shoppers actually look.

Deep Dive: one product, one week, end to endShow

Sam sells a new digital kitchen scale, product P7. It is listed in two leaf categories, "Kitchen Scales" and "Baking Tools", both under "Home & Kitchen" in the tree variant. The base design ranks only the two leaves.

  1. Monday 09:00. Listing. The catalogue adds P7 with its two categories. A CDC event updates the mapping topic, and the Flink job's broadcast state now knows P7's categories. P7 has no sales, so its product page shows no rank line (pr:T08:P7 = []).
  2. Monday 10:14. First sale. Asha buys one unit. The order transaction writes an outbox row. Within a second, a PLACED event (event id e1, quantity 1, occurred at 10:14) is on Kafka. The bucketer adds 1 to (P7, hour 10).
  3. Monday 11:05. First rank. The 11:05 run ranks hour 10. P7's window total is 1. In "Kitchen Scales" (about 8,000 products with sales this week), about 5,500 products have more than 1 unit and 2,500 are tied on 1. P7 gets competition rank #5,501 and shows "#5,501 in Kitchen Scales". The page reads it from pr:T10:P7 through Redis.
  4. Tuesday. Steady sales. P7 sells 20 to 40 units an hour after a cooking blogger mentions it. Each hourly snapshot moves it up: #812, #140, #38. Each move is a new pr: value under a new version. No cache entry is ever invalidated. Readers just follow the pointer.
  5. Wednesday 14:00 to 14:59. A deal. P7 is a lightning deal and sells 3,000 units in the hour. The speed layer sees P7's partial-hour total pass the current #100's score in Kitchen Scales at about 14:09, and passing #1 by 14:20. At 14:25 the overlay list for Kitchen Scales shows P7 at #1, and the product page (which also reads the overlay for products in it) agrees. The velocity check sees that the buyers are spread across thousands of established accounts, so nothing is held back.
  6. Wednesday 14:31. A bulk order. A buyer orders 400 units for an office. The per-line cap counts 20. The order is real and ships, but it cannot buy a rank.
  7. Wednesday 15:05. The hourly snapshot. The incremental run adds hour 14 (3,000 + 20 capped units, minus 6 cancellations) to P7's total and ranks it #1 in Kitchen Scales and #4 in Baking Tools. The validator notes that a top-100 entry changed by more than 1,000 places in an hour, finds a matching deal in the deal calendar, and passes. The pointer moves to T15. The overlay for 14:25 is now older than the snapshot and is ignored.
  8. Thursday. A late batch of events. A relay incident at 03:00 delayed 20 minutes of events by 2 hours. The bucketer applies them to the 02:00 and 03:00 buckets and bumps their versions. The 06:05 run sees the changed versions and applies the differences. P7's total rises by 12 units an hour late. The daily batch at 04:00 had already reported a small difference for those hours, which resolved by 06:05.
  9. Next Wednesday 15:00. The deal leaves the window. With the flat window, P7's total drops by 3,000 at once and it falls from #1 to #9. With the decayed score (if adopted), its score had been easing down all week, and the drop is a small step.
  10. Next Thursday. A return wave. Fifteen units from the deal are returned. Their original sale hour (last Wednesday at 14:00) is outside the window, so the rank is unaffected. The returns are recorded in the log for seller analytics and audits.

Every step uses only the mechanisms in the design: outbox events, event-time buckets, caps, a validator gate, versioned snapshots, a narrow speed layer and late corrections. None of them needed the read path to compute anything.

Deep Dive: a 45-minute interview plan for this problemShow
MinutesWhat to do
0–5Clarify: what "popular" means (units, orders, revenue), the window (rolling 7 days), refresh rate (hourly, faster for hot products), several categories per product, cancellations and returns, top N or full ranks, scale
5–10Numbers: 10 M products, 1,000 categories, 1 B sales a month (400 per second), 100 B reads a month (40,000 per second), 40 bytes per sale (40 GB a month), 233 M sales a week, 12 M ranked rows per snapshot
10–20High-level design: outbox and Kafka, sales log in the object store, hourly batch or incremental ranker, sales_rank table, Redis serving store, Rank Service, CDN for best sellers pages
20–25Data model and API: versioned sales_rank keyed for both queries, hourly buckets, product-category mapping; the two GET endpoints with snapshot versions and cursor paging
25–40Deep dives (choose with the interviewer): the MapReduce job and fan-out, incremental windows and late events, versioned snapshots and caching, speed layer for hot products, manipulation
40–45Bottlenecks, failure handling and evolution

Follow-up questions to prepare for.

  1. Why not update the rank on every sale? Reads outnumber writes 100 to 1. The answer only needs to change hourly, and per-sale updates of ranks cost a lot and create inconsistent reads. Precompute snapshots instead.
  2. Walk me through the MapReduce job. Step one maps sales to ((category, product), units) and sums them in combiners and reducers. Step two re-keys by category and sorts, either in the reducer or by secondary sort in the shuffle.
  3. A product is in five categories. What changes? Aggregate per product first, then fan out to categories with a broadcast join. The product's pr: value stores all five ranks together.
  4. How do you avoid recomputing a whole week every hour? Use hourly buckets and a sliding sum (add the newest hour, subtract the expired one), with a daily full recompute as a check.
  5. What happens when an event arrives two hours late? It goes into the bucket for its event-time hour, and the bucket version is bumped. The next run applies the difference, and the daily batch confirms it.
  6. How do readers avoid seeing half-old, half-new ranks? Versioned keys and an atomic pointer switch, with rollback by moving the pointer back.
  7. How do you cache something that changes every hour? Use versioned keys, so values never change and no invalidation is needed. Warm the cache before the switch, coalesce requests and use stale-while-revalidate at the CDN.
  8. A product goes viral. How fast does it show up? Within minutes through the speed layer for the top 100. Other ranks update at the hourly snapshot.
  9. How do you stop a seller buying their way to #1? Caps per line and per buyer, distinct-buyer scoring, fraud corrections, velocity anomaly holds and a validator movement check.
  10. Would you use a count-min sketch? Not at 400 sales per second. Exact counts are cheap, and a sketch's error swamps tail counts. Sketches are for finding heavy hitters in much larger streams.
  11. Redis is down. What happens? Replicas fail over. In-process caches cover hot keys. Misses go to SQL behind a circuit breaker, and the page renders without a rank if needed.
  12. How would you support 20 marketplaces? Rank per marketplace with a marketplace field in every key. Compute once per marketplace and replicate snapshots to the serving regions. Share the pipeline code.
Deep Dive: variants of the problemShow

"Rank by revenue, or by a mix of signals." Replace units with revenue (units × price, in one currency). Revenue favours expensive products, so a "top grossing" list differs from "best selling". Mixed scores (units plus page views plus add-to-cart events) need more inputs and weights. They also raise the bar for manipulation defences, because views are cheaper to fake than purchases. The pipeline is unchanged; only the scoring function and its inputs change.

"Movers and shakers." Rank products by how much their rank improved over, say, the last 24 hours, limited to products in the top 10,000 so that the list is not flooded by tail products jumping from #400,000 to #4,000. Compute it from two snapshots during the build, and store it as another per-category list.

"Per marketplace and per region." Each country store has its own rank. Every key, bucket and snapshot gets a marketplace dimension. The pipeline runs once per marketplace (or one job with marketplace in the key), and serving regions receive the snapshots of the marketplaces they serve. Global products appear in several marketplaces with different ranks.

"Real-time leaderboard." For a game or a live event, ranks must change within a second of each score. Then the design flips: a Redis sorted set per leaderboard with ZINCRBY on every event, ZREVRANK for "my rank" and ZREVRANGE for the top N. There are no snapshots, and the challenges become hot keys and sharding very large boards. The top-K and trending case study covers this in depth.

"Category trees with deep hierarchies." Each sale counts in its leaf categories and every ancestor (deduplicated). The number of ranked (category, product) rows grows by the depth of the tree. Top-level categories become huge and skewed, so range-partitioned sorts and histogram tail ranks matter more.

"Personalised best sellers." "Best sellers among people like you" needs segments (age group, region, interests) or full personalisation. Segment-level ranks are the same pipeline with segment as one more key dimension. Full personalisation is a recommendation problem, covered by the recommendation system case study.

"All-time and long windows." An all-time best sellers list is a running sum that never subtracts, plus periodic re-computation from the warehouse. Monthly and yearly lists are daily buckets summed in the warehouse, computed once a day, and cached for a day.

Small scale (a shop with 50,000 products). One PostgreSQL database holds orders and a sales_daily table. A cron job runs every hour: INSERT INTO sales_rank SELECT ... ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY units DESC) over the last 7 days, into a new snapshot id, then updates a one-row pointer table. An application cache (or HTTP caching) in front of the two queries handles the reads. The concepts (snapshot, pointer, cache, caps) are the same at both ends of the scale; only the machinery changes.

Deep Dive: how the system evolves from v1 to v3Show

v1: launch. The order service ships sale log lines to the object store. An hourly Spark job sums the last 7 days per (category, product) and sorts, writing a new snapshot partition to the sales_rank table in PostgreSQL. A pointer row selects the live snapshot. A Rank Service reads SQL replicas through a Redis cache-aside layer, and best sellers pages go through a CDN. What must be right from day one:

  • every sale counted once (event ids),
  • cancellations subtracted,
  • snapshots versioned and published atomically,
  • caps per order line, and
  • every response labelled with its snapshot.

v2: scale and freshness. Replace log shipping with a transactional outbox and Kafka. Add the Flink hourly bucketer and the incremental ranker, with the daily full batch as reference and reconciliation. Make Redis the serving store, written in full on each publish, with SQL as the durable copy. Add the validator gate and rollback, in-process caches with warming and single-flight, and hot-key replication. Add the speed layer for the top 100 per category every 5 minutes. Strengthen manipulation defences: distinct-buyer scoring, fraud corrections and velocity holds.

v3: platform. Multiple marketplaces and regions, with snapshots computed once and replicated. Category trees with ancestor expansion. Time-decayed scores, adopted after a shadow period. Movers and shakers, revenue ranks and segment-level ranks as further lists from the same pipeline. Bulk-loaded read-only stores if snapshots outgrow memory. Freshness and correctness SLOs, dashboards and peak-day runbooks. Each step adds lists and dimensions at the edges while the core stays the same: immutable events, buckets, a reproducible snapshot, a validation gate, an atomic pointer and caches with versioned keys.

Key Takeaways#

  • Precompute, then serve. Ranks change hourly and are read 100 times for every sale. Compute a complete snapshot once an hour, and make every read a key lookup from memory.
  • Ingest with an outbox, not dual writes. The transactional outbox and CDC turn every committed order line into exactly one event, without adding latency to checkout. Consumers dedupe by event id and subtract cancellations, returns and fraud.
  • MapReduce is the clear baseline. Map sales to ((category, product), units), combine and reduce to sums, then sort per category. Aggregate per product before fanning out to categories, use a map-side join for the mapping, and partition big categories by range to fix skew.
  • Windows are a product decision. A rolling 7-day sum built from 168 hourly buckets updates in seconds. Flat windows have a cliff when big sales fall out, and exponential or forward decay removes it, with an equivalent window of about 1.44 × the half-life.
  • Use event time, a grace period and late corrections. Events go in the bucket of the hour the sale happened. Late events bump bucket versions, and a daily full recompute keeps the incremental state honest.
  • Versioned snapshots plus an atomic pointer give consistent reads, instant rollback and caches that never need invalidation. The price is a cache stampede at publish time, which warming, single-flight and stale-while-revalidate remove.
  • Layer the caches deliberately. Use a CDN for identical best sellers pages, in-process caches for hot keys, Redis as the serving store, SQL as the durable copy and explicit "no rank" entries against penetration.
  • The top and the tail are different problems. Partial sorts or sorted structures handle the top 100. Full sorts or score histograms handle tail ranks, where ties are everywhere and one sale moves a product thousands of places.
  • Products in many categories multiply the work, not the complexity, if each product's sales are summed once and fanned out with the current mapping. Ancestors in a category tree must be deduplicated.
  • A public rank needs defences. Use caps per line and buyer, distinct-buyer scoring, fraud corrections, velocity holds and a validator that refuses suspicious snapshots.
  • Keep the processing model as simple as the requirements allow. An hourly incremental snapshot is the authority, and a narrow speed layer handles hot products. Exact counts beat sketches at 400 sales per second.