Chapter 7 of 8System design and scaling

System Design and Scalability

Our MVP runs happily on one machine. This chapter shows what breaks first as usage grows, and the tools engineers reach for, in the order you would actually need them.

Contents · Chapter 7 of 8

What you will learn

  • What "scaling" means, and why a Twitter-like app is read-heavy
  • The order in which real systems grow, from one server to many services
  • Database bottlenecks, read replicas, caching strategies and load balancing
  • Message queues, fan-out for celebrity accounts, time-ordered ids and sharding
  • When microservices help, when they hurt, and how to estimate load on paper

Why it matters

Our MVP runs comfortably on one machine. That's not a weakness: most apps never need more. But when growth comes, the fixes are well known, and applying them in the wrong order wastes months. Knowing what breaks first, and why is what system design interviews test and what senior engineers actually do.

This chapter explains rather than builds

Chapters 3–6 gave you working, tested code. Here, most code samples are sketches that show an idea. Each one is labelled "Simplified example — not part of Chirp". When something is already in Chirp, the sample comes straight from the project files and says so.

What "scale" actually means

"Will it scale?" bundles together three different kinds of growth:

  • More users: more accounts, more follow relationships, more open WebSocket connections.
  • More data: posts pile up forever. Tables grow, indexes grow, backups take longer.
  • More requests at the same moment (concurrency): this usually bites first. A server that is fine with a few requests at a time can fall over when many arrive together, for example when a famous account posts.

Two words you will hear constantly:

  • Latency: how long one request takes, from click to answer. Users feel latency.
  • Throughput: how many requests the system completes per second. Operators watch throughput.

Analogy: a coffee shop

Latency is how long you wait for your coffee. Throughput is how many coffees the shop sells per hour. Hiring a second barista raises throughput, but it doesn't make any single coffee faster. Buying a faster machine lowers latency. Scaling work is about knowing which of the two you need, and where the queue is forming.

Social apps are read-heavy

People scroll far more often than they post. Every post is written once, but read by everyone who follows the author, many times over. That's why this chapter spends most of its time on reads: caches, replicas and pre-built timelines. It's also why the home feed, the read that touches the most data, dominates the design. You met it in chapter 4 (pull) and chapter 6 (push); here we see what happens to it at large scale.

Rule one: measure before you change anything

Every technique below costs something: money, complexity, new failure modes. Add one only when a measurement shows the problem it solves: slow query logs, CPU and memory graphs, request latency percentiles, connection pool waits. Guessing leads to caches nobody needed and queues nobody understands.

From one server to many: the scaling journey

Real systems grow in a fairly predictable order. Each step fixes the bottleneck of the previous one, and introduces a new problem that becomes the next bottleneck. Step through it: for each stage, notice the symptom that forces the change, what it fixes, and what it costs.

The scaling journey. Eight stages, each forced by a real symptom. Most apps stop around stage 3 or 4, and that's fine.
  1. One server. Spring Boot and PostgreSQL share one machine. Cheap and simple, and exactly right for the first users. Symptom that ends it: the app and the database fight over the same CPU and memory, and you can't upgrade one without restarting the other.
  2. Separate database server. The database gets its own machine (or a managed service such as Amazon RDS) with plenty of memory for its cache and fast disks. Backups and upgrades get easier. New cost: every query now crosses the network, so the number of queries per request starts to matter (the N+1 problem from chapter 4).
  3. Add a cache. Symptom: the same reads (profiles, timelines) hit PostgreSQL over and over. Redis answers repeat reads from memory, which is what Chirp does since chapter 6. New cost: cached data can be stale, so every write must invalidate or update it.
  4. Load balancer + several app servers. Symptom: one app server's CPU is maxed out, or a deploy means downtime. Run identical copies behind a load balancer. This only works because the app servers are stateless: nothing about a logged-in user lives in one server's memory (more below). New cost: anything that is kept in memory, like WebSocket connections, now lives on just one of the copies.
  5. Read replicas. Symptom: the database CPU is busy with reads even after caching. Copies of the database (replicas) take read queries; the primary keeps all writes. New cost: replicas lag slightly behind, so a user can fail to see what they just wrote.
  6. CDN + object storage. Symptom: images and JavaScript files use most of the bandwidth. Store them in S3 and serve them through a CDN (content delivery network): servers near the user keep copies, so bytes travel a short distance and never touch our app. New cost: cached files must be versioned (Vite already puts a hash in each file name) or purged when they change.
  7. Queue + workers. Symptom: slow side jobs (fan-out to followers, image resizing, emails, search indexing) make requests slow or fail when one step fails. The API records the job in a queue and answers immediately; workers process the queue at their own pace. New cost: work is now eventually done, and jobs can run twice, so they must be safe to repeat.
  8. Partitioned data, split services. Symptom: one primary database can't take all the writes, or one codebase is slowing down many teams. Data is split across several databases by a key such as user id (sharding), and large areas of the product become separate services. New cost: queries across shards, distributed failures, and far more operational work. This is where very large platforms live; few apps ever need it.

The rest of the chapter zooms in on each stage.

Database bottlenecks: what breaks first

In most web apps, the database is the first thing to struggle. App servers are easy to copy; a database holds the one true copy of the data, so it's much harder to multiply. Before reaching for big architectural changes, fix these, roughly in this order.

1. Slow queries

One missing index can make a query read the whole table. Chapter 3 showed the real difference on our profile query: with the (author_id, id DESC) index PostgreSQL jumps straight to the right rows; without it, it walks the table. At scale, slow queries hurt twice: they're slow themselves, and they hold a connection while they run, so everyone else waits. Turn on slow-query logging (log_min_duration_statement in PostgreSQL), and use EXPLAIN ANALYZE on anything that appears there.

2. Running out of connections

Opening a database connection is expensive, so Spring Boot keeps a pool of open connections (HikariCP) and lends one to each transaction. HikariCP's default pool size is 10 connections per app server. That number matters once you add app servers: every copy brings its own pool, and PostgreSQL has a hard limit (max_connections, 100 by default). Five app servers with pools of 30 would ask for 150 connections and some would be refused.

  • A bigger pool is not automatically faster: a database with a few CPU cores can only run a few queries truly at once; the rest queue anyway.
  • Keep transactions short. Chirp never calls Redis, S3 or another service while holding a transaction open for long, partly for this reason.
  • With many app servers, put a connection pooler such as PgBouncer in front of PostgreSQL, so many app connections share a few real ones.
spring:
  datasource:
    hikari:
      maximum-pool-size: 20        # per app server: total = servers × this
      connection-timeout: 3000     # ms to wait for a free connection before failing

3. Hot rows: when everyone updates the same row

Chirp counts likes with UPDATE posts SET like_count = like_count + 1. That's correct (no lost updates) because PostgreSQL locks the row during the update. But when a post goes viral and thousands of people like it at once, they all queue for that single row lock. The database is fine overall; one row is the bottleneck. Two common remedies:

  • Batch the counts. Count in Redis with INCR (fast, in memory), and write the total to PostgreSQL every few seconds. The trade-off: the database count is slightly behind, and a Redis crash can lose the last few seconds unless you rebuild from the likes table.
  • Sharded counters. Split one counter into several rows and add them up when reading. Concurrent likes usually land on different rows, so they rarely wait for each other.

Simplified example — not part of Chirp

A sharded like counter in PostgreSQL: each like adds 1 to one of 16 rows picked at random.

CREATE TABLE post_like_counter_shards (
    post_id BIGINT   NOT NULL,
    shard   SMALLINT NOT NULL,
    count   INTEGER  NOT NULL DEFAULT 0,
    PRIMARY KEY (post_id, shard)
);

-- One like: bump a random shard (0..15). Two likes rarely touch the same row.
INSERT INTO post_like_counter_shards (post_id, shard, count)
VALUES (42, floor(random() * 16)::int, 1)
ON CONFLICT (post_id, shard) DO UPDATE SET count = post_like_counter_shards.count + 1;

-- The total: add up the shards.
SELECT coalesce(sum(count), 0) AS like_count FROM post_like_counter_shards WHERE post_id = 42;

4. Too many writes

Caches and replicas only help reads. If the single primary can't keep up with writes (posts, likes, follows, notifications), the options are: make each write cheaper (fewer indexes on write-heavy tables, batch inserts), move non-urgent writes to a queue (notifications can be written a moment later), store some data in a system built for heavy writes, and eventually split the data across several primaries (sharding).

Read replicas and replication lag

A read replica is a copy of the database that continuously applies the changes made on the primary. Writes go to the primary; reads can go to any replica. Since Chirp is read-heavy, adding replicas multiplies how many reads the system can serve.

The catch: in the usual setup replication is asynchronous. The primary confirms a write as soon as it is saved, and ships the change to replicas afterwards. Most of the time that takes a moment, but a busy replica can fall behind. That delay is called replication lag, and it produces a very confusing bug. Step through it:

Read-your-own-writes. Asynchronous replication means a replica can briefly miss a write that the primary already confirmed.
  1. Alice publishes a new post.
  2. Writes always go to the primary. PostgreSQL saves the post and confirms it; Alice sees 201 Created.
  3. The change streams to the replicas. Replica 1 applies it straight away.
  4. Alice opens her profile to admire her post.
  5. Reads are spread across replicas, and this one goes to replica 2, which is busy and a little behind.
  6. Replica 2 hasn't applied the insert yet. Alice's profile shows her old post count, and her new post is missing. To Alice, it looks like Chirp lost her post.
  7. A moment later replica 2 catches up. The data was never lost: it is eventually consistent.
  8. The fix: read-your-own-writes. For a short time after a user writes, send their reads to the primary (or to a replica known to have caught up). Everyone else keeps reading from replicas.

Which reads can tolerate lag? Someone else's profile, a search result or a feed is fine a moment late. Your own just-written post, your password change or a payment is not. Deciding this per query is part of the design.

Simplified example — not part of Chirp

Spring can send read-only transactions to a replica. Chirp already marks its read methods with @Transactional(readOnly = true), so with a wrapper like this, those reads would go to the replica and everything else to the primary. You would still need a read-your-writes rule on top.

@Bean
@Primary
DataSource dataSource(@Qualifier("primaryDataSource") DataSource primary,
                      @Qualifier("replicaDataSource") DataSource replica) {
    // Picks the real connection when the transaction starts:
    // @Transactional(readOnly = true) uses the replica, everything else the primary.
    LazyConnectionDataSourceProxy proxy = new LazyConnectionDataSourceProxy(primary);
    proxy.setReadOnlyDataSource(replica);
    return proxy;
}

In production

Managed databases (Amazon RDS and Aurora, Google Cloud SQL, Azure Database for PostgreSQL) create replicas with a few clicks and report the lag as a metric. Alert on it: a replica that's minutes behind is serving stale data to everyone who reads from it.

Caching strategies

Chapter 6 added a cache with one specific strategy, cache-aside. It's the most common, but not the only one. They differ in one question: who talks to the database, and when? Pick a tab and press Play.

Cache-aside. The application manages the cache itself. This is ProfileCache in Chirp.
  1. The app looks in the cache first.
  2. Not there (first read, or it expired).
  3. The app reads the database itself.
  4. …and stores the answer for next time. Writes go to the database and delete the cache key, so the next read rebuilds it. Simple, and the cache can fail without breaking anything.
Read-through. The app only ever talks to the cache; the cache loads missing data itself.
  1. The app asks the cache, and only the cache.
  2. On a miss, the cache (or a caching library) loads from the database.
  3. It keeps the result…
  4. …and returns it. The app code is simpler, but the cache layer must know how to load each kind of data. Spring's @Cacheable gives a similar feel inside one application.
Write-through. Every write updates the cache and the database before answering.
  1. The app writes to the cache…
  2. …which writes to the database straight away.
  3. The database confirms.
  4. Only then does the app answer. The cache is always fresh, but every write pays for two stores, and data that's never read still fills the cache.
Write-behind (write-back). Writes land in the cache and reach the database later, in batches.
  1. The app writes to the cache only.
  2. It answers immediately: very fast writes.
  3. Every few seconds, a job copies the totals to the database. Great for counters (see hot rows). The risk: if the cache dies before a flush, those writes are lost unless you can rebuild them.

Invalidation and TTLs

"There are only two hard things in computer science: cache invalidation and naming things," goes the old joke. Chirp uses two tools together, and you should too:

  • Explicit eviction when we know data changed: following someone evicts both profiles; a new post evicts the author's profile. Chapter 6 runs this after the transaction commits, so a reader can't re-cache the old value in between.
  • A TTL (time to live, 10 minutes for profiles) as a safety net: if an eviction is ever missed, the stale value still disappears on its own.

Cache stampedes and hot keys

Picture a very popular profile whose cache entry expires. In the next instant, hundreds of requests miss at once and all go to the database to rebuild the same value. That's a cache stampede (or thundering herd), and it can knock over a database that was fine a moment earlier. Common remedies:

  • Let only one request rebuild: take a short lock (for example Redis SET key value NX PX 5000); the others wait briefly or serve the stale value.
  • Add jitter to TTLs, such as 10 minutes ± a random minute, so keys created together don't expire together.
  • Refresh early in the background for keys you know are hot.

A related problem is the hot key: one key read so often that the single Redis node holding it is overloaded, even though the cluster as a whole is idle. The usual fixes are a tiny in-process cache in each app server for a few seconds, or several copies of the key (profile:star#1, profile:star#2…) read at random.

Load balancing and horizontal scaling

There are two ways to handle more traffic on the application tier:

  • Scale up (vertically): a bigger machine. Simple, no code changes, but there's always a biggest machine, and it's still one point of failure.
  • Scale out (horizontally): more machines running the same code, with a load balancer in front that spreads requests across them and stops sending to ones that fail.

Why stateless servers matter

Scaling out only works if any server can handle any request. A server is stateless when it keeps nothing about a user between requests. Our JWT design from chapter 4 gives us exactly that. Each request carries its own signed token, and any copy of the app can check it with the shared secret, without a session stored in one server's memory:

AuthUser user = jwtService.parse(header.substring("Bearer ".length()));
var authentication = new UsernamePasswordAuthenticationToken(user, null, List.of());
SecurityContextHolder.getContext().setAuthentication(authentication);

Had we used classic server sessions kept in memory, a user logged in on server 1 would look logged out on server 2. The workarounds are sticky sessions (the load balancer always sends a user to the same server) or a shared session store such as Redis. Both work, but stateless tokens avoid the problem entirely.

Try it: a load balancer in action

Send some requests. Switch between strategies, then stop server 2 and watch the load balancer route around it. Processing times are simulated: each request takes a random 1–4 seconds so that you can see "least connections" doing its job.

  1. Nothing sent yet.
Load balancing, simulated in your browser. Round robin takes turns; least connections picks the server with the fewest requests in progress.

What you just saw maps onto real behaviour:

  • Round robin takes turns. It's fair when every request costs about the same.
  • Least connections sends work to the least busy server, which is better when some requests (a big feed page) take much longer than others (a like).
  • Health checks: real load balancers call a URL on each server regularly and take failing ones out of rotation. Chirp already exposes one, /actuator/health, which is exactly what an AWS Application Load Balancer or a Kubernetes probe would call. Open-source nginx detects failures passively (a request fails, the server is skipped for a while); active health checks are part of NGINX Plus and of cloud load balancers.

Simplified example — not part of Chirp

The nginx from chapter 8 sends /api/ to one backend. Spreading it across three copies is a small change:

upstream chirp_api {
    least_conn;                                 # or leave it out for round robin
    server app1:8080 max_fails=3 fail_timeout=10s;
    server app2:8080 max_fails=3 fail_timeout=10s;
    server app3:8080 max_fails=3 fail_timeout=10s;
}

server {
    listen 80;
    location /api/ {
        proxy_pass http://chirp_api;
        proxy_set_header Host $http_host;
    }
}

Why WebSockets complicate load balancing

A normal HTTP request is short: any server can take the next one. A WebSocket stays open for minutes or hours on one server. The load balancer must support the upgrade (chapter 8's nginx config adds the Upgrade headers for this), connections pile up unevenly after a server restarts, and, the big one, a notification created on server A has to reach a user whose connection lives on server B. That's the next section.

Real-time notifications across many servers

Chapter 6's NotificationSocketHandler keeps open connections in a map in its own memory. With one server, that's perfect. With three, it has a gap: it can only deliver to people connected to this server.

public void onNotification(NotificationEvent event) {
    Set<WebSocketSession> sessions = sessionsByUser.getOrDefault(event.recipientId(), Set.of());
    if (sessions.isEmpty()) {
        return;   // the user is offline: they will see it in the list next time

The standard fix is a publish/subscribe channel that every server listens to. Whoever creates the notification publishes it once; every server receives it and delivers it to the connections it holds. Redis has this built in (PUBLISH / SUBSCRIBE), and we already run Redis.

Delivering across servers. Every server subscribes to one channel and delivers to the connections it holds.
  1. Bob likes Alice's post. The load balancer happened to send his request to server A.
  2. Server A saves the notification, then looks for Alice's WebSocket in its own map. It isn't there: Alice is connected to server B. With chapter 6's code the live message stops here (she would still see it in the list later).
  3. Instead, server A publishes the message to a Redis channel.
  4. Every server subscribed to the channel receives it, server A included; only server B has a connection for Alice.
  5. Server B finds Alice's session and pushes the message down her WebSocket. The badge updates.

Simplified example — not part of Chirp

With Spring Data Redis the change is small: publish instead of sending locally, and let every server subscribe. deliverLocally stands for the session lookup that onNotification does today.

// 1. After the commit, publish instead of looking up sessions directly.
@TransactionalEventListener
public void onNotification(NotificationEvent event) {
    redis.convertAndSend("notifications", json.writeValueAsString(event));
}

// 2. Every server subscribes, and delivers to the sessions it holds.
@Bean
RedisMessageListenerContainer notificationListener(RedisConnectionFactory factory,
                                                   NotificationSocketHandler handler) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);
    container.addMessageListener(
            (message, pattern) -> handler.deliverLocally(new String(message.getBody(), StandardCharsets.UTF_8)),
            new ChannelTopic("notifications"));
    return container;
}

Redis pub/sub is fire-and-forget: a server that is restarting at that moment misses the message. That's acceptable here, because the notification is already saved in PostgreSQL and the badge is recalculated on the next page load. When every message must be processed, use Redis Streams or a message broker (next section), which keep messages until consumers acknowledge them.

Message queues: doing work later

Look at what happens in Chirp when Alice posts: save the post, then (after the commit) push its id into every follower's timeline. For a few followers that's instant. For a very large follower list, the fan-out is a lot of work, and today it runs in a background thread on the same server. If that server restarts halfway, the remaining followers never get the post. This is Chirp's fan-out today:

@Async
@TransactionalEventListener
public void onPostCreated(PostCreatedEvent event) {
    String id = String.valueOf(event.postId());
    List<Long> audience = new ArrayList<>(follows.findFollowerIds(event.authorId()));
    audience.add(event.authorId());                    // you see your own posts too
    for (long userId : audience) {
        String key = key(userId);
        // LPUSHX only adds to lists that exist. Users without a cached timeline get one built on their next read.
        Long length = redis.opsForList().leftPushIfPresent(key, id);
        if (length != null && length > MAX_LENGTH) {
            redis.opsForList().trim(key, 0, MAX_LENGTH - 1);

A message queue (or log) moves that work off the request path and makes it durable. The API writes a small message, "post 42 was created", answers the user immediately, and separate workers process messages at their own pace. If a worker crashes, the message is still in the queue and another worker picks it up.

Producer, queue, consumers. The request finishes as soon as the message is safely stored.
  1. Alice posts a photo.
  2. The API saves the post in PostgreSQL and adds two messages to the queue: "fan out post 42" and "resize the image of post 42".
  3. Alice gets her answer straight away. She doesn't wait for any follower's timeline.
  4. A fan-out worker takes the first message and pushes the post id into followers' timelines, then acknowledges it, so the queue can forget it.
  5. An image worker takes the second message and crashes before acknowledging it.
  6. No acknowledgement came, so the queue delivers the message again. This is at-least-once delivery: a message can be processed twice, so the worker must be idempotent (doing it twice has the same effect as once).
  7. If a message fails again and again (say, a corrupt file), after a few attempts it is moved to a dead-letter queue for a human to inspect, instead of blocking everything behind it.

Idempotency: safe to run twice

Because messages can arrive more than once, every consumer must cope with repeats. Chirp already uses the main technique in several places. Liking is idempotent because the database refuses a second row for the same pair:

public boolean add(long userId, long postId) {
    return jdbc.sql("INSERT INTO likes (user_id, post_id) VALUES (?, ?) ON CONFLICT DO NOTHING")
            .params(userId, postId)
            .update() == 1;
}

And timeline reads drop duplicate ids, so a fan-out that pushed the same post twice still shows it once:

public Optional<List<Long>> read(long userId, long cursor, int limit) {
    List<String> ids = redis.opsForList().range(key(userId), 0, MAX_LENGTH - 1);
    if (ids == null || ids.isEmpty()) {
        return Optional.empty();
    }
    return Optional.of(ids.stream().map(Long::valueOf).distinct().filter(id -> id < cursor).limit(limit).toList());

Kafka, RabbitMQ or SQS?

ToolModelGood at
Apache KafkaA durable, ordered log split into partitions. Consumers track their own position and can replay old messages.High-volume event streams that several systems read independently (timelines, search indexing, analytics all reading "PostCreated").
RabbitMQA broker with queues and flexible routing (exchanges). Messages are removed once acknowledged.Task queues and routing jobs to the right workers.
Amazon SQSA fully managed queue: no servers to run. Standard queues are at-least-once; FIFO queues keep order.Simple background jobs on AWS with almost no operations work.
Redis StreamsAn append-only stream inside Redis, with consumer groups and acknowledgements.Moderate volumes when you already run Redis.

Whichever you use, keep queues bounded and watched: alert when the backlog grows, because a queue that only ever grows means your workers can't keep up, and the "later" in "do it later" quietly becomes "never". Want to go deeper? See the Apache Kafka roadmap.

Fan-out at scale: celebrities and ids

The celebrity problem

Chapter 6 compared pull (build the feed when it's read) and push (copy each new post into followers' timelines when it's written). Push makes reading cheap, which is what a read-heavy app wants. But think about an account with a huge following: one post means one timeline write per follower. Even with queues and workers, that's a burst of work for a single post, and it repeats every time the account posts.

The well-known answer is a hybrid. Twitter engineers have publicly described building home timelines by fan-out on write into an in-memory cache cluster, while treating accounts with very large followings differently: their posts are not pushed, but merged in when a follower reads their timeline. Ordinary accounts get push; the few huge ones get pull.

Hybrid fan-out. Push for ordinary accounts, pull for the few with enormous followings.
  1. Alice posts. She's an ordinary account, so her post is fanned out.
  2. Her post id is pushed into each follower's timeline list, Bob's included. Cheap per post.
  3. A star posts. Pushing to every follower would be a huge burst of writes, so the post is just stored once, with the star's other posts.
  4. Bob opens his feed.
  5. The feed builder reads Bob's pre-built timeline (push) and the newest posts of the few stars Bob follows (pull)…
  6. …merges them by time and returns one page. Bob can't tell which posts arrived by which route.

Time-ordered ids without one central counter

Chirp's ids come from a PostgreSQL sequence (BIGSERIAL). They increase over time, which our cursor pagination relies on (id < cursor means "older"). Once posts are written to many databases, there's no single sequence anymore. Twitter's public answer was Snowflake: 64-bit ids that each server generates on its own, with the timestamp in the high bits, so ids still sort by time:

0
41 bits: milliseconds since an epoch
10 bits: machine
12 bits: sequence

The 12-bit sequence counts ids made by one machine in the same millisecond, so two machines can never produce the same id, and no database round-trip is needed. Try it below. The demo uses Twitter's original custom epoch (4 November 2010), which is public.

Generate and decode a Snowflake-style idRuns in your browser
Press "Generate id".

Partitioning (sharding) the data

When one primary database can no longer take the writes, or the data no longer fits comfortably on one machine, you split it: each shard is a separate database holding part of the data. The choice that matters most is the shard key. For Chirp, user id is natural: a user's account, posts and timeline live together on one shard, so the common queries ("this user's posts", "this user's timeline") touch one database.

What gets harder:

  • Queries across shards. "Search all posts" or "who follows Alice?" may touch every shard. Systems keep separate indexes for these (a search cluster, a follower graph store) instead of asking every shard.
  • Transactions across shards. Bob (shard 1) likes Alice's post (shard 3): there's no single transaction covering both. You design around it, often with events and idempotent consumers.
  • Moving data. Adding a shard means some data must move, which is why how keys map to shards matters.

Adding a shard without moving everything

The obvious mapping is shard = hash(userId) % N. It spreads users evenly, but change N from 4 to 5 and most users suddenly map to a different shard. Consistent hashing places shards at many points on a ring; a key belongs to the next shard clockwise. Adding a shard only takes over the slices next to its points, so only a small share of keys move. The demo hashes 10,000 sample user ids both ways and counts how many would have to move.

Modulo vs consistent hashingComputed live

Shards: 4

Press "Add a shard".

Postpone sharding as long as you can

A single well-tuned PostgreSQL primary with replicas and a cache goes a very long way. Before sharding, try: better indexes, archiving old data, moving heavy-but-simple data (timelines, counters) to Redis, and a bigger machine. Sharding is a one-way door: it changes every query.

Microservices: when and why

A monolith is one application (like Chirp) deployed as one unit. Microservices split the product into separate applications, each owning its data and talking to the others over the network. Click the services in this plausible split of a large Twitter-like system:

One possible split. Solid lines are requests; dashed lines are events that services react to.
API gateway
The single entry point: checks the token once, applies rate limits and routes each request to the right service. In Chirp, this job is done by Spring Security plus the controllers.
Users service
Accounts, profiles and the follow graph. Owns the users and follows data. Other services ask it, rather than reading its tables.
Posts service
Creates, stores and deletes posts. When a post is created it publishes a PostCreated event instead of calling the others directly.
Timeline service
Consumes PostCreated events, fans posts out to followers' timelines (with the celebrity hybrid), and serves home feeds. Our TimelineService and FeedService, grown up.
Notifications
Consumes like, reply and follow events, stores notifications and holds the WebSocket connections (with pub/sub between its servers).
Media service
Issues presigned upload URLs, resizes images in the background and serves them through a CDN. Its scaling needs (CPU for image work) are very different from the others.
Search service
Consumes post events and keeps a search index (for example OpenSearch or Elasticsearch), because full-text search across a huge number of posts outgrows a single PostgreSQL index.
Event bus
Kafka (or similar) carries events between services, so the posts service doesn't need to know who cares about a new post.
Apps
The web and mobile clients. They see one API, whether there is one service behind it or twenty.

Reasons to split

  • Many teams step on each other in one codebase; each team can own and deploy its service independently.
  • Parts have very different scaling needs (image processing vs. the feed).
  • A failure or slow deploy in one area shouldn't take down everything.

What it costs

  • Function calls become network calls that can be slow, fail or time out.
  • No transactions across services; data is eventually consistent.
  • Debugging needs distributed tracing; deploying needs automation for many services.

The usual advice is modular monolith first. Chirp is already organised by feature (auth, user, post, feed, notification, upload, search), and those package boundaries are exactly where services would split later. Keep the boundaries clean (each feature owns its tables, others go through its service class), and splitting becomes possible when a real reason appears: usually team size, rarely traffic alone.

Our MVP versus a large-scale platform

Every concern in Chirp has a "large-scale" counterpart. None of them is needed until measurements say so.

ConcernChirp (this course)A large-scale Twitter-like platform
ApplicationOne Spring Boot appMany services behind gateways and load balancers, in several regions
DatabaseOne PostgreSQLMany partitioned stores, replicas everywhere, different databases for different data
Home feedPush into Redis lists, pull as fallbackFan-out on write into a large in-memory cluster, hybrid pull for huge accounts, ranking ("For you")
IdsPostgreSQL BIGSERIALDistributed time-ordered ids (Snowflake-style)
Background work@Async thread after commitDurable event logs (Kafka) with many consumer services
NotificationsOne server's WebSocket mapDedicated connection servers, pub/sub between them, mobile push
ImagesS3 + presigned uploadUpload service, background resizing to several sizes, CDN
SearchPostgreSQL full-text indexA dedicated search system fed by events
OperationsDocker Compose on one machineContainer orchestration, autoscaling, on-call rotations, dashboards and alerts

Notice how much stays the same: the tables, the core loop, the push-vs-pull idea, stateless auth and idempotent writes are all things you've already built. Large systems are mostly the same ideas, multiplied and separated.

Observability and protection

You can't scale what you can't see. Three kinds of signals, often called the three pillars:

  • Metrics: numbers over time, such as request rate, error rate, latency percentiles (p50, p95, p99), pool usage and queue backlog. Spring Boot Actuator plus Micrometer exports them to Prometheus, CloudWatch and others.
  • Logs: what happened, with context (user id, request id). Ship them to one searchable place.
  • Traces: one request followed across every service and query it touched (OpenTelemetry). Essential once there's more than one service.

Graceful degradation

A system with many parts always has something failing. Good systems keep the core working with the extra parts turned off. Chirp already does this: if Redis is down, the feed falls back to the pull query instead of failing:

private List<Long> timelineIds(long userId, long before, int limit) {
    try {
        return timelines.read(userId, before, limit).orElseGet(() ->
                // No timeline cached yet: build it from the database once, then serve from Redis.
                timelines.rebuild(userId).stream().filter(id -> id < before).limit(limit).toList());
    } catch (DataAccessException e) {
        log.warn("Redis unavailable, using the pull feed: {}", e.getMessage());
        return posts.findFeedIds(userId, before, limit);

Rate limiting

Protect the system from abuse and accidents (a buggy client posting in a loop): limit how often each user can do expensive things. A load balancer or API gateway can do it per IP address; per-user limits need the user id, so they often live in the app, backed by Redis so that all servers share the count.

Simplified example — not part of Chirp

A fixed-window limit: at most 30 posts per user per minute (the limit is a product decision). Production systems often use sliding windows or token buckets, which are smoother at the window edges.

public boolean allowPost(long userId) {
    long minute = System.currentTimeMillis() / 60_000;
    String key = "rate:posts:" + userId + ":" + minute;
    Long count = redis.opsForValue().increment(key);        // atomic INCR, shared by every server
    if (count != null && count == 1) {
        redis.expire(key, Duration.ofMinutes(2));           // clean up old windows automatically
    }
    return count != null && count <= 30;                  // false: answer 429 Too Many Requests
}

Back-of-the-envelope estimation

Before choosing between "one database" and "shards", engineers estimate load on paper, roughly. The goal is the right order of magnitude (tens, thousands or millions per second), not precision. The method:

  1. Start from users and behaviour: daily active users, and how often each one posts and reads.
  2. Turn per-day into per-second: a day has 86,400 seconds.
  3. Allow for peaks: traffic isn't flat; multiply the average by a peak factor.
  4. Multiply by fan-out where one action causes many writes (push timelines).
  5. Estimate storage: items per day × size of each item.

These inputs are made up on purpose

The numbers below are hypothetical inputs chosen to make the arithmetic easy to follow. They are not measurements of Chirp, Twitter or any real service. Change them in the calculator and watch how the conclusions shift.

Suppose 1,000,000 daily active users, each posting 2 times and opening their feed 10 times a day, with 200 followers on average, a peak of 3× the average, and about 300 bytes stored per post:

QuantityArithmeticResult
Posts per day1,000,000 × 22,000,000
Posts per second (average / peak)2,000,000 ÷ 86,400; × 3≈ 23 / ≈ 69
Feed reads per second (average / peak)1,000,000 × 10 ÷ 86,400; × 3≈ 116 / ≈ 347
Timeline inserts per second with push (average / peak)2,000,000 × 200 ÷ 86,400; × 3≈ 4,630 / ≈ 13,889
New post text per day / per year2,000,000 × 300 B; × 365≈ 600 MB / ≈ 219 GB

What would this hypothetical tell us? The writes of posts themselves are modest, and feed reads are a few hundred per second at peak: one well-indexed database with a cache could plausibly handle that. The striking line is fan-out: push turns each post into hundreds of timeline writes, which is why those writes go to Redis rather than PostgreSQL, and why the celebrity hybrid exists. Images, which we left out, would dwarf the text storage, which is why they go to S3 and a CDN.

Estimation calculatorHypothetical inputs

For more practice with these trade-offs, work through the system design roadmap, and the Redis roadmap for caching and timelines in depth.

Common mistakes

Scaling before measuring

Adding replicas, queues or Kubernetes because "we'll need it" multiplies the parts that can fail, while the real bottleneck (often one missing index) stays.

Fix: find the bottleneck with metrics and EXPLAIN ANALYZE, fix that, measure again.

Starting with microservices

A small team splitting a new product into many services spends its time on network failures, deployments and data synchronisation instead of features.

Fix: a modular monolith with clean feature boundaries; split when a real reason (usually team size) appears.

Caching without an invalidation plan

Users see old follower counts or deleted posts for minutes, and nobody knows which write should have cleared which key.

Fix: for every cached value, write down which writes change it; evict after commit; always set a TTL as a safety net.

Forgetting replica lag

Reads move to replicas and users start reporting "my post disappeared" right after posting.

Fix: read-your-own-writes for the author (primary for a short time after they write), and monitor replication lag.

Unbounded, unwatched queues

Workers fall behind silently; the backlog grows for days until the "later" work is hopelessly late or the broker runs out of space.

Fix: alert on queue depth and message age; add workers or shed low-value work; use dead-letter queues for poison messages.

Assuming each message is delivered exactly once

A retried message sends a notification twice or counts a like twice.

Fix: make consumers idempotent: unique constraints, ON CONFLICT DO NOTHING, de-duplicating reads, or a table of processed message ids.

Keeping user state in one server's memory

Sessions or WebSocket subscriptions stored in a single server break as soon as there are two servers behind a load balancer.

Fix: stateless tokens (as Chirp does), shared stores (Redis) for what must be shared, and pub/sub for real-time delivery.

Key takeaways

  • Scaling is a sequence: each fix removes one bottleneck and introduces the next problem. Measure first, then change one thing.
  • Social apps are read-heavy, so caches, replicas and pre-built timelines carry most of the load.
  • The database usually struggles first: slow queries, connection limits, hot rows, then write volume.
  • Replicas lag; protect "read your own writes". Caches go stale; plan invalidation and set TTLs.
  • Stateless app servers make horizontal scaling easy; WebSockets need pub/sub across servers.
  • Queues move slow work off the request path; consumers must be idempotent because delivery is at-least-once.
  • At large scale, fan-out becomes hybrid, ids become distributed (Snowflake), data is sharded, and teams may split services, but the core ideas are the ones you already built.

Check your understanding

Alice posts, reloads her profile, and her new post is missing. A few seconds later it appears. What is the most likely cause?

  1. The post was saved twice
  2. Her read went to a read replica that hadn't applied the write yet
  3. The load balancer dropped the request
  4. The JWT expired
Asynchronous replication means replicas lag slightly behind the primary. The fix is read-your-own-writes: route the author's reads to the primary for a short time after writing.

Why can Chirp's app servers be put behind a load balancer without sticky sessions?

  1. Because Redis stores every session
  2. Because PostgreSQL remembers who is logged in
  3. Because each request carries a signed JWT that any server can verify
The servers are stateless: the token itself proves who the user is, and every server has the same secret to check it.

A queue redelivers a "PostCreated" message after a worker crash. What keeps the timeline from showing the post twice?

  1. Idempotent processing, such as de-duplicating ids when reading the timeline
  2. Using a bigger queue
  3. Making the worker faster
  4. A longer cache TTL
At-least-once delivery means repeats will happen. Consumers must be safe to run twice; Chirp's timeline read uses .distinct(), and likes rely on ON CONFLICT DO NOTHING.

An account with an enormous following posts. With pure push, what is the problem?

  1. The post can't be stored
  2. One post causes a huge burst of timeline writes, one per follower
  3. Followers can't read it
Push costs work proportional to the follower count at write time. The hybrid approach skips fan-out for such accounts and merges their posts at read time.

What is usually the best first step when the app feels slow?

  1. Split it into microservices
  2. Add read replicas
  3. Measure, and find the actual bottleneck (for example a slow query)
  4. Switch databases
Every scaling technique has a cost. Measurement tells you which one, if any, solves the problem you actually have.

Exercise: design "Trending topics"

Chirp wants a "Trending" box showing the 10 hashtags used most in the last hour, updated every minute, for all users. On paper: where do you count hashtag uses, how do you keep counts for "the last hour", where is the top-10 list stored, and what happens when a user posts? Keep it on the request path as little as possible.

Show a sample answer

Off the request path: when a post is created, publish PostCreated (we already have this event). A worker extracts hashtags from the text, so posting stays fast.

Counting by time window: keep one Redis sorted set per minute, e.g. trend:2026-11-05T14:07, and ZINCRBY each hashtag in the current minute's set; give each set a TTL of a little over an hour.

The top-10: once a minute, a scheduled job combines the last 60 minute-sets with ZUNIONSTORE into trend:last-hour and reads the top 10 with ZREVRANGE … 0 9; it saves that small list under one key that every app server reads (a cache everyone shares).

Trade-offs: the list is up to a minute old, which is fine for trends. Counting the same post twice after a redelivery would inflate a tag slightly; if that matters, remember processed post ids for an hour. At very large scale you would partition the counting by hashtag and use approximate counting, but this design is plenty for Chirp.

Finished this chapter? Tick it off. Progress is saved in this browser only.