A small URL shortener built with FastAPI, PostgreSQL, Redis, and Snowflake IDs.
-
Start Postgres and Redis:
docker compose up -d
-
Create
.env.localwith the required settings:ENV=local DATABASE_URL=postgresql+asyncpg://usr:pass@localhost:5432/urlshortener REDIS_HOST=localhost REDIS_PORT=6379 -
Install dependencies and run:
pip install -r requirements.txt python run.py
The server runs at
http://localhost:8001.
curl -X POST http://localhost:8001/shorten \
-H "Content-Type: application/json" \
-d '{"url": "https://github.com"}'Returns a short code (or the existing code if the URL was already shortened).
GET /{code} responds with a 302 redirect to the original URL, or 404 if the code doesn't exist.
POST /shortengenerates a Snowflake ID, encodes it in base62, stores it in PostgreSQL, and caches it in Redis (1h TTL).GET /{code}checks Redis first, then the DB (with a Redis lock to avoid cache stampedes), then redirects.- Rate limiting (SlowAPI, fixed-window): 5 requests/sec on GET, 1 request/sec on POST, keyed by client IP.
FastAPI · SQLAlchemy (async) · PostgreSQL · Redis · SlowAPI · Snowflake IDs