Skip to content

Repository files navigation

URL Shortener

A small URL shortener built with FastAPI, PostgreSQL, Redis, and Snowflake IDs.

Quick start

  1. Start Postgres and Redis:

    docker compose up -d
  2. Create .env.local with the required settings:

    ENV=local
    DATABASE_URL=postgresql+asyncpg://usr:pass@localhost:5432/urlshortener
    REDIS_HOST=localhost
    REDIS_PORT=6379
    
  3. Install dependencies and run:

    pip install -r requirements.txt
    python run.py

    The server runs at http://localhost:8001.

API

Create a short URL

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).

Resolve a short URL

GET /{code} responds with a 302 redirect to the original URL, or 404 if the code doesn't exist.

How it works

  • POST /shorten generates 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.

Stack

FastAPI · SQLAlchemy (async) · PostgreSQL · Redis · SlowAPI · Snowflake IDs

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages