Skip to content

About

Load-tested URL shortener: FastAPI + PostgreSQL + Redis + Kafka, with Snowflake IDs, cached redirects and batched click analytics.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

10 Commits

Folders and files

Repository files navigation

URL Shortener

A URL shortener built as a load-testing exercise: start with the obvious FastAPI + PostgreSQL implementation, measure where it breaks under k6, then fix each bottleneck and measure again. A single API process serves ~875 RPS at a 100 ms median and 177 ms P95, and throughput grows by adding replicas.

POST /api/shorten returns a Base62-encoded Snowflake ID; GET /{code} redirects from Redis in under a millisecond; clicks fan out through an in-memory queue into Kafka and are folded back into PostgreSQL by a worker that commits offsets idempotently.

Architecture

                    client
                      │
                      ▼
                ┌───────────┐
                │   nginx   │  static frontend + reverse proxy
                └─────┬─────┘
                      │
              ┌───────▼────────┐        hit ──────────────► 302 (no DB, no Kafka)
              │    FastAPI     │
              └───┬────────┬───┘
        miss      │        │  enqueue (never blocks)
          ┌───────▼──┐  ┌──▼──────────────┐
          │  Redis   │  │ asyncio.Queue   │
          └───────┬──┘  └──┬──────────────┘
                  │        │ drain loop, 100 ms batches
          ┌───────▼──┐  ┌──▼──────────────┐
          │ Postgres │◄─│ Kafka consumer  │  aggregates clicks per code
          └──────────┘  └─────────────────┘  commits offsets + counts atomically

Design decisions

  • Snowflake IDs, not hashes. 41-bit timestamp + 10-bit machine ID + 12-bit sequence gives roughly 4M IDs per second per node with no coordination and no collision retry loop. INSTANCE_ID is what keeps replicas apart; a clock that moves backwards raises instead of silently handing out duplicates.
  • Base62 of the ID. Dense, URL-safe, and reversible — the ID is the sort key, so insert order and time order match.
  • A pool that waits instead of failing. redis-py caps its default connection pool at 100 and raises MaxConnectionsError past it — under load that turned cache hits into PostgreSQL reads. The pool is sized explicitly and callers queue briefly for a connection, so a burst slows down instead of losing the cache.
  • Cache-first redirects. A hit is one Redis GET and a 302; the row is only read from PostgreSQL on a miss, then cached for an hour.
  • Analytics must never slow down a redirect. Click events go into a bounded asyncio.Queue (put_nowait, no await) and a background loop drains them to Kafka in batches every 100 ms. If the queue is full, events are dropped — a dropped click is cheaper than a slow redirect.
  • Idempotent consumption. The worker batches per partition, aggregates counts, locks a consumer_offsets row with SELECT ... FOR UPDATE, skips batches at or below the stored offset, then commits counts and offset in one transaction before committing the Kafka offset. Replays after a crash are no-ops.

Measured performance

GET /{code} through nginx against a cache-warm stack: k6, 30 s per run, three runs per level, median reported. One API replica on a 12-core Docker Desktop host, seven containers on the same machine as the load generator.

Load Throughput Median P95
50 VUs 882 RPS 50 ms 113 ms
100 VUs 875 RPS 100 ms 177 ms

Each request is one Redis GET and a non-blocking enqueue, so what saturates is the API process itself: a single uvicorn worker pins a core. Past that the process is the queue, so latency climbs while throughput holds — the signal to add replicas.

Add replicas for more throughput:

docker compose up -d --scale api=3

nginx re-resolves api through Docker DNS (resolver 127.0.0.11, plus resolve on an upstream that keeps connections alive), so replicas can be added or replaced without restarting the proxy.

Quick start

Requires Docker and Docker Compose.

docker compose up --build

Then open http://localhost for the web form, or use the API directly:

# shorten
curl -X POST http://localhost/api/shorten \
  -H 'Content-Type: application/json' \
  -d '{"url": "https://example.com/some/long/path"}'
# {"short_code":"Ab3xY9zQ1","short_url":"http://localhost/Ab3xY9zQ1"}

# follow it (302)
curl -i http://localhost/Ab3xY9zQ1

# health
curl http://localhost/api/shorten -o /dev/null -w '%{http_code}\n'   # 405 on GET
curl http://localhost/health

Services and ports: nginx 80, API 8000 (published, so localhost:8000 works directly), PostgreSQL 5432, Redis 6379, Kafka 9094 (host listener). docker compose up --scale api=3 runs three API replicas; nginx re-resolves the api service name through Docker's DNS every 10 seconds, so a recreated API container is picked up instead of leaving nginx pointed at a dead address.

API

Method Path Body / Params Response
POST /api/shorten {"url": "https://..."} 200 {"short_code", "short_url"}
GET /{short_code} 1–12 alphanumeric chars 302 to the target, 400 malformed, 404 unknown
GET /health — 200 {"status": "ok"}

Configuration

All settings come from environment variables (see app/config.py); the Compose file supplies development defaults.

Variable Default Purpose
DATABASE_URL postgresql://admin:admin@postgres:5432/url_db PostgreSQL DSN (asyncpg is derived from it)
REDIS_HOST / REDIS_PORT redis / 6379 Redirect cache
KAFKA_BOOTSTRAP_SERVERS kafka:9092 Analytics broker
KAFKA_TOPIC_ANALYTICS url_clicks Click event topic
BASE_URL http://localhost:8000 Prefix used in the returned short_url
INSTANCE_ID 1 Snowflake machine ID (0–1023), must differ per replica

The credentials in docker-compose.yml are for local development only.

Project layout

app/
  main.py            FastAPI app: /health, /api/shorten, /{short_code}
  id_generator.py    Snowflake ID generator (thread-safe, clock-regression guard)
  base62.py          ID → short code
  cache.py           async Redis client
  db.py              async engine for the API, sync engine for the worker
  models.py          URLs and consumer_offsets tables
  analytics.py       bounded queue + 100 ms Kafka drain loop
  worker.py          Kafka consumer: aggregate clicks, idempotent offset commit
frontend/index.html  single-page form
nginx.conf           static files + proxy to the API
init.sql             schema and indexes (also created by SQLAlchemy on startup)
k6/                  load tests (via nginx, and direct to the API)
tests/               unit and integration scripts

Tests

Unit tests need no services:

python tests/test_logic.py               # 100k IDs: uniqueness + ordering
python tests/test_snowflake_overflow.py  # sequence rollover under load

Integration scripts expect the stack from docker compose up to be running. The smoke, redirection and cache scripts were run against a clean docker compose up -d and all three pass; click events written through Kafka reach PostgreSQL as click_count.

python tests/smoke_test.py            # shorten + follow a redirect
python tests/test_redirection.py      # cache miss → 302 → row present
python tests/test_cache_behavior.py   # cold vs warm cache (restarts Redis)
python tests/test_concurrent.py       # 100 concurrent writes
python tests/spike_test.py            # burst of concurrent writes
python tests/stress_master.py         # input validation and edge cases

Load tests (k6, 500 VUs for 30 s):

k6 run k6/load_test.js     # through nginx on :80
k6 run k6/direct_test.js   # straight to the API on :8001

Known limitations

  • Single-node PostgreSQL, Redis and Kafka; the --scale api=3 path shares them, so the datastores are the next bottleneck, not the API.

  • Analytics are best-effort: events are dropped when the queue is full or Kafka is unreachable, by design.

  • No custom aliases, expiry, or per-user ownership yet — every code is generated.

  • requirements.txt is unpinned, so a fresh build resolves the newest releases. That is not hypothetical: SQLAlchemy 2.1 moved the default postgresql:// DBAPI from psycopg2 to psycopg v3 and the API would not start, so app/db.py now names the driver explicitly for the sync and async engines.

  • One API replica (a single uvicorn process) saturates around 1,000–1,300 RPS on a 12-core host; throughput scales with --scale api=N, and the nginx configuration supports replicas without pinning an address.

License

MIT — see LICENSE.

About

Load-tested URL shortener: FastAPI + PostgreSQL + Redis + Kafka, with Snowflake IDs, cached redirects and batched click analytics.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages