Skip to content
Visual explainer 5h to learn 5 steps

Caching, replication, sharding & databases

Choose storage and caching strategies and justify them.

By Invicly Tech, , in Interview Preparation. About 13 minutes to read.

Topic 16 of 27

In short

Data choices dominate system design: which database, how to cache, how to copy data for reads and how to split it across machines. Each choice trades latency, consistency and complexity.

Explained simply

Most of a system design is about data: where it lives, how fast you can read it, and what happens when a machine fails. The servers that run your code are easy to copy. The data is the hard part.

A cache is a small, fast store that keeps copies of popular data in memory, so you do not ask the slower database every time. It is like keeping your keys by the door instead of searching the house each morning. The hard part is keeping the copy fresh when the real data changes.

Replication means keeping copies of the whole database on several machines. One machine, the leader, takes the writes and passes them on to followers, which can serve reads. If the leader dies, a follower can take its place.

Sharding means splitting the data into pieces and putting each piece on a different machine, for example users A to M on one and N to Z on another. You shard when the data or the write traffic is too big for one machine. It gives you more room but makes queries that span pieces harder.

Press Play on a diagram to walk through it one step at a time.

CompareSQL vs NoSQL
SQL (relational)
  • Tables with a fixed schema
  • Joins and ACID transactions
  • Scale reads with replicas
  • Orders, payments, users
NoSQL
  • Key-value, document, wide-column
  • Flexible schema
  • Built-in horizontal scaling
  • Feeds, sessions, huge event logs
SequenceLeader-follower replication
Client
Leader
Follower
  1. 1write: update profile
    Client to Leader: write: update profile
  2. 2ack after local commit
    Leader to Client: ack after local commit
  3. 3replicate change log (async)
    Leader to Follower: replicate change log (async)
  4. 4read profile
    Client to Follower: read profile
  5. 5maybe stale until caught up
    Follower to Client: maybe stale until caught up
SequenceCache-aside: a read miss, then a hit
App
Redis
Database
  1. 1GET user:42
    App to Redis: GET user:42
  2. 2miss (nil)
    Redis to App: miss (nil)
  3. 3SELECT * FROM users WHERE id = 42
    App to Database: SELECT * FROM users WHERE id = 42
  4. 4row
    Database to App: row
  5. 5SET user:42 with a 300 s TTL
    App to Redis: SET user:42 with a 300 s TTL
  6. 6Next request: GET user:42
    App to Redis: Next request: GET user:42
  7. 7hit, no database call
    Redis to App: hit, no database call
LayersLayers of caching on the read path
  1. 1
    Browser cache

    Cache-Control headers; no request at all

  2. 2
    CDN edge

    Static files and public pages near the user

  3. 3
    In-process cache

    Tiny, per server, microseconds

  4. 4
    Shared cache (Redis)

    Shared by all servers, under a millisecond

  5. 5
    Database buffer pool

    Hot pages already in database memory

  6. 6
    Disk

    The slowest and final source of truth

In depth

Choosing a database: let the access pattern decide

Start with how the data is read and written, not with a favourite product. Do you need joins and multi-row transactions, as with orders and payments? Choose a relational database such as PostgreSQL or MySQL. Do you look things up by a single key at huge scale, as with sessions or carts? A key-value store such as Redis or DynamoDB fits. Do records have flexible, nested fields? A document store such as MongoDB. Do you write enormous streams of time-ordered events? A wide-column store such as Cassandra. Do you need full-text search with relevance ranking? Elasticsearch or OpenSearch.

Large files such as images and videos go in object storage, with only their URL in the database. Many real systems use several of these, each for the job it does best.

MapStorage by job
What does the data need?
  • Joins and transactions
    • PostgreSQL, MySQL
  • Fast lookup by key
    • Redis, DynamoDB
  • Flexible documents
    • MongoDB
  • Huge write streams
    • Cassandra, ScyllaDB
  • Full-text search
    • Elasticsearch, OpenSearch
  • Big files
    • Object storage such as S3

Caching patterns and how they fail

Cache-aside is the most common: the app checks the cache, and on a miss reads the database and stores the result with a TTL (time to live). On a write, update the database and then delete the cache key, so the next read reloads fresh data. Deleting is safer than updating the cache, because two racing updates can leave the cache holding the older value. Write-through writes to the cache and database together. Write-back (write-behind) writes only to the cache and flushes to the database later: very fast, but data is lost if the cache dies first.

The classic failure is a stampede: a hot key expires and thousands of requests hit the database at once. Fixes: let one request rebuild the key while others wait or get the old value, and add random jitter to TTLs so many keys do not expire together. When memory fills up, the cache evicts keys, usually the least recently used (LRU).

  • On write: update the database, then delete the key
  • Always set a TTL, with jitter
  • Stampede: one rebuilder, others wait
  • Write-back trades safety for speed

Replication: synchronous, asynchronous and failover

With synchronous replication the leader waits for a follower to confirm each write. No committed data is lost if the leader dies, but every write is slower, and a slow follower slows everyone. With asynchronous replication the leader confirms at once and followers catch up a little later. Writes are fast, but followers lag (replication lag), and a failover can lose the last few writes. Many setups mix the two: one synchronous follower and the rest asynchronous.

Lag causes a classic bug: a user saves their profile, reloads, and a lagging follower shows the old version. To give read-your-writes, send that user's reads to the leader for a short time after they write. Failover itself has risks: if the old leader comes back still thinking it leads, two leaders accept writes (split brain), so systems use fencing to shut the old one out.

Sharding strategies and their trade-offs

Range sharding splits by key ranges, such as dates or user names A to F. Range queries stay on one shard, but new data often lands on the same shard and makes it hot. Hash sharding puts a key on shard hash(key) mod N. Load spreads evenly, but a range query must ask every shard, and changing N moves most keys. Consistent hashing places shards and keys on a ring, so adding a shard moves only about 1/N of the keys. Directory sharding keeps a lookup table from key to shard: flexible, but the table is another service to run.

Pick a shard key that spreads load and keeps data queried together on the same shard, such as user_id for a user's own data. Hot keys, like a celebrity's profile, may need extra caching or splitting the key into several sub-keys. Joins and transactions across shards are slow and complex, so design to avoid them.

CompareThree ways to shard
Range
  • Split by key ranges
  • Range scans stay on one shard
  • Newest keys can make a hot shard
Hash
  • Shard = hash(key) mod N
  • Even spread of load
  • Range queries hit every shard
Directory
  • Lookup table: key to shard
  • Move data freely
  • The table is one more system to run

Justifying your choices out loud

Interviewers score the reasoning, not the product name. Use a four-part sentence: the requirement, the choice, the trade-off and the mitigation. For example: "Orders need transactions, so I'll use PostgreSQL. It has a single write leader, which limits write throughput, but our estimate of 500 writes per second is well within one machine. If that grows, we can shard by customer_id."

Do the same for caching: "Product pages are read 100 times for each write, so a Redis cache-aside layer with a 5-minute TTL removes most database reads. Prices may be stale for up to 5 minutes, so on a price change we delete the key." This shows you know what each choice costs and how you would contain the cost.

  • Requirement: what the data needs
  • Choice: the store or pattern
  • Trade-off: what it costs
  • Mitigation: how you limit that cost

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Compare SQL and NoSQL stores~1h
  2. 2
    Learn cache-aside and write-through caching~1h
  3. 3
    Explain leader-follower replication~1h
  4. 4
    Shard data with consistent hashing~1h
  5. 5
    Justify storage choices with trade-offs~1h

Key points

  • Cache-aside reads the cache first and fills it on a miss; write-through updates both on writes.
  • Replicas scale reads and add redundancy, but async replicas can serve stale data.
  • Sharding splits data by a key; consistent hashing moves few keys when nodes change.
  • Pick a shard key that spreads load evenly and keeps related data together.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import bisect, hashlib

def h(key):
    return int(hashlib.md5(key.encode()).hexdigest(), 16)

class Ring:
    def __init__(self, nodes, vnodes=100):
        self.ring = sorted((h(f'{n}#{i}'), n) for n in nodes for i in range(vnodes))
        self.keys = [k for k, _ in self.ring]
    def node_for(self, key):
        i = bisect.bisect(self.keys, h(key)) % len(self.ring)
        return self.ring[i][1]

# Ring(['db1', 'db2', 'db3']).node_for('user:42')

Virtual nodes spread each server around the ring for even load.

Cache-aside for user profiles with Redis

A profile page is read thousands of times for every edit. On a read, try Redis first. On a miss, load from the database and store the result for 300 seconds. On an update, write the database first and then delete the key, so the next read refills it with fresh data. If Redis is down, the reads still work, just more slowly, because the database is the source of truth.

python
import json
import redis
r = redis.Redis(host="localhost", port=6379)
def get_user(user_id, db):
    key = f"user:{user_id}"
    cached = r.get(key)
    if cached is not None:
        return json.loads(cached)              # hit
    user = db.fetch_user(user_id)              # miss: ask the database
    if user is not None:
        r.set(key, json.dumps(user), ex=300)   # keep for 5 minutes
    return user
def update_user(user_id, fields, db):
    db.update_user(user_id, fields)            # source of truth first
    r.delete(f"user:{user_id}")                # then invalidate

Adding a fifth shard: mod N vs consistent hashing

Users are spread over 4 shards with hash(user_id) mod 4. Traffic grows and you add a fifth. With mod 5, a key stays put only if hash mod 4 equals hash mod 5, which is true for about 1 key in 5, so about 80% of all users must move: a huge migration. With consistent hashing, the new shard takes over a few arcs of the ring from its neighbours, and only about 1/5 (20%) of keys move, all onto the new shard. Virtual nodes (each shard placed at many points on the ring) keep the arcs, and so the load, even.

Quick reference

  • Cache-aside: read cache, on a miss read the database and fill; on write, update the DB then delete the key
  • Set a TTL on every cache key and add random jitter so keys do not all expire at once
  • Write-back caching is fastest but loses data if the cache dies before flushing
  • Async replication: fast writes, but followers lag and a failover can lose recent writes
  • Read-your-writes: route a user's reads to the leader for a short time after they write
  • Going from mod 4 to mod 5 moves about 80% of keys; consistent hashing moves about 20%
  • Range sharding keeps scans cheap, but the newest keys can pile onto one hot shard
  • Store big files in object storage such as S3 and keep only the URL in the database

Common mistakes

  • Sharding by a key like country, creating hot shards.
  • Reading your own write from a lagging replica.
  • Adding a cache without an invalidation plan.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A very popular cache key expires and thousands of requests hit the database at once. What is the best fix?

Question 2

2Where should an app store 5 MB profile videos?

Question 3

3A user edits their profile, reloads, and sees the old version. What is the most likely cause?

Question 4

4What is the main drawback of hash sharding?

Question 5

5What is the main cost of synchronous replication?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Pick a data store for each, with one reason: user accounts and payments; login sessions; product images; 1 million click events per second for analytics.

  2. Exercise 2medium

    Write a cache read in Python with redis-py that prevents a stampede: on a miss, only one caller rebuilds the value while the others wait and retry.

  3. Exercise 3hard

    A chat app stores billions of messages. Choose a shard key, explain how you would read one conversation, and how you would handle one huge, very active group chat.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

When should I choose NoSQL over SQL?
Choose NoSQL when your access pattern is simple key or document lookups at very high scale, or the schema changes often. Stay with SQL when you need joins, transactions and strict constraints, which covers most business data.
What is the difference between replication and sharding?
Replication copies the same data to several machines for read capacity and safety. Sharding splits different data across machines for more storage and write capacity. Large systems use both: each shard is replicated.
Should I use Redis or Memcached?
Memcached is a simple, multi-threaded key-value cache. Redis adds data structures such as lists, sets and sorted sets, optional persistence and replication, so it is the more common choice today.
How do I handle cache invalidation?
Set a TTL on every key so stale data expires on its own, and delete the key whenever the underlying data changes. For data that must never be stale, such as balances, read from the database instead.

Go deeper

ShareXLinkedInWhatsApp