SteelReed

Search

Search posts, questions…

7. System Design

Caching in system design: cache tiers, the limits of Redis, and a 1-million-QPS counter case study

Where caches sit between the client and the database, three jobs (speeding up, buffering, sharing data), the limits of one Redis in numbers, designing like/view counters for a social network at 1 million QPS, unread broadcast notification counts with read pointers, and five small problems solved with Redis data structures.

18 Nov 20268 min readSenior

–

1. The problem

A viral post gets 10,000 likes per second. The simple code runs UPDATE post_count SET like_count = like_count + 1 WHERE post_id = ?: 10,000 transactions fighting over one row, and a DB node handles only a few hundred TPS of that kind. The like API times out and drags the feed down with it.

2. Key idea

Caches aren't only for faster reads. They also act as a buffer (collect writes and push them to the DB in batches; lose it and the data is gone) and as a place to share data across instances. Pick the layer by asking: how stale is acceptable, and who may see it.

Layer What it caches How it's refreshed
Client, CDN static files, public responses Cache-Control, hashed file names; the server can't delete them
Local cache in the service config, small catalogs short TTL; one copy per instance
Redis query results, counters, sessions cache-aside, TTL; shared by all instances
Database buffer pool, page cache self-managed
Counter design Use when Don't use when
Direct UPDATE ... + 1 a few hits per second per row hot rows with thousands per second
Redis HINCRBY + batch job likes, views, followers at scale numbers must be exact immediately (money)
HyperLogLog "unique viewers" with ~0.81% error you must know whether a specific person viewed
last_read_id pointer counting unread broadcasts per-user notifications

At 1 million QPS you need about 15–20 Redis masters: the node count is set by single-threaded CPU, usually not RAM.

3. In Java

JAVA
public void like(long postId, long userId) {
    int inserted = jdbc.update(
        "INSERT INTO post_like(post_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
        postId, userId);                           // unique (post_id, user_id): a double-click gives 0
    if (inserted == 1) {
        redis.opsForHash().increment("post:" + postId, "like", 1);   // HINCRBY, atomic
        redis.opsForSet().add("dirty:posts", String.valueOf(postId));
    }
}
 
@Scheduled(fixedDelay = 5000)
void flush() {                                     // batched: one UPDATE per dirty post
    for (String id : redis.opsForSet().pop("dirty:posts", 1000)) {
        Object likes = redis.opsForHash().get("post:" + id, "like");
        jdbc.update("UPDATE post_count SET like_count = ? WHERE post_id = ?", likes, id);
    }
}

Other languages: Go's go-redis and Node.js's ioredis have the same HINCRBY and SPOP; the logic is identical.

Unread broadcasts with a pointer, and other Redis structures

Sending a promotion to 10 million users with INCR unread:{user} each is ~200 seconds at 50K commands/s, mostly for users who never open the app. Instead: broadcasts get increasing IDs, each user stores last_read_id, and the unread count is ZCOUNT broadcasts (last_read +inf when the user opens the app.

Problem Structure
Read-compute-write racing across clients Lua script
Cancel an order after 15 minutes ZSET, score = run time
Count unique IPs per day HyperLogLog, 12 KB per counter
"Is this username taken" on a public API Bloom filter: "not present" is certain

Packing counters into small hashes (≤ 128 fields to keep the listpack encoding) saves about 5× RAM compared with one key per counter.

4. Working with AI

Hand to AI: estimating RAM and node counts, writing the flush job, generating a k6 load test for a viral post.

Check yourself in AI-written code:

  • There's a unique constraint on (post_id, user_id); the counter only increments when the insert creates a row.
  • No client-side GET then SET on the same key; use an atomic command or Lua.
  • Personal responses (cart, balance) carry Cache-Control: private or no-store.
  • A periodic reconciliation job recounts from post_like to fix drift after Redis incidents.

5. Exercises

Exercise 1: Review an AI-written counter

The AI wrote a like endpoint and says "Redis is single-threaded, so it never miscounts". A week later a post liked by 1,200 people shows 1,530. Find the bugs and fix them.

JAVA
public void like(long postId, long userId) {
    Long count = (Long) redis.opsForValue().get("likes:" + postId);
    redis.opsForValue().set("likes:" + postId, count == null ? 1 : count + 1);
    likeRepo.save(new PostLike(postId, userId));
}
Solution 1
  • Race: GET and SET are two commands; Redis is atomic per command, not per sequence. Two requests both read 10 and both write 11 (undercount).
  • Double counting: nothing checks whether this user already liked. Double-clicks, network retries and two devices all increment; that's where the extra 330 comes from.
  • Order: the counter goes up before the DB save; if save fails the counter still went up.

Fix as in section 3: unique (post_id, user_id), INSERT ... ON CONFLICT DO NOTHING, HINCRBY only when one row was inserted. Add a reconciliation job with SELECT COUNT(*) FROM post_like WHERE post_id = ? to repair drifted numbers.

Exercise 2: Choose an unread-count design

The system has 10 million users. For promotional broadcasts the AI offers: (A) each broadcast runs INCR unread:{user} for every user via a worker; (B) each user stores last_read_id and the unread count is computed when the app opens. Pick one, give the reason and when the choice flips.

Solution 2

Pick B. A costs ~10 million commands per broadcast (about 200 seconds at 50K commands/s), mostly for users who never open the app, and a worker dying halfway leaves half the users without the notification. B writes one row per broadcast; reading is one O(log n) ZCOUNT.

The choice flips for per-user notifications (someone commented on your post): each one touches a single user, and a direct INCR is simplest. Real systems usually combine both: pointers for broadcasts, counters for personal notifications.

Summary

  • Caches closer to the client are cheaper but harder to invalidate; personal responses must never be cached publicly.
  • A buffer isn't a cache: the data exists nowhere else, so losing it loses it.
  • One Redis does about 50K SET/s and 80K GET/s; node counts are usually set by CPU.
  • Like counters: unique in the DB, HINCRBY in Redis, batched writes, periodic reconciliation.
  • Unread broadcasts: a last_read_id pointer, not a 10-million-command fan-out.

Further reading: Rate limiting: algorithms and Redis.

Practice interview questions on this topic

All Caching & Redis questions →All System Design questions →

Loading comments…