URL Shortener System Design
Build a URL shortener with a Python API, PostgreSQL, and Redis on Docker.
Introduction
โก๏ธ 30 Second Summary
URLs can be absurdly long.
A URL shortener takes a giant link and gives you a tiny one (like bit.ly/abc123) that redirects to the same place. Services like Bitly and TinyURL power billions of these redirects for social media posts, marketing emails, and SMS messages every day.
In this project, you will build a working URL shortener on your machine using three connected services: an API server, a database, and a cache layer. You'll orchestrate them with Docker Compose and learn the architecture patterns behind one of the most common system design interview questions.
What You'll Build
A URL shortener that converts long URLs into short codes and redirects users, powered by a Python Flask API, a PostgreSQL database, and a Redis cache running together on your machine.
This diagram shows the flow for creating short URLs:
The API stores the long URL, converts its database ID into a short code, and returns the new short URL.
And this diagram shows the process we'll build for opening short URLs using caching:
The API checks Redis first, falls back to PostgreSQL after a cache miss, and stores the result in Redis for the next request.
By the end of this project, you'll have:
- ๐งช A Flask API server that accepts long URLs and returns unique short codes.
- ๐ข๏ธ A PostgreSQL database and Redis cache working together for persistent storage and fast lookups.
- ๐ณ A Docker Compose configuration that orchestrates all three services as a distributed system on your machine.
- ๐ Secret Mission: Add rate limiting to prevent API abuse using Redis as a counter store.
Are there any prerequisites?
None. This project includes setup instructions for all tools you need, including Docker Desktop and your code editor.
Set Up Your Environment
To build a URL shortener with multiple services, you need three things on your machine: a terminal for running commands, Docker for running each service as a container, and a code editor for working with your project files.
In this step, you will install and configure all three tools so you are ready to start building.
In this step, get ready to:
- Open Terminal and create your project folder.
- Install Docker Desktop to run your services as containers.
- Install Cursor as your code editor.
Open Terminal and create your project folder
You need a command line tool to run commands, create files, and manage your project. Every operating system has one built in.
macOS
โ๏ธ Already open
Great. Onwards! Continue to creating the project folder below.
โง Help me open Terminal
- Press Cmd+Space to open Spotlight search.
- Type Terminal and press Enter to open it.
Spotlight displays Terminal as the top result, ready to open.
- You should see a window with a blinking cursor ready for you to type commands.
Terminal is open with a command prompt ready for your input.
Windows
โ๏ธ Already open
Great. Skip ahead to creating the project folder below.
โง Help me open PowerShell
- Press the Windows key to open your search bar.
- Type PowerShell and press Enter to open it.
- You should see a blue window with a blinking cursor ready for you to type commands.
Linux
โ๏ธ Already open
Great. Skip ahead to creating the project folder below.
โง Help me open Terminal
- Press Ctrl+Alt+T to open Terminal. On most Linux distributions, this keyboard shortcut opens the default terminal emulator.
- If that does not work, open your application menu and search for Terminal.
- You should see a window with a blinking cursor ready for you to type commands.
What are the basic terminal commands?
You only need four commands for this project:
- pwd prints where you are (your current folder).
- ls lists files in the current folder.
- cd changes directory (moves you to a different folder).
- mkdir creates a new folder.
- Move to your Desktop by running this command:
cd ~/Desktop
Your terminal prompt now shows Desktop as your current location.
The prompt now shows that Terminal is working from your Desktop directory.
- Create your project folder and move into it by running these commands:
mkdir url-shortener && cd url-shortener && mkdir app
Your terminal is now inside the url-shortener folder with the app subfolder created.
The prompt confirms that you are inside the new `url-shortener` directory.
What do these commands do?
cd ~/Desktop moves you to your Desktop folder. This ensures your project ends up somewhere easy to find.
mkdir url-shortener creates a folder called url-shortener on your Desktop.
cd url-shortener moves you inside it. mkdir app creates an app subfolder where your Python code will live.
- Confirm the folder structure was created by running:
ls
- You should see app in the output.
The `ls` output lists `app`, confirming that the subfolder exists.
Don't see the app folder?
- Make sure you ran all three parts of the command. If ls shows nothing, try running pwd to check if you are inside ~/Desktop/url-shortener.
- If you are not in the right folder, run cd ~/Desktop/url-shortener and try ls again.
Having trouble creating folders in Terminal?
Install Docker Desktop
Your URL shortener needs three separate services running at the same time:
- An API server - to receive incoming requests (like "shorten this URL" or "redirect me") and route them to the right place.
- A database - to store the mapping between short codes and their original long URLs so they persist even after restarts.
- A cache. - to keep frequently accessed URL mappings in memory so popular links redirect instantly without hitting the database every time.
Docker Desktop lets you spin up all three as isolated containers on your machine, so you can build a real multi-service system without paying for cloud servers.
macOS
โ๏ธ Already installed
Nice - let's double check Docker Desktop is open and ready.
- Look for the whale icon in your menu bar at the top of the screen.
The whale icon in the menu bar confirms that Docker Desktop is running.
Don't see the whale icon?
No worries - you probably have Docker Desktop installed but not running. Let's open it manually.
- Press Cmd+Space to open Spotlight search.
- Type Docker and press Enter to open Docker Desktop.
- You might need to enter the password to your computer to give it permission to run - that's okay!
- Wait for the whale icon to appear in your menu bar at the top of the screen. When it stops animating, Docker is ready.
Still not seeing the whale icon after opening Docker Desktop?
โง Install Docker
- Open your browser and go to docker.com/get-started.
- Click Download for Mac (choose Apple Silicon or Intel Chip depending on your Mac).
- Double-click the downloaded Docker.dmg file to open the installer.
- Drag the Docker icon to the Applications folder.
How do I know which Mac I have?
Click the Apple menu in the top-left corner of your screen, then click About This Mac. If it says "Apple M1", "M2", "M3", or "M4", choose Apple Silicon. If it says "Intel", choose Intel Chip.
- Press Cmd+Space, type Docker, and press Enter to open Docker Desktop.
- Accept the Docker Subscription Service Agreement when prompted.
- Wait for the whale icon in your menu bar to stop animating. This means Docker Desktop is running.
What will I see on first launch?
Docker Desktop presents an installation window on first launch where you can accept the default settings. macOS may ask for your password to grant privileged access. This is normal and required for Docker to set up its networking.
Windows
โ๏ธ Already installed
Make sure Docker Desktop is running. Look for the whale icon in your system tray (bottom-right corner of your screen). If it is there and not animating, you are ready. Skip to the version check below.
Don't see the whale icon?
Docker Desktop is installed but not running. You need to open it manually.
- Press the Windows key to open your search bar.
- Type Docker and press Enter to open Docker Desktop.
- Wait for the whale icon to appear in your system tray (bottom-right corner of your screen). When it stops animating, Docker is ready.
Still not seeing the whale icon after opening Docker Desktop?
โง Install Docker
- Open your browser and go to docker.com/get-started.
- Click Download for Windows.
- Double-click Docker Desktop Installer.exe to run the installer.
- When the installer asks which mode to use, choose per-user installation (recommended, no admin rights needed).
- Make sure the Use WSL 2 instead of Hyper-V option is selected on the Configuration page, then click Ok.
- Wait for the installation to finish, then click Close and restart if prompted.
What is WSL 2?
WSL 2 (Windows Subsystem for Linux) lets Docker run Linux containers on your Windows machine. The Docker installer enables it automatically. If Windows asks you to enable WSL 2 for the first time, approve it.
- Press the Windows key, type Docker, and press Enter to open Docker Desktop.
- Accept the Docker Subscription Service Agreement when prompted.
- Wait for the whale icon in your system tray to stop animating. This means Docker Desktop is running.
Linux
โ๏ธ Already installed
Make sure Docker Desktop is running. Check for the Docker Desktop icon in your system tray or run docker --version in your terminal. If you see a version number, skip to the version check below.
โง Install Docker
- Open your browser and go to docs.docker.com/desktop/setup/install/linux/.
- Select your Linux distribution (Ubuntu, Debian, Fedora, or Arch) and follow the official installation steps.
- After installation, open Docker Desktop from your application menu.
- Accept the Docker Subscription Service Agreement when prompted.
- Wait for Docker Desktop to finish starting. The whale icon in your system tray will stop animating when it is ready.
Alternative: Docker Engine without Desktop
If you prefer not to install Docker Desktop, you can install Docker Engine directly using your package manager. The commands in this project work the same way with either option.
- Switch back to Terminal and verify Docker is installed by running:
docker --version
You should see a version number like Docker version 27.x.x printed in the output.
The version number confirms that the Docker command is available in Terminal.
โ๏ธ I see a version number
Docker is installed and ready. Nice!
Docker returns its installed version, confirming that the installation succeeded.
- Now verify Docker Compose is also available by running:
docker compose version
Docker Compose returns its version, confirming that it is ready to orchestrate your services.
โ๏ธ I see a version number
You're all set. Docker and Docker Compose are both ready.
โง Command not found or error
Docker Compose isn't being recognised. Try these fixes:
- Make sure Docker Desktop is fully running (whale icon visible and not animating). Docker Compose is bundled with Docker Desktop and only works when it's active.
- Close your terminal window and open a new one. Docker registers its commands when it starts, but existing terminal sessions may not pick them up.
- If you previously installed the older standalone docker-compose (with a hyphen), note that this project uses the newer docker compose (with a space). Update Docker Desktop to the latest version to get it.
Still getting an error with docker compose?
โง Command not found
Docker is not available in your terminal. Try these fixes:
- Make sure Docker Desktop is fully running. Look for the whale icon in your menu bar at the top of the screen.
- Close your Terminal window and open a new one. Docker adds itself to your path when it starts, but existing terminal sessions may not pick this up.
- If it still does not work, restart Docker Desktop and try again.
Need more help getting Docker working?
Why Docker for this project?
In system design interviews, you draw boxes for "API Server", "Database", and "Cache". Docker lets you literally run those boxes on your machine as separate containers.
Why do we need Docker Compose?
Docker Compose is the configuration file that tells Docker to start these services and connect them together. In production, companies use Kubernetes for this, but the mental model is the same.
Install Cursor and open your project
This project involves multiple files across different languages:
- Python for the API
- YAML for Docker configuration
- A Dockerfile for the container setup.
Cursor gives you a file tree sidebar and syntax highlighting that make jumping between these files much easier than a basic text editor.
- Do you already have Cursor installed?
macOS
โ๏ธ Already installed
Great! Onwards we go!
โง Install Cursor
- Open your browser and go to cursor.com/en/downloads.
- Click Download for macOS.
- Double-click the downloaded .dmg file and drag Cursor to the Applications folder.
- Press Cmd+Space, type Cursor, and press Enter to open it.
Windows
โ๏ธ Already installed
Great. Open Cursor and skip to the instructions below for opening your project folder.
โง Install Cursor
- Open your browser and go to cursor.com/en/downloads.
- Click Download for Windows.
- Double-click the downloaded .exe file to run the installer.
- Follow the prompts and click Install to complete the setup.
- Press the Windows key, type Cursor, and press Enter to open it.
Linux
โ๏ธ Already installed
Great. Open Cursor and skip to the instructions below for opening your project folder.
โง Install Cursor
- Open your browser and go to cursor.com/en/downloads.
- Download the .deb file (Ubuntu/Debian) or .rpm file (Fedora/RHEL) for your system.
- Double-click the downloaded package to install it using your system's package manager, or install from the terminal.
- Open Cursor from your application menu or by typing cursor in your terminal.
First launch adds the update repository
When Cursor launches for the first time, it automatically adds its package repository to your system. Future updates will come through your normal package manager.
- Open Cursor by pressing Cmd+Space, typing Cursor, and pressing Enter.
Spotlight displays Cursor as the selected application, ready to open.
- Click File in the top menu bar.
- Click Open Folder.
The File menu shows **Open Folder**, which lets you load the project into Cursor.
- Navigate to your Desktop, select the url-shortener folder, then click Open.
How do I find the url-shortener folder?
In the Open Folder dialog, navigate to your Desktop using the sidebar. You should see the url-shortener folder listed there. If you do not see it, look for the Desktop shortcut in the left panel of the dialog.
You should now see the url-shortener folder open in Cursor's home page.
The Explorer sidebar shows the `url-shortener` directory with its `app` subfolder.
Don't see the app folder in Cursor?
- Make sure you opened the url-shortener folder, not the app folder inside it.
- If the Explorer sidebar is collapsed, click the file icon at the top of the left sidebar to expand it.
Need help setting up Cursor?
Great stuff!
Now we've got our project folder created and ready on Desktop, Docker sitting waiting for us, and Cursor open. Let's go!
Next up, you will create all the project files that define your multi-service architecture.
Create the Architecture
Create the Infrastructure
Your tools are installed and your project folder is open in Cursor. Now it's time to lay the foundation for your system.
In this step, you'll create the infrastructure files that define how your services are built, connected, and started. The application logic comes in the next step.
In this step, get ready to:
- Define the three-service architecture in a Docker Compose file.
- Create the container build recipe, Python dependencies, and database schema.
- Understand why PostgreSQL is the right storage choice for this system.
Create the Docker Compose file
The docker-compose.yml file is the blueprint for your entire system. It tells Docker Compose which services to run, how to connect them, and in what order to start them.
- Press Cmd+L (macOS) or Ctrl+L (Windows) to open Cursor's chat.
- Type Create a new empty file called docker-compose.yml in the root of the project and press Enter.
Cursor Chat shows the request to create the Docker Compose file at the top level of the project.
- Click Accept if Cursor prompts you to create the file.
The **Accept** button confirms Cursor is ready to create `docker-compose.yml`.
- Open the empty created file by clicking on docker-compose.yml.
What are we doing in this file?
In this file, you'll define three services that make up the URL shortener system: a Python API server, a PostgreSQL database for permanent storage, and a Redis cache for fast lookups.
The file also tells Docker Compose how the services connect to each other, what order to start them in, and how to confirm each one is healthy before the next one launches.
๐ก Why three seperate services?
This is separation of concerns. The API handles HTTP logic, PostgreSQL handles durable storage (data survives restarts), and Redis handles speed (in-memory lookups in microseconds vs. milliseconds for disk).
In a system design interview, interviewers want to hear you reason about WHY each exists, not just that they do. Each service can also scale independently.
- Paste the following code into the new file:
The empty `docker-compose.yml` file is open and ready for the service definitions.
services:
web:
build: ./app
ports:
- "5000:5000"
environment:
- REDIS_HOST=redis
- REDIS_PORT=6379
- POSTGRES_HOST=db
- POSTGRES_DB=urlshortener
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
db:
image: postgres:16-alpine
environment:
- POSTGRES_DB=urlshortener
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
volumes:
- postgres_data:/var/lib/postgresql/data
- ./app/init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:
What does this file do?
This file defines three services that work together:
- web is your Python API server. It builds from the ./app folder and exposes port 5000 on your machine.
- db is a PostgreSQL database that stores URL mappings permanently. The healthcheck uses pg_isready -U postgres to confirm it's accepting connections.
- redis is a Redis cache for fast lookups. Its healthcheck uses redis-cli ping to confirm it's ready.
The depends_on with condition: service_healthy ensures the database and cache are fully ready before the API server starts.
Tell me more about Docker Compose orchestration
- Save the file with Cmd+S.
- Confirm you see docker-compose.yml listed at the top level of the url-shortener folder in the Explorer sidebar.
The Explorer sidebar shows `docker-compose.yml` saved beside the `app` directory.
Don't see the file in the sidebar?
Make sure you created it at the root of url-shortener, not inside the app subfolder. If it's in the wrong place, right-click the file and select Delete, then recreate it by hovering over url-shortener at the top of the sidebar.
help me fix my docker-compose.yml file location
โ๏ธ Awesome, I've got everything!
Great. Make sure you've saved docker-compose.yml before moving on.
โง I'd like to double check the full code
Here is the complete docker-compose.yml for comparison:
services:
web:
build: ./app
ports:
- "5000:5000"
environment:
- REDIS_HOST=redis
- REDIS_PORT=6379
- POSTGRES_HOST=db
- POSTGRES_DB=urlshortener
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
db:
image: postgres:16-alpine
environment:
- POSTGRES_DB=urlshortener
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
volumes:
- postgres_data:/var/lib/postgresql/data
- ./app/init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:
Create the supporting files
Now you'll create three files inside the app folder. These define the Python dependencies, the container build recipe, and the database table.
First, the Python dependencies (file one out of three for the app).
- In Cursor's chat, type Create a new empty file called requirements.txt inside the app folder and press Enter.
Cursor Chat shows the request to create `requirements.txt` inside the `app` directory.
- Click Accept if prompted when Cursor creates the file.
- Open the new requirements.txt file.
- Paste the following code into the file:
flask==3.1.3
redis==5.3.1
psycopg2-binary==2.9.12
The file lists Flask, Redis, and PostgreSQL client packages with pinned versions.
What are these packages?
- flask is a lightweight Python web framework for handling HTTP requests.
- redis is the Python client library for talking to your Redis cache.
- psycopg2-binary is the Python client library for connecting to PostgreSQL.
๐ก What's requirements.txt in plain English?
This is a shopping list. Your app needs three tools to work, so this file tells Docker: "before you run anything, go grab these three things." Without it, your code would crash immediately because it wouldn't have the tools it needs.
- Save requirements.txt with Cmd+S (macOS) or Ctrl+S (Windows).
Next, the container build recipe (file two out of three for the app).
- In Cursor's chat, type Create a new empty file called Dockerfile inside the app folder and press Enter.
Cursor Chat shows the request to create a `Dockerfile` inside the `app` directory.
- Click Accept if Cursor prompts you to when creating the file.
- Paste the following code into the file:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
The `Dockerfile` now contains the recipe for building and starting the Python application container.
What does this Dockerfile do?
A Dockerfile is a recipe for building a container image. This one starts from a slim Python 3.12 base image, installs the packages from requirements.txt, copies your application code into the image, and runs app.py when the container starts.
๐ก What's a Dockerfile in plain English?
This is a recipe card for building a mini-computer. It says: start with a fresh computer that already has Python, install the shopping list, copy your code in, and run it. Every time Docker builds your app, it follows this recipe from the top.
- Save Dockerfile with Cmd+S (macOS) or Ctrl+S (Windows).
Third file in the app - the database table.
- In Cursor's chat, type Create a new empty file called init.sql inside the app folder and press Enter.
Cursor Chat shows the request to create `init.sql` inside the `app` directory.
- Paste the following code into the file:
CREATE TABLE IF NOT EXISTS urls (
id SERIAL PRIMARY KEY,
long_url TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The SQL creates the `urls` table with an ID, the original URL, and a creation timestamp.
What does this SQL do?
This creates the urls table with three columns: an auto-incrementing id (used to generate short codes), the original long_url, and a created_at timestamp.
Docker automatically runs this file when the PostgreSQL container starts for the first time because the compose file mounts it into /docker-entrypoint-initdb.d/.
๐ก What's init.sql in plain English?
This creates a spreadsheet for your database. The spreadsheet has three columns: a unique number, the original long URL, and the date it was saved. The database automatically runs this file the very first time it starts up, so the spreadsheet is ready before your app tries to use it.
๐ก Why PostgreSQL over a NoSQL database?
For a URL shortener, your data is highly structured (ID, URL, timestamp). A relational database gives you ACID transactions, meaning no duplicate short codes even under concurrent writes. It also gives you auto-incrementing IDs that feed directly into Base62 encoding.
This is a stronger interview answer than "I like SQL." You're choosing PostgreSQL because the data model fits relational storage and you need guaranteed uniqueness.
- Save init.sql with Cmd+S (macOS) or Ctrl+S (Windows).
Validate your compose file
Before moving on, let's make sure Docker can read your compose file without errors. This doesn't start any containers. It just checks that your YAML is correctly formed and all the references make sense.
- Open Cursor's built-in terminal by pressing Ctrl+` (macOS and Windows).
- Validate your compose file by running:
cd ~/Desktop/url-shortener
docker compose config
- Do you see a response?
- If everything is correct, Docker prints back your full compose configuration with all the defaults filled in.
- Look for your three services (web, db, redis) listed with their settings.
Seeing a YAML error?
YAML is very sensitive to spacing. The most common mistakes are mixing tabs with spaces, or having the wrong indentation level. Every nested item must be exactly two spaces deeper than its parent.
Copy and paste your docker-compose.yml from the double-check tab above to start fresh, then save and try again.
help me fix my docker-compose.yml YAML error
Your infrastructure is in place. You have the orchestration blueprint, the container recipe, the dependencies list, and the database schema. Next up, you'll write the actual application logic that ties it all together.
Build the URL Shortener Logic
Your infrastructure files are ready. You have a Docker Compose blueprint, a container recipe, a dependencies list, and a database schema. Now it's time to write the brain of the system.
In this step, you'll create app.py, the Python file that handles both jobs of a URL shortener: converting long URLs into short codes, and redirecting short codes back to the original URL.
In this step, get ready to:
- Build Job 1: the endpoint that takes a long URL and returns a short code.
- Build Job 2: the endpoint that takes a short code, finds the original URL, and redirects the visitor.
- Review how the services discover and connect to each other.
Create the application file
This is the largest and most important file in the project. It contains the Flask API server, the Base62 encoding logic, and the two main endpoints.
- In Cursor's chat, type Create a new empty file called app.py inside the app folder and press Enter.
- Open the new app.py file.
You'll build this file piece by piece. Job 1 (shortening) has three parts, then Job 2 (redirecting) has one.
Job 1: Turn a long URL into a short code
The first job is shortening. Someone sends a long URL, the app saves it to a database, and hands back a short code. The full flow looks like this:
Receive long URL โ store in database โ get a unique ID back โ encode that ID into a short code โ cache it โ return the short URL.
How does a database ID become a short URL?
When you save a URL to PostgreSQL, the database automatically assigns it a unique number. The first URL you store gets ID 1, the second gets ID 2, the third gets ID 3, and so on. This auto-incrementing number is the "database ID."
Your shortener takes that number and converts it into a short string using Base62 encoding. For example, ID 1 becomes 1, ID 62 becomes 10, ID 3844 becomes 100.
This means every short code maps back to exactly one database row. No collisions, no duplicates, no randomness to manage. The database does the hard work of guaranteeing uniqueness for you.
Set up the app and connections
The first chunk establishes the tools and connections the shortener needs: the Flask web server, a Redis cache for fast lookups, and a PostgreSQL connection for permanent storage.
- Paste this code into app.py:
import os
import string
from flask import Flask, request, redirect, jsonify
import redis
import psycopg2
app = Flask(__name__)
# Define the 62 characters used for short codes (0-9, a-z, A-Z)
ALPHABET = string.digits + string.ascii_lowercase + string.ascii_uppercase
# Connect to Redis for fast lookups
cache = redis.Redis(
host=os.environ.get("REDIS_HOST", "redis"),
port=int(os.environ.get("REDIS_PORT", 6379)),
decode_responses=True,
)
def get_db():
"""Connect to PostgreSQL for permanent storage."""
return psycopg2.connect(
host=os.environ.get("POSTGRES_HOST", "db"),
database=os.environ.get("POSTGRES_DB", "urlshortener"),
user=os.environ.get("POSTGRES_USER", "postgres"),
password=os.environ.get("POSTGRES_PASSWORD", "postgres"),
)
What does this code do?
This chunk connects your app to everything it needs: a web server to hear incoming requests, a fast cache for quick lookups, and a database for permanent storage.
- Flask is the web framework that listens for incoming requests (like "shorten this URL" or "redirect me").
- cache connects to Redis. Redis is an in-memory store that's extremely fast to read from. You'll use it as a shortcut so the app doesn't hit the database for every redirect.
- get_db() opens a connection to PostgreSQL. This is where URLs are permanently stored. Even if Redis restarts and loses its data, the database still has everything.
- ALPHABET defines the 62 characters (0-9, a-z, A-Z) that short codes are made of. This is the character set for Base62 encoding.
- Save app.py with Cmd+S (macOS) or Ctrl+S (Windows).
You won't see any output yet because the app isn't running. The next chunk adds the encoding logic that turns database IDs into short codes.
Build the Base62 encoder
Now you need the functions that convert between a number (the database ID) and a short string (the code that goes in the URL). These two functions are inverses of each other.
- Below the get_db() function, paste this code:
def base62_encode(num):
"""Convert a database ID into a short alphanumeric string."""
if num == 0:
return ALPHABET[0]
result = []
while num > 0:
num, remainder = divmod(num, 62)
result.append(ALPHABET[remainder])
return "".join(reversed(result))
def base62_decode(code):
"""Convert a short code back into the original database ID."""
num = 0
for char in code:
num = num * 62 + ALPHABET.index(char)
return num
What does this code do?
These two functions are a pair. One encodes, the other decodes:
- base62_encode() takes a number like 1 or 3844 and turns it into a short string like 1 or 100. It works like counting in base-62 instead of base-10.
- base62_decode() does the reverse. Given a short code like 100, it returns 3844. The redirect endpoint uses this to look up the original URL by its database ID.
๐ก Why Base62 and not something else?
You need short, URL-safe strings. Base62 uses only letters and digits (no special characters that break URLs). A 7-character code gives 62^7 = 3.5 trillion unique URLs.
- Save app.py with Cmd+S (macOS) or Ctrl+S (Windows).
You won't see any output yet because the app isn't running. Next, you'll build the endpoint that calls these functions to actually shorten a URL.
Wire up the /shorten endpoint
This is where the whole flow comes together. The endpoint receives a long URL, stores it, gets the database ID, encodes it, caches it, and returns the short URL.
- Below the base62_decode() function, paste this code:
@app.route("/shorten", methods=["POST"])
def shorten_url():
# Grab the long URL from the request body
data = request.get_json()
if not data or "url" not in data:
return jsonify({"error": "Missing url field"}), 400
long_url = data["url"]
# Save to PostgreSQL - the database assigns an auto-incrementing ID
conn = get_db()
cur = conn.cursor()
cur.execute("INSERT INTO urls (long_url) VALUES (%s) RETURNING id", (long_url,))
url_id = cur.fetchone()[0]
conn.commit()
cur.close()
conn.close()
# Encode the database ID into a short code
short_code = base62_encode(url_id)
# Cache the mapping for fast redirects later
cache.set(short_code, long_url)
return jsonify({"short_url": f"http://localhost:5000/{short_code}", "short_code": short_code}), 201
What does this code do?
This is the full shortening flow in action:
- RETURNING id is the key line. When PostgreSQL inserts the URL, it auto-assigns the next available ID (1, 2, 3...) and RETURNING id sends that number straight back to your code. This is where the database ID comes from.
- base62_encode(url_id) takes that number and converts it into a short code. If this is the first URL you've shortened, url_id is 1 and the short code is 1. The 100th URL gets a longer code.
- cache.set(short_code, long_url) stores the mapping in Redis so that when someone visits the short URL, the redirect is instant (no database query needed).
The endpoint returns a 201 status code (meaning "created") along with the short URL the caller can share.
- Save app.py with Cmd+S (macOS) or Ctrl+S (Windows).
Job 1 is complete. Your app can now accept a long URL and return a short code. Next, you'll add Job 2 so it can handle the reverse: someone visits a short code and gets sent to the original URL.
Job 2: Redirect a short code to the original URL
The second job is redirecting. Someone visits a short code, the app figures out which long URL it belongs to, and sends the person there.
- Below the shorten_url() function, paste this code:
@app.route("/<short_code>")
def redirect_url(short_code):
# Check the fast cache first
long_url = cache.get(short_code)
if long_url:
print("CACHE HIT", flush=True)
return redirect(long_url, code=302)
# Cache miss - fall back to the database
print("CACHE MISS - querying database", flush=True)
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT long_url FROM urls WHERE id = %s", (base62_decode(short_code),))
result = cur.fetchone()
cur.close()
conn.close()
if not result:
return jsonify({"error": "Short URL not found"}), 404
# Found it in the database - cache it for next time
long_url = result[0]
cache.set(short_code, long_url)
return redirect(long_url, code=302)
What does this code do?
When someone clicks a short link, the app needs to figure out which original URL it points to and send them there instantly. Speed matters here because redirects happen far more often than shortening.
This second chunk handles job two (redirecting):
- redirect_url() handles GET requests. It first checks Redis (fast), falls back to PostgreSQL (slower), caches the result for next time, and issues a 302 redirect.
The cache-first pattern is a core system design technique. Checking the fast cache first and only bothering the slower database on a miss keeps redirects snappy under load.
Add the health check and start the server
Two pieces are left: a /health endpoint that confirms the server is up, and the code that actually starts the server.
- Below the redirect_url() function, paste this code:
@app.route("/health")
def health():
return jsonify({"status": "healthy"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
What does this code do?
- health() returns a simple status response so you can verify the server is running.
- app.run() starts the web server and keeps it listening for requests. Without it, Python reaches the end of the file and exits, and your container stops.
- if __name__ == "__main__": runs app.run() only when Python starts this file directly, which is what the CMD line in your Dockerfile does.
- host="0.0.0.0" lets requests from outside the container reach Flask. Without it, Flask only listens inside the container.
- Save app.py with Cmd+S (macOS) or Ctrl+S (Windows).
- Check the Explorer sidebar. Your app folder should now contain four files: app.py, Dockerfile, init.sql, and requirements.txt.
Missing app.py in the sidebar?
Make sure you created it inside the app folder, not at the root of url-shortener. If it's in the wrong place, right-click the file, select Delete, and recreate it inside app.
help me fix my app.py file location
โ๏ธ Awesome, I've got everything!
Great. Make sure app.py is saved and you can see all four files in the app folder.
โง I'd like to double check the full code
Here is the complete app.py for comparison:
import os
import string
from flask import Flask, request, redirect, jsonify
import redis
import psycopg2
app = Flask(__name__)
# Define the 62 characters used for short codes (0-9, a-z, A-Z)
ALPHABET = string.digits + string.ascii_lowercase + string.ascii_uppercase
# Connect to Redis for fast lookups
cache = redis.Redis(
host=os.environ.get("REDIS_HOST", "redis"),
port=int(os.environ.get("REDIS_PORT", 6379)),
decode_responses=True,
)
def get_db():
"""Connect to PostgreSQL for permanent storage."""
return psycopg2.connect(
host=os.environ.get("POSTGRES_HOST", "db"),
database=os.environ.get("POSTGRES_DB", "urlshortener"),
user=os.environ.get("POSTGRES_USER", "postgres"),
password=os.environ.get("POSTGRES_PASSWORD", "postgres"),
)
def base62_encode(num):
"""Convert a database ID into a short alphanumeric string."""
if num == 0:
return ALPHABET[0]
result = []
while num > 0:
num, remainder = divmod(num, 62)
result.append(ALPHABET[remainder])
return "".join(reversed(result))
def base62_decode(code):
"""Convert a short code back into the original database ID."""
num = 0
for char in code:
num = num * 62 + ALPHABET.index(char)
return num
@app.route("/shorten", methods=["POST"])
def shorten_url():
# Grab the long URL from the request body
data = request.get_json()
if not data or "url" not in data:
return jsonify({"error": "Missing url field"}), 400
long_url = data["url"]
# Save to PostgreSQL - the database assigns an auto-incrementing ID
conn = get_db()
cur = conn.cursor()
cur.execute("INSERT INTO urls (long_url) VALUES (%s) RETURNING id", (long_url,))
url_id = cur.fetchone()[0]
conn.commit()
cur.close()
conn.close()
# Encode the database ID into a short code
short_code = base62_encode(url_id)
# Cache the mapping for fast redirects later
cache.set(short_code, long_url)
return jsonify({"short_url": f"http://localhost:5000/{short_code}", "short_code": short_code}), 201
@app.route("/<short_code>")
def redirect_url(short_code):
# Check the fast cache first
long_url = cache.get(short_code)
if long_url:
print("CACHE HIT", flush=True)
return redirect(long_url, code=302)
# Cache miss - fall back to the database
print("CACHE MISS - querying database", flush=True)
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT long_url FROM urls WHERE id = %s", (base62_decode(short_code),))
result = cur.fetchone()
cur.close()
conn.close()
if not result:
return jsonify({"error": "Short URL not found"}), 404
# Found it in the database - cache it for next time
long_url = result[0]
cache.set(short_code, long_url)
return redirect(long_url, code=302)
@app.route("/health")
def health():
return jsonify({"status": "healthy"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
Try running your health check
You just wrote a health() function that should reply when someone visits /health. Let's see what happens if you try to visit it right now.
On a Mac? Free up port 5000 first
macOS uses port 5000 for AirPlay Receiver, the same port your app needs. If it's on, your requests reach AirPlay instead of your app, and Docker Compose can fail later with an address already in use error.
- Open System Settings > General > AirDrop & Handoff.
- Turn off AirPlay Receiver.
You can turn it back on when you finish this project.
help me free up port 5000 on my Mac
- Try reaching your health check page by running:
curl http://localhost:5000/health
- You should see Connection refused.
- Your app.py exists as a file on your computer, but nobody is actually running it yet. It's like having a recipe written down but the kitchen is closed.
This is exactly why you need Docker Compose. In the next step, it will read your files, build containers, and start your app so it's actually listening for visitors.
Review how the services connect
You now have five files that make up your entire app. Woohoo!
But here's a question: your Python code connects to a database called db and a cache called redis. How does it actually find them?
The answer is Docker Compose.
- When you start the app, Docker Compose puts all three containers on the same private network: your Flask API (named web in the compose file), the PostgreSQL database (named db), and the Redis cache (named redis).
- On that network, each container is reachable by its name. So when your Flask code says "connect to redis", Docker knows exactly which container to route that to. No IP addresses, no configuration files. Just names.
How does service discovery work?
In production systems, services use DNS-based service discovery to find each other. Docker Compose gives you the same pattern locally for free. The service names in your compose file (web, db, redis) become hostnames on the private network.
This is the same concept as DNS-based service discovery in Kubernetes. The mental model you're building here transfers directly to production infrastructure discussions in interviews.
๐ก Why Base62 encoding for short codes?
You need short, URL-safe strings. Base62 uses [0-9, a-z, A-Z] giving 62 characters. A 7-character code gives 62^7 = 3.5 trillion unique URLs.
Compare alternatives: MD5 hashing requires collision detection. UUIDs are too long. Base62 on an auto-increment ID is simple and guarantees uniqueness because each database ID maps to exactly one short code.
Your architecture is fully defined. All five files are in place and ready to run. Next, you'll start all three services with a single command and see them come alive.
Launch and Verify
Your architecture is fully defined in code. You have a Flask API, a PostgreSQL database, and a Redis cache described across five files. Now it's time to turn those definitions into running services.
In this step, you'll use Docker Compose to build your Flask image, pull the database and cache images, and start everything in one command. Then you'll verify that all three services are healthy and talking to each other.
In this step, get ready to:
- Start all three containers with a single Docker Compose command.
- Confirm the Flask API responds to a health check.
- Verify PostgreSQL and Redis are connected through their logs.
Build and start all services
You already validated this file in the previous step, so you know it's correct. Now Docker Compose will actually build and run everything: your Flask image, the PostgreSQL and Redis images, the private network, and all three containers.
- In Cursor's terminal (still open from the previous step), make sure you're in the url-shortener folder by running:
cd ~/Desktop/url-shortener
- Build and start all three services (your Flask API, the PostgreSQL database, and the Redis cache) by running:
docker compose up --build -d
This launches your Flask API (for handling incoming requests), PostgreSQL (stores URLs permanently), and Redis (speeds up redirects with a fast cache):
What does this command do?
- docker compose up reads your docker-compose.yml and starts all defined services.
- --build forces Docker to build your Flask image from the Dockerfile instead of using a cached version.
- -d runs everything in detached mode, so your terminal stays free for other commands.
The first run takes 1-2 minutes as Docker downloads the PostgreSQL and Redis images.
โ๏ธ All containers started successfully
You should see all three containers created and healthy with no errors. Move on to the next section.
โง "the Dockerfile cannot be empty"
This means your Dockerfile inside the app folder was created but never saved with content. You likely pasted the code but forgot to press Cmd+S (macOS) or Ctrl+S (Windows).
Go back to app/Dockerfile in Cursor, paste the Dockerfile content from Step 2 (check the double-check tab if you need it), save the file, then re-run:
docker compose up --build -d
help me fix my empty Dockerfile error
โง "address already in use" on port 5000
This means another app on your machine is already using port 5000. On macOS, AirPlay Receiver commonly occupies this port.
To find and stop whatever is using port 5000, run:
lsof -i :5000
This shows the process using port 5000. Note the PID (process ID) number in the output, then kill it:
kill -9 [[PROCESS_ID="the PID number from the lsof output above"]]
On macOS, you can also disable AirPlay Receiver:
- Open System Settings > General > AirDrop & Handoff
- Turn off AirPlay Receiver.
Once the port is free, re-run:
docker compose up --build -d
help me fix my port 5000 conflict
- Check the status of all containers by running:
docker compose ps
You should see three services listed: web, db, and redis. All three should show a status of running.
โ๏ธ I see all three services running
All three containers are healthy. Move on to the next section.
โง I only see db and redis (web is missing or Exited)
Your Flask container likely started with an empty or unsaved app.py. Run this to confirm:
docker compose ps -a
If you see web with a status of Exited (0) and no output from docker compose logs web, it means Python ran the file but found nothing to execute. The file was empty when Docker built the image.
To fix this:
- Open app.py in Cursor and confirm it has all the code from this step (check the double-check tab in the previous step if needed).
- Look for a dot on the app.py tab in Cursor. A dot means unsaved changes. Press Cmd+S (macOS) or Ctrl+S (Windows).
- Rebuild the container by running:
docker compose up --build -d
- Verify all three are running by running:
docker compose ps
You should now see web, db, and redis all showing a status of Up.
help me fix my web container that keeps exiting
Test the health endpoint
In the last step, you tried visiting /health and got Connection refused. Now that Docker Compose has started your containers, let's try the same command again. This time, your app is actually running.
- View the Flask web server logs by running:
docker compose logs web
- You should see Flask reporting that it started on port 5000.
- Test the health endpoint by running:
curl http://localhost:5000/health
- You should see this response:
{"status":"healthy"}
Seeing a connection refused error?
PostgreSQL may still be initializing. Wait 10 seconds and run the curl command again. The depends_on health checks in your docker-compose.yml ensure the database is ready before Flask starts, but network timing can vary.
If it still fails after 30 seconds, run docker compose down and then docker compose up --build -d to restart everything cleanly.
Need more help? Help me fix a connection refused error on localhost:5000.
Verify database and cache connections
The health endpoint confirms Flask (the app) is running, but you also want to verify that PostgreSQL and Redis themselves started correctly. Their logs tell you the full story.
- Check the PostgreSQL logs by running:
docker compose logs db
- Scroll through the response and read carefully.
- You should see a message confirming Success. You can now start the database server using:
- Check the Redis logs by running:
docker compose logs redis
- Scroll through the response, reading carefully.
- You should see a message confirming Ready to accept connections.
Why health checks matter in production
In production, load balancers use health endpoints to decide which servers can receive traffic. If a server's database connection dies, it reports unhealthy and stops receiving requests.
This is how systems achieve high availability. Your docker-compose.yml uses the same pattern with its healthcheck blocks. Docker waits for pg_isready and redis-cli ping to succeed before declaring the services healthy.
๐โโ๏ธ Logs showing errors?
- If PostgreSQL shows permission errors, make sure Docker Desktop has file sharing enabled for your project directory.
- If Redis shows a port conflict, another Redis instance may be running on your machine. Stop it or change the port in docker-compose.yml.
Need help reading Docker logs? Help me understand what these Docker logs mean.
All three services are running and verified. Your distributed system is live on your machine. Next up, you'll create short URLs, test redirects, and watch the cache-aside pattern in action.
Test and Observe the System
Your services are running and connected. Now it's time to actually use your URL shortener and watch the system design concepts come to life.
In this step, you will create short URLs, test how redirects work, and observe the caching layer in real time. These are the exact scenarios interviewers expect you to walk through on a whiteboard.
In this step, get ready to:
- Create short URLs via the API and observe Base62-encoded short codes.
- Test URL redirection and observe HTTP status codes.
- Flush the cache and watch the cache-aside pattern in action.
Create a short URL
Your API server is listening on port 5000 and ready to accept requests. The /shorten endpoint accepts a JSON body with a url field and returns a short code.
- Create your first short URL by running this command:
curl -X POST http://localhost:5000/shorten -H "Content-Type: application/json" -d '{"url": "https://www.google.com"}'
- You should see a JSON response containing a short_url and short_code field. The first URL you create gets the short code 1.
What does this response mean?
Your URL was saved to PostgreSQL, which gave it ID 1 (the first entry in the database). The short code is just that ID converted into a URL-safe string. For small numbers like 1, 2, or 9, the code looks the same as the number.
Once you hit ID 10, letters start appearing (a, b, c...) because Base62 uses digits plus lowercase and uppercase letters. The app also cached the mapping in Redis so future lookups skip the database entirely.
โ๏ธ I see a JSON response with short_url and short_code
Woohoo! Your URL shortener is working.
Continue onwards!
โง I see a 500 Internal Server Error
This means Flask is running but the urls table doesn't exist in PostgreSQL. Confirm by checking the logs:
docker compose logs web
Look for relation "urls" does not exist in the output. This happens when your containers started before init.sql was saved correctly. PostgreSQL only runs init scripts on the first volume creation.
Fix it by running these two commands separately (press Enter after the first one finishes):
docker compose down -v
docker compose up --build -d
The -v flag removes the database volume, forcing PostgreSQL to re-initialize and run your init.sql. After both commands finish, retry the curl command above.
Help me fix my 500 Internal Server Error on /shorten
โง I see Connection refused
Your containers may not be running. Run docker compose ps to check. If the web container shows Exited or is missing, go back to the previous step and follow the troubleshooting there.
If all containers show running, PostgreSQL may still be initializing. Wait 10 seconds and try the curl command again.
Help me debug my curl connection error
- Create a second short URL with a different address to see the codes increment:
curl -X POST http://localhost:5000/shorten -H "Content-Type: application/json" -d '{"url": "https://github.com"}'
- This time the response should show short code 2. Can you see it?
- Each new URL gets the next ID from PostgreSQL, producing a unique short code every time.
Why POST for creation and GET for redirect?
POST creates a new resource (the short URL mapping). GET retrieves or redirects. This is REST API design.
๐ก Top interview tip!
Interviewers expect you to choose the right HTTP verbs and explain why. Using POST for writes and GET for reads is the foundation of RESTful design.
Visit your short URL
You created a short URL. Now let's see what happens when someone visits it. Does it actually send them to Google?
- Check where your short URL redirects to by running:
curl -I http://localhost:5000/1
What does the "I" do in that command?
The -I flag tells curl to show the server's reply without actually following the redirect. Look for two lines in the output:
Look in the response - can you see the following?
- HTTP/1.1 302 FOUND โ this means "go somewhere else." The server is telling the browser to redirect.
- Location: https://www.google.com โ this is where it sends them. The original URL you shortened.
- Check your app's logs to see how it handled that request:
docker compose logs web --tail 5
- Look for CACHE HIT in the output. The app found the URL in Redis and never touched the database.
Why 302 instead of 301?
Both 302 and 301 mean "redirect." The difference is that 301 means permanent. The browser remembers it and never contacts your server again for that link.
With 302 (temporary), every click goes through your server. This lets you count how many times each link was clicked. The trade-off: 301 is faster for users but you lose analytics. Interviewers love asking about this.
๐โโ๏ธ Seeing a 404 Not Found?
The path /1 only works after you've created at least one short URL. Make sure the POST command from the previous substep returned a successful response first.
If you ran docker compose down at any point, the database was wiped. Re-run the POST command to create a new entry, then try this curl again.
Help me figure out why my redirect is returning 404
Observe caching in action
You just saw CACHE HIT in the logs. The app found the URL in Redis (which stores data in memory) and skipped PostgreSQL (which reads from disk). At scale, a URL shortener handles millions of redirects per day. If every single one queried the database, the database would collapse under the load.
Caching keeps the fast path fast. But what happens when the cache doesn't have the answer? Let's force a cache miss and watch the app fall back to the database.
- Flush all data from Redis by running this command:
docker compose exec redis redis-cli FLUSHALL
- You should see OK printed in your terminal. Redis is now empty.
- Prove the cache is empty by asking Redis for your short code's key:
docker compose exec redis redis-cli GET 1
- You should see (nil). Redis no longer knows what short code 1 maps to.
- Access the same short URL again to trigger a cache miss:
curl -I http://localhost:5000/1
You still get a 302 FOUND redirect. The user experience is identical. But the logs tell a different story this time.
- Check the logs again:
docker compose logs web --tail 5
- This time you see CACHE MISS - querying database. The app looked in Redis, found nothing, and had to query PostgreSQL instead.
- Now check Redis again for the same key:
docker compose exec redis redis-cli GET 1
Do you remember earlier, when Redis returned (nil) for this key?
Now you see https://www.google.com!
The app queried PostgreSQL after the cache miss, served the redirect, and stored the result back in Redis for next time. That's the cache-aside pattern in action.
What is the cache-aside pattern?
Cache-aside means the app is responsible for managing what goes into the cache. When someone visits a short URL, the app checks Redis first. If Redis doesn't have the answer, the app queries PostgreSQL and saves the result into Redis so the next request is faster.
The alternative is "write-through," where the app writes to both the cache and database at the same time. Cache-aside is simpler to build but the cache can get out of date. Write-through keeps things in sync but slows down every write. Interviewers love asking about this trade-off.
๐โโ๏ธ FLUSHALL command not working?
Make sure the Redis container is still running. Run docker compose ps and confirm the redis service shows a healthy status.
Help me troubleshoot my Redis FLUSHALL command
Secret mission
Add Rate Limiting
Your URL shortener works, but what stops someone from flooding it with thousands of requests? In this secret mission, you'll add a Redis-based rate limiter that blocks abusive clients. This is the exact follow-up question interviewers ask after you design a URL shortener.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely on your local machine using Docker. There are no cloud services or ongoing costs to worry about.
Decide whether to keep your resources running, pause them to come back later, or delete them entirely.
Resources you used:
- Docker containers (web, db, redis) running locally.
- Docker volume (postgres_data) storing your database on disk.
- Docker images cached locally (approximately 500MB total disk space).
- The url-shortener project folder on your machine.
Keep everything running
No action needed. Choose this if you are still actively building or experimenting with your URL shortener.
- Leave Docker Desktop running. Your URL shortener stays available at localhost:5000.
- Your containers, database volume, and project files remain intact.
- Docker Desktop uses some system memory while running, but there is no financial cost.
Pause - I'll come back to this later
Shut down your running containers to free up memory, but keep all your data and project files for next time.
- In Terminal, make sure you are in your url-shortener folder.
- Stop the containers by running:
docker compose stop
This pauses all three containers without deleting your database data or cached URLs.
- When you are ready to resume, navigate back to the url-shortener folder and run:
docker compose start
Your URL shortener will be available again at localhost:5000 with all your previous short URLs intact.
Delete - I don't want to use this again
Remove all project resources completely and reclaim your disk space.
- In Terminal, make sure you are in your url-shortener folder.
- Remove the containers and the database volume by running:
docker compose down -v
This removes all three containers and deletes the postgres_data volume. All your stored short URLs are permanently gone.
- Reclaim disk space used by downloaded Docker images by running:
docker system prune
Docker will ask you to confirm. Type y and press Enter to proceed. This removes stopped containers, unused networks, dangling images, and the build cache.
- Finally, delete the project folder. Navigate to the parent directory that contains your url-shortener folder, then run:
cd ..
rm -rf url-shortener
Windows users
Replace the rm -rf command with:
rmdir /s /q url-shortener
Nice Work!
Nice Work!
Nice work! You just built a fully functional URL shortener backed by three interconnected services, all running on your own machine.
You've learned how to:
- Build a multi-service distributed system with a Python API, PostgreSQL database, and Redis cache that shortens URLs and redirects users.
- Apply the cache-aside pattern and explain 301 vs 302 redirect trade-offs the way interviewers expect.
- Use Docker Compose to orchestrate containers with health checks, networking, and startup dependencies.
- Secret Mission: Implemented Redis-based rate limiting with atomic counters and TTL expiration to prevent API abuse.
Ready to quiz yourself?