Skip to main content

System Design Drill Day 20: Counting at Scale for Views and Trending

How to count product views, unique viewers and "trending now" without melting MySQL, using Redis counters, HyperLogLog and time-bucketed sorted sets.

Updated 12 min readMarkdown
Part of seriesSystem Design Drills
System Design Drill Day 20: Counting at Scale for Views and Trending

A product page says "1.4k people viewed this today", and the home page has a "Trending in Kathmandu" row that shifts every few minutes. Both look like simple counters until a sale starts and thousands of shoppers hit the same few products at once.

A plain views = views + 1 breaks under that kind of load. So the counts get buffered in Redis and flushed to MySQL in batches, unique viewers come from HyperLogLog, and the trending list is built so that old spikes fade out by themselves.

Core concepts

Start with the obvious version. Every page view runs UPDATE products SET views = views + 1 WHERE id = ?. On a quiet day nobody notices. During a big sale, a single popular phone might get hundreds of views a second, and every one of those updates wants a row lock on the same row. They queue up behind each other, the page request waits on a counter nobody urgently needs, and the replicas fall behind (Day 4) because the binlog is full of counter bumps.

This is the hot row problem. The fix is easy to say: stop writing every single view to the database.

Redis runs commands one at a time and in memory, so INCR and HINCRBY are atomic and thousands of increments a second on one key are no problem. Absorb the views in Redis, then flush the totals to MySQL every minute or so as one batched upsert. MySQL sees one write per product per minute instead of one per view.

You do pay for this. Counts are a little stale, and if Redis dies you can lose up to one flush window. For a view counter, fine. For money, no way, and that's why Day 18 kept the ledger in MySQL with exact entries.

Two paths for a page view: the naive path updates the products row on every view and all requests queue on one row lock, while the buffered path increments a Redis hash and a scheduled job flushes the totals to MySQL in one batched upsert every minute

Figure 1: Per-view row updates pile up on one lock; buffering in Redis turns them into one write per minute.

Unique viewers are harder. "1,400 views" might just be 200 people hitting refresh. The normal way to count distinct visitors is a set of visitor ids per product per day. A popular product can have tens of thousands of ids in there, and you keep one set for every product, for every day.

HyperLogLog (HLL) answers one question, "roughly how many distinct things have I seen?", in a fixed amount of memory. In Redis a dense HLL key is capped at 12 KB no matter how many items go in. Small ones use a compact sparse form that is much smaller than that. The count has a standard error of about 0.81%.

The catch: you can't ask whether a specific visitor is in it, and you can't remove anyone. PFADD adds, PFCOUNT estimates, and PFCOUNT across several keys (or PFMERGE) gives you the union. That's how seven daily keys become a weekly unique count.

Trending is a ranking over a moving window. A Redis sorted set with ZINCRBY gives you a live leaderboard, but one all-time set just rewards whatever was popular last month. The usual fix is time buckets: one sorted set per hour, then a periodic ZUNIONSTORE over the last 24 buckets with weights that shrink for older hours, say 0.9 per hour of age. A spike from yesterday morning counts for less than one from the last hour, and it drops out completely when its bucket leaves the window.

Pause and think: Why not just keep a Redis set of visitor ids per product per day and call SCARD?

Answer: It works but the memory grows with every distinct visitor, and you pay that for every product and every day you keep. HyperLogLog never goes above about 12 KB per key, and small ones are far smaller, in exchange for an approximate count and no way to list or remove members.

The design problem

An online marketplace has about 2 million products and runs on 3 Laravel app servers, MySQL and Redis. During a festival sale, product pages peak at about 3,000 views per second, and the top handful of products take a large share of that.

Build three things:

  • A "viewed N times today" counter on each product page.
  • A seller dashboard showing daily views and daily unique viewers per product, kept for 90 days.
  • A "Trending now" row on the home page: the top 50 products over the last 24 hours, weighted toward recent activity, refreshed every few minutes.

Bots and someone holding F5 should not be able to push a product into trending. Losing a minute of counts in a Redis failure is acceptable. Slowing down the product page is not.

Try the problem before reading the solution.

Questions to think about

  1. Why does UPDATE products SET views = views + 1 fall over at a sale peak, and what replaces it?
  2. How do you count unique viewers per product per day without storing every visitor id, and what do you give up?
  3. How do you compute "trending in the last 24 hours" so it updates often and old spikes fade?

Model solution

Recording a view

Record the view after the response has gone out, so the page never waits on it. In Laravel that can be a terminable middleware or a small /track beacon the page fires. Drop obvious bots by user agent, and rate limit per session or IP (Day 7) so one person reloading counts at most once every few minutes.

Each counted view runs one Redis pipeline:

  • HINCRBY views:pending {product_id}:{date} 1 for the raw count
  • PFADD uv:{product_id}:{date} {visitor_id} for unique viewers, where visitor_id is the user id or a cookie id for guests
  • SET seen:{product_id}:{visitor_id} 1 NX EX 86400 to spot a first view

If that SET actually created the key, the app follows up with ZINCRBY trend:{yyyymmddHH} 1 {product_id}. That is cheap anti-gaming. Repeat views from the same person still count as views, but they push trending at most once a day per product.

You might be tempted to use PFADD's return value for this instead. Don't. It returns 1 only when one of the HLL's internal registers changes, which is close to exact on a small key, but once a product has tens of thousands of uniques most genuinely new visitors return 0. The hottest products would get undercounted in exactly the list that is supposed to show them. The seen: keys cost one small key per visitor and product, and they expire on their own.

Set an EXPIRE on each uv: key (about 8 days) and each hourly trend: key (about 26 hours) so nothing grows forever.

Flushing to MySQL

A scheduled job runs every minute. It renames views:pending to views:flush:{batch_id}, which is atomic, so new views land in a fresh hash while the job works on the old one. If nothing was viewed in the last minute the key doesn't exist and RENAME throws "no such key", so check EXISTS first or treat that error as "nothing to flush".

Each hash field is {product_id}:{date}, so a batch flushed at 00:00:30 still files the last few seconds of yesterday under yesterday. The job reads the renamed hash and writes it in chunks of about 1,000 rows. product_daily_stats needs a UNIQUE KEY (product_id, date) for the upsert to have something to collide on:

INSERT INTO product_daily_stats (product_id, date, views)
VALUES (?, ?, ?), ...
AS new
ON DUPLICATE KEY UPDATE views = views + new.views;

That row alias syntax needs MySQL 8.0.19 or later. The older VALUES(views) form still runs, but 8.0.20+ warns that it is deprecated.

The risky moment is a crash after the insert commits but before the Redis key is deleted. The next run would add the same batch twice. Record batch_id in a stat_flushes table with a unique key inside the same MySQL transaction as the upsert, and skip any batch already recorded. That is Day 9 idempotency applied to a cron job. The other half is not forgetting the batch: before renaming anything, the job does a SCAN for leftover views:flush:* keys from a crashed run and finishes those first. The batch id check then either skips them or applies them exactly once.

Flush flow: views increment the views:pending hash per product and date, the minute job first finishes any leftover batch keys, renames the pending hash to a batch key if it exists, upserts the totals into product_daily_stats together with a batch id row in one transaction, then deletes the batch key; a rerun after a crash finds the batch id already recorded and skips it

Figure 2: Rename, upsert with a batch id in one transaction, then delete.

The product page reads today's count from product_daily_stats, cached for a minute. It can lag the real number by a minute or two. Nobody will notice.

Unique viewers go into the same table, but only once a day. Shortly after midnight a job runs PFCOUNT uv:{id}:{yesterday} for products that had views and stores the number. Seller dashboards read 90 days of history from MySQL, and today's live figure straight from PFCOUNT. A weekly unique count is PFCOUNT over the seven daily keys, not the sum of seven daily numbers, because the same person can visit on several days. That only works while the daily uv: keys are still alive, so with the 8 day expiry you get the last week and nothing older. If sellers want weekly uniques for older weeks, PFMERGE each finished week into its own key and keep that for 90 days.

Every 5 minutes a job runs ZUNIONSTORE trend:24h 24 trend:{h} trend:{h-1} ... trend:{h-23} WEIGHTS 1 0.9 0.81 ... 0.09 over the last 24 hourly buckets, trims it with ZREMRANGEBYRANK to the top 200, filters out products that are out of stock or hidden, and caches the final top 50 as JSON. The home page only ever reads that cached list.

The weights are 0.9 to the power of the bucket's age in hours, so the 23 hour old bucket still counts at about 9%. Don't step them down by a flat 0.1 per hour. By the eleventh bucket the weight hits zero, after that it goes negative, and Redis will happily subtract old views from a product's score.

Views are a weak signal on their own. You can mix in stronger ones by giving them bigger increments, for example 10 points for an add to cart and 30 for an order, fed from the existing order events through the outbox (Day 11). Purchases are much harder to fake than views.

Trending: a visitor's first view of a product, gated by a SET NX dedupe key, increments the current hourly sorted set, a job every five minutes merges the last 24 hourly sets with weights of 0.9 per hour of age into trend:24h, trims and filters it, and caches the top 50 that the home page reads

Figure 3: Hourly buckets merged with decaying weights into one cached top 50.

Pause and think: A product had a huge spike 23 hours ago and nothing since. What happens to it over the next two hours?

Answer: Its weight is small now, about 9% with 0.9 per hour decay, so unless the spike was enormous it has probably slipped well down the list. Once that hour leaves the 24 bucket window it stops counting at all and drops off on the next 5 minute rebuild.

Answers to the questions

Answer:

  1. Every view takes a row lock on the same product row, so at hundreds of views per second on one product the updates queue behind each other, page latency climbs and the binlog floods the replicas. Buffer counts in Redis with HINCRBY and flush them to MySQL every minute as one batched upsert, guarded by a batch id so a rerun can't double count.
  2. Use a HyperLogLog per product per day: PFADD each visitor id and read the estimate with PFCOUNT. Memory stays at most 12 KB per key. You give up exactness (about 0.81% standard error), the ability to list or remove visitors, and you must union keys with PFCOUNT or PFMERGE rather than adding daily numbers.
  3. Keep one sorted set per hour, increment it only for a visitor's first view of the day (a SET NX dedupe key) plus weighted cart and order events, and every few minutes merge the last 24 hourly sets with ZUNIONSTORE and geometric WEIGHTS such as 0.9 per hour of age. Trim, filter unavailable products and cache the top 50. Old spikes lose weight each hour and vanish when their bucket leaves the window.

Scaling later

One Redis handles 3,000 pipelines a second easily. If the counters ever outgrow it, split views:pending into several hashes by product id modulo N, which is Day 6 sharding again. If sellers later get billed per view or click, these approximate counts are no longer good enough, and every billable event goes to an append-only log that gets aggregated exactly.

Interview one-liner

"Never bump a hot row per event. Buffer counters in Redis and flush them in idempotent batches, use HyperLogLog for unique counts, and build trending from hourly sorted sets merged with decaying weights, accepting slightly stale and approximate numbers where money isn't involved."

Conclusion

Most counters on a product page only need to be roughly right and never slow, so they belong in Redis first and MySQL later. Pick exact or approximate per number on purpose: views and trending can drift a little, billing can't.

Try it yourself

Start Redis locally, then PFADD 100,000 random ids into one key and compare PFCOUNT with the real number. Check the key size with MEMORY USAGE, then put the same ids in a normal set and compare.

Then create three hourly sorted sets with a few products each, merge them with ZUNIONSTORE ... WEIGHTS 1 0.5 0.25, and watch how the ranking changes when you bump the oldest hour.


This is part of my daily System Design Drills series.

No comments yet. Be the first to comment.