Video in progress

Strong Middle 🏗️ System design

How do you compute the 100 most viewed products (top-K) over the last hour in real time?

At small volume, ZINCRBY on Redis sorted sets per time slice, then merging several slices with ZUNIONSTORE, is enough. On a very large stream you need approximate structures like a count-min sketch inside stream processing, plus two-stage aggregation.

📖 Answer

The simple solution: UPDATE products SET views = views + 1 on every view and ORDER BY views DESC LIMIT 100. This gives you the "top of all time", not "the last hour", and on top of that it chokes the DB with writes.

Medium volume — Redis sorted sets, per-minute slices:

ZINCRBY views:2026-11-03T14:05  1  product:42      # on every view
EXPIRE  views:2026-11-03T14:05  4000

# a background job every 10 seconds:
ZUNIONSTORE top:1h 60 views:...T13:06 ... views:...T14:05
ZREVRANGE   top:1h 0 99 WITHSCORES

The window "slides": old minutes aren't added to the union, and they expire on their own through the TTL. The result is cached, so users read the ready-made top:1h, not the ZUNIONSTORE.

Writing views one at a time can get expensive too — collecting them in the application for 1–2 seconds and sending the ZINCRBY in batches cuts the load a lot.

A very large stream (hundreds of thousands of events per second, a million different products): events go to Kafka, a stream job computes a local top per partition, and then those are merged. If keeping a counter per product is too expensive, a count-min sketch estimates the frequency approximately and a small heap holds only the candidates. The result is a bit approximate — for "trends" that's usually acceptable.

One more thing: bots and a single user refreshing repeatedly distort the top. Before counting, do a short-lived dedup by (user, product).