Skip to content

Design a Price Tracker (CamelCamelCamel)

Intermediate 82 min read Part 17 of 18

Design a CamelCamelCamel-style price tracker: collect prices for 500M products, schedule checks politely, store price history, and send price-drop alerts.

The Problem#

We want to build a price tracking service like CamelCamelCamel. It watches the prices of products on a big online store such as Amazon, keeps a history of every price change, draws a chart of that history, and emails or pushes an alert when a product falls below a price the user chose. A browser extension shows the chart right on the store's product page, and lets the user subscribe to a price drop with one click.

It sounds small: fetch a price, save it, compare it with a number. Three things make it a real design problem:

  1. The catalogue is huge, and we do not own it. A store like Amazon lists hundreds of millions of products. We can only learn a price by asking the store (through an official API, or by downloading the product page), and the store limits how often we may ask. We cannot check everything every minute, so we must decide what to check, and how often.
  2. History adds up. Years of price points for hundreds of millions of products is a lot of data, and a chart must still load in under half a second.
  3. Alerts are a fan-out problem. When a popular gadget drops in price on a sale day, tens of thousands of people may be waiting for exactly that drop, and all of them should hear about it within the hour, once, and not again if the price wobbles.

A browser extension adds a fourth twist: a million users looking at product pages are a free, constant stream of fresh price observations. But that data comes from machines we do not control, so it can be wrong or malicious.

An analogy. Think of a team of mystery shoppers for a giant department store. They cannot visit every shelf every hour, so a manager sends them first to the aisles customers care about (products people are watching) and to the shelves where prices change often, and visits the dusty corners once a week. Each shopper writes down prices in a ledger. When a price falls below what a customer asked for, the manager phones that customer. Some customers also phone in prices they saw themselves; the manager is grateful, but checks before acting on a surprising one.

CamelCamelCamel itself is a real, modest-sized business: Wikipedia notes it was founded by Daniel Green in 2008, that a failure of three hard drives on its database server in January 2019 took it down for several days, and that its operator has put its running costs at about $11,000 a month. That is a useful reminder that a well-designed tracker does not need a giant budget; most of the design is about being clever with a limited fetch budget.

Background: a few terms used in this design#

  • Product identifier. Amazon identifies products by the ASIN (Amazon Standard Identification Number), a 10-character code. For books with a 10-digit ISBN, the ASIN equals the ISBN. The ASIN appears in the product page URL, which is how an extension knows which product is on screen. Other stores use SKUs, UPC/EAN barcodes or their own ids.
  • Offer. One seller's price for a product. A product page can have many offers: the store's own price, third-party sellers selling new, and used or refurbished offers. Trackers usually keep separate histories for a few price types (for example, store price, third-party new, used).
  • Price observation. One reading: (product, price type, price, currency, time, source). Sources are our scheduled checks, an official API, or extension reports.
  • Scraping. Downloading web pages with a program and extracting data from the HTML. The alternative is an API: a documented interface the store provides for partners, with its own limits.
  • Politeness. Limiting how fast we fetch from a site so we do not overload it, and respecting its robots.txt file, a standard text file where a site lists which paths automated clients may and may not fetch.
  • Rate limit. A cap on requests per second or per day, set by the store (for an API) or by us (to be polite).
  • Price drop alert. A user's rule: "tell me when product X's store price is at or below $Y" (or "drops by Z%").
  • Fan-out. Turning one event (a price change) into many messages (one per subscriber).
  • Content script. The part of a browser extension that runs inside a web page and can read its content.

Clarifying Questions#

QuestionAssumed answer
Which stores?Amazon first, in several countries (each country is a separate catalogue with its own prices). The design should allow other stores later.
How many products?About 500 million product pages across countries. Many are long tail with few viewers.
How many users?20 million registered users; 1 million daily active extension users; 3 million website visits a day.
How many alerts do users set?100 million active alert subscriptions, on about 40 million distinct products.
How fresh must prices be?Not real time. A price-drop alert within 1 hour of the change is the target for watched products. Long-tail products can be days old.
Which price types?Store price, third-party new, used. Alerts can target any of them.
Alert conditions?Price at or below a target, or a percentage drop from the current price.
Alert channels?Email and push (mobile app and extension).
How do we get prices?Official product API where allowed, plus fetching public product pages within published rules and our own politeness limits, plus extension reports.
History length?Since we started tracking the product; years. Charts for 1 month, 3 months, 1 year, all time.
Chart latency?Under 500 ms for the price history of a product, on the website and in the extension.
Consistency?Availability over consistency. A chart that is a few minutes behind is fine.

Requirements#

Functional requirements#

  1. Users can view the price history of a product as a chart (store, third-party new, used), on the website or in the browser extension on the store's product page.
  2. Users can subscribe to price-drop alerts with a target price or a percentage, from the website or with one click in the extension.
  3. Users receive an alert by email or push when the condition is met, once per drop.
  4. Users can manage their tracked products and alerts (list, edit, pause, delete).
  5. The system continuously collects prices for tracked and popular products, and discovers new products.
  6. The extension contributes price observations from pages users view (with consent).
  7. Optional pages: "top price drops today" and category deal lists, built from the same data.

Out of scope: product search and discovery on our site beyond simple lookup, cross-store price comparison, reviews and ratings, buying through us (we only link to the store).

Non-functional requirements#

  • Scale: 500 million products, 100 million alert subscriptions, 1 million extension users.
  • Politeness and compliance: stay within every store's API limits and published crawling rules. Never overload a store. Prefer official data sources.
  • Freshness: alerts within 1 hour of a price change for watched products; daily or better for popular products; weekly at least for the long tail.
  • Latency: price history chart in under 500 ms (p99), extension overlay in under 300 ms from page load for popular products.
  • Availability over consistency: 99.9% for reading charts and creating alerts; eventual consistency is acceptable everywhere.
  • Correctness of alerts: no alerts from fake or garbled prices; no duplicate alerts for the same drop.
  • Cost: low. Fetch budget is the scarce resource; storage and compute must be cheap per product.
  • Privacy: the extension sends only what is needed (product id, prices, country), never browsing history.

Capacity Estimation#

The fetch budget is the key number. Everything else is cheap by comparison.

  • If we checked all 500 million products once a day: 500 M / 86,400 ≈ 5,800 fetches per second, forever. That is far more than a polite client should send to one store, and far more than an official API allows.
  • Official APIs are tight. Amazon's Product Advertising API 5.0, as its rate documentation described it, started each new partner at 1 request per second and 8,640 requests per day, raising the limits with the sales the partner referred (one extra request per day for every 5 cents of shipped revenue, and one extra request per second, up to 10, for every $4,320). One request could ask for up to 10 products. So even a large partner at 10 requests per second gets at most about 100 products per second, about 8.6 million product checks a day. (Amazon has since announced that PA-API 5 is deprecated in favour of a new Creators API; the exact limits of any API must be read from its current terms.)
  • So the plan is tiered freshness:
TierProductsCheck intervalChecks per day
Hot: has subscribers, or many views5 Mabout every hour120 M
Warm: some views or recent changes45 Mdaily45 M
Cold: the long tail450 Mevery 2–4 weeks15–30 M
Total500 Mabout 180–195 M a day

That is about 2,200 checks per second on average. Extension reports and the official API cover part of it; the rest must come from carefully paced page fetches spread across countries (each country store is a separate site with its own limits). Even this budget would be large for a small company; the design must work at a tenth of it too, by shrinking the hot tier to products with active alerts and leaning harder on the extension.

Extension observations.

  • 1 million daily active users, each viewing about 15 product pages a day: 15 million observations a day, about 175 per second, with evening peaks of 1,000 per second.
  • They are concentrated on popular products, exactly the ones we most want fresh. A product viewed by 1,000 extension users a day gets an observation every 90 seconds without any fetch from us.

Price changes.

  • Most long-tail products change price rarely. Popular products can change several times a day (sellers reprice automatically).
  • Assume on average 0.3 changes per product per day, counting only checked products: about 60 million price changes a day, 700 per second, with sale-day peaks of 10× (7,000 per second).

Storage.

DataCalculationSize
Products (metadata, title, image URL, category)500 M × 1 KB500 GB
Raw observations (kept 30 days)200 M checks + 15 M reports a day × 100 bytes21 GB a day, about 650 GB
Price history, change-only60 M changes a day × 20 bytes (product, type, time, price, compressed)1.2 GB a day, about 440 GB a year
Daily summaries (min, max, last per day)500 M × 3 types × 365 days × 12 bytes, but only for days with data, so far lessunder 1 TB a year
Subscriptions100 M × 100 bytes10 GB
Users20 M × 1 KB20 GB
Alert log (sent alerts)3 M a day × 200 bytes600 MB a day

Two observations: storing only changes (not every check) cuts history by about 3×, and the whole price history of the catalogue fits comfortably in a single-digit number of terabytes after years of operation. This is a modest data problem; the hard part is the fetch budget and the fan-out.

Reads.

  • Charts: 3 million website visits plus 15 million extension product views a day: about 18 million chart requests a day, 200 per second on average, 2,000 at peak.
  • Most requests are for popular products, so a cache in front of the history store absorbs most of them.

Alerts.

  • 100 million subscriptions. On a typical day perhaps 2–3% trigger: 2–3 million alerts a day, about 30 per second on average.
  • On a big sale day, many popular products drop at once. A single product with 50,000 watchers that drops below most of their targets produces 40,000 alerts in one go. Peaks of 5,000–10,000 alerts per second are possible for short periods.
QuantityAveragePeak
Price checks (all sources)2,200/s4,000/s (scheduler catch-up)
Extension reports175/s1,000/s
Price changes700/s7,000/s
Chart requests200/s2,000/s
Alerts sent30/s10,000/s
Price historyabout 440 GB a year

Core Entities#

  • Product: store, country, product id (ASIN), title, image, category, current prices per type, last checked time, tier, next check time.
  • PriceObservation: product, price type, price, currency, availability (in stock or not), observed time, source (scheduler, API, extension), source details (install id, trust score).
  • PricePoint: a confirmed change in the history: product, price type, time, price. Stored only when the price changes.
  • User: email, push tokens, country, preferences.
  • Subscription (alert): user, product, price type, condition (target price or percent), state (armed, triggered, paused), last notified price and time.
  • Notification: subscription, price that triggered it, channel, status, sent time.
  • ExtensionInstall: anonymous install id, trust score, report counts, first seen.
  • CheckTask: product, due time, priority, attempt count (the unit of work for the scheduler).

API Design#

# Price history (public, cacheable)
GET  /v1/products/{store}/{country}/{productId}
  -> { title, image, current: { amazon: 24.99, new3p: 23.50, used: 18.00 },
       lastChecked, tracked: true }
GET  /v1/products/{store}/{country}/{productId}/history?type=amazon&range=1y
  -> { points: [[t, price], ...], min, max, avg, resolution: "daily" }
 
# Alerts (authenticated)
POST   /v1/subscriptions   { store, country, productId, priceType, targetPrice? | dropPercent? }
  -> 201 { subscriptionId, state: "armed" }
GET    /v1/subscriptions?cursor=...
PATCH  /v1/subscriptions/{id}  { targetPrice?, paused? }
DELETE /v1/subscriptions/{id}
 
# Extension
GET  /v1/ext/overlay?store=amazon&country=us&productId=B0XXXXXXX
  -> { history summary (small), current, subscribed?: true }
POST /v1/ext/observations   X-Install-Id: <random id>
  { store, country, productId, prices: { amazon: 24.99, new3p: 23.50 },
    inStock: true, observedAt }
  -> 202
 
# Deals (public)
GET  /v1/deals?country=us&category=electronics&window=24h

Design notes:

  • History is returned at a resolution that fits the chart. A one-year chart needs at most a few hundred points; the server down-samples (daily min/max) instead of sending every change. This keeps responses small and cacheable.
  • Public product and history endpoints are cacheable by CDN and by the extension, with short TTLs (minutes for hot products, hours for cold ones).
  • Observations are fire and forget (202). The extension never waits for them, and the server treats them as untrusted input (deep dive 4).
  • Subscriptions are idempotent by (user, product, price type): subscribing twice updates the target instead of creating a duplicate.
  • The install id is random and not tied to the user account unless the user signs in, which limits what we learn about any person while still letting us score sources.

High-Level Design#

We build the design requirement by requirement.

1) Collecting prices#

Prices arrive from three sources. All of them end up as observations on one Kafka topic, so the rest of the system does not care where a price came from.

  • The scheduler decides which products are due for a check, in priority order, and puts check tasks on a queue.
  • Fetch workers take tasks, ask the rate limiter for permission (a token per store and country), then call the official API when it covers the product, or fetch the public product page when allowed.
  • The parser extracts prices, stock status and title from the response. Parsers are versioned per store and page layout.
  • The observation intake receives reports from the extension, attaches the install's trust score and rejects obviously bad data early.

2) Turning observations into price history#

The price processor compares each observation with the current price of that product and price type:

  • Same price: update last_checked only. No history row.
  • Different price, trusted source (our own check or API): write a history point, update the current price, publish a price change event.
  • Different price, extension source: accept if it agrees with recent data or comes from trusted installs; otherwise send it to verification, which asks the scheduler for an urgent check of that product. Only a confirmed change becomes history.

3) Viewing price history#

  • The history service answers chart requests. For long ranges it reads the daily summary table (one row per product, type and day with min, max, close); for short ranges it reads the raw change points.
  • Popular charts are cached in Redis and at the CDN for a few minutes. When a product's price changes, its cache entry is invalidated.

4) Subscribing to alerts#

Creating a subscription stores (user, product, type, target). If the product is new to us, the product registry adds it, and the scheduler starts tracking it. Every subscription also raises the product's priority: products people are waiting on move to the hot tier.

5) Matching price changes to subscribers and notifying#

For each price change, the alert matcher finds subscriptions on that product whose condition is now satisfied and which are still armed. It marks them triggered and puts one notification job per user on the queue. The notification service applies user preferences (channels, quiet hours, one digest instead of many mails), sends through email and push providers, and records the result.

The full high-level design#

Components:

  • API gateway: authentication for user actions, per-user and per-install rate limits, routing.
  • History service: chart data at the right resolution, with caching.
  • Subscription service: create, edit and delete alerts; tells the registry which products matter.
  • Product registry: the catalogue we track, with tier, priority and next check time per product.
  • Scheduler: picks due products in priority order and emits check tasks, within budgets per store.
  • Fetch workers and parsers: call the API or fetch pages within rate limits; extract prices.
  • Observation intake: validates and scores extension reports.
  • Price processor: deduplicates observations, detects changes, verifies suspicious ones, writes history and publishes change events.
  • Alert matcher and notification service: find who should hear about a change and deliver it once.
  • Stores: Kafka; a wide-column store (Cassandra) or time-series store for history; PostgreSQL for users and subscriptions; Redis for current prices, caches and rate limits; object storage for raw pages kept briefly for parser debugging; a warehouse for analytics.

Key Flows#

Flow 1: A scheduled price check#

  1. The scheduler pops the most urgent due product from its partition and emits a task.
  2. The worker asks the rate limiter for a token for that store and country. If none is available, the task waits; it is never sent faster than the budget.
  3. The worker calls the API (batching up to the API's per-call limit) or fetches the page, and the parser extracts prices.
  4. The price processor sees a change from 29.99 to 24.99, writes a history point, updates the current price and publishes a change event.
  5. The product's next check time is recomputed from its priority and how often it changes (deep dive 2).

Flow 2: An extension report that needs verification#

A 90% drop reported by one unknown install is suspicious. The processor does not write it or alert anyone. It asks for an urgent check from our own fetcher. If the check confirms the price, the change is written and alerts fire (slightly later, but correctly). If not, the report is discarded and the install's trust score drops.

Flow 3: Viewing a chart in the extension#

The extension reads the product id from the page URL (for Amazon, the ASIN is part of the URL), so it does not need to parse the page to know what to show. Most popular products are served from the CDN or Redis in a few milliseconds; a cold product needs one partition read (tens of milliseconds).

Flow 4: One-click subscribe from the extension#

Flow 5: A price drop reaches the subscribers#

The matcher reads only subscriptions on this product whose target is at or above the new price, thanks to an index on (product, price type, target). Marking them triggered in the same step makes the alert happen once; the subscription re-arms when the price later rises above the target again (deep dive 5).

Data Model#

Price history in Cassandra (one partition per product and price type, rows ordered by time):

CREATE TABLE price_points (
  product_key  text,        -- 'amazon:us:B0EXAMPLE1'
  price_type   text,        -- 'amazon' | 'new3p' | 'used'
  bucket       int,         -- year, to cap partition size
  at           timestamp,
  price_cents  int,
  in_stock     boolean,
  PRIMARY KEY ((product_key, price_type, bucket), at)
) WITH CLUSTERING ORDER BY (at DESC);
 
CREATE TABLE daily_summary (
  product_key  text,
  price_type   text,
  day          date,
  min_cents    int,
  max_cents    int,
  close_cents  int,
  PRIMARY KEY ((product_key, price_type), day)
) WITH CLUSTERING ORDER BY (day DESC);

Subscriptions in PostgreSQL (sharded by product key so that the matcher's query hits one shard):

CREATE TABLE subscriptions (
  id                  UUID PRIMARY KEY,
  user_id             UUID NOT NULL,
  product_key         TEXT NOT NULL,
  price_type          TEXT NOT NULL,
  target_cents        INT  NOT NULL,
  state               TEXT NOT NULL,      -- armed | triggered | paused
  last_notified_cents INT,
  created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (user_id, product_key, price_type)
);
CREATE INDEX subs_match ON subscriptions (product_key, price_type, target_cents)
  WHERE state = 'armed';
CREATE INDEX subs_by_user ON subscriptions (user_id);
  • Partition by product and type, bucketed by year. A chart reads one or a few partitions in time order, which is exactly what a wide-column store does best. Bucketing keeps partitions small even for products that change price thousands of times.
  • Prices are integer cents with the currency implied by the store country. No floating point in money.
  • The partial index on armed subscriptions keeps the matcher's query a short range scan: "target at or above the new price" for one product.
  • UNIQUE (user_id, product_key, price_type) makes subscribing idempotent.
  • Sharding subscriptions by product makes matching cheap but "list my alerts" a cross-shard query. The subs_by_user index per shard plus a small user-to-subscriptions lookup table (or a second copy keyed by user) fixes that.
DataStoreWhy
Price history and daily summariesCassandra (or ScyllaDB); a time-series database is an alternativeAppend-heavy writes, reads by one key over a time range, cheap at terabyte scale
Current pricesRedis plus a durable copy in the product registryRead on every observation; tiny per product
Product registry and schedulePostgreSQL sharded by product key, or CassandraNeeds updates of priority and next check time
Users and subscriptionsPostgreSQLTransactions, uniqueness, simple queries
Observations and changesKafkaBuffer, replay, many consumers
Raw fetched pages (short retention)Object storageParser debugging and re-parsing
Analytics and dealsData warehouse or OLAP storeAggregations across products

See Choosing a Database: A Decision Guide and Apache Cassandra in Practice.

Deep Dives#

1. Collecting prices: APIs, page fetching and crowdsourcing#

There are four ways to learn a price. A good design uses all of them, in order of preference.

SourceHow it worksStrengthsWeaknesses
Official product APIDocumented calls (for Amazon, the affiliate product API) returning prices and offers as JSONStructured, stable, allowed, cheap to parseTight quotas, often tied to affiliate sales; may not include every price type or every product
Partner feedsBulk files or streams of prices from retailers or affiliate networksVery cheap per product, covers whole cataloguesOnly where a partnership exists; may be hours old
Fetching public product pagesDownload the HTML a browser would get and extract pricesCovers anything a visitor can seeMust respect robots.txt and terms; layouts change; heavy to parse; easy to overload a site if done carelessly
Browser extension reportsThe extension reads prices from pages the user is already viewingFree, fresh, concentrated on popular productsUntrusted; biased to what users browse; privacy-sensitive

Official APIs first. For Amazon, the Product Advertising API was the documented route for affiliates. Its published rules (described in the capacity section) tied the request budget to the sales the partner referred: one request per second and 8,640 per day to start, growing with shipped revenue, up to 10 requests per second, with up to 10 products per request. Access was lost after 30 days without referred sales. This is typical of retailer APIs: they are a business arrangement, not a free data tap. A tracker that earns affiliate commission from the "buy" links it shows can grow its API budget by sending buyers, which aligns its incentives with the store's. Amazon now directs partners to a successor, the Creators API, so the adapter for this source must be replaceable.

Page fetching, carefully. Where an API does not cover a price type or a product, fetching public pages may be possible, but it is the source with the most responsibility:

  • Read the rules. Check the site's robots.txt (and re-check it daily). The Robots Exclusion Protocol dates from 1994 and was published as an IETF standard, RFC 9309, in 2022. It is advisory, but a well-behaved client follows it. Also read the site's terms of use; some forbid automated access entirely, and then the right answer is an API, a feed, or not tracking that site.
  • Legal history. Automated access against a site's wishes has led to court cases. In eBay v. Bidder's Edge, eBay tried to block an auction aggregator whose bot did not follow its robots.txt, and in May 2000 a court issued an injunction, on trespass grounds, ordering the aggregator to stop accessing eBay's servers by automated means. Legal rules differ by country and change, so a real company takes legal advice; the system design's job is to make compliance easy (per-site switches, limits, audit logs).
  • Identify yourself. Send a clear user agent with contact details, so the site can reach you rather than block you.
  • Be gentle. A per-site rate limit far below what the site could serve, spread evenly (no bursts), and immediate back-off on error codes such as 429 (too many requests) and 503. Treat a block page or a challenge page as a stop signal, not a puzzle to solve: slow down or stop for that site and alert an operator. Evading a site's defences is both a terms violation and, in many places, a legal risk.
  • Fetch only what you need. One product page per check; no images, scripts or styles. Conditional requests (If-Modified-Since, ETag) where the site supports them.

Parsing. Prices on a product page live in structured places (embedded JSON data, microdata such as schema.org Offer, or specific HTML elements). The parser:

  • Prefers structured data embedded in the page over visual elements.
  • Has one extraction rule set per store and layout version, with tests built from saved example pages.
  • Normalises currency formats ("1.299,00 €" in Germany versus "$1,299.00"), and records the currency explicitly.
  • Recognises states that are not prices: out of stock, "see price in cart", price ranges for variants, subscription prices, coupons that apply at checkout.
  • Reports its own health: the share of pages where extraction failed, per store and layout. A sudden jump means the layout changed; the system pauses writes from that parser rather than storing garbage.

Variants and offers. A shirt in five sizes and three colours may be 15 child products under one parent, each with its own price. Track children separately but group them on the product page. A product with many third-party sellers has a "buy box" winner (the offer shown by default) and a list of other offers; the tracked "third-party new" price is usually the lowest new offer, including or excluding shipping, and the definition must be fixed and documented, because a chart that mixes definitions is wrong.

Extension reports are covered in deep dive 4. Their great value is freshness on exactly the products people care about; their risk is trust.

How the sources combine. For each product the registry records which sources can cover it. The scheduler prefers, in order: a recent extension observation from trusted installs (no fetch needed), an API call (batched), then a page fetch if allowed. The fetch budget is spent only where the cheaper sources leave a gap.

2. Scheduling price checks at scale#

The scheduler decides, every second, which of 500 million products to check next. It must spend a fixed budget (per store, per country) where it creates the most value.

What makes a check valuable?

  • Watchers. A product with 10,000 armed alerts matters more than one with none; a missed drop hurts real users.
  • Proximity to a target. If the current price is $24.99 and the nearest target is $24.50, a small drop triggers alerts. If the nearest target is $10, checking hourly is wasteful.
  • Change rate. Products that change often need frequent checks to keep history accurate; products that have not changed in a year can wait.
  • Views. Popular products are shown in charts often; stale charts look bad.
  • Staleness. Time since the last check.
  • Free coverage. If extension users report this product every few minutes, we may not need to check it at all.

A priority score. A simple, explainable formula works well:

priority(p) = w1 * log(1 + watchers(p))
            + w2 * nearness(p)          # 1 if a target is within 5% of current price, falling to 0
            + w3 * change_rate(p)       # estimated changes per day, capped
            + w4 * log(1 + views_7d(p))
            - w5 * fresh_coverage(p)    # recent trusted extension reports
interval(p) = clamp(base / priority(p), 30 min, 30 days)
next_check_at = last_checked_at + interval(p)

The weights are tuned by measuring outcomes: how many real price changes were caught within the hour for watched products, per thousand checks spent.

Estimating change rate. If a product's price changes as a Poisson process with rate λ, and we check it every I hours, the chance it changed since the last check is 1 − e^(−λI). We observe only whether it changed between checks, not how many times, so the simple estimate "changes seen / time" undercounts fast-changing products. Junghoo Cho and Hector Garcia-Molina studied exactly this for web crawlers (their work on estimating change frequency and on synchronising a local copy of the web, around 2000–2003) and proposed bias-corrected estimators. A practical version: over the last n checks, X of them saw a change; estimate

lambda_hat = -ln( (n - X + 0.5) / (n + 0.5) ) / I

which stays finite when every check saw a change and is close to unbiased for reasonable n.

A surprising result about freshness. Cho and Garcia-Molina also showed that if the goal is to keep the average freshness of a collection high under a fixed budget, checking items in proportion to how often they change is worse than checking everything at the same rate, and the optimal policy actually checks the fastest-changing items less than proportional, because they go stale again almost immediately. For a price tracker the goal is different (we care about catching drops below targets, not average freshness), which is why watchers and nearness to targets dominate our score. But the lesson carries over: do not let a handful of products whose price flickers every few minutes eat the budget.

The scheduler's data structure. We need "give me the next due products" over 500 million items, with frequent priority updates.

  • Partition the catalogue by hash of product key into, say, 1,024 partitions. Each scheduler instance owns some partitions (leases in ZooKeeper or a database table), so instances scale out and fail over.
  • Within a partition, a time-bucketed queue: buckets of one minute, each holding the product keys due in that minute. A product is added to the bucket for its next_check_at. Every minute, the scheduler drains the current bucket into the task queue, sorted by priority. This is a timing wheel, cheaper than a global sorted set when items are many and times are coarse.
  • For the hot tier, a Redis sorted set per partition (score = next check time) is simpler and fast enough; 5 million hot items across partitions is easy.
  • Cold items live in the database with an index on next_check_at; a sweeper loads the next hour's worth into the wheel.

Budgets and back-pressure. Each store and country has a budget (checks per second). The scheduler emits tasks no faster than the budget; if more products are due than the budget allows, the lowest-priority tasks slip to later buckets. Slippage is measured per tier; a growing backlog in the hot tier is an alert, because it means alerts will be late.

Catch-up after an outage. After a fetch outage, millions of tasks are overdue. Do not try to run them all at once (that would hit the store hard). Keep the same rate limit and order by priority; the hot tier recovers first.

Event-driven triggers. Some events bypass the schedule: a new subscription on an untracked product, a suspicious extension report needing verification, or a user opening a product page whose data is older than its tier allows. These go to a small high-priority queue with its own reserved slice of the budget (say 10%).

3. Discovering and tracking 500 million products#

We cannot track what we do not know about. And of the products we know, most should cost almost nothing to keep.

Where new products come from.

  1. Users. Pasting a product URL on the website, or subscribing in the extension, adds the product at once.
  2. Extension views. When an extension user opens a product page we have never seen, the overlay request itself tells us the product exists (and the observation gives us a first price).
  3. The store's own listings. Category pages, best-seller lists, new-release lists and deals pages (via the API where available, or as allowed pages) reveal popular products. The API's search operation can enumerate products by keyword and category within its quota.
  4. Sitemaps. Many large sites publish sitemaps for search engines; where a store's rules allow their use, they list product URLs in bulk.
  5. Links between products. "Customers also bought" and variation families point to related products, like links in a web crawl.

Discovery is a small version of a web crawler's URL frontier (see the separate web crawler case study): new product keys go into a registry with a low starting priority, deduplicated by canonical key (store:country:productId), and the scheduler takes it from there.

Canonical keys and duplicates. The same product appears under many URLs (with tracking parameters, with or without a title slug, through different country domains). Normalise every URL to the canonical key before lookup. Variants share a parent id; keep both the child key (for prices) and the parent key (for grouping).

Tiers move both ways.

EventEffect
First subscriptionPromote to hot
Views in the last 7 days above a thresholdPromote to warm or hot
Price changed in the last few checksShorten interval within the tier
No watchers, no views, no changes for 90 daysDemote to cold
Product page gone (404) or "currently unavailable" for monthsMark dormant: check monthly, stop if gone for a year

The cost of a cold product. A cold product is one registry row (about 1 KB), a few history points, and one check every few weeks. 450 million cold products cost about 450 GB of registry and 15–30 million checks a day. That is the price of being able to show a history the moment someone first looks at an obscure product, which is a core part of the service's value.

Do we need all 500 million? Not on day one. A practical launch tracks products that users ask for, plus the top few million by popularity, and grows the catalogue as the extension discovers what people view. The design scales to the full catalogue, but the fetch budget decides how fast.

Country stores are separate. Amazon in the US, UK, Germany, Japan and elsewhere are different sites with different prices and currencies; some products share an id across countries, many do not. Treat each country as its own catalogue with its own budget, while letting users see "this product in other countries" when ids match.

4. Handling bad and malicious extension data#

The extension is a great source, but every report comes from a machine we do not control. A competitor, a seller, or a prankster can send fake prices: a fake drop to trigger alerts for thousands of people (spam or brand damage), a fake rise to hide a real deal, or a flood of junk to overload us. Some reports are simply wrong: a page rendered with a coupon, a regional price, a price shown to a logged-in Prime member, or a broken parse after the store changed its layout.

Principle: extension data can trigger our own verification, but cannot by itself trigger alerts unless it is corroborated.

Layer 1: validation at intake.

  • Schema and type checks; prices within sane limits (positive, below a cap).
  • The product must exist in our registry or be a valid id format.
  • Per-install rate limits (a real user views maybe dozens of products a day, not thousands) and per-IP limits (see Rate Limiting and Throttling).
  • The extension version must be a known, current version.

Layer 2: plausibility against what we know.

  • Compare with the current price and recent history. A change within normal volatility for this product (for example, under 20% for an item that moves often) is plausible; a 90% drop is not, unless it is a known sale day.
  • Compare with other recent reports on the same product. If five installs saw $24.99 in the last 10 minutes and one says $4.99, the outlier is suspect.

Layer 3: trust scores per install.

  • Each install starts with low trust. Trust rises when its reports agree with our own checks and with other installs, and falls sharply when they disagree.
  • New installs created in bulk (many installs from one network, all reporting the same products) are a classic Sybil attack: one attacker pretending to be many users (the name comes from John Douceur's 2002 paper "The Sybil Attack", which showed that without a trusted authority vouching for identities, a system cannot stop one party from posing as many). Count corroboration by independent sources (different networks, older installs), not by raw number of reports.
  • Signed-in users can earn more trust over time, but we never fully trust any client.

Layer 4: verification by our own check. A plausible but surprising change, or any change that would fire many alerts, triggers an urgent check by our fetcher or the API. Only confirmed prices enter history and fire alerts. This adds a few minutes of delay to the alerts most at risk of being fake, well within the 1-hour target.

on extension_observation(o):
    if not valid(o): drop
    t = trust(o.install)
    delta = abs(o.price - current(o.product)) / current(o.product)
    if o.price == current(o.product): refresh_last_seen; return
    if t >= HIGH and delta <= normal_volatility(o.product) and alerts_affected(o) < 100:
        accept(o)                     # write history, publish change
    elif corroborated(o, min_independent_installs = 3, window = 15 min):
        accept(o)
    else:
        hold(o); request_urgent_check(o.product)

What not to do. Do not rely on the client to prove honesty. Code signing, obfuscation or "secret" keys in the extension do not stop someone who reads the extension's source; anything the extension can do, an attacker can do too. Trust must come from server-side evidence: agreement with independent sources and with our own checks.

Privacy. The extension should send only the store, country, product id, prices and a coarse time, plus a random install id. No URLs of other sites, no browsing history, no personal data. Collect only on product pages of supported stores (the content script's match patterns enforce that), and ask for consent at install with a clear switch to turn contributions off. Fewer data collected means less to protect and less to misuse.

5. Processing price changes and matching alerts#

Every confirmed change must be checked against the subscriptions on that product, quickly and exactly once.

Ordering. The price changes topic in Kafka is partitioned by product key, so all changes for one product are processed in order by one matcher instance. Without that, a drop to $24.99 followed by a rise to $29.99 could be processed in reverse, sending an alert for a price that no longer exists.

Matching a target-price alert. For a change on product p, type t, from old price o to new price n:

-- subscriptions that the new price satisfies and that are armed
SELECT id, user_id, target_cents
FROM subscriptions
WHERE product_key = $p AND price_type = $t
  AND state = 'armed'
  AND target_cents >= $n
ORDER BY target_cents DESC
LIMIT 1000;          -- page through large result sets

The partial index on (product_key, price_type, target_cents) WHERE state = 'armed' turns this into one short index range scan. A product with 50,000 watchers, of whom 40,000 have targets at or above the new price, is paged through in 40 batches of 1,000.

Percentage alerts. "Tell me when it drops 20% from today's price" can be stored as an absolute target at creation time (today's price × 0.8), which turns it into the same query. Alerts relative to a moving reference ("20% below the 90-day average") need the reference recomputed daily by a batch job, which rewrites their targets.

Exactly once, in practice. Delivery through Kafka is at least once: a matcher can crash after sending notifications and before committing its offset, and the change will be processed again. Make every step idempotent:

  1. In one database transaction per batch: UPDATE subscriptions SET state = 'triggered', last_notified_cents = $n WHERE id = ANY($ids) AND state = 'armed' RETURNING id. Only the rows that actually flipped are returned.
  2. Enqueue notification jobs only for the returned ids, with an idempotency key (subscription_id, change_id).
  3. The notification service records each key it has sent and skips repeats.

If the matcher crashes between steps 1 and 2, a recovery query finds subscriptions triggered by this change without a notification job, and enqueues them. Alternatively use the outbox pattern: write the notification jobs into an outbox table in the same transaction as the state change (see Distributed Transactions: 2PC, Sagas and Outbox).

Re-arming and hysteresis. After an alert, the subscription is triggered. When should it fire again?

  • If the price goes back above the target and later drops again, the user probably wants another alert. So when a change moves the price above target × 1.02 (a small margin), re-arm the subscription.
  • The margin is hysteresis: without it, a price that flickers between $24.99 and $25.01 around a $25 target would send an alert every flicker.
  • Optionally, notify again within the triggered state if the price falls much further (for example, another 10% lower than the last notified price), because "it dropped even more" is useful news.
  • Many users want one alert and then to stop; offer "alert once and pause".

Out of stock. A price with no stock is not a deal. Do not fire alerts for out-of-stock offers; record the stock state in history so charts show gaps.

Bad changes that slipped through. If a price change is later found to be wrong (a parser bug wrote $2.99 instead of $29.99), we may have alerted thousands of people. Keep the change id on every notification, so a correction can be sent to exactly the affected users and the history point can be deleted. Parser health checks (deep dive 1) and verification (deep dive 4) make this rare.

Throughput. 700 changes per second on average, 7,000 on sale days. Most products have no subscribers, so most changes need only an index lookup that returns nothing (fast, and avoidable entirely with a small in-memory set of "products with any armed subscription" in front, kept as a Bloom filter or a Redis set, see Probabilistic Data Structures for Big Data). The expensive part is the few hot products with tens of thousands of matches, which is a fan-out problem for the next deep dive.

6. Notification fan-out#

On a big sale day, alerts arrive in bursts: one product dropping can produce 40,000 notifications at once, and hundreds of products drop in the same hour. The notification path must absorb the bursts, deliver within the hour, respect user preferences and provider limits, and never send the same alert twice.

Pipeline.

  • Partition by user, so all of one user's alerts go through the same worker. That makes digests and per-user limits easy: if Sam has 12 alerts firing within 10 minutes on a sale day, they receive one email listing all 12, not 12 emails.
  • Preferences: channel choices, quiet hours (delay pushes until morning in the user's time zone), language and currency.
  • Per-channel queues so a slow email provider does not delay pushes.
  • Provider limits. Email providers and push services limit sending rates and penalise senders whose messages bounce or get marked as spam. Senders are paced per provider; bursts wait in the queue, which is fine against a 1-hour target. 40,000 emails at 2,000 per second take 20 seconds.

Delivery guarantees. At least once from the queue, deduplicated by the idempotency key (subscription_id, change_id) stored in the delivery log (a key-value table with a TTL of a few days). Retries with exponential backoff on provider errors; permanent failures (invalid email, expired push token) disable that channel for the user and are shown in their settings.

Freshness check before sending. Because notifications may wait in the queue during a burst, the sender re-reads the current price just before sending. If the price has already gone back above the target, the alert can be suppressed or rewritten ("dropped to $24.99 for a short time; now $29.99"). Sending a deal that is already gone is a bad experience, and on sale days prices can move within minutes.

Fairness and priority. Sale-day bursts should not starve other notifications (password resets, account emails). Use separate queues and sender pools by priority. Within alerts, the first alert for a long-awaited target is more valuable than the fifth "it dropped further" alert; the priority field lets the senders favour the former when they are behind.

Unsubscribe and compliance. Every email carries a one-click unsubscribe for that alert and for all alerts, and the system honours it immediately. Bulk senders must also follow email authentication rules (SPF, DKIM, DMARC) so mail is not marked as spam. This is the same machinery as a general notification platform, described in the separate notification system case study.

7. Storing price history#

The access pattern is simple and fixed: append new points per product; read one product's points over a time range. Almost never "all products at once" (that is analytics, handled separately).

Bad: one big table, no useful index. Put every observation in a single relational table and query WHERE product = ? AND at BETWEEN ? AND ? without an index on product and time. Each chart query scans billions of rows. Adding replicas or shards only divides the scan: with N rows and M nodes, each node still scans N/M rows per query, which is far too slow. The fix is not more machines but organising data the way it is read.

Better: a relational table with a composite index or partitioning. PostgreSQL with a primary key on (product_key, price_type, at) makes each chart an index range scan. Partitioning by time (monthly) keeps indexes small and makes retention easy. This works well to a few billion rows on a large machine, and with sharding by product key beyond that. Its weakness is write amplification and index maintenance at hundreds of millions of inserts a day, and vacuum overhead for an append-only workload.

Good fit: a wide-column store. Cassandra (or ScyllaDB) stores each partition's rows sorted by the clustering key on disk:

  • Partition key (product_key, price_type, year); clustering key at. One chart is one or a few sequential partition reads.
  • Writes go to a commit log and an in-memory memtable, then flush to immutable SSTables: an LSM tree, ideal for append-heavy workloads (see Apache Cassandra in Practice).
  • Scaling is adding nodes; data spreads by partition key via consistent hashing (see Consistent Hashing).
  • Use time-window compaction for the raw observations table (with TTL), and leveled compaction for history, which is read often.

What about a time-series database? Time-series databases (Prometheus-style stores, InfluxDB, TimescaleDB) are built for "values of metric X over time" and compress such data superbly. The catch is cardinality: we would have 1.5 billion series (500 million products × 3 price types), most of them updated a few times a month. Many TSDBs are designed for millions of active series with regular samples, not billions of sparse ones, and index memory grows with series count. TimescaleDB (built on PostgreSQL) handles high cardinality better than most and is a reasonable choice; the decision depends on the team's tools. The wide-column store is the safe default for this shape.

Store changes, not checks. If a product is checked 24 times a day and its price changes once, store one point, plus a last_checked time in the registry. The chart draws a flat line until the next change. This is run-length encoding at the application level and cuts storage by the check-to-change ratio (often 10× or more for hot products).

Compression. Within a partition, times are increasing and prices repeat or move a little. Delta encoding of times (store the difference from the previous point) and of prices, with variable-length integers, packs a typical point into 3–6 bytes. The store's own block compression (LZ4 or Zstandard) then squeezes repeated patterns. Facebook's Gorilla paper (Pelkonen and others, VLDB 2015) shows the extreme version of this idea for metrics: delta-of-delta timestamps and XOR-encoded floating-point values, averaging about 1.37 bytes per point on their data. Our prices are integers in cents, which compress even more simply.

Retention.

DataKeep
Raw observations (every check and report)30 days, for debugging and re-processing
Change pointsForever (this is the product)
Daily summariesForever
Raw fetched pages7 days, sampled

Backups matter more than they seem. The price history is irreplaceable: nobody can go back in time and re-check last year's prices. Wikipedia's account of CamelCamelCamel's January 2019 outage, after three disks failed on its database server and the service was down for several days, is the cautionary tale. Replicate across failure domains (replication factor 3 across availability zones), take regular snapshots to object storage in another region, and test restores.

8. Serving fast price-history charts#

Target: under 500 ms for the website, under 300 ms for the extension overlay. A chart is small, but a long history can hold thousands of points, and charts are requested 2,000 times a second at peak.

Down-sample on the server. A chart 600 pixels wide cannot show more than about 600 points. For each range, pick a resolution:

RangeResolutionPoints
1 monthevery changeup to a few hundred
3 monthshourly min and maxup to about 2,000, usually far fewer
1 yeardaily min, max and close365
All timeweekly or dailya few hundred to a few thousand

Keep min and max per bucket, not just an average: users care about the lowest price ever, and averaging would hide a one-day drop. Another well-known approach for line charts is Largest-Triangle-Three-Buckets (from Sveinn Steinarsson's 2013 thesis on down-sampling time series for visual representation), which picks the point in each bucket that best preserves the visual shape; for price charts, min and max per bucket are simpler and more honest.

Precompute daily summaries. Computing daily min and max from raw points on every request is wasteful. Two ways to maintain them:

  • Batch: a job every few minutes (or hourly) reads new change points from Kafka or the history store, aggregates by product, type and day, and upserts daily_summary. Simple and robust, a few minutes behind.
  • Streaming: a stream processor (Flink or Kafka Streams) keeps today's min, max and close per product in state and writes updates as changes arrive. More up to date, more moving parts.

This is the same choice as in an ad-click aggregator: pre-aggregating into a query-optimised table beats aggregating at read time, and batch is good enough unless the freshness target demands streaming. Here, the current day can always be computed on the fly from today's raw points (a handful), merged with the precomputed history, so batch is enough.

Statistics with the chart. Highest, lowest, average and current price, and "lowest in 90 days" badges. Store them alongside the daily summaries per product, updated by the same job.

Caching layers.

  1. Browser and extension cache: the overlay response is cached for a few minutes.
  2. CDN: chart responses are public and identical for all users, so they cache at the edge with Cache-Control: public, max-age=300 and stale-while-revalidate (see Content Delivery Networks (CDN)).
  3. Redis: the history service caches assembled charts per (product, type, range) for 10 minutes; a price change on that product deletes its keys.
  4. History store: the final source.

With a high share of requests on popular products, the CDN and Redis absorb most of the 2,000 requests a second; the store sees a few hundred partition reads a second, trivial for a Cassandra cluster.

Chart as image or as data? A server-rendered image (PNG or SVG) is simple to embed anywhere (emails, forum posts) and caches well; data (JSON) lets the client draw interactive charts with hover values. Many services offer both: images for sharing and emails, data for the website and extension.

Hot products. On a sale day, one product may get thousands of chart requests a second. Request coalescing in the history service (one rebuild per key) and the CDN's own collapsing of concurrent misses prevent stampedes on the store (see Cache Failure Modes: Stampedes, Hot Keys and Penetration).

9. Respecting retailer rate limits#

The store is not our infrastructure, and it owes us nothing. Rate limits are the hardest constraint in the system, and also the one that decides whether the service can exist at all.

Kinds of limits.

LimitSet byExampleHow we learn it
API quota per second and per dayThe store's API terms1 to 10 requests per second; daily caps tied to referred salesDocumentation; 429 responses; quota headers
Items per API callAPI designUp to 10 products per requestDocumentation
Crawl rulesrobots.txt and terms of useDisallowed paths; sometimes a crawl delayFetch robots.txt per host
Our own politeness budgetUsFor example, no more than a few requests per second per host, evenly spreadPolicy
Adaptive limitsThe store's servers, implicitlySlower responses, 503s, challenge pagesMonitoring

A distributed rate limiter. Fetch workers run on many machines, but each store's budget is global. A token bucket per (store, country, source) in Redis, refilled at the budget rate, is the standard solution (see Rate Limiting and Throttling):

-- Lua script run atomically in Redis: take one token or say how long to wait
local tokens, ts = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
tokens = tonumber(tokens) or capacity; ts = tonumber(ts) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
if tokens >= 1 then
  redis.call('HMSET', KEYS[1], 'tokens', tokens - 1, 'ts', now)
  return 0                        -- go
else
  redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
  return (1 - tokens) / rate      -- seconds to wait
end

To avoid one Redis call per fetch at thousands per second, each worker can lease a small batch of tokens (say 10) at a time.

Batching API calls. If the API accepts 10 products per call, the scheduler groups due products by store and country into batches of 10 before handing them to workers. That multiplies the effective budget by 10. Group hot products that are due within the same minute; a few seconds of waiting to fill a batch costs nothing against a 1-hour target.

Adaptive back-off. Treat signs of strain as a request to slow down:

  • On 429 or 503, honour any Retry-After header; otherwise halve the rate for that host and increase it slowly (additive increase, multiplicative decrease, the same idea TCP uses for congestion control).
  • On rising latency, reduce concurrency before errors appear.
  • On a challenge or block page, stop fetching from that host and alert a person. Do not try to get around it.

Allocating the budget. With a fixed budget per store, the question is who gets it:

  1. A reserved slice (say 10%) for urgent checks: new subscriptions, verification of suspicious reports.
  2. The hot tier, in priority order.
  3. The warm tier.
  4. The cold tier with whatever is left, which naturally stretches its interval when the budget is tight.

When the store asks you to stop. Wikipedia notes that during the COVID-19 pandemic CamelCamelCamel agreed to an Amazon request to stop tracking prices in some regions. The system should make that easy: a per-store and per-country switch that stops fetching and shows users a clear message, without losing the history already collected.

Cost of politeness. Being polite is not only ethical; it is what keeps the data flowing. A tracker that hammers a store gets blocked and loses its source; one that stays within limits, identifies itself and drives sales through affiliate links is a partner the store can tolerate.

10. The browser extension#

The extension is both a product (charts and one-click alerts on the store's page) and a data source. Its design is constrained by what browsers allow.

How it works in Chrome (Manifest V3).

  • A content script is declared in the manifest with match patterns limited to the supported stores' product pages. Chrome's documentation describes content scripts as files that run in the context of web pages and can read and change the page through the DOM, then pass information to the rest of the extension.
  • Content scripts live in an isolated world: their JavaScript variables are invisible to the page and to other extensions, and vice versa. The page cannot read the extension's state, but the extension must still treat everything it reads from the page as untrusted.
  • Content scripts can call only a few extension APIs directly (storage, messaging, i18n); for anything else, such as network requests to our API with the user's sign-in token, they send a message to the extension's service worker. In Manifest V3, the long-lived background page of older extensions was replaced by a service worker that runs only when needed.
  • Manifest V3 forbids remotely hosted code: all JavaScript must ship inside the reviewed package. So extraction rules cannot be shipped as code from our server; they can be shipped as data (for example, a list of CSS selectors or JSON paths per layout) that the packaged code interprets, which keeps updates fast without breaking the rule.
  • Chrome's guidance also warns content scripts against evaluating page data as code (no eval or string setTimeout), and to sanitise any content fetched from elsewhere before inserting it into the page, to avoid cross-site scripting.

Overlay performance.

  1. On page load, the content script reads the product id from the URL (cheap, no parsing).
  2. It asks the service worker for the overlay; the worker checks its local cache, then calls our overlay endpoint (served by the CDN).
  3. The overlay is a small summary (current prices, 90-day low, a compact series of a few dozen points) so it renders in a few kilobytes.
  4. The full chart loads only when the user opens the panel.

Target: overlay visible within 300 ms of the page becoming interactive for popular products, without slowing the store's page.

Collecting observations. After the page renders, the content script extracts prices using the current rule set, and the service worker sends one observation (batched with others, every few minutes) to the intake API. It sends nothing for pages outside the match patterns, and nothing at all if the user has turned contributions off.

Version skew. A million installs update gradually, so at any time several extension versions are live. The API is versioned; old versions keep working for months. Each observation carries the extension version and rule-set version, so a bad rule set can be identified and its data ignored retroactively.

Load from the extension. Overlays: about 15 million a day, 175 per second, peaks of 1,000 to 2,000 per second, almost all cacheable. Observations: similar count, small payloads, accepted with 202. Subscriptions: tens of thousands a day. All modest; the CDN does most of the work.

11. Deal pages, analytics and fake discounts#

The same data powers "top price drops today" pages, category deal lists and weekly email digests. These are queries across many products, which the per-product history store is bad at.

The analytics path. The price changes topic is also loaded into a data warehouse or OLAP store (BigQuery, Snowflake, ClickHouse, Redshift), where columnar storage makes aggregations over millions of rows fast. Every few minutes, a job computes:

  • Biggest drops in the last 24 hours, by percentage and by amount, per country and category, for products with enough views to matter.
  • Products at their lowest price in 90 days or ever.
  • Counts and trends for internal dashboards (checks spent, changes found, alerts sent).

The results are written to small, query-ready tables (or Redis lists) that the deal pages read directly. This is the familiar pattern: write raw events to a store optimised for writes, pre-aggregate in batches (or in a stream processor when freshness matters), and serve reads from an analytics store built for them.

Batch or stream? A deals page that is five minutes old is fine, so batch jobs every few minutes are enough. If a product wanted "flash deal" pushes within seconds, a stream processor such as Flink, with windowed aggregation per category and event-time processing for late observations, would be the upgrade. Start with batch.

Fake discounts. A common trick is to raise a list price shortly before a sale so the "discount" looks bigger. A price tracker is exactly the tool to expose it: compare the sale price with the median price over the previous 30 or 90 days, not with the "was" price the store shows. The deals ranking should use drop versus typical price, which naturally ignores inflated reference prices.

Category normalisation. Store categories are deep and change; map them to a stable, coarse category tree of our own for deal pages, using the store's category path plus title keywords.

12. Reliability, multi-store expansion and cost#

Failure isolation by store and country. Each store and country has its own budget, parser versions, fetch worker pool and health metrics. A layout change on one country's site, or a block, affects only that slice. Feature switches per store and country can pause fetching, pause extension intake, or pause alerts.

Parser health as a first-class signal. The most common silent failure in scraping systems is not downtime but wrong data: a layout change makes the parser pick the wrong number (a shipping fee, a "was" price, a unit price per 100 g). Defences:

  • Per-parser extraction success rate and the share of observations that "changed" (a jump from 5% to 60% means the parser is reading something else).
  • Canary products with known prices checked frequently.
  • Automatic pause of history writes and alerts for a parser whose metrics jump, with a person to review.
  • Raw pages stored briefly, so that after a fix the affected period can be re-parsed.

Alert pipeline safety. Because a wrong price can alert thousands of people, add a circuit breaker on alert volume: if a single product or parser would trigger far more alerts than usual, hold them for verification first (deep dive 4) or for a human check on sale days.

Adding a new store. The design is store-neutral by construction: canonical keys include the store; adapters wrap each store's API or pages; parsers are per store; budgets are per store. Adding a store means a new adapter, a parser, a key normaliser and a budget, plus extension match patterns for its product pages.

Cost. Wikipedia cites CamelCamelCamel's running costs at about $11,000 a month. Our larger design would cost more, but the shape of the bill is instructive:

  • Fetching (workers, bandwidth, parsing) is the biggest compute cost when page fetching is used; APIs and extension reports are far cheaper per price.
  • Storage is small: a few terabytes of history across all products.
  • Notifications cost per email and push; digests reduce volume and cost.
  • CDN costs are low because chart responses are small and highly cacheable.

The way to keep the bill small is the same as the way to be polite: spend fetches only where they matter.

Observability. Key metrics (see Observability: Logs, Metrics and Traces):

  • Checks per second per store versus budget; backlog per tier.
  • Share of watched products checked within their target interval.
  • Detection delay: time from a price change (estimated from extension reports and checks) to its alert.
  • Parser success rate per store and layout.
  • Extension reports accepted, held, rejected; verification confirmations.
  • Alerts matched, sent, suppressed (price recovered), failed; digest rates.
  • Chart latency p50 and p99, cache hit rates.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Store tightens limits or blocks usPrices go stale; alerts lateOfficial APIs first; per-store budgets; back-off; budget favours watched products; lean on extension reports
Store changes page layoutParser reads wrong numbers; false alertsStructured data first; parser health metrics; automatic pause; canary products; re-parse from raw pages
Fake extension reportsFalse alerts to thousands of usersValidation, trust scores, independent corroboration, verification check before alerts
Sale-day surge of price changesMatcher and notification backlogKafka buffering, partitioned matchers, paging, per-user digests, provider pacing
Hot product with huge subscriber listBurst of tens of thousands of alertsBatched matching, notification queue, freshness check before sending
Duplicate alerts after crashesUsers annoyed, unsubscribeState flip plus idempotency keys; outbox; delivery log
Price flicker around targetAlert stormsHysteresis on re-arming; "alert once" option
Scheduler backlog after outageHot tier latePriority order during catch-up; reserved urgent budget; same rate limits
History store node lossSlower charts, risk to dataReplication factor 3 across zones; snapshots in another region; restore tests
Cache stampede on a viral productSpike on the history storeCDN collapsing, Redis coalescing, stale-while-revalidate
Email deliverability dropsAlerts land in spamSPF, DKIM, DMARC; one-click unsubscribe; volume pacing; bounce handling
Subscription DB hot shardSlow matching for very popular productsShard by product key with hot-product splitting; read replicas for matching

What Interviewers Expect#

Mid-level. Gets the requirements and scale right, then designs a working pipeline: a scheduler that triggers price checks, workers that fetch prices, a store of price history, and a job that compares new prices with alert targets and sends email. Chooses a sensible data model (history keyed by product and time) and knows that charts should not scan a table. Mentions rate limits from the store.

Senior. Explains the fetch budget and tiered, priority-based scheduling, and why official APIs and batching come first. Treats extension data as untrusted and designs verification. Designs alert matching with an index on product and target, handles exactly-once delivery with state flips and idempotency keys, and adds hysteresis. Picks a storage design for history (wide-column partitions, change-only points, daily summaries) and caching for charts. Handles notification spikes with queues and digests.

Staff and above. Frames the whole system around a scarce, external budget and the value of each check, with an explicit priority model and measurement of detection delay. Discusses compliance and the relationship with the store (terms, robots.txt, affiliate alignment, stop switches) as design inputs. Covers parser drift and data quality as the main operational risk, Sybil-resistant trust for crowdsourced data, cardinality trade-offs between time-series and wide-column stores, backup strategy for irreplaceable history, and per-store isolation for expansion.

Deep Dive: Sizing every tier with real numbersShow

The capacity section gave rates. This deep dive turns them into machines, so the design can be costed and so an interviewer's "how many servers?" has a reasoned answer. Every figure is an estimate with stated assumptions; real numbers would come from load tests.

Fetch workers. Of the 2,200 checks per second, assume the official API covers about 100 products per second (10 requests per second, 10 products each) and extension reports remove the need for about another 300 checks per second on popular products. That leaves roughly 1,800 page fetches per second at steady state, rising to 3,500 during catch-up.

  • A product page is large. Compressed HTML for a big retailer's product page is often 100–200 KB; uncompressed it can be 1 MB or more. Take 150 KB on the wire.
  • Bandwidth: 1,800 × 150 KB ≈ 270 MB/s, about 2.2 Gbit/s, or roughly 700 TB a month. Bandwidth is the largest single cost of page fetching, which is another reason to prefer APIs, extension data and conditional requests (If-None-Match and If-Modified-Since, where the store supports them, turn an unchanged page into a tiny 304 response).
  • Network time: a fetch takes 200–800 ms end to end. With asynchronous I/O, one process can keep hundreds of requests in flight, so network concurrency is not the limit: 1,800 per second × 0.5 s = 900 requests in flight across the fleet.
  • CPU: parsing is the real cost. Decompressing and parsing 1 MB of HTML into a DOM and running selectors costs perhaps 20–50 ms of CPU. Taking structured data (JSON-LD or embedded JSON) with a streaming tokenizer, instead of building a full DOM, can bring that to 5–10 ms. At 30 ms per page: 1,800 × 0.03 = 54 CPU cores. With 50% headroom and spread across regions near each country store: about 12–16 machines with 8 cores each.
  • Headless browsers (Chromium driven by Playwright or Puppeteer) cost 10–50× more CPU and memory per page. Use them only for stores whose prices exist only after scripts run, and only for the hot tier there.

Scheduler. It must hand out 2,200 due checks per second and update each product's next check time.

  • If every product lives in one Redis sorted set (score = next check time), 500 M members × about 100 bytes (member, score, skip-list overhead) is about 50 GB. That fits in a sharded Redis cluster, but it is wasteful for cold products that are touched every few weeks.
  • Better: keep hot and warm products (50 M) in Redis sorted sets sharded by product key (about 5 GB total), and keep cold products as time buckets in the registry database ("all cold products due on day D in partition P"), loaded into Redis a few hours before they are due.
  • Each scheduler shard pops due items with ZRANGEBYSCORE ... LIMIT and ZADD for the next time. At 2,200 pops and 2,200 updates per second, a cluster of 4–6 Redis shards is lightly loaded (one Redis shard handles 50,000–100,000 simple commands per second).

Kafka. Messages are small: an observation or change is about 200–300 bytes.

TopicPeak rateSize per dayPartitions
check results (every check)4,000/sabout 50 GB64
extension observations1,000/sabout 4 GB32
price changes7,000/sabout 18 GB64, keyed by product
alerts to send10,000/sabout 1 GB64, keyed by user

Peak throughput is a few MB/s, which is tiny for Kafka. With 7 days of retention and replication factor 3, storage is about 1.5 TB. Three to five brokers are enough; the partition counts are set by the consumer parallelism we want, not by volume (see Apache Kafka in Practice).

History store (Cassandra).

  • Writes: 700 changes per second on average and 7,000 at peak, plus daily summary updates. A single Cassandra node handles thousands to tens of thousands of small writes per second, so write load is not the driver.
  • Data: about 440 GB a year of change-only points plus under 1 TB of summaries. Over five years, with replication factor 3: (2.2 TB + up to 5 TB) × 3 ≈ 15–20 TB. Compressed on disk it is smaller.
  • With about 2–4 TB per node as a comfortable density, 6–9 nodes across three availability zones. The cluster is sized for data volume and durability, not throughput.
  • Reads: of 2,000 chart requests per second at peak, the CDN and Redis absorb 90–95%, leaving 100–200 reads per second. Each read is one or a few partitions. Easy.

Current prices and overlay cache (Redis). One entry per tracked product with current price per type and last change time: 500 M × about 60 bytes ≈ 30 GB, or only hot and warm products (50 M, about 3 GB) with the rest read from the registry on a miss. Chart response cache for popular products: a few GB. One cluster of 6 shards with replicas holds all of it (see Redis in Practice).

Product registry. 500 M rows × 1 KB = 500 GB plus indexes. Writes are the scheduler's next-check updates for cold products (small) and the current-price updates (700 per second). PostgreSQL sharded by product key into 8–16 shards, each 50–100 GB, is comfortable. A wide-column store works equally well, because access is almost always by product key.

Subscriptions (PostgreSQL). 100 M rows × 100 bytes = 10 GB, plus the partial index on armed subscriptions (another 5–8 GB). This fits on one primary with read replicas. We still shard by product key into 4–8 shards so that matching for one product touches one shard and so a sale-day burst spreads across machines. Matching at 7,000 changes per second, each an indexed range read returning a handful of rows in about 1 ms, needs about 7 CPU cores of query work spread across shards.

Notification senders. At 10,000 alerts per second at peak, each send is an HTTPS call to an email or push provider taking 50–200 ms. With asynchronous senders, 10,000 × 0.1 s = 1,000 requests in flight: 10–20 sender pods. The real limit is the provider's account rate and the receiving mail systems' tolerance, which is why the queue absorbs the peak and spreads it over minutes.

API and chart servers. 2,000 chart requests per second at peak with most served by the CDN: the origin sees a few hundred per second. Overlay requests from the extension (1,000 per second at peak) are small key lookups. 6–10 stateless API servers across two regions, autoscaled.

Totals. Roughly 15 fetch machines, 6 Redis shards (plus replicas), 5 Kafka brokers, 9 Cassandra nodes, 8–16 small PostgreSQL shards for the registry plus 4–8 for subscriptions, 20 sender pods and 10 API servers, plus the warehouse. That is a few dozen machines, not thousands. The cost and the risk sit in fetching, which is why the design spends so much care on the fetch budget.

Calibration against a real service. Wikipedia reports that CamelCamelCamel's operating costs were about $11,000 a month. That is consistent with the conclusion above: a price tracker at this kind of scale is a modest fleet, and a small team can run it if fetching is efficient.

Deep Dive: The math of catching a price dropShow

"Check hot products hourly" sounds reasonable, but how good is it? This deep dive puts numbers on it, so that check intervals become a decision instead of a guess.

Model. Treat price changes of one product as a Poisson process with rate λ changes per hour. Some changes are drops that cross a user's target. A drop can be short: a "lightning deal" or a repricing war can lower a price for a while and raise it again.

Question 1: how long until we notice a lasting drop? If we check every I hours and a drop happens at a uniformly random moment between checks, the delay until the next check is uniform on [0, I], so the average delay is I/2 and the worst case is I.

  • Hourly checks: average 30 minutes, worst 60 minutes. That meets the "within 1 hour" target, with no slack for queueing and sending.
  • Every 30 minutes: average 15 minutes, worst 30 minutes.
  • Extension observations at random times add to our checks. If extension users view a product at rate μ per hour (Poisson), the gap between "looks" from both sources is shorter: the combined look rate is 1/I + μ (treating scheduled checks roughly as a Poisson process for the estimate). A product with 100 extension views a day (μ ≈ 4 per hour) and hourly checks gets a look about every 12 minutes on average.

Question 2: what fraction of short drops do we miss? Suppose a drop lasts D hours and then reverts. With strictly periodic checks every I hours:

  • If D ≥ I, we always see it (some check lands inside the drop).
  • If D < I, the chance that a check lands inside the drop is D / I.

Worked example: a 20-minute lightning drop (D = 1/3 h).

Check intervalChance we see itAverage delay if seen
4 hours1/12 ≈ 8%about 10 min into the drop
1 hour1/3 ≈ 33%about 10 min
20 minutes100%about 10 min
10 minutes100%about 5 min

Checking 6× more often moves us from 33% to 100% for this kind of drop, at 6× the fetch cost. For one product with 50,000 watchers that may be worth it; for a product with 3 watchers it is not. This is exactly the trade-off the priority score encodes.

Question 3: random or periodic checks? If checks were random (a Poisson process of checks at rate 1/I), the chance of at least one check inside a drop of length D is 1 − e^(−D/I). For D = I/3 that is 1 − e^(−1/3) ≈ 28%, a little worse than 33% for periodic checks. For long drops, periodic checks guarantee detection while random checks only make it likely (for D = I, 63% vs 100%). Prefer evenly spaced checks for watched products, with a small random offset per product so the whole fleet does not fire at the same second.

Question 4: how should a fixed budget be split? Say we can afford B checks per hour across N watched products. Product i has w_i watchers whose targets are near the current price and a drop rate d_i (drops per hour). The expected number of "missed or late alerts" falls as product i is checked more often, with diminishing returns. A simple, useful rule, which comes from minimising the sum of w_i × d_i × (I_i / 2) subject to the total budget Σ(1/I_i) = B, gives:

check rate of product i   ∝   sqrt( w_i × d_i )

(The square root comes from a standard Lagrange-multiplier argument: the cost of product i is proportional to w_i d_i I_i, the budget constraint is a sum of 1/I_i, and setting the derivatives equal gives I_i ∝ 1/sqrt(w_i d_i).) So a product with 100× more watchers deserves about 10× more checks, not 100×. This square-root rule is a useful default for the priority score; it tempers the pull of very popular products and leaves budget for the long middle.

Question 5: does checking more often make history more accurate? History needs fewer checks than alerts. A daily chart for a product that changes once a week loses nothing with daily checks. History accuracy matters most for "lowest price ever" claims; there, a missed short dip means the record low is too high. We state this honestly in the interface ("lowest price we recorded") rather than pretending to perfect knowledge.

Estimating rates from data. λ and d_i come from the history itself, using the bias-corrected estimator from deep dive 2 (because checks see "changed or not", not "how many times"). Estimates for new products start from a category prior (for example, electronics change more often than books) and update as data arrives, a simple Bayesian blend:

lambda_estimate = (prior_changes + observed_changes) / (prior_hours + observed_hours)

with prior_changes and prior_hours chosen so the prior counts as, say, two weeks of data. After a month of checks, the product's own data dominates.

What this buys in an interview. Being able to say "hourly checks catch only about a third of 20-minute drops, and the square-root rule tells us how to share the budget" turns a scheduling discussion into a quantitative one, which is what separates senior answers.

Deep Dive: Three ways to find the subscriptions a price change triggersShow

Deep dive 5 used a partial index in PostgreSQL. It is the right first choice, but it helps to know the alternatives and when each wins. The query is always the same shape: given (product, price type, new price), find armed subscriptions whose target is at or above the new price. That is a range query on one sorted list per product, and the three options differ only in where that sorted list lives.

Option A: a partial B-tree index in the subscriptions database.

  • Index on (product_key, price_type, target_cents) restricted to armed rows. A change does one B-tree descent (3–4 levels, upper levels cached in memory) and then reads the matching leaf entries in order.
  • Cost: about 1 ms per change plus a little per matched row. At 7,000 changes per second at peak spread over 4–8 shards, each shard runs 1,000–2,000 such queries per second, comfortable for PostgreSQL.
  • Strengths: one source of truth, so the state flip (armed to triggered) and the outbox insert happen in the same transaction as the lookup. No sync problems.
  • Weaknesses: every change is a network round trip to a database; a sale-day burst on one shard competes with user writes (new subscriptions, edits).

Option B: a sorted set per product in Redis.

  • Key subs:{product}:{type}, member = subscription id, score = target in cents. A change runs ZRANGEBYSCORE key new_price +inf.
  • Memory: 100 M members × about 80 bytes ≈ 8 GB, spread across shards.
  • Lookups take well under a millisecond. But Redis is now a copy of the subscriptions table, kept in sync through change data capture from PostgreSQL. A missed update means a missed or wrong alert, so the matcher must still confirm each candidate in PostgreSQL with the conditional state flip. Redis becomes a fast filter, PostgreSQL stays the judge.
  • Wins when most changes match nobody (most do: the new price is above every target), because those changes never touch the database at all.

Option C: subscriptions as local state in the matcher (a stream-table join).

  • Changes are already partitioned by product in Kafka. Publish the subscriptions table as a compacted Kafka topic (via change data capture), partitioned the same way. Each matcher instance keeps the subscriptions for its partitions in a local embedded store such as RocksDB, sorted by (product, type, target). This is the stream-table join that Kafka Streams and Flink provide.
  • A change is matched with a local disk or memory read: microseconds, no network.
  • State size: about 10 GB of subscriptions over 64 partitions is about 160 MB per partition. When a partition moves to another instance, restoring it from the compacted topic takes seconds to a minute.
  • The state flip still needs care: the matcher emits "fire" events with idempotency keys (subscription id, change id), and a single writer applies the flip in PostgreSQL. Because the local copy can lag the source table by a moment, a subscription edited a second ago might fire on its old target; the writer checks the current target before flipping.
  • Wins at very high change rates and when the database must be protected from bursts.

Recommendation. Start with Option A. Add Option B as a filter if most database lookups return nothing and the database is busy. Move to Option C only if change volume grows by another order of magnitude. Say this order in an interview: it shows that the simplest correct option comes first.

A cheap side product: target histograms. For each product, keep a small histogram of armed targets (for example, counts per 1% band below the current price). It costs a few hundred bytes per watched product and answers "how many alerts would this price fire?" instantly. The extension intake uses it to decide whether a surprising report must be verified first (the alerts_affected check in deep dive 4), and the notification service uses it to pre-scale senders when a big drop is coming through.

Deep Dive: Encoding a price series, worked byte by byteShow

Deep dive 7 said a point compresses to a few bytes. Here is why, with a real calculation.

Raw size. A naive point is a 64-bit timestamp and a 64-bit price: 16 bytes. Our change-only history for one product and price type in one yearly partition:

PointTimePrice (cents)
1Jan 3, 09:0022,900
2Jan 3, 10:0018,900
3Jan 3, 11:0022,900
4Jan 4, 09:0021,900
5Jan 4, 10:0019,900
6Jan 8, 00:0622,900

Six points × 16 bytes = 96 bytes.

Step 1: store differences, not values. Times only increase, and consecutive prices are close. Store the first point in full (relative to the partition start), then each point as (time since previous, price minus previous).

Step 2: round time to what we need. Charts and alerts do not need seconds. Store time in minutes. The time deltas become 60, 60, 1,320, 60 and 5,166 minutes.

Step 3: variable-length integers. A varint stores 7 bits per byte, using the top bit to say "more bytes follow". Values below 128 take 1 byte, below 16,384 take 2, below about 2 million take 3. Price deltas can be negative, so first map them with zigzag encoding (0 → 0, −1 → 1, 1 → 2, −2 → 3, …), which keeps small negative numbers small.

first point: minutes since partition start (2 bytes), price 22900 (3 bytes)
point 2: dt=60 (1 byte),   dp=-4000 -> zigzag 7999 (2 bytes)
point 3: dt=60 (1 byte),   dp=+4000 -> zigzag 8000 (2 bytes)
point 4: dt=1320 (2 bytes), dp=-1000 -> zigzag 1999 (2 bytes)
point 5: dt=60 (1 byte),   dp=-2000 -> zigzag 3999 (2 bytes)
point 6: dt=5166 (2 bytes), dp=+3000 -> zigzag 6000 (2 bytes)
total: 5 + 3 + 3 + 4 + 3 + 4 = 22 bytes

That is 22 bytes instead of 96, about 3.7 bytes per point, before any block compression. A header byte per block (encoding version, price type) adds almost nothing.

Why not delta-of-delta like Gorilla? The Gorilla paper encodes the difference between consecutive time deltas, which is nearly always zero for metrics sampled every 10 or 60 seconds, so most timestamps cost about one bit. Our points are change events at irregular times, so delta-of-delta rarely hits zero and saves little. Likewise, Gorilla's XOR trick targets floating-point values whose bits barely change between samples; we store integers in minor units, where a plain zigzag delta is simpler and just as small. Knowing why a technique works lets you judge when it does not apply.

Step 4: block compression. The storage engine compresses blocks of many partitions with LZ4 or Zstandard. Price deltas repeat (sellers often move between the same few prices, and round amounts like −1,000 cents are common), so general compression typically removes another 20–50%.

Old history in columnar files. Partitions older than two years are rarely read. Export them to Parquet files in object storage, sorted by product and time. Columnar formats use dictionary and run-length encoding for repeated values and delta encoding for sorted columns, so the archive is cheap and still queryable by the warehouse for analytics.

What this means at scale. 60 million changes a day at about 4 bytes is about 240 MB a day of encoded points, under 100 GB a year before replication. The 20 bytes per point used in the capacity section is deliberately conservative; it leaves room for per-point provenance (source and parser version as small ids), which the testing and operations deep dive below shows is worth keeping.

Deep Dive: A 45-minute interview plan and follow-up questionsShow

Minutes 0–5: requirements. Ask who the users are (shoppers on the website, extension users), which stores (one big store first, more later), how many products and subscriptions, how fresh alerts must be, and whether we may use an official API. State the scale: 500 M products, 100 M subscriptions, alerts within an hour for watched products, charts under 500 ms.

Minutes 5–10: the key insight and estimates. Say early that the fetch budget is the binding constraint: checking everything daily would need about 5,800 fetches per second, more than any store will accept from one client. Propose tiers and show that the total drops to about 2,200 per second, and that history is only hundreds of GB a year. This frames the rest of the interview.

Minutes 10–20: high-level design. Draw the collection path (scheduler, fetchers and API clients, extension intake, parser), the change pipeline (Kafka keyed by product), the history store, the matcher and the notification service, and the read path for charts with caches. Walk one price change through the system.

Minutes 20–40: deep dives. Pick two or three, ideally the ones the interviewer leans towards:

  1. Scheduling under a budget (priority score, square-root rule, catch-up).
  2. Trusting extension data (validation, trust, corroboration, verification check).
  3. Matching and exactly-once alerts (index, state flip, hysteresis, outbox).
  4. History storage and fast charts (change-only points, daily summaries, down-sampling, caching).

Minutes 40–45: failures and growth. Store blocks, parser drift, sale-day spikes, adding stores, cost.

Follow-up questions and strong short answers.

  1. "Why not just scrape everything every hour?" 500 M per hour is about 140,000 fetches per second; no store tolerates that, and it would cost a fortune in bandwidth. Most products have no watchers and rarely change; spend checks where they change outcomes.
  2. "What if the store blocks you?" Treat a block as a signal to slow down or stop, not something to get around. Rely on the official API and on extension data contributed by consenting users; the hot tier shrinks to products with active alerts; alerts become slower and we say so in the product.
  3. "How do you stop a fake drop from alerting 50,000 people?" Extension reports cannot trigger alerts alone unless corroborated by independent installs; large fan-outs always wait for our own verification check.
  4. "A price goes 25.00, 24.99, 25.00, 24.99 around a $25 target. What happens?" The first crossing fires and flips the subscription to triggered. It re-arms only after the price rises above target × 1.02 (or on user action), so no alert storm.
  5. "How do you guarantee no duplicate alerts?" Update the subscription with a conditional state change and record the alert in the same transaction (outbox); the sender uses (subscription_id, change_id) as an idempotency key so retries are safe.
  6. "How do charts stay under 500 ms for a product with 10 years of history?" Do not read raw points: read daily summaries (about 3,650 rows), down-sample to about 500 points with min and max per bucket, and serve from CDN and Redis.
  7. "Why Cassandra and not PostgreSQL for history?" Postgres works at small scale; at billions of points the partitioned append-and-range-read pattern and easy horizontal growth favour a wide-column store. A time-series database is a valid alternative if the number of series fits its cardinality limits.
  8. "How would you add Walmart or Best Buy?" New adapter, parser, canonical key format, budget and extension match patterns; everything else is store-neutral by design. Cross-store product matching (same item, different stores) is a separate, harder feature.
  9. "What if a parser starts reading the shipping fee as the price?" Parser health metrics (sudden change rate jump), canary products and automatic pause of alerts for that parser; re-parse stored raw pages after the fix and correct history.
  10. "Sale day: 5 million products change in an hour. What breaks first?" The notification path: Kafka absorbs the burst, matchers scale by partition, alerts are batched into per-user digests and paced to provider limits. Hot products with huge watcher lists are paged through the index in chunks.
  11. "How do you handle currency and country?" Each country store is its own catalogue and budget; prices are stored in the store's currency as integers of minor units; conversion only happens for display.
  12. "What is the single most important metric?" Detection delay for watched products (the time from a real price change to the alert), backed by the share of watched products checked within their target interval.

Common mistakes. Designing a generic crawler and forgetting the budget; trusting extension data; scanning all subscriptions on every change; storing every check instead of only changes; using floats for money; ignoring the store's terms and limits.

Deep Dive: One price drop, end to endShow

Follow one real-looking alert from the store to a phone, with timings. Sam watches a pair of headphones in the US store. Their target is $199; the price has been $229 for weeks. The product has 18,000 watchers and sits in the hot tier with a 30-minute check interval because it is popular and near many targets.

10:00:00. The seller drops the price to $189 on the store.

10:04:10. An extension user, Kai, opens the product page. The content script reads the price from the page's structured data and sends an observation: product key, price type "new", $189.00, in stock, install id, extension version. The intake API validates it, finds Kai's install has medium trust, and sees that the drop (17%) is larger than this product's normal swings and would affect about 9,000 subscriptions. Policy: hold and verify. It writes the observation to Kafka and asks the scheduler for an urgent check.

10:04:11. The scheduler puts the product at the front of the urgent lane for the US store's budget. The token bucket has tokens: the request is allowed.

10:04:13. An API client asks the official API for the product (batched with 9 other urgent products in one request). Response: $189.00, in stock, offered by the store itself.

10:04:13.2. The parser normalises the result into an observation (source "api", confirmed). The change detector compares with the current price in Redis ($229.00) and emits a price change event: product, type, old $229.00, new $189.00, time, change id. In parallel, the held extension observation is marked confirmed and Kai's install gains a little trust.

10:04:13.4. The history writer appends the point to the product's current partition in Cassandra and updates today's summary (min $189). The chart cache key for this product is invalidated, so the next chart request rebuilds with the new point.

10:04:13.5. The matcher consumer for the product's Kafka partition reads the change. It queries the subscription shard for the product: armed subscriptions with type "new" and target ≥ $189.00, in pages of 5,000. About 9,000 rows come back in two pages, Sam's among them.

10:04:14. For each page, a transaction flips the subscriptions from armed to triggered and inserts outbox rows (subscription id, change id, user id, price, target). The outbox relay publishes alert events to the alerts topic, keyed by user.

10:04:15–10:06. Notification workers read alerts. For Sam, preferences say "push and email, send immediately". The worker checks the price is still current in Redis ($189.00, yes), checks the dedupe log for (Sam's subscription, change id) (not sent), and sends a push through the platform push service and an email through the email provider. For users who chose a daily digest, the alert goes into their digest buffer instead. The provider pacing spreads the 9,000 sends over about two minutes.

10:05:02. Sam's phone shows: "Headphones are $189 (your target $199). Lowest in 90 days." The deep link opens the product page with an affiliate tag.

Detection delay. About 4 minutes from the store change to detection (thanks to Kai's view), and 5 minutes to Sam's notification. Without any extension view, the scheduled 30-minute check would have found it at a random point within 30 minutes: on average 15 minutes.

What if Kai's report were fake? The verification check would return $229.00. The held observation is rejected, Kai's install loses trust, and nothing reaches history or alerts. If many installs from one network sent the same fake price, the intake would flag the cluster and lower all their trust.

What if the price goes back to $229 at 10:05? Workers that have not yet sent the alert re-check the current price and suppress it (recording "suppressed, price recovered"). Those already sent cannot be recalled; the product page shows the real current price, so no one is misled for long. Sam's subscription stays triggered and re-arms only when the price goes above $203 (target × 1.02) and stays there, or when Sam re-arms it.

Deep Dive: Matching the same product across storesShow

Once we track more than one store, users want "this blender is $79 here, $72 at another store". That needs entity resolution: deciding that two listings in different catalogues are the same physical product. It is a classic and surprisingly hard problem.

Why it is hard. Titles differ ("Acme X200 Blender, 1200W, Black" vs "ACME Blender X-200 (Black) 1.2 kW"), sellers list bundles and refurbished units, variants differ in colour and size, and model numbers vary by region. A wrong match is worse than no match: telling users that a used unit or a smaller size is "the same product, cheaper" damages trust.

Strong identifiers first. Most retail products carry a GTIN (Global Trade Item Number, the barcode number managed by the GS1 standards body). The 12-digit UPC used in North America and the 13-digit EAN used in much of the world are both GTIN forms, and a UPC can be written as an EAN with a leading zero. When both listings expose the same GTIN (in structured data, an API field, or the barcode in specifications), that is a strong match. Manufacturer part numbers (MPN) plus brand are the next best key. Books have ISBNs; on Amazon, as noted earlier, a book's ASIN equals its ISBN-10.

Even strong identifiers need care: some sellers reuse or invent barcodes, and one GTIN can cover a pack while another covers a single unit. Treat identifiers as strong evidence, not proof.

Probabilistic matching for the rest. For listings without shared identifiers, use the standard record-linkage pipeline. The theory goes back to Ivan Fellegi and Alan Sunter's 1969 paper "A Theory for Record Linkage", which framed matching as comparing field agreements and computing a likelihood ratio for "match" versus "non-match", with two thresholds that split pairs into match, non-match and "send to review".

  1. Blocking. Comparing every listing with every other is impossible (500 M × 500 M). Group candidates by cheap keys: same brand plus same normalised model token, or the same category plus close title embeddings (nearest-neighbour search over vectors). Each listing is compared only with a few dozen candidates.
  2. Pairwise features. Brand equal, model number equal after normalising ("X-200" → "x200"), title token overlap (Jaccard), title embedding similarity, key attributes equal (capacity, size, colour, wattage), price ratio (a 70% price gap hints at a different item or a bundle), image similarity.
  3. Scoring. A gradient-boosted model or a small neural model trained on labelled pairs gives a match probability. Labelled pairs come from GTIN matches (free positives), user reports ("this is not the same item") and human review.
  4. Clustering. Pairwise matches form a graph; connected components become product clusters. Guard against chaining (A matches B, B matches C, but A and C are different sizes) by requiring high internal similarity, or by splitting clusters whose members disagree on key attributes.
  5. Thresholds by use. Show "compare prices" only at high confidence (precision over recall). Use lower-confidence clusters for internal analytics only.

Data model. A product_cluster table maps listing keys to a cluster id with a confidence and a method (GTIN, MPN, model). Price comparison reads the current price of each listing in the cluster, converted for display. Clusters change over time, so alerts stay attached to a single listing; a "best price across stores" alert is a separate subscription type that reads the cluster.

Cost. Matching runs in batch (daily for new listings, weekly for a full refresh), on the warehouse or a Spark-style job, not in the request path. The cost is dominated by embedding computation and candidate comparisons, which blocking keeps to a few billion pairs, a modest batch job.

Deep Dive: Legal, ethical and relationship constraints as design inputsShow

A price tracker reads data from businesses that did not build their sites for it. The technical design and the rules that govern collection are tied together, and a strong design treats those rules as requirements, not as obstacles. (This is a design discussion, not legal advice; a real service needs lawyers in each country it operates in.)

Prefer permission. The best data source is one the store offers for this purpose: an official product API, an affiliate data feed, or a partnership. A tracker that earns affiliate commission when users buy through its links is aligned with the store (it sends buyers), which is why affiliate-style APIs exist. The costs are limits and terms, which the scheduler must respect.

When reading public pages.

  • robots.txt is a convention from 1994, formalised as RFC 9309 in 2022. It is advisory, not a technical lock, but honouring it is the clearest signal of good behaviour, and it is the store's own statement of what automated clients may fetch.
  • Terms of use may forbid automated access. Whether such terms bind a visitor depends on the country and on how the terms were presented; courts have gone different ways (for example, an Irish court in 2010 held that an airline's click-wrap terms were binding on a fare-comparison site, while a US court in 2010 held that browse-wrap terms had to be brought to users' attention to be enforceable).
  • Load. The strongest legal theories against scrapers have often been about harm to the site's systems. In eBay v. Bidder's Edge (2000) a US court granted an injunction against an auction aggregator on trespass-to-chattels grounds. In a 2014 case, the shopping site QVC alleged that a price aggregator's crawler sent up to 36,000 requests per minute and crashed its site for two days. Our per-store budgets, slow ramp-up and back-off are not only courtesy; they are what keeps a tracker from causing that kind of harm.
  • After a request to stop, continuing is a different matter. In Craigslist v. 3Taps (2012 onwards), a court held that a cease-and-desist letter plus IP blocking was enough to support a claim under the US Computer Fraud and Abuse Act. Later, in hiQ Labs v. LinkedIn, the Ninth Circuit held (2019, reaffirmed after the Supreme Court's 2021 Van Buren decision narrowed the Act) that scraping public pages did not violate that Act. The law is unsettled and varies by country. The design rule is simple: a block, a cease-and-desist or a request from the store is a stop signal, handled by the per-store switch from deep dive 12.
  • Facts versus expression. In the US, the Feist decision held that facts themselves are not protected by copyright; a price is a fact, but product descriptions, photos and reviews are creative content. Store only what the product needs (ids, prices, availability, a title for display) and link to the store for the rest. Image URLs pointing to the store, rather than copied images, keep us on the safe side and cost nothing to store.

Personal data. Prices are not personal data, but users, their watch lists and extension telemetry are. Collect the minimum, explain it at install time, allow export and deletion of a user's account and subscriptions, and keep extension observations free of browsing history. Regulators have been clear that "publicly visible" does not mean "free to reuse" when it comes to people's data; a price tracker should never collect seller or reviewer personal data it does not need.

Honesty with users. Label history as "prices we recorded", show when a price was last checked, and never claim "lowest price ever" when our coverage of that product is thin. When a store asks us to stop tracking a region, say so in the product rather than showing stale prices as current. Wikipedia's account of CamelCamelCamel agreeing to Amazon's request to stop tracking prices in some regions during the COVID-19 pandemic is an example of the switch in action.

Deep Dive: Testing, rollout and day-to-day operationsShow

A price tracker fails quietly. Nothing crashes when a parser starts reading the wrong number; users simply get wrong alerts or none. Testing and operations therefore focus on data correctness, not just uptime.

Parser tests.

  • Golden pages. Keep a corpus of saved product pages per store and layout (normal, on sale, out of stock, many sellers, variants, coupons, regional prices, "see price in cart"). Each has the expected extraction result. Every parser change runs against the corpus in CI (see CI/CD and Deployment Strategies).
  • Fresh samples. A daily job fetches a small, polite sample of live pages per store and compares parser output with the API result for the same products. Disagreement above a small threshold opens an incident before users notice.
  • Shadow parsers. A new parser version runs beside the old one on real traffic, writing results to a side table. Promote it only when it agrees on almost all pages and its disagreements are explained.

Matcher and alert tests.

  • Property tests for the matching rules: for any price sequence, a subscription fires at most once per crossing, never fires above target, and re-arms only after the hysteresis band.
  • Replay tests: feed a recorded day of price changes (including a sale day) into a staging stack and compare alerts with expected counts and timing.
  • Idempotency tests: kill matchers and senders at random points during replay, then check that no alert is lost and none is duplicated.

Load tests. Simulate a sale day: 10× price changes for an hour, a few products with 50,000 watchers each, and email provider throttling. Watch detection delay, Kafka lag and alert queue depth. The goal is a graceful slope (alerts a few minutes slower, digests larger), not a cliff.

Rollout.

  • Extension releases go out in stages (for example 1%, 10%, 50%, 100% of installs) through the browser store's staged rollout, with server-side switches that can ignore reports from a bad version.
  • Parser rule updates ship as data (deep dive 10), versioned and reversible in seconds.
  • Scheduler changes (new priority weights) roll out per store and are compared with detection-delay metrics before and after.

Runbooks for common incidents.

SignalLikely causeFirst action
Change rate for a parser jumps from 5% to 50%Layout change, reading wrong fieldPause alerts for that parser; inspect raw pages; ship rule fix; re-parse
Block pages or errors rise for one storeBudget too high, or new rules from storeCut that store's rate; check terms and robots.txt; switch to API and extension
Hot-tier lag growsFetch fleet short, or catch-up after outageShrink warm and cold budgets temporarily; add workers if the store allows more
Alert queue grows on sale dayProvider throttlingSwitch more users to digests; pace sends; check provider status
Many extension reports heldFake data campaign, or new store layoutInspect clusters by network and version; tighten trust thresholds
Chart p99 risesCache miss storm on viral productCheck collapsing and TTLs; pre-warm daily summary cache

Data repair. Because history is the product's memory, every fix ends with a repair: find points written by a bad parser version (each point records parser version and source), delete or correct them, rebuild daily summaries for affected days, and invalidate chart caches. Recording provenance on every point is what makes repair possible.

Backups. Take daily snapshots of the history store and copy them to object storage in another region, and keep the Kafka change topic (or its archive in object storage) long enough to replay a few days. Test restores regularly: Wikipedia's account of CamelCamelCamel's January 2019 outage after three disks failed, which kept the site down for several days, is a reminder that years of history are the one thing a tracker cannot re-fetch.

Deep Dive: Variants of the problem and how the design changesShow

Interviewers often twist this question. The core (a budgeted collector, a change pipeline, a history store and a matcher) stays the same; the twist changes which part is hard.

Back-in-stock alerts. "Tell me when this sold-out console is available." The trigger is availability, not price, and the timing is brutal: stock may last minutes. The hot tier for these products needs checks every few minutes, extension reports are especially valuable, and the alert must go out in seconds (push first, email later). Fan-out is large and bursty, and fairness matters: sending 200,000 alerts at once for 5,000 units means most users arrive to a sold-out page. Some trackers randomise send order or send in waves.

Flight and hotel price alerts. Prices depend on the date, route, cabin, number of travellers and even the point of sale, so a "product" is a search query, and the number of possible queries is huge. The collector runs fare searches (through partner APIs, since airline and travel sites are expensive to query) only for watched routes and dates, and shares results between users who watch the same query. Prices are volatile, so alerts state "as of" times. The separate flight booking case study covers why fare search is costly.

Seller-side competitor monitoring (B2B). A retailer tracks competitors' prices for its own repricing. There are fewer products (thousands to millions), checks are frequent (hourly or faster), and customers pay for freshness and coverage. Matching across stores (the cross-store deep dive) becomes the core feature, and the output feeds a repricing engine rather than an email.

Price history for a marketplace's own catalogue. If the store itself builds the feature, collection disappears: every price change is an event in its own systems. The problem becomes pure stream processing: subscribe to price change events, store history, match alerts. All the fetch budget complexity vanishes, which is a good reminder of where this design's difficulty comes from.

Receipts and price-protection claims. A service that tells users "the price dropped after you bought; claim a refund" needs order data (shared by the user, often from email receipts), per-store price-protection rules, and a reliable price at a past moment. History accuracy and provenance matter even more, because a claim needs evidence.

Very small scale. For 10,000 products and 50,000 users, a single PostgreSQL instance holds products, history and subscriptions; a cron job checks prices through the official API; a query on each change finds subscriptions; an email provider sends alerts. Saying this in an interview shows judgment: the big design exists because of scale, not because it is the only correct answer.

Deep Dive: How the system evolves from version 1 to version 3Show

Version 1: one store, API only, thousands of users. A web app where users paste a product link and set a target. One PostgreSQL database for products, prices and subscriptions. A scheduler loop checks watched products through the official API within its quota, oldest first. On each change, an indexed query finds matching subscriptions and an email is sent. History is a table indexed by (product, time). Charts are rendered from that table with daily down-sampling in SQL. This version proves the value with tiny cost.

Version 2: more products, the extension, millions of users. The API quota no longer covers watched products often enough, so careful page fetching is added with per-store budgets and a priority scheduler. The extension launches, bringing both users and observations, which forces the trust and verification layers. Kafka arrives as the backbone between collection, history, matching and notifications, because several consumers now need the same change stream. History moves to Cassandra as it grows past what one database handles comfortably, with daily summaries for charts and a CDN in front. Notifications get their own service with preferences and digests.

Version 3: many stores and countries, deals and analytics. Each store and country becomes an isolated slice (adapters, parsers, budgets, switches). A warehouse powers deal pages and internal analytics. Cross-store matching powers price comparison. The scheduler uses estimated change rates and the square-root rule. Operations mature: parser health dashboards, golden pages, replay tests, provenance and repair tooling, cross-region backups.

Each step is driven by a measured pain (stale prices, slow charts, alert storms), not by ambition. That is the story interviewers want to hear when they ask "how would this evolve?".

Key Takeaways#

  • The fetch budget is the design. Checking everything often is impossible and impolite; tiers, priorities and the square-root rule decide where each check goes.
  • Prefer permission over scraping. Official APIs and affiliate feeds first, careful page fetching second, and treat blocks and requests to stop as stop signals.
  • Crowdsourced data needs server-side trust. Extension reports are fresh and free but untrusted; validate, score installs, require independent corroboration, and verify before large fan-outs.
  • Store only changes, summarise for reads. Change-only history, daily summaries and down-sampling keep years of history small and charts fast.
  • Match with an index, alert exactly once. Find subscriptions by (product, type, target) with a partial index; flip state and write the outbox in one transaction; use hysteresis.
  • Notifications are the spike. Sale days turn one change into tens of thousands of alerts; queues, digests, pacing and freshness re-checks keep them correct and polite.
  • Correctness fails quietly. Parser health metrics, golden pages, provenance on every point and repair tooling matter more than raw uptime.
  • History is irreplaceable. Replicate across zones, back up across regions and test restores.
  • Isolate by store and country. Separate budgets, parsers and switches let one site's change or block affect only its slice, and make new stores cheap to add.