N system design cheat sheet: the 5 building blocks, what each one fixes and what it costs - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/system-design-cheat-sheet/
☷ system design cheat sheet: the 5 building blocks, what each one fixes and what it costs - nicnonac guides _□×

← back to guides

system design cheat sheet: the 5 building blocks, what each one fixes and what it costs

Stacks · 10 min read · posted Nov 29, 2026, 10:10 pm

System design interviews mostly come down to a handful of building blocks. Once you know what problem each one fixes and what it costs, you can put most designs together out of them.

This is the cheat sheet from the reel. It covers the five blocks in it. For each one you get the problem it fixes, the idea, a small piece of Python you can run, the trade-off to say out loud, and the follow-up questions to expect.

This is the interview-level version. The code is small enough to run on a laptop and leaves out most of what makes these hard in production. Its job is to make the idea concrete.

the quick lookup

Start from the problem, not from the tool.

the problem reach for
the same data is read again and again, and the database is slow caching
one server can't take the traffic, or can't be allowed to go down load balancing
the data no longer fits on one database machine sharding
a request sets off slow work the user shouldn't have to wait for a message queue
one client can flood the API for everyone else rate limiting

1. caching

The problem. Reading from a database means disk and often a network hop, and most apps read the same few things constantly: the same profile, the same product page, the same feed.

The idea. Keep a copy of the answer in memory, in something like Redis or Memcached. Check there first. Only go to the database when the copy is missing, then save it for next time. That pattern is called cache-aside.

In code.

import time

db = {42: {"name": "nic"}}
cache = {}                      # in real life this is Redis or Memcached
TTL = 60                        # how many seconds a copy is trusted for

def get_user(id):
    hit = cache.get(id)
    if hit and hit["expires"] > time.time():
        return hit["user"]                          # cache hit: no database
    user = dict(db[id])                             # cache miss: the slow part
    cache[id] = {"user": user, "expires": time.time() + TTL}
    return user

def update_user(id, fields):
    db[id].update(fields)
    cache.pop(id, None)         # drop the copy so the next read is fresh

This is the one in the reel: four requests for user 42, and only the first one touches the database.

The trade-off to say out loud. The copy can be stale. Someone changes their name and the cache keeps serving the old one until it expires or you delete it. A short TTL means fresher data and more database load, and a long one means the opposite. Deciding when to throw a copy away is called invalidation, and it's the hard part.

Expect to be asked.

  • What happens when the cache is full? It evicts something, usually the least recently used entry (LRU).
  • What if a popular key expires and a thousand requests miss at once? That's a stampede. Let one request rebuild the copy while the others wait or get the old one.
  • Where else can you cache? In the browser, and at a CDN for images and other static files.

2. load balancing

The problem. One server has a ceiling, and when it dies your whole site is down.

The idea. Run several copies of the server and put a load balancer in front. It hands each request to one of them. The simplest rule is round robin: take turns.

In code.

from itertools import cycle

class LoadBalancer:
    def __init__(self, servers):
        self.servers = servers
        self.healthy = set(servers)
        self._turn = cycle(servers)

    def route(self):
        for _ in self.servers:                  # at most one full lap
            server = next(self._turn)
            if server in self.healthy:
                return server
        raise RuntimeError("no healthy servers")

In the reel nine requests go to three servers and each one gets three. The healthy set is the other half of the job: the balancer pings each server every few seconds and stops sending traffic to one that doesn't answer.

The trade-off to say out loud. The servers have to be stateless. If server 1 keeps your login session in its own memory and your next request lands on server 2, you're logged out. So sessions move to a shared store, often the cache from section 1. And the load balancer is now the single point of failure, so real setups run two.

Expect to be asked.

  • What other rules are there? Least connections sends each request to the least busy server. Hashing the user's id or IP sends the same user to the same server every time.
  • What does the load balancer do when a server dies mid-request? The request fails or is retried on another server, which is only safe if the request can be repeated without harm.
  • What would you use? NGINX and HAProxy are the common ones to run yourself, and every cloud sells one.

3. database sharding

The problem. One database machine has a limit on how much it can store and how many writes it can take. Past that, a bigger machine stops being an option.

The idea. Split the data across several databases, called shards, and use a rule to decide where each row lives. The usual rule is to hash a key, like the user id, and take the remainder.

In code.

shards = [dict() for _ in range(4)]         # four separate databases

def shard_for(user_id):
    return shards[hash(user_id) % len(shards)]

def save(user):
    shard_for(user["id"])[user["id"]] = user

def load(user_id):
    return shard_for(user_id).get(user_id)  # one shard to ask, not four

In the reel user 1041 goes to db1, because 1041 % 4 is 1, and it will be found there every time. Python's hash() returns the number itself for an integer, which is why that works here. For strings it changes between runs, so a real system uses a fixed hash function.

The trade-off to say out loud. Anything that needs more than one shard gets hard: a join across users, a count of everyone, a transaction that touches two shards. Adding a shard is the other problem. Go from 4 shards to 5 with this rule and 80% of the users now hash to a different database and have to be moved. Consistent hashing is the fix, because it moves only about one share of the keys.

Expect to be asked.

  • How is this different from replication? Replication copies the same data to several machines, for more reads and for safety. Sharding splits different data across machines, for more writes and more storage. Big systems do both.
  • How do you pick the key? You want one that spreads the data evenly and that most queries already include. A key where one value is huge, like a celebrity's user id, gives you one overloaded shard.
  • When would you do this? Last. Indexes, caching, read replicas and a bigger machine are all cheaper, so say you'd try those first.

4. message queues

The problem. Some work is slow: sending an email, resizing a video, charging a card through someone else's API. If the request waits for it, the user waits for it, and a spike in traffic takes the whole thing down.

The idea. The server writes a message to a queue saying what needs doing, and answers the user straight away. Separate workers read the queue and do the work at their own pace.

In code.

import queue
import threading

q = queue.Queue()
sent = []

def checkout(order):
    q.put(order)                # hand the slow work to the queue
    return "ok"                 # and answer the user straight away

def worker():
    while True:
        order = q.get()
        sent.append(order)      # stands in for sending the email
        q.task_done()

threading.Thread(target=worker, daemon=True).start()
for order in range(1, 6):
    checkout(order)
q.join()                        # wait until the worker has cleared the queue
print(sent)                     # [1, 2, 3, 4, 5]

This is the reel: five orders go in faster than the worker can take them, the queue fills, and then it drains. Nothing is lost and nobody waits. In a real system the queue is its own service, like RabbitMQ, Amazon SQS or Kafka, so the messages survive a server restart.

The trade-off to say out loud. The work now happens later, so the user sees "your order is processing" instead of a finished result. A worker can also crash halfway through a message. The queue hands that message out again, so the same one can be processed twice. Workers have to be idempotent, meaning that doing a job twice leaves the same result as doing it once.

Expect to be asked.

  • What if a message keeps failing? After a few tries it moves to a dead letter queue so it stops blocking the others, and a person looks at it.
  • How do you know when to add workers? Watch the queue length. If it keeps growing, the workers are falling behind.
  • Is the order kept? With one worker, yes. With several, not by default.

5. rate limiting

The problem. One client, whether it's a bug, a scraper or an attack, can send enough requests to slow the API down for everyone.

The idea. Give each client a budget. The token bucket is the usual way: each client has a bucket that holds a few tokens and refills at a steady rate. A request takes a token. If the bucket is empty, the request is refused with HTTP status 429, Too Many Requests.

In code.

import time

class TokenBucket:
    def __init__(self, capacity, per_second):
        self.capacity = capacity            # the biggest burst allowed
        self.rate = per_second              # tokens added each second
        self.tokens = capacity
        self.last = time.monotonic()

    def allow(self):
        now = time.monotonic()
        self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True                     # 200
        return False                        # 429 Too Many Requests

In the reel the bucket holds five. A burst of seven requests gets five through and two refused, then the bucket tops up and the next one passes.

The trade-off to say out loud. A limit that's too tight blocks real users, and one that's too loose protects nothing. The bucket's size sets how big a burst you forgive, and the refill rate sets the long-run limit. With several servers the count also has to live somewhere they all share, usually Redis, or each server hands out its own full budget.

Expect to be asked.

  • Limit by what? By user or API key when people are logged in, by IP address when they aren't.
  • Where does it sit? As early as possible, at the API gateway or the load balancer, so a refused request costs you almost nothing.
  • What does the client get back? A 429, with a Retry-After header saying how long to wait.

how they fit together

A request usually meets them in this order.

client -> rate limiter -> load balancer -> app servers -> cache -> database (shards)
                                               |
                                               +-> queue -> workers

how to use this in an interview

Don't open with any of them. Start with what the system has to do and roughly how big it is: how many users, how many reads for every write, how much data. Draw the simplest thing that works, which is one server and one database.

Then find where it breaks first and add the block that fixes that. Say the cost as you add it. "Reads are far more common than writes here, so I'd put a cache in front of the database, and I'd accept profiles being up to a minute stale" is the kind of sentence the interviewer is listening for.

honest limitations

Five blocks isn't the full set. Replication, indexes, CDNs and consistent hashing only get a mention here, and each one could be its own section.

The code runs in one process on one machine. The real versions are separate services on a network, and most of the difficulty is in what happens when one of them is slow or down.

For the longer version, the two free resources I link in my big tech internship prep guide are The System Design Primer on GitHub and freeCodeCamp's System Design for Beginners.

If you're preparing for the coding rounds too, the coding interview cheat sheet and the data structures cheat sheet are the same idea for those.

← all guides

Done nicnonac.com 56.6k