Learn System Design by Growing a Django App (Step by Step)
The fastest way to learn system design is to take one small app, put real load on it, and fix whatever breaks first. That’s this whole guide. You’ll build a Django link shortener, measure it with a load test, then add an index, a Redis cache, a write buffer, a rate limit, more servers and a fallback for when Redis dies. Every change gets measured, including the ones that didn’t help.
I’m a data and backend developer who has been building with Django since 2018, and I’ve designed systems like secure data delivery for a research lab. Most system design guides are thirty boxes, forty arrows and zero running code. This one runs.
Every command, output and number below came from a real run on my M2 Max, with Docker 29.9.2 in Docker Desktop (12 CPUs and 7.7 GB of memory for its VM), Python 3.14.8, Django 6.1.3, Gunicorn 26.2.0, PostgreSQL 18.6, Redis 8.8.4, nginx 1.30.6 and Locust 2.47.0. They’re laptop numbers, not production numbers. Read them as before and after, never as a promise.
What is system design?
System design is deciding how the parts of a software system fit together. Which database, where the cache goes, what happens when traffic grows ten times, and what breaks when one part dies. Code answers how one feature works. System design answers how the whole thing holds up.
You’ll see five words over and over.
- Latency. How long one request takes. This guide reports p95, the time that 95 out of 100 requests beat. Averages hide the slow ones, and users notice the slow ones.
- Throughput. How many requests per second the system handles.
- Bottleneck. The one part that limits everything else. Fix it and a new one shows up. Always.
- Trade-off. What you give up to get something. A cache makes reads fast and makes data a little stale.
- Load test. A program that pretends to be many users at once, so you can measure latency and throughput before real users do it for you.
How do you learn system design?
You learn system design the way you learn anything in backend work. Build something small, break it on purpose, and explain why it broke. Reading about caches teaches you the word. Watching a cache cut your latency in half, then watching your app die when the cache server stops, teaches you the design.
So every step below is one design habit, shown as one change to a real app. The app stays the same the whole way through, a link shortener called Shortly. It’s the classic exercise for a reason. It’s small enough to finish in an afternoon, and it has every problem big systems have, just smaller.
What do you need before you start?
- Docker Desktop, or Docker Engine with Compose. New to Docker? Start with this Docker tutorial, then come back. This guide uses the same Compose setup as Django in Docker.
- Python 3.12 or newer on your machine, with Django 6.1.3 in a virtual environment. You only need it to create the project and its migrations. Everything else runs in containers.
- Basic Django. Models, views and URLs. If migrations still feel like magic, read Django ORM and migrations first.
- A sheet of paper. Seriously.
The twelve steps at a glance
- Start from what users do
- Do the back-of-envelope math
- Sketch the data model and the URLs
- Build the simplest version that works
- Load test it to get a baseline
- Find the slow query and add the right index
- Cache hot links in Redis
- Move click writes off the request path
- Rate limit link creation
- Add more web servers behind nginx
- Break Redis on purpose and design for failure
- Decide when to split into services
Steps 1 to 5 give you a working app and a baseline. Steps 6 to 11 are the upgrades, one bottleneck at a time, and you can stop after any of them. Step 12 is the big-picture call.
Step 1. Start from what users do
My habit is to start from the people who will use it. What will they do? How will they interact with it? Then I design backward, all the way down to the data model and the tech stack.
A link shortener has two kinds of users. One person makes a short link. Many people click it. Walk through what each one does.
- A creator pastes a long URL and gets a short one back.
- A visitor opens the short link and lands on the long URL without waiting.
- The creator checks how many clicks the link got this week.
Those three are your functional requirements, what the system does. Now write the non-functional requirements, how well it does it. These are the ones that shape the design.
- Redirects feel instant. Under 100 milliseconds at p95, measured at the server.
- Redirects survive a broken helper. If the cache dies, links still work, just slower.
- Nobody can flood link creation. One address gets 10 new links a minute.
- Stats can be a minute old. Nobody needs a live click counter, and that freedom is worth a lot.
Each line maps to a later step. The cache is Step 7, the flood rule is Step 9, and the broken helper is Step 11. Writing these down feels like homework. Skipping them is how you end up caching the wrong thing.
Step 2. Do the back-of-envelope math
Back-of-envelope math means rough numbers you can work out in a minute. You’re not after the right answer. You’re after the right order of magnitude, so you know whether you need one server or a hundred.
Pick targets for a made-up shortener and let Python do the arithmetic. Save this as estimate.py.
"""Back-of-envelope math for the link shortener. Every input is a guess you can change."""
SECONDS_PER_DAY = 24 * 60 * 60
new_links_per_day = 100_000
redirects_per_day = 10_000_000 # 100 reads for every write
peak_factor = 5 # busiest minute vs the daily average
years_kept = 5
bytes_per_link = 500 # URL, code, date, index entries
bytes_per_click = 100 # link id, time, index entries
avg_writes = new_links_per_day / SECONDS_PER_DAY
avg_reads = redirects_per_day / SECONDS_PER_DAY
links_total = new_links_per_day * 365 * years_kept
clicks_total = redirects_per_day * 365 * years_kept
print(f'New links: {avg_writes:,.1f}/s on average, {avg_writes * peak_factor:,.1f}/s at peak')
print(f'Redirects: {avg_reads:,.0f}/s on average, {avg_reads * peak_factor:,.0f}/s at peak')
print(f'Each click is also a write, so peak writes are {avg_reads * peak_factor:,.0f}/s too')
print(f'Links after {years_kept} years: {links_total:,} rows, {links_total * bytes_per_link / 1e9:,.0f} GB')
print(f'Clicks after {years_kept} years: {clicks_total:,} rows, {clicks_total * bytes_per_click / 1e12:,.1f} TB')
Run it.
$ python estimate.py
New links: 1.2/s on average, 5.8/s at peak
Redirects: 116/s on average, 579/s at peak
Each click is also a write, so peak writes are 579/s too
Links after 5 years: 182,500,000 rows, 91 GB
Clicks after 5 years: 18,250,000,000 rows, 1.8 TB
Three things jump out. Reads beat writes 100 to 1, so caching reads will pay off. Every click is also a write, so the “read-heavy” app is secretly write-heavy too. And the clicks table grows into the billions, so any query on it needs an index from day one. Those three facts drive Steps 6 to 8.
You’ll check two of these guesses, the bytes per row, against real tables in Step 4.
Step 3. Sketch the data model and the URLs
I sketch on paper. Just boxes and arrows, and the arrows are the data flow. A box for each table and each page, and an arrow wherever data moves between them. Follow the arrows and you can see which box gets hit hardest. If it doesn’t fit on one page, it’s too complicated for version one.
Shortly needs two tables. A Link holds the code and the long URL. A Click holds one row per visit, with the time, so the stats page can count by day.
| Method | URL | What it does |
|---|---|---|
| GET | / |
Shows the form |
| POST | / |
Creates a short link |
| GET | /<code> |
Redirects to the long URL with a 302 |
| GET | /<code>/stats |
Shows clicks in the last 7 days |
A 302 is a temporary redirect. A 301 is permanent, and browsers may cache it (RFC 9110). A cached redirect never reaches your server, so those clicks never get counted.
Codes are seven random letters and digits. That’s 62 to the power of 7, about 3.5 trillion codes, so even 182 million links fill about 0.005% of them. Random codes also stop people from guessing their neighbor’s links. unique=True makes the database reject a duplicate. A retry loop would handle that rare case, and I left it out to keep the code short.
Step 4. Build the simplest version that works
The simplest version that works still needs four parts. PostgreSQL stores the data, Django runs the app, Gunicorn runs Django with several worker processes, and nginx sits in front. Gunicorn’s own docs say it plainly, “We strongly recommend running Gunicorn behind a proxy server” (Gunicorn deploy docs). Gunicorn’s default workers handle one request at a time, so a slow client on a bad phone connection can hold a worker hostage. nginx reads the whole request first, then hands it over in one fast piece.
How do you create the project?
mkdir shortener && cd shortener
python -m venv venv
source venv/bin/activate
pip install Django==6.1.3
django-admin startproject config .
python manage.py startapp links
What goes in the models and views?
Replace links/models.py.
import secrets
import string
from django.db import models
from django.utils import timezone
ALPHABET = string.ascii_letters + string.digits
def new_code():
"""Seven random letters and digits, about 3.5 trillion possible codes."""
return ''.join(secrets.choice(ALPHABET) for _ in range(7))
class Link(models.Model):
code = models.CharField(max_length=12, unique=True, default=new_code)
target_url = models.URLField(max_length=2000)
created_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return f'{self.code} -> {self.target_url}'
class Click(models.Model):
link = models.ForeignKey(Link, on_delete=models.CASCADE, related_name='clicks')
created_at = models.DateTimeField(default=timezone.now)
Replace links/views.py. The redirect looks up the link, saves a click, and sends a 302. The stats page counts the last 7 days.
from datetime import timedelta
from django import forms
from django.db.models import Count
from django.db.models.functions import TruncDate
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils import timezone
from .models import Click, Link
class LinkForm(forms.ModelForm):
class Meta:
model = Link
fields = ['target_url']
widgets = {'target_url': forms.URLInput(attrs={'placeholder': 'https://example.com/a/very/long/link'})}
def home(request):
form = LinkForm(request.POST or None)
link = None
if request.method == 'POST' and form.is_valid():
link = form.save()
form = LinkForm()
return render(request, 'links/home.html', {'form': form, 'link': link})
def follow(request, code):
link = get_object_or_404(Link, code=code)
Click.objects.create(link=link)
return redirect(link.target_url)
def stats(request, code):
link = get_object_or_404(Link, code=code)
return render(request, 'links/stats.html', {'link': link, **click_stats(link.id)})
def click_stats(link_id):
"""Clicks in the last 7 days: the total, a count per day, and the latest 10."""
since = timezone.now() - timedelta(days=7)
week = Click.objects.filter(link_id=link_id, created_at__gte=since)
return {
'total': week.count(),
'days': list(week.annotate(day=TruncDate('created_at'))
.values('day').annotate(clicks=Count('id')).order_by('day')),
'latest': list(week.order_by('-created_at').values_list('created_at', flat=True)[:10]),
}
def healthz(request):
return HttpResponse('ok')
Replace config/urls.py.
from django.urls import path
from links import views
urlpatterns = [
path('', views.home, name='home'),
path('healthz', views.healthz),
path('<str:code>', views.follow, name='follow'),
path('<str:code>/stats', views.stats, name='stats'),
]
Replace config/settings.py. Secrets come from the environment, and the database URL comes from Compose.
"""Settings for the link shortener. Every secret comes from the environment."""
import os
from pathlib import Path
import dj_database_url
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'links',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
WSGI_APPLICATION = 'config.wsgi.application'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {'context_processors': ['django.template.context_processors.request']},
},
]
DATABASES = {
'default': dj_database_url.config(conn_max_age=60, conn_health_checks=True),
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
USE_TZ = True
TIME_ZONE = 'UTC'
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STORAGES = {
'staticfiles': {'BACKEND': 'whitenoise.storage.CompressedManifestStaticFilesStorage'},
}
What do the templates look like?
Three small templates and one stylesheet. Create links/templates/links/base.html.
{% load static %}<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Shortly{% endblock %}</title>
<link rel="stylesheet" href="{% static 'links/style.css' %}">
</head>
<body>
<main class="wrap">
<header class="top"><a href="{% url 'home' %}" class="brand">Shortly</a><span class="tag">a link shortener for learning system design</span></header>
{% block content %}{% endblock %}
</main>
</body>
</html>
Then links/templates/links/home.html.
{% extends 'links/base.html' %}
{% block content %}
<section class="card">
<h1>Shorten a link</h1>
<form method="post" class="row">
{% csrf_token %}
{{ form.target_url }}
<button type="submit">Shorten</button>
</form>
{% if form.errors %}<p class="error">{{ form.target_url.errors.0 }}</p>{% endif %}
{% if link %}
<div class="result">
<a href="{% url 'follow' link.code %}">{{ request.get_host }}/{{ link.code }}</a>
<a class="muted" href="{% url 'stats' link.code %}">stats</a>
</div>
{% endif %}
</section>
{% endblock %}
Then links/templates/links/stats.html.
{% extends 'links/base.html' %}
{% block title %}Stats for {{ link.code }}{% endblock %}
{% block content %}
<section class="card">
<h1>/{{ link.code }}</h1>
<p class="muted">{{ link.target_url }}</p>
<p class="big">{{ total }} <span>clicks in the last 7 days</span></p>
<table>
<thead><tr><th>Day</th><th>Clicks</th></tr></thead>
<tbody>{% for d in days %}<tr><td>{{ d.day|date:"D, M j" }}</td><td>{{ d.clicks }}</td></tr>{% endfor %}</tbody>
</table>
<h2>Latest clicks</h2>
<ul class="times">{% for t in latest %}<li>{{ t|date:"M j, H:i:s" }}</li>{% empty %}<li>None yet</li>{% endfor %}</ul>
</section>
{% endblock %}
And links/static/links/style.css. Change it however you like, but the file has to exist, or the static files step fails.
:root { --bg: #0f1115; --card: #171a21; --ink: #e8e9ec; --mute: #9aa0aa; --line: #2a2f39; --acc: #c8794f; }
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 16px/1.5 system-ui, -apple-system, sans-serif; }
.wrap { max-width: 640px; margin: 0 auto; padding: 48px 16px; }
.top { display: flex; align-items: baseline; gap: 12px; margin-bottom: 24px; }
.brand { color: var(--ink); font-weight: 700; font-size: 20px; text-decoration: none; }
.tag, .muted { color: var(--mute); font-size: 14px; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 24px; }
h1 { margin: 0 0 16px; font-size: 24px; }
h2 { margin: 24px 0 8px; font-size: 16px; }
.row { display: flex; gap: 8px; }
input { flex: 1; min-width: 0; padding: 10px 12px; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); font: inherit; }
button { padding: 10px 16px; border: 0; border-radius: 8px; background: var(--acc); color: #fff; font: inherit; font-weight: 600; cursor: pointer; }
.result { margin-top: 16px; display: flex; justify-content: space-between; padding: 12px; border: 1px dashed var(--line); border-radius: 8px; }
.result a { color: var(--acc); }
.error { color: var(--acc); }
.big { font-size: 40px; font-weight: 700; margin: 8px 0 16px; }
.big span { font-size: 16px; font-weight: 400; color: var(--mute); }
table { width: 100%; border-collapse: collapse; }
td, th { text-align: left; padding: 6px 0; border-bottom: 1px solid var(--line); }
th { color: var(--mute); font-weight: 500; }
.times { margin: 0; padding-left: 18px; color: var(--mute); font-size: 14px; }
How do Docker, Gunicorn and nginx fit together?
Create requirements.txt.
Django==6.1.3
gunicorn==26.2.0
psycopg[binary]==3.3.8
dj-database-url==3.1.2
whitenoise==6.12.0
Create the Dockerfile. Gunicorn reads its worker count from WEB_CONCURRENCY, which matters in Step 10.
FROM python:3.14-slim
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Static files are baked into the image, so containers start fast.
RUN SECRET_KEY=build-only python manage.py collectstatic --noinput \
&& addgroup --system app && adduser --system --ingroup app app
USER app
EXPOSE 8000
# Gunicorn reads its worker count from WEB_CONCURRENCY.
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", \
"--no-control-socket", "--access-logfile", "-"]
Create nginx/nginx.conf. The resolve part matters more than it looks.
By default nginx looks up web once, when it starts. Recreate the web container and it gets a new address, and nginx keeps knocking on the old door with 502 errors. Without it, this demo breaks at Step 7, the moment Redis joins and web gets a new address. With resolve, nginx asks Docker’s DNS again every 5 seconds.
Docker runs that DNS server at 127.0.0.11 inside every container on a custom network, which is what Compose creates (Docker networking docs). The resolve parameter needs the zone and resolver lines next to it, and it’s in free nginx since 1.27.3 (nginx upstream docs).
# Docker's built-in DNS. Look names up again every 5 seconds, so nginx
# follows web containers when they're recreated or scaled.
resolver 127.0.0.11 valid=5s ipv6=off;
upstream django {
zone django 64k;
# One address per web container. nginx takes turns between them.
server web:8000 resolve;
}
server {
listen 80;
location / {
proxy_pass http://django;
proxy_set_header Host $host;
# Overwrite, never append, so a client can't fake its address.
proxy_set_header X-Forwarded-For $remote_addr;
}
}
Create compose.yaml. Three design choices hide in here. migrate runs once before the web servers start, so two containers never race to migrate. web has no published port, so the only way in is through nginx. And nginx gets two kernel settings, because Gunicorn’s default workers close the connection after every request, so under heavy load nginx can run out of local ports and start answering 502.
services:
db:
image: postgres:18.6-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
POSTGRES_DB: app
volumes:
- postgres_data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U postgres -d app"]
interval: 5s
retries: 10
# Runs once and exits, so web containers never race to migrate.
migrate:
build: .
command: python manage.py migrate --noinput
env_file: .env
environment:
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/app
depends_on:
db:
condition: service_healthy
# No published port. Only nginx can reach it.
web:
build: .
env_file: .env
environment:
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/app
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-3}
depends_on:
migrate:
condition: service_completed_successfully
# The front door. It buffers slow clients and spreads requests over web.
nginx:
image: nginx:1.30.6-alpine
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
ports:
- "8000:80"
# Gunicorn closes each connection after one request, so nginx opens a
# new one every time. More local ports, reused sooner, stop it running out.
sysctls:
net.ipv4.ip_local_port_range: "1024 65000"
net.ipv4.tcp_tw_reuse: 1
depends_on:
- web
volumes:
postgres_data:
Create .env from this example with your own random values, plus a .dockerignore.
SECRET_KEY=change-me
POSTGRES_PASSWORD=change-me
ALLOWED_HOSTS=localhost,127.0.0.1,nginx
.env
staticfiles/
__pycache__/
*.pyc
loadtest/results/
How do you start it and load data?
Make the first migration.
$ python manage.py makemigrations links
Migrations for 'links':
links/migrations/0001_initial.py
+ Create model Link
+ Create model Click
Start everything.
$ docker compose up -d --build
$ docker compose ps
SERVICE STATUS PORTS
db Up 7 seconds (healthy) 5432/tcp
nginx Up 1 second 0.0.0.0:8000->80/tcp, [::]:8000->80/tcp
web Up 1 second 8000/tcp
An empty database can’t show you a bottleneck. Ten links load in a blink no matter how bad your design is. So add a seed command that loads 10,000 links and 3 million clicks, skewed so a few links are hot and most are cold, like real traffic. Save it as links/management/commands/seed_links.py, with an empty __init__.py in management/ and in commands/.
"""Load demo data so the database is big enough to show real bottlenecks."""
from django.core.management.base import BaseCommand
from django.db import connection
LINKS = 10_000
CLICKS = 3_000_000
class Command(BaseCommand):
help = 'Create 10,000 links and 3 million clicks spread over the last 30 days.'
def handle(self, *args, **options):
with connection.cursor() as cur:
cur.execute('TRUNCATE links_click, links_link RESTART IDENTITY')
cur.execute('SELECT setseed(0.42)')
# Seeded codes are s00001 to s10000, so the load test can guess them.
cur.execute(
"""INSERT INTO links_link (code, target_url, created_at)
SELECT 's' || lpad(i::text, 5, '0'),
'https://example.com/page/' || i,
now() - interval '60 days'
FROM generate_series(1, %s) AS i""",
[LINKS],
)
# power(random(), 3) piles most clicks onto the low ids,
# so a few links are hot and most are cold, like real traffic.
cur.execute(
"""INSERT INTO links_click (link_id, created_at)
SELECT 1 + floor(power(random(), 3) * %s)::int,
now() - random() * interval '30 days'
FROM generate_series(1, %s)""",
[LINKS, CLICKS],
)
cur.execute('ANALYZE links_link, links_click')
self.stdout.write(f'Seeded {LINKS:,} links and {CLICKS:,} clicks.')
$ docker compose exec web python manage.py seed_links
Seeded 10,000 links and 3,000,000 clicks.
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8000/s00001
302 https://example.com/page/1
Now check the Step 2 guesses against the real tables.
table_name | row_count | bytes_per_row
------------+-----------+---------------
links | 10000 | 162
clicks | 3000001 | 82
(2 rows)
I guessed 500 bytes per link and 100 per click. The real numbers include index space, and the example URLs are short, so real URLs push the link number up. Close enough to trust the order of magnitude, which was the whole point. And here’s the skew.
link_id | clicks
---------+--------
1 | 139294
2 | 36504
3 | 25340
(3 rows)
One link holds 139,294 clicks. Remember that link. It’s about to cause trouble.
Step 5. Load test it to get a baseline
A baseline is the number every later step gets compared against. Without one, “it feels faster” is the only evidence you’ll ever have, and feelings don’t survive a code review.
Locust is a load testing tool where you describe your users in plain Python. Save this as loadtest/locustfile.py. It sends 80% redirects and 20% stats pages, aimed at the same hot and cold links as the seed data. allow_redirects=False matters. Locust follows redirects by default (Locust docs), so without it, Locust would follow every 302 to example.com and load test somebody else’s server.
"""The same load for every step: 80% redirects, 20% stats pages."""
import random
from locust import FastHttpUser, constant, task
def seeded_code():
# Same skew as seed_links, so hot links get most of the traffic.
n = 1 + int(random.random() ** 3 * 10_000)
return f's{min(n, 10_000):05d}'
class Visitor(FastHttpUser):
wait_time = constant(0)
@task(8)
def follow(self):
with self.client.get(f'/{seeded_code()}', name='/[code]',
allow_redirects=False, catch_response=True) as r:
if r.status_code != 302:
r.failure(f'expected 302, got {r.status_code}')
@task(2)
def stats(self):
self.client.get(f'/{seeded_code()}/stats', name='/[code]/stats')
Run Locust in its own container on the Compose network, so it reaches nginx by name and Docker Desktop’s port forwarding stays out of the numbers.
docker run --rm --network shortener_default \
--sysctl net.ipv4.ip_local_port_range="1024 65000" \
--sysctl net.ipv4.tcp_tw_reuse=1 \
-v "$PWD/loadtest:/mnt/locust:ro" \
locustio/locust:2.47.0 -f /mnt/locust/locustfile.py \
--host http://nginx --headless -u 50 -r 50 --processes 6 -t 60s --only-summary
That’s 50 users with no pause between requests, for 60 seconds, spread over 6 Locust processes so Locust itself never becomes the bottleneck. Add nginx to ALLOWED_HOSTS in .env, or Django answers every request with a 400.
How do you keep a load test fair?
Every step below got the same treatment. A 45-second cool-down so the laptop’s temperature doesn’t skew later steps, a 15-second warm-up, then three 60-second runs.
Before each run the script deleted the clicks the last run added, vacuumed the table and emptied Redis, so every run started from the same 3 million rows. The tables show the median of the three runs. While Locust ran, docker stats sampled each container’s CPU every couple of seconds. Locust also rounds each response time before it works out percentiles, to the nearest millisecond under 100 ms and the nearest 10 ms up to a second (Locust’s stats code). So a p95 of 130 ms means about 130, give or take 5.
What did the baseline show?
| Requests per second | p50 | p95 | Database CPU | Web CPU |
|---|---|---|---|---|
| 714 (runs ranged 707 to 737) | 60 ms | 130 ms | 335% | 80% |
CPU here is the Docker kind, where 100% means one full core. PostgreSQL used more than three cores while the web container used less than one. That’s your bottleneck.
Check it against Step 1 and Step 2. The p95 target was 100 ms, and the baseline missed it. Redirects alone ran at 571 a second, against a peak target of 579, so it missed that one by a hair. Version one doesn’t meet its own requirements, which is exactly what version one is for.
Step 6. Find the slow query and add the right index
The redirect does one lookup by code, and unique=True already gave that column an index. The stats page is different. It reads every click for one link in the last 7 days, three times, and the hot link has 139,294 of them. EXPLAIN ANALYZE asks PostgreSQL how it ran a query and how long it took.
$ docker compose exec db psql -U postgres -d app -c "EXPLAIN ANALYZE SELECT COUNT(*) FROM links_click WHERE link_id = 1 AND created_at >= now() - interval '7 days'"
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Finalize Aggregate (cost=23513.23..23513.24 rows=1 width=8) (actual time=27.774..31.885 rows=1.00 loops=1)
Buffers: shared hit=4751 read=14724 written=15
-> Gather (cost=23513.01..23513.22 rows=2 width=8) (actual time=27.649..31.881 rows=3.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=4751 read=14724 written=15
-> Partial Aggregate (cost=22513.01..22513.02 rows=1 width=8) (actual time=25.872..25.873 rows=1.00 loops=3)
Buffers: shared hit=4751 read=14724 written=15
-> Parallel Bitmap Heap Scan on links_click (cost=1681.97..22478.47 rows=13817 width=0) (actual time=4.667..25.386 rows=10837.33 loops=3)
Recheck Cond: (link_id = 1)
Filter: (created_at >= (now() - '7 days'::interval))
Rows Removed by Filter: 35594
Heap Blocks: exact=6501
Buffers: shared hit=4751 read=14724 written=15
Worker 0: Heap Blocks: exact=6493
Worker 1: Heap Blocks: exact=6325
-> Bitmap Index Scan on links_click_link_id_873d3412 (cost=0.00..1673.68 rows=143100 width=0) (actual time=4.312..4.313 rows=140885.00 loops=1)
Index Cond: (link_id = 1)
Index Searches: 1
Buffers: shared hit=5 read=111
Planning:
Buffers: shared hit=89 read=1
Planning Time: 0.409 ms
Execution Time: 31.930 ms
(24 rows)
Read it from the bottom. PostgreSQL used the foreign key index Django creates on its own to find all of link 1’s clicks, then fetched each row from the table and threw away the ones older than 7 days. “Rows Removed by Filter” is wasted work, done on every stats view.
The fix is an index that matches the question, link first, then time. Django won’t create this one for you. Add a Meta class to Click in links/models.py.
class Click(models.Model):
link = models.ForeignKey(Link, on_delete=models.CASCADE, related_name='clicks')
created_at = models.DateTimeField(default=timezone.now)
class Meta:
indexes = [
# The stats page asks "clicks for this link, newest first".
models.Index(fields=['link', '-created_at'], name='click_link_newest_idx'),
]
$ python manage.py makemigrations links
Migrations for 'links':
links/migrations/0002_click_click_link_newest_idx.py
+ Create index click_link_newest_idx on field(s) link, -created_at of model click
$ docker compose build && docker compose run --rm migrate
Container shortener-db-1 Running
Container shortener-db-1 Waiting
Container shortener-db-1 Healthy
Container shortener-migrate-run-6d6c5da90529 Creating
Container shortener-migrate-run-6d6c5da90529 Created
Operations to perform:
Apply all migrations: contenttypes, links
Running migrations:
Applying links.0002_click_click_link_newest_idx... OK
real 2.49
user 0.06
sys 0.03
$ docker compose up -d
Building the index on 3 million rows took about 2.5 seconds. A plain AddIndex locks the table against writes while it builds (PostgreSQL docs), which is fine on a laptop and a bad afternoon on a busy production table. On PostgreSQL, Django’s AddIndexConcurrently builds it without blocking writes. Now the same query.
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=2094.52..2094.53 rows=1 width=8) (actual time=5.045..5.046 rows=1.00 loops=1)
Buffers: shared hit=4 read=127
-> Index Only Scan using click_link_newest_idx on links_click (cost=0.43..2011.62 rows=33160 width=0) (actual time=0.059..3.163 rows=32510.00 loops=1)
Index Cond: ((link_id = 1) AND (created_at >= (now() - '7 days'::interval)))
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=4 read=127
Planning:
Buffers: shared hit=103 read=7
Planning Time: 0.635 ms
Execution Time: 5.083 ms
(11 rows)
An index-only scan with zero heap fetches. The query went from 31.930 ms to 5.083 ms, about 6 times faster.
| Step | Requests per second | p95 | Database CPU | Web CPU |
|---|---|---|---|---|
| 5. Baseline | 714 | 130 ms | 335% | 80% |
| 6. Index | 1,260 | 61 ms | 163% | 138% |
One migration, 1.8 times the throughput, and the p95 target is met. The database is still the busiest box though, because every redirect still reads a link from it and writes a click to it.
Step 7. Cache hot links in Redis
A cache keeps answers you already worked out somewhere faster, so you don’t work them out again. Redis is an in-memory data store, and Django ships a Redis cache backend. Because Redis is its own server, every web container shares one cache, which matters in Step 10.
Add Redis to compose.yaml, under services.
redis:
image: redis:8.8.4-alpine
Give web the address in its environment block, and make it wait for Redis in depends_on.
REDIS_URL: redis://redis:6379/0
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_started
Add the client to requirements.txt.
redis==8.1.0
Add the cache to the bottom of config/settings.py.
# Redis holds the cache, so every web container shares it.
REDIS_URL = os.environ.get('REDIS_URL', 'redis://redis:6379/0')
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': REDIS_URL,
}
}
Now cache the two things that get read the most. A link never changes once it’s made, so it can live in Redis for an hour. Stats change all the time, so they get 60 seconds. That’s the “stats can be a minute old” line from Step 1 paying for itself. In links/views.py, add from django.core.cache import cache at the top, add get_link, and use it in both views.
def get_link(code):
"""A link never changes once it's made, so keep it in Redis for an hour."""
key = f'link:{code}'
link = cache.get(key)
if link is None:
link = get_object_or_404(Link, code=code)
cache.set(key, link, timeout=60 * 60)
return link
def follow(request, code):
link = get_link(code)
Click.objects.create(link=link)
return redirect(link.target_url)
def stats(request, code):
link = get_link(code)
# Stats may be up to 60 seconds old. That's the trade for not counting on every view.
data = cache.get_or_set(f'stats:{code}', lambda: click_stats(link.id), timeout=60)
return render(request, 'links/stats.html', {'link': link, **data})
Rebuild, click a link, open its stats page, and look inside Redis.
$ docker compose up -d --build
$ docker compose exec redis redis-cli --scan
:1:link:s00001
:1:stats:s00001
The :1: prefix is Django’s cache key version.
| Step | Requests per second | p95 | Database CPU | Web CPU |
|---|---|---|---|---|
| 6. Index | 1,260 | 61 ms | 163% | 138% |
| 7. Redis cache | 1,760 | 37 ms | 42% | 190% |
The database dropped to 42% CPU, and for the first time the web container is the busiest box. The bottleneck moved, like it always does. Most reads now stop at Redis. Every redirect still inserts one click row into PostgreSQL and waits for its own commit, and that’s the next target.
One warning before you cache everything. A cache is a copy, and copies go stale. Shortly gets away with an hour because links can’t be edited. Add an edit button and you also have to delete link:<code> from Redis every time someone saves, or visitors land on the old URL for up to an hour.
Step 8. Move click writes off the request path
The request path is everything that happens between a visitor asking for a page and getting it. The visitor doesn’t care whether the click got saved. They care about the redirect. So save the click later, in batches.
The plan is a Redis list. The web container pushes link id:time onto it, one quick write to memory instead of a database commit. A separate worker takes up to 1,000 at a time and saves them with one INSERT. Save this as links/clicks.py.
"""Keep click writes off the request path with a Redis list."""
import time
import redis
from django.conf import settings
QUEUE = 'clicks'
client = redis.Redis.from_url(settings.REDIS_URL)
def record_click(link_id):
"""Push "link id:unix time" onto the list. Postgres sees it a moment later."""
client.rpush(QUEUE, f'{link_id}:{time.time()}')
Save the worker as links/management/commands/flush_clicks.py.
"""Move buffered clicks from Redis into Postgres, up to 1,000 at a time."""
import time
from datetime import UTC, datetime
from django.core.management.base import BaseCommand
from links.clicks import QUEUE, client
from links.models import Click
class Command(BaseCommand):
help = 'Run forever, saving buffered clicks in batches.'
def handle(self, *args, **options):
while True:
batch = client.lpop(QUEUE, 1000)
if not batch:
time.sleep(0.5)
continue
rows = []
for item in batch:
link_id, ts = item.decode().split(':')
rows.append(Click(link_id=int(link_id),
created_at=datetime.fromtimestamp(float(ts), UTC)))
# One INSERT for the whole batch instead of one per click.
Click.objects.bulk_create(rows)
In links/views.py, import record_click from .clicks and swap one line in follow.
def follow(request, code):
link = get_link(code)
record_click(link.id)
return redirect(link.target_url)
Then run the worker as its own Compose service, from the same image.
# Saves the clicks that web pushed onto the Redis list.
clicks:
build: .
command: python manage.py flush_clicks
env_file: .env
environment:
DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD}@db:5432/app
REDIS_URL: redis://redis:6379/0
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_started
Rebuild, click a link three times, and count.
$ docker compose up -d --build
$ for i in 1 2 3; do curl -s -o /dev/null localhost:8000/s09999; done
$ sleep 2
$ docker compose exec db psql -U postgres -d app -tAc "SELECT count(*) FROM links_click WHERE link_id = 9999 AND created_at > now() - interval '1 minute'"
3
| Step | Requests per second | p95 | Database CPU | Web CPU |
|---|---|---|---|---|
| 7. Redis cache | 1,760 | 37 ms | 42% | 190% |
| 8. Click buffer | 2,356 | 32 ms | 21% | 224% |
The database is down to 21%, close to idle. The three runs swung from 1,717 to 2,780 requests a second, the widest spread in this guide, so read the gain as real but rough. Either way, the web container now does nearly all the work, so that’s where Step 10 goes.
What did this trade away?
Durability, a little. The worker pops a batch, then saves it. If it crashes between those two lines, up to 1,000 clicks are gone.
If Redis restarts before the worker catches up, the clicks waiting in the list are gone too. For click stats that’s a fair trade. For payments it’s a lawsuit. Redis documents a reliable queue pattern with LMOVE that keeps each item in a processing list until the worker confirms it.
Step 9. Rate limit link creation
A rate limit caps how often one client can do something. Step 1 said one address gets 10 new links a minute. The simplest version is a fixed window. Count requests per address per minute in Redis, and refuse once the count passes 10 with HTTP 429, “Too Many Requests”.
Add these to links/views.py (plus import time at the top), and check the limit at the top of home.
def client_ip(request):
# Behind nginx, REMOTE_ADDR is nginx itself. nginx overwrites
# X-Forwarded-For with the address it saw, and only nginx can reach web.
return request.META.get('HTTP_X_FORWARDED_FOR') or request.META['REMOTE_ADDR']
def over_limit(request, limit=10, window=60):
"""Fixed window: each IP address may create 10 links per minute."""
key = f'rate:{client_ip(request)}:{int(time.time() // window)}'
cache.add(key, 0, timeout=window) # does nothing if the key exists
return cache.incr(key) > limit
def home(request):
if request.method == 'POST' and over_limit(request):
context = {'form': LinkForm(), 'limited': True}
return render(request, 'links/home.html', context, status=429)
form = LinkForm(request.POST or None)
link = None
if request.method == 'POST' and form.is_valid():
link = form.save()
form = LinkForm()
return render(request, 'links/home.html', {'form': form, 'link': link})
cache.add only sets a key that doesn’t exist yet, and cache.incr adds one in Redis itself, so two web containers can’t both read 9 and both write 10. Show the message in links/templates/links/home.html, right above the form.errors line.
{% if limited %}<p class="error">You can make 10 links a minute. Try again shortly.</p>{% endif %}
Why does the IP address come from a header?
Behind nginx, every request reaches Django from nginx’s address. Rate limit by REMOTE_ADDR and all your users share one limit of 10 links a minute, which is a very effective way to stop everyone.
nginx writes the real address into X-Forwarded-For, and the config from Step 4 overwrites that header instead of appending to it. Django can trust it here for one reason. The web service has no published port, so nothing but nginx can reach it. If clients can talk to Django directly, they can fake the header.
Does it work?
The Django test client can post 12 times in a row from inside the container.
$ docker compose exec web python manage.py shell -c "
from django.test import Client
c = Client(HTTP_HOST='localhost')
print([c.post('/', {'target_url': 'https://example.com/'}).status_code for _ in range(12)])"
9 objects imported automatically (use -v 2 for details).
[200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 429, 429]
Ten links, then two refusals. The test client skips nginx and the CSRF check, which is fine for testing the limiter itself.
A fixed window has one known hole. Someone can send 10 requests in the last second of one minute and 10 more in the first second of the next, which is 20 in two seconds. Sliding windows and token buckets fix that, and they’re big enough for their own post.
Step 10. Add more web servers behind nginx
Scaling out means adding more copies of a server, instead of buying a bigger one. The web container is the bottleneck now, so give it more workers. Two ways to get 9 workers make a fair comparison, one container with 9 or three containers with 3 each.
$ WEB_CONCURRENCY=9 docker compose up -d --scale web=1
$ WEB_CONCURRENCY=3 docker compose up -d --scale web=3
$ docker compose ps --format 'table {{.Name}}\t{{.Status}}'
NAME STATUS
shortener-clicks-1 Up 4 minutes
shortener-db-1 Up 23 minutes (healthy)
shortener-nginx-1 Up 23 minutes
shortener-redis-1 Up 14 minutes
shortener-web-1 Up 7 seconds
shortener-web-2 Up 7 seconds
shortener-web-3 Up 7 seconds
Did nginx find all three? Send 300 redirects and count Gunicorn’s access log lines per container.
codes
300 302
per-container
100 web-1
100 web-2
100 web-3
All 300 got a 302, split exactly even, with no nginx restart. That’s the resolve line from Step 4 doing its job.
| Step | Requests per second | p95 | Database CPU | Web CPU |
|---|---|---|---|---|
| 8. 1 container x 3 workers | 2,356 | 32 ms | 21% | 224% |
| 10. 1 container x 9 workers | 5,135 | 13 ms | 27% | 422% |
| 10. 3 containers x 3 workers | 4,501 | 24 ms | 25% | 414% |
Going from 3 workers to 9 roughly doubled throughput, to 5,135 a second with a p95 of 13 ms. The web tier was the bottleneck, and more workers fixed it.
Three containers did a little worse than one big one, 4,501 against 5,135, and their p95 was almost double. On one laptop, three containers don’t add a single CPU. One container with 9 workers is also one shared line, where any free worker grabs the next request. nginx deals requests to three containers in turn, its default round-robin (nginx upstream docs), so a request can land on a container whose 3 workers are all busy while another container sits idle.
nginx also has least_conn, which sends each request to the container with the fewest active connections. That’s the usual fix for this, and this replay didn’t test it.
So why run three? Because one can crash, or restart for a deploy, while the other two keep serving. And because three containers can live on three machines, which is where real scale-out happens. One container can’t.
Measured with Locust 2.47.0 and drawn with Python.
Step 11. Break Redis on purpose and design for failure
Every box you add is a box that can die. Step 1 said redirects must survive a broken helper. Time to check. Stop Redis while the load test runs the Step 10 code.
$ docker compose stop redis
| Redis | Requests per second | p95 | Failed requests |
|---|---|---|---|
| Down, Step 10 code | 805 | 100 ms | 100% |
Every request failed with a 500. Redis held a copy of the data and PostgreSQL still had all of it, but the code treated the cache as required. Here’s the error, straight from the cache.
$ docker compose exec web python manage.py shell -c "from django.core.cache import cache; cache.get('link:s00001')"
redis.exceptions.ConnectionError: Error -2 connecting to redis:6379. Name or service not known.
Django’s Redis backend doesn’t catch connection errors for you. So catch them yourself, and treat a dead cache like a miss. In links/views.py, import RedisError from redis.exceptions, add two small helpers, and use them wherever the views touch the cache.
def cache_get(key):
try:
return cache.get(key)
except RedisError:
return None # Redis is down, so treat it as a miss and ask Postgres
def cache_set(key, value, timeout):
try:
cache.set(key, value, timeout)
except RedisError:
pass # the next request will try again
def get_link(code):
"""A link never changes once it's made, so keep it in Redis for an hour."""
key = f'link:{code}'
link = cache_get(key)
if link is None:
link = get_object_or_404(Link, code=code)
cache_set(key, link, timeout=60 * 60)
return link
def follow(request, code):
link = get_link(code)
record_click(link.id)
return redirect(link.target_url)
def stats(request, code):
link = get_link(code)
# Stats may be up to 60 seconds old. That's the trade for not counting on every view.
key = f'stats:{code}'
data = cache_get(key)
if data is None:
data = click_stats(link.id)
cache_set(key, data, timeout=60)
return render(request, 'links/stats.html', {'link': link, **data})
The rate limiter needs a choice. If Redis is down, do you let link creation through or block it? This version fails open, so a short outage doesn’t lock out every user.
def over_limit(request, limit=10, window=60):
"""Fixed window: each IP address may create 10 links per minute."""
key = f'rate:{client_ip(request)}:{int(time.time() // window)}'
try:
cache.add(key, 0, timeout=window) # does nothing if the key exists
return cache.incr(key) > limit
except RedisError:
return False # fail open: a short outage shouldn't block every user
Clicks fall back to a direct insert, the slow way from Step 4, which beats losing them. Import RedisError and Click at the top of links/clicks.py.
# Give up after 200 ms, so a dead Redis fails fast instead of hanging requests.
client = redis.Redis.from_url(settings.REDIS_URL, socket_timeout=0.2,
socket_connect_timeout=0.2)
def record_click(link_id):
"""Push "link id:unix time" onto the list. Postgres sees it a moment later."""
try:
client.rpush(QUEUE, f'{link_id}:{time.time()}')
except RedisError:
Click.objects.create(link_id=link_id) # Redis is down: write it directly
And the worker waits instead of crashing, with the same RedisError import.
try:
batch = client.lpop(QUEUE, 1000)
except RedisError:
batch = None # Redis is down: wait and try again
Last, short timeouts in config/settings.py, so a Redis that hangs instead of dying fails in 200 ms instead of taking every worker down with it.
# Fail fast when Redis is down, instead of hanging the request.
'OPTIONS': {'socket_timeout': 0.2, 'socket_connect_timeout': 0.2},
Same test, same dead Redis, then Redis back.
| Redis | Requests per second | p95 | Failed requests |
|---|---|---|---|
| Down, Step 10 code | 805 | 100 ms | 100% |
| Down, with fallbacks | 261 | 320 ms | 0% |
| Back up | 4,255 | 27 ms | 0% |
Slow beats broken, but look how slow. With Redis down, every link works, at 261 requests a second, slower than even the Step 5 baseline. Every request still asks Redis first, waits for that to fail, then asks PostgreSQL.
The fix for that is a circuit breaker, a switch that stops calling a dead service for a few seconds after it fails, so requests go straight to the fallback. Bring Redis back and the speed comes back with no restart. The failure runs used one run each, 30 seconds for the broken code and 60 for the others.
Step 12. Decide when to split into services
Here’s the whole design, drawn the way it actually runs.
The obvious next question is microservices. A microservice is a separate app with its own deploy, talking to the others over the network. My take is modular first, split later. I split features into multiple Django apps inside one project. It keeps the software modular, and I always know where each feature lives.
For Shortly, that means two Django apps in one project.
shortener/
├── config/
├── links/ # create links, redirect
└── analytics/ # clicks, the worker, the stats page
One codebase, one deploy, one database, but each feature has a clear home. The demo keeps everything in links to stay short.
Notice you already have a split that matters. The clicks worker runs as its own process from the same image, so it scales, restarts and fails on its own. That’s most of what people want from a microservice, without a second codebase.
Split a feature into its own service when one of these is true, and not before.
- It scales differently. The redirect path needs nine workers, while the admin pages need one.
- It deploys on a different schedule. One team ships daily, another monthly.
- It must fail alone. Step 11 showed one dead dependency taking every request down. Every network call you add is another one of those.
- A separate team owns it. That one’s about people, not computers.
None of those are true for Shortly. A single deploy handled thousands of requests a second on a laptop. Splitting it now would add network calls, deploys and failure points, and buy nothing.
Which system design concepts does each step teach?
Here’s the whole guide on one page. Every number is the median of three runs from the tables above.
| Step | System design concept | What it did to Shortly |
|---|---|---|
| 1 | Functional and non-functional requirements | Set the targets, p95 under 100 ms and 10 new links a minute per address |
| 2 | Back-of-envelope estimation | Showed reads beat writes 100 to 1, and every click is a write |
| 3 | API and data model design | Four URLs and two tables |
| 4 | High-level architecture, reverse proxy | A working app with 10,000 links and 3 million clicks |
| 5 | Load testing and baselines | 714 requests a second, p95 130 ms, database as the bottleneck |
| 6 | Database indexing | 1,260 requests a second, p95 61 ms, 1.8x faster |
| 7 | Caching | 1,760 requests a second, p95 37 ms |
| 8 | Write buffering, async processing | 2,356 requests a second, p95 32 ms |
| 9 | Rate limiting | Ten links, then HTTP 429 |
| 10 | Horizontal scaling, load balancing | 5,135 requests a second with 9 workers, p95 13 ms |
| 11 | Fault tolerance, graceful degradation | With Redis down, failed requests went from 100% to 0% |
| 12 | Monolith vs microservices | Kept one deploy, split by Django app |
From the baseline to nine workers, throughput grew about 7x on the same laptop. No step needed a new language, a new framework or a second codebase.
How does this map to system design interviews?
Almost one to one. System design interviews ask you to walk through the same path out loud, usually at a whiteboard.
- Requirements, functional and non-functional. Step 1.
- Estimates, traffic and storage. Step 2.
- API and data model. Step 3.
- High-level design, the boxes and arrows. Step 4.
- Deep dives, find the bottleneck and fix it. Steps 6 to 9.
- Scale and failure. Steps 10 and 11.
- Trade-offs, said out loud. Every step had one.
The difference is that in an interview you can’t run a load test, so you say what you’d measure and what you’d expect. Having actually watched a bottleneck move from the database to the web tier makes that a lot easier to say with a straight face. If your interview loop also has a Python coding round, these Python interview questions cover the language side.
What should you remember?
- Start from what users do, then turn it into numbers you can test.
- Measure before you change anything. A baseline is the cheapest tool in system design.
- Fix the busiest box first. The CPU numbers pointed at it every time.
- Every fix moves the bottleneck. Expect it.
- Every cache and every queue is a trade. Write down what you gave up.
- Assume each part will die, and decide what happens when it does.
- Keep one deploy until a real reason forces a split.
Frequently asked questions
Do you need microservices to scale Django?
No. One Django deploy with an index, a cache, a write buffer and enough workers went from 714 to 5,135 requests a second here, on one laptop. Past one machine, you add more machines running the same app behind a load balancer. That’s still one codebase.
Why Locust and not ab or wrk?
Locust describes users in Python, so the load test speaks the same language as the app, and you can mix pages and pick hot links like real traffic. Tools like wrk push more raw requests from one process. Use them when you need a bigger hammer than Locust gives you.
Are these numbers what production will see?
No. Everything ran on one laptop with Docker Desktop, so the database, the cache, the app and the load test all shared the same CPUs. Use the numbers to compare steps with each other. In production, run the same Locust file against a staging copy of your real setup.
What should you learn next?
Database replication and read replicas, a CDN in front of the redirects, real task queues like Celery, and how to watch a live system with metrics and tracing. Each one is the same loop you just did. Measure, find the busiest box, fix it, measure again.
Which step surprised you the most when you ran it yourself, or did your bottleneck land somewhere mine didn’t?