Scrivio Interview library
DesignIntermediate6 min read · updated 13 November 2026

A video platform shows view and like counts. During a live event a few videos receive 200,000 like and view increments per second, and a single database row per video cannot keep up. Advertisers are billed on views.

Design the counting so it scales, and explain where exact counts are required and how you get them.

We split counting into two paths. Display counts are approximate and eventual: each pod aggregates increments in memory for about a second and adds the batch to a sharded counter in Redis, so 200,000 increments per second become a few hundred writes spread over many keys. Billed views are exact and auditable: every view is an event with an id in a durable log such as Kafka, deduplicated and counted by a replayable stream or batch job, reconciled against the display counter, and never billed from it.

Background to this question

Counting sounds trivial until one row has to absorb 200,000 updates a second. At that point a single database row becomes a lock that every request waits on, and the obvious fixes trade accuracy for speed. The interesting part of this question is that the same number, views, serves two audiences with very different needs: viewers who want a number that moves, and advertisers who pay for an exact one. In this answer, we will see why one row cannot keep up, design the fast display path with batching and sub-counters, design the exact billing path with events and deduplication, and then connect them with reconciliation and abuse rules.

1Why a Single Row Cannot Keep Up

UPDATE video SET views = views + 1 WHERE id = 9 takes a row lock, writes the change to the log and releases the lock at commit. Every concurrent increment on the same row must wait for the one before it. Even at an optimistic 0.2 ms per commit, one row handles about 5,000 updates per second, forty times less than we need, and every waiting transaction holds a connection.

The same problem appears in Redis on a single key: Redis is fast, but one key lives on one shard and one thread, so a single very hot key can saturate that shard. The fix in both cases is the same idea: fewer writes, and spread over more places.

2Requirements: Two Audiences, Two Paths

For display, viewers want a count that grows and is roughly right; a delay of a few seconds or an error of a fraction of a percent harms nobody. For billing, advertisers pay per view, so we need a count that is exact under our rules, explainable in an audit, and correct even after failures and retries. Those requirements are too different for one mechanism, so we build two paths from the same stream of events.

Step throughTwo counting paths
  1. Video podsreceive view and like events
  2. Display pathin-memory batch per second -> sharded Redis counter
  3. Billing patheach view event with an id -> Kafka
  4. Stream or batch jobdedupe by event id, apply view rules, exact totals
  5. Billing store and reconciliationbilled views, compared with display counts

5 layers, from the top down. Step through them one at a time.

3The Display Path: Batching and Sub-Counters

Each pod keeps a map from video id to a pending count, using a LongAdder so many threads can increment without contention. Once a second it swaps the map out and sends one INCRBY per video to Redis. If 50 pods each see 4,000 increments per second for a hot video, Redis receives 50 writes per second for that video instead of 200,000.

To avoid a single hot key, we split each video's counter into N sub-counters, for example 64 keys views:9:0 to views:9:63, and each flush picks one at random. Reading sums the 64 keys, which is cheap with a pipeline, or a small job sums them every second into a display key that pages read.

Java
ConcurrentHashMap<Long, LongAdder> pending = new ConcurrentHashMap<>();
void onView(long videoId) { pending.computeIfAbsent(videoId, k -> new LongAdder()).increment(); }
@Scheduled(fixedRate = 1000)
void flush() {
var batch = pending; pending = new ConcurrentHashMap<>(); // (pending is volatile)
batch.forEach((id, n) -> {
int shard = ThreadLocalRandom.current().nextInt(64);
redis.opsForValue().increment("views:" + id + ":" + shard, n.sum()); // 4,000 increments -> 1 write
});
}

Notice that a crash loses at most one second of this pod's increments. For a display number that is acceptable, which is exactly why we must never bill from it. Simple swapping like this can also drop an increment that races with the swap, which again only matters for display.

4The Billing Path: Exact and Auditable

Billing starts from events, not counters. Each view is recorded as an event with a unique id, the video, the viewer or session, the timestamp and the information the view rules need, such as watch time. The event is written to Kafka, which is a durable, replayable log. The producer is idempotent and the event id is generated once on the client or the edge, so a retried send carries the same id.

A stream job, for example Kafka Streams or Flink, or a periodic batch job, reads the events, deduplicates by event id, applies the rules for what counts as a billable view, and writes exact totals per campaign and period. Because the log is kept, the job can be replayed after a bug fix or a dispute, and every billed number can be traced back to the events behind it.

Step throughOne billable view
PlayerEdge APIKafkaBilling jobBilling store
view event, id e-81f, watched 31 s
produce (idempotent), key = video id
202 accepted
consume
seen e-81f before? no. watched over 30 s? yes
add 1 to campaign 17, hour 20:00
retry of e-81f after a timeout
seen e-81f: skip

8 messages in order. Play them, or step through them one at a time.

5Reconciliation and Abuse Rules

The display counter and the billing count will differ: the display path loses a second of data on crashes and counts raw events, while billing removes duplicates and invalid views. We compare them regularly, per video and hour, and alert when the difference exceeds what we expect, because a large gap usually means a bug in one path. Advertisers are always billed from the billing path.

For billing, correctness depends more on rules than on throughput. What counts as a view, such as a minimum watch time, how often one viewer can count per video per day, and how bots and click farms are filtered, are business rules applied in the billing job. Idempotency on event ids prevents double counting from retries, and abuse filtering prevents counting views that should never have been paid for.

6Follow-up questions

What happens to the in-memory batches if a pod crashes?

The increments since the last flush are lost, up to one second of that pod's share. For display counts that is a tiny, invisible error, and the counter is regularly corrected from the exact path anyway. Billing does not depend on these batches at all, because each view was written to Kafka as its own event before being acknowledged, so a crash never loses a billable view.

Could we use a probabilistic structure instead of counters?

For unique viewer counts, yes: a HyperLogLog in Redis estimates distinct viewers with about 1 percent error in 12 KB per key. For total views it does not help, since a sharded counter is already cheap. Neither is suitable for billing, which needs exact, explainable numbers.

Why choose 64 sub-counters?

It is a balance: enough keys that the hottest video's writes spread across shards and no key gets more than a few writes per second after batching, but few enough that summing them on read stays cheap. We can make N larger only for the videos that are actually hot.

7Conclusion

In this answer, we saw that a single row or key cannot absorb 200,000 increments per second, so display counts use in-memory batching per pod and sharded sub-counters in Redis, accepting small losses. Billing uses a separate exact path: view events with ids in Kafka, deduplicated and filtered by a replayable job, reconciled against the display counter and never billed from it.

What to say in the interviewAbout 80 seconds aloud

Open with

I would separate the display count from the billing count. For display, the count can be approximate and a few seconds behind, so each pod aggregates increments in memory with a LongAdder and flushes once a second with an INCRBY to Redis, which turns 200,000 increments per second into a few hundred writes.

Then, if they want more

To avoid a single hot key, each video gets something like 64 sub-counters, chosen at random on each flush, and we sum them on read or with a small periodic job. If a pod crashes we lose at most a second of its increments, which is fine for display.

Billing needs exact, auditable numbers, so every view is written as an event with a unique id to Kafka with an idempotent producer. A stream or batch job deduplicates by event id, applies the rules for what counts as a view, like minimum watch time and bot filtering, and writes exact totals per campaign.

Because the log is kept, we can replay it after a bug or a dispute. We reconcile the display counter against the billing totals regularly and alert on drift, and we never bill from the display counter.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design the counting so it scales, and explain where exact counts are required and how...": https://scrivio-interview-library.netlify.app/architecture/sd-fundamentals/8db2848586/