Quick revision
The short answer
We count each view in Redis with one HINCRBY on a per-interval hash, spread over several hashes so no single key gets hot. Every few seconds a flusher takes a closed interval atomically (RENAME to a processing key), applies the deltas to PostgreSQL in batched UPDATEs while recording the batch id in the same transaction, and deletes the processing key only after the commit. If a flusher dies we simply retry; if a Redis primary dies we lose at most the unflushed, unreplicated seconds, which we bound with the flush interval, AOF and replicas.
What to remember
In this answer, we saw that a write-behind counter turns 50,000 writes per second into one database write per video per interval. Events go to sharded per-interval hashes with HINCRBY, a flusher takes each closed interval with RENAME, applies deltas in batched UPDATEs, records the batch id in the same transaction and deletes the key only after the commit. A flusher crash costs only delay, while a Redis failure loses a bounded few seconds that we choose with the flush interval, AOF and replicas, and we watch the age of the oldest pending batch.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We count each view in Redis with one HINCRBY on a per-interval hash, spread over several hashes so no single key gets hot. Every few seconds a flusher takes a closed interval atomically (RENAME to a processing key), applies the deltas to PostgreSQL in batched UPDATEs while recording the batch id in the same transaction, and deletes the processing key only after the commit. If a flusher dies we simply retry; if a Redis primary dies we lose at most the unflushed, unreplicated seconds, which we bound with the flush interval, AOF and replicas.
Why this question is asked
View counters are the classic case where the database cannot take every write, but nobody minds if the number on the page is a few seconds behind. Interviewers like this question because it tests whether we can use write-behind, where the cache takes the write first and the database is updated later, without losing track of what has and has not been saved. In this answer, we will size the problem, choose the Redis data structures, walk through one flush step by step, make the flush safe to retry, look at what a Redis failure costs, and finish with reading and monitoring the counts.
1Rough Numbers First
Writing each view to PostgreSQL means 50,000 row updates per second, many on the same few popular rows, each taking a row lock and writing a new row version and a WAL record. The hot rows serialize on their locks.
About 200,000 distinct videos get views in a minute. If we flush every 10 seconds, an interval holds 500,000 events but touches at most a few tens of thousands of distinct videos, and far fewer in practice, because views concentrate on popular videos. So we make one write per video per interval instead of one per event. That is the point of write-behind for counters: the database cost follows the number of distinct keys, not the number of events.
2The Redis Data Structures
Each event becomes a single HINCRBY, an O(1) command that adds a number to one field of a hash. The key names an interval and a shard, and the field is the video id. The interval is the event time rounded down to 10 seconds, and the shard is a hash of the video id modulo 16.
Why 16 hashes instead of one? In Redis Cluster a key lives on exactly one node, so a single hash would put all 50,000 increments per second on one node. Spreading video ids over 16 keys spreads the work over the cluster; we deliberately avoid a hash tag such as {views}, which would force all 16 keys onto one node again.
Why a new key per interval? Because once the clock passes the end of an interval, no new events write to that key, so it can be taken away as a whole. The long EXPIRE is only a safety net; it must be much longer than any flusher outage we expect, or the safety net itself would lose data. The application pipelines events in batches of a few hundred commands per round trip.
3How One Flush Works
A flusher runs every few seconds and looks for interval keys older than the current interval plus a short grace period, say 2 seconds for clock skew. It first renames each one to a processing key. RENAME is atomic, so once it returns, the batch belongs to the flusher and nothing else can add to it.
Then it reads the processing key with HGETALL (or HSCAN for a very large hash) and applies the deltas in one transaction, about 1,000 rows per statement. Notice that the UPDATE adds a delta rather than setting a total, which is what lets intervals and retries combine correctly.
7 messages in order. Play them, or step through them one at a time.
The key is deleted only after the database has committed the batch.
So each video costs one row update per interval, whether it got one view or ten thousand. A very large hash can be split into several transactions, each with its own sub-batch id such as 7:1731500000:part3.
4Making the Flush Safe to Retry
The dangerous moments are the gaps between steps. If the flusher crashes before the commit, the transaction rolls back and the processing key is still in Redis, so the next flusher simply applies it again. If it crashes after the commit but before the DEL, the processing key is also still there, but this time the deltas are already in the database. Applying them again would double the counts.
That is why the batch id goes into the flushed_batches table in the same transaction as the updates. When a retry finds that the INSERT inserted 0 rows, it knows the batch was already applied, skips the UPDATE and just deletes the key. The commit is the single point that decides whether a batch happened, and it decides both things at once. On startup, every flusher first looks for leftover views:processing:* keys and finishes them before taking new intervals.
If several flushers run for availability, give each a set of shards or a short lease per shard; the batch id check keeps even a race safe, but ownership avoids wasted work. Rows in flushed_batches can be deleted after a day.
5What Happens When a Flusher or a Redis Node Fails
A failed flusher costs only delay. Events keep accumulating in new interval keys, and when a flusher comes back it works through the backlog in interval order, losing nothing as long as it finishes before the safety TTL.
A failed Redis primary is different, because during the delay Redis holds the only copy of the counts. Replication is asynchronous, so increments not yet sent to the replica disappear when it is promoted. The loss is bounded by roughly the flush interval plus the replication lag, a few seconds of views.
We choose that bound on purpose. A shorter interval lowers the possible loss but raises database writes. AOF with appendfsync everysec means a restarted node loses at most about one second, and replicas with automatic failover keep the service available. For view counts that is enough; for money, this would be the wrong design altogether.
| Failure | What is lost | How we recover |
|---|---|---|
| Flusher crashes before commit | Nothing | Retry applies the processing key |
| Flusher crashes after commit | Nothing | Batch id found, skip updates, delete key |
| Redis primary fails | Unreplicated, unflushed deltas | Replica promoted; loss bounded by interval |
| Database slow or down | Nothing, counts lag | Backlog flushed in interval order |
6Reading and Watching the Counts
The page can show the stored database value, at most one interval plus the flush time behind. For fresher numbers we add the pending deltas: HGET on the open interval keys and any processing key for that video's shard, added to the database value.
The metrics that matter are the age of the oldest unflushed interval, flush duration, rows per flush, and how far the database lags. An alert on the oldest pending interval, for example older than 60 seconds, catches a stuck flusher long before the safety TTL could lose anything.
7Follow-up questions
How would you rebuild counts if a whole batch was lost?
Only if we kept the raw events somewhere else. A common design publishes each view to Kafka as well, with a retention of a few days, and the counter is a fast path in front of it. To rebuild, we recount the events of the lost interval from Kafka and apply the deltas with a new batch id. If there is no raw log, the batch is gone, and the honest answer is that for view counts that was the accepted loss window.
Why add a delta instead of writing the total from Redis?
Because Redis is not the system of record for the total. After a failover Redis may have lost some increments, and writing its total would silently replace the database value with a smaller one. Adding deltas means each interval only ever adds what it counted, and the database total stays correct even when a batch is retried or arrives late.
8Conclusion
In this answer, we saw that a write-behind counter turns 50,000 writes per second into one database write per video per interval. Events go to sharded per-interval hashes with HINCRBY, a flusher takes each closed interval with RENAME, applies deltas in batched UPDATEs, records the batch id in the same transaction and deletes the key only after the commit. A flusher crash costs only delay, while a Redis failure loses a bounded few seconds that we choose with the flush interval, AOF and replicas, and we watch the age of the oldest pending batch.
Open with
I would count in Redis and flush to PostgreSQL in batches. Each view is one HINCRBY on a hash keyed by a 10-second interval and one of 16 shards, so no single key takes all the increments.
Then, if they want more
Every few seconds a flusher renames each closed interval to a processing key, which is atomic, reads it, and runs UPDATE views = views + delta in chunks. In the same transaction it inserts the batch id into a flushed_batches table, and it deletes the processing key only after the commit.
A crash before the commit means the retry reapplies the batch; after it, the retry sees the batch id and just deletes the key. A flusher failure only delays counts. A Redis primary failure can lose the deltas that were neither replicated nor flushed, so the loss is about one interval plus replication lag.
I would pick the interval with the product owner, use AOF everysec and replicas, keep raw events in Kafka if counts may need rebuilding, and alert on the age of the oldest pending interval.
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 a write-behind counter with Redis and a database flusher: the data structures...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/8f02104af5/