Design a View Counter: Counting at High Write Volume
Why incrementing a database row on every view collapses under load, and how event streams, batching, sharded counters and deduplication give accurate counts at scale.
A view counter records how many times a video, post or page has been viewed and displays that number. The feature looks trivial: add one each time someone watches.
The difficulty is volume and concentration. A popular video can receive tens of thousands of views per second, all targeting the same counter. These notes explain why the direct approach fails and how counting systems are built.
1. Requirements
- Functional: record a view when a user watches a video; display the total view count for a video.
- Functional: count unique or valid views, so that refreshing the page repeatedly does not inflate the number.
- Non-functional: handle a very high write rate, including spikes on a single viral video.
- Non-functional: recording a view must not slow down or break playback.
- Consistency: the displayed count may lag by a few seconds. Eventual consistency is acceptable. (Counts used for billing or creator payouts need higher accuracy and are computed separately.)
- Workload: write-heavy for recording; read-heavy for displaying.
2. Scale estimation
Assume 1 billion views per day. That is about 10,000 writes per second on average, perhaps 50,000 at peak, and a single viral video may account for a large share of that at a given moment. Reads of the count are even more frequent, since the number is shown wherever the video appears. The count itself is tiny: 100 million videos with an 8-byte counter each is under 1 GB.
3. Why a direct database increment fails
The straightforward implementation runs an UPDATE that adds one to the video's row on every view. A relational database must lock the row for the duration of each update so that concurrent increments do not overwrite each other. When thousands of requests per second target the same row, they queue behind that lock. This is row lock contention.
Each update also writes to the transaction log and to the replicas. Latency rises, connections pile up, and because the videos table also serves title and metadata queries, those slow down too. A feature that should be invisible ends up degrading the whole product.
-- Executed once per view. For a viral video, thousands of these per second -- all wait for the same row lock. UPDATE videos SET view_count = view_count + 1 WHERE id = 123;
4. Record events, aggregate later
The core idea is to separate recording a view from updating the count. When a view occurs, the service publishes a small event (video ID, user or device ID, timestamp) to a stream such as Kafka and returns at once. Appending to a log is cheap and has no contention on a shared row.
A consumer reads the events and aggregates them in memory over a short window, for example five seconds. At the end of the window it writes one update per video: if a video received 40,000 views in the window, the database receives a single statement adding 40,000 instead of 40,000 statements adding one. This is batching, and it reduces the database write rate by several orders of magnitude.
WRITE PATH
Player --> View API --> Kafka topic "views" (partitioned by videoId)
|
v
Stream aggregator (5-second windows, dedup)
| |
v v
Redis: INCRBY views:{videoId} n Counts DB: UPDATE ... + n (one write per video per window)
|
Raw events --> data warehouse (exact counts, analytics)
READ PATH
Client --> Video API --> Redis views:{videoId} --(miss)--> Counts DBconst pending = new Map(); // videoId -> views in the current window
function onViewEvent(event) {
if (isDuplicate(event)) return; // see deduplication below
pending.set(event.videoId, (pending.get(event.videoId) || 0) + 1);
}
setInterval(async () => {
const batch = new Map(pending);
pending.clear();
for (const [videoId, n] of batch) {
await db.query(
"UPDATE video_counts SET views = views + $1 WHERE video_id = $2", [n, videoId]
);
await redis.incrby("views:" + videoId, n);
}
// commit Kafka offsets only after the batch is written
}, 5000);5. Sharded counters
Where counts must be updated directly at a high rate, a single counter is split into several sub-counters, called shards. Each increment goes to one shard chosen at random or by hashing the request. Because writes are spread across N rows or keys, contention falls by a factor of N. The total is the sum of all shards, computed on read and cached.
The trade-off is that reading is slightly more work, which is acceptable because the sum changes slowly relative to how often it is read and can be cached for a few seconds.
video_view_shards (video_id, shard_id, count) PRIMARY KEY (video_id, shard_id) (123, 0) 4,812,551 (123, 1) 4,809,120 (123, 2) 4,815,004 ... (123, 9) 4,811,377 write: UPDATE ... SET count = count + 1 WHERE video_id = 123 AND shard_id = random(0..9) read : SELECT SUM(count) FROM video_view_shards WHERE video_id = 123 (cache the result)
6. Deduplication
A view count is only meaningful if it resists trivial inflation. Refreshing a page ten times should not add ten views, and a retried request should not count twice. The aggregator therefore checks each event against recent history before counting it.
A simple rule is one view per user (or device) per video within a time window. This is implemented with a key such as seen:{videoId}:{userId} in Redis, set with a TTL using an atomic set-if-absent; the view is counted only if the key was newly created. For very high volumes, a Bloom filter gives the same check in far less memory at the cost of a small false-positive rate.
If the requirement is the number of distinct viewers and not the number of views, a HyperLogLog estimates the count of unique users in a few kilobytes with an error of around one percent. Further rules, such as a minimum watch duration and bot filtering, are applied in the same stage.
7. Serving the count
Counts are read far more often than they change in a way a user could notice. The current value is kept in Redis and returned from there. The UI shows rounded values such as 1.2M, so a delay of a few seconds is invisible. This is a deliberate use of eventual consistency: the displayed number converges to the true value shortly after the views occur.
8. Accuracy and failure handling
- The aggregator commits its position in the stream only after writing a batch. If it crashes, the uncommitted events are replayed. This is at-least-once processing, so a small overcount is possible unless the batch write is made idempotent, for example by storing the window ID with the update.
- Raw events are retained and also loaded into a data warehouse. A periodic batch job recomputes exact counts from them and corrects any drift in the fast counters. Combining a fast approximate path with a slow exact path is a common pattern.
- Hot videos: partitioning the stream by video ID keeps a video's events together for aggregation, but a single viral video can overload one partition. Adding a random suffix to the key for very hot videos spreads them, with the partial counts combined afterwards.
- The same design applies to likes, impressions, download counts and any other high-volume counter.
Interview summary
- Requirements: very high write rate, eventual consistency acceptable, must not affect playback.
- Do not increment a database row per view: row lock contention.
- Publish view events to a stream and aggregate in batches.
- Use sharded counters where direct increments are needed, and deduplicate views.
- Serve counts from a cache; reconcile against raw events for exact numbers.
Summary
A counter that is updated on every event becomes a point of contention. The scalable design records each view as an event, aggregates events in short windows, and applies one batched update per video. Sharded counters spread direct increments, deduplication keeps the number honest, a cache serves reads, and a batch job over the raw events provides the exact figure.
Puneet Tiwari
Full Stack Developer
