Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Design how a product shows counts such as 'unread messages' and 'orders this month' for millions of users without running COUNT on large tables at read time.

We treat counts as data that is maintained on the write path rather than computed at read time: an increment in the same transaction as the change, or a consumer applying events. Hot counters are sharded into several rows or aggregated asynchronously to avoid lock contention, periodic recomputation corrects drift, and each counter is classified as exact or eventually consistent. Counts are served from a summary table or Redis, with the source of truth written down for each one.

Why this question is asked

Badges such as '3 unread' and figures such as '12 orders this month' look trivial on a screen, but for millions of users they are read on almost every page view, and running COUNT on a large table each time would cost more than everything else the page does. Interviewers ask this design question to see whether we can move work from read time to write time without creating contention or silent drift. In this answer, we will see why read-time counting fails, maintain counters on the write path, handle hot counters, correct drift, decide on exactness, and choose where the counts live.

1Why Counting at Read Time Does Not Scale

A query such as SELECT count(*) FROM messages WHERE user_id = ? AND read = false is fine for one user with 30 messages. Run it on every page view for 5 million active users, some of whom have 200,000 messages, and the database spends its time re-counting numbers that barely change between two page loads. An index helps, but a count still visits every matching entry. The idea of the design is simple: since a count changes only when a write happens, update it when the write happens and make reading it a single-row lookup.

2Maintain Counters on the Write Path

There are two ways to maintain a counter. The first is to update it in the same database transaction as the change itself, so the count is always exactly consistent with the data.

Java
@Transactional
public void deliver(Message m) {
messageRepository.save(m);
jdbc.sql("UPDATE mailbox_counts SET unread = unread + 1 WHERE user_id = ?")
.param(m.recipientId()).update(); // committed together with the message
}
-- orders this month: one row per user and month, created on first use
INSERT INTO monthly_order_counts (user_id, month, n) VALUES (?, date_trunc('month', now()), 1)
ON CONFLICT (user_id, month) DO UPDATE SET n = monthly_order_counts.n + 1;
Step throughEvent-driven counter update
Order serviceDatabaseBrokerCounter consumer
insert order + outbox row (one transaction)
relay publishes OrderPlaced
deliver OrderPlaced (at least once)
if event id unseen: n = n + 1, remember id
page view: read counter row
12 orders this month

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

Reads become one-row lookups; the counter may trail the data by the consumer's lag.

The second is to publish an event, OrderPlaced or MessageRead, and let a consumer update the counters. This decouples the counter from the main write and can feed several counters from one event, but the count lags behind by the consumer's delay, and the consumer must be idempotent, applying each event once even if it is delivered twice, for example by recording processed event ids. The transactional outbox pattern makes sure events are not lost between the database and the broker.

3Handling Hot Counters

A counter row that many transactions update at the same time becomes a hot spot. Each UPDATE takes a row lock until its transaction commits, so a global counter, or the counter of a celebrity account receiving thousands of messages a second, serialises every write behind it.

The standard fix is to shard the counter: keep, say, 16 rows for one counter, increment a random one, and sum them when reading. Contention drops roughly sixteenfold and the read is still a tiny query. Another option is to write each increment as a small delta row, or into an in-memory buffer, and have a background job fold the deltas into the counter every few seconds.

Java
// 16 shards per counter; the application picks one shard per write
int shard = ThreadLocalRandom.current().nextInt(16);
jdbc.sql("UPDATE counter_shards SET n = n + 1 WHERE counter_id = ? AND shard = ?")
.param(counterId).param(shard).update(); // 1 row updated
-- reading sums the shards
SELECT sum(n) FROM counter_shards WHERE counter_id = ?; -- 16 rows, still instant

Notice that the shard number is chosen in Java, once per write. Writing random() inside the WHERE clause would be a bug, because PostgreSQL evaluates a volatile function for every row it checks, so the statement could update no shard or several.

4Correcting Drift With Recomputation

Any maintained counter can drift from the truth: a bug that forgets an increment on one path, a manual data fix, an event lost before the outbox was introduced. So the design includes a periodic recomputation. A job counts the real rows for a batch of users, compares with the stored counter, fixes differences and reports how many it found. For 'orders this month' it can recompute last month's figures once the month is closed; for unread counts it can recompute users who were active today. The number of corrections becomes a health metric: if it rises, some write path is broken.

5Exact or Eventually Consistent, Counter by Counter

Not every counter needs the same guarantee, and deciding per counter keeps the system simple where it can be.

Counter policy
CounterNeeds exact?MechanismServed from
Unread messagesclose enough, seconds of lag oksame-transaction incrementsummary table
Orders this monthyes for invoicesupsert per user and monthsummary table
Likes on a popular postnosharded or async deltasRedis, shown as 1.2k
Account balanceyes, alwaysnot a counter: ledger sum or locked rowdatabase only
Write down the source of truth next to each counter.

For counters where eventual consistency is acceptable, the UI can also show approximations openly, such as '99+' for unread messages or '1.2k' followers, which hides small lags and makes sharding and caching easier.

6Where the Counts Live

A summary table in the main database is the simplest home: transactional, backed up and easy to recompute. Redis, with its atomic INCR and DECR, is attractive for very hot or very high-volume counters and for serving reads at low latency, but it is a cache unless it is configured and operated as a durable store, so we decide explicitly whether Redis is the source of truth or a copy that can be rebuilt from the database. The documented answer matters during incidents: when two numbers disagree, everyone must know which one wins.

7Follow-up questions

Why not use a materialized view?

A materialized view is refreshed as a whole, so for millions of users it either becomes stale between refreshes or costs as much as the counts it replaces. It suits periodic reports, not badges that should change seconds after a message arrives.

How does a counter handle deletes and status changes?

Every operation that changes what is counted must adjust the counter: a delete decrements, marking a message read decrements unread, and moving an order to another month adjusts both months. Listing these paths explicitly is part of the design, and the recomputation job catches the ones we missed.

What happens when Redis loses its data?

If Redis is a cache, we rebuild the affected counters from the database's summary table or by recomputation, possibly lazily on first read. That is why the source of truth must be in the database or another durable store for any counter people rely on.

8Conclusion

In this answer, we saw how to show counts for millions of users without counting at read time. We maintain counters on the write path, in the same transaction or through idempotent event consumers, shard or batch hot counters to avoid row contention, and recompute periodically to correct drift. Each counter gets an explicit decision on exactness, approximate display where acceptable, and a documented source of truth, whether it is served from a summary table or Redis.

What to say in the interviewAbout 90 seconds aloud

Open with

I would stop computing counts at read time and maintain them as data. When a message arrives, the same transaction that saves it increments the recipient's unread counter, so the badge is a single-row read.

Then, if they want more

For orders this month I keep a row per user and month and upsert it on each order. Where coupling the write is not desirable, I publish an event through an outbox and let an idempotent consumer update the counter, accepting a small lag.

The first risk is hot rows: a global or celebrity counter updated by many concurrent transactions serialises on the row lock, so I shard it across, say, sixteen rows and sum them on read, or record deltas and fold them in asynchronously.

The second risk is drift from bugs or missed paths, so a periodic job recomputes counters from the real rows, fixes differences and reports how many it found. I would decide per counter whether it must be exact, like order counts used for invoices, or can be eventually consistent and shown approximately, like 99+ unread or 1.2k likes.

Counts would live in a summary table, with Redis for very hot ones, and I would document for each counter which store is the source of truth so there is no argument when they disagree.

About this answer

Last updated
12 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 documentation below. 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 how a product shows counts such as 'unread messages' and 'orders this month' for...": https://scrivio-interview-library.netlify.app/databases/query-optimization/f5aeaafb15/