Skip to main content

Overview

The Short-URL API requires configuration for database connections, CORS policies, authentication, and performance optimization. This guide covers all configuration aspects for deploying the API in development and production environments.

MongoDB Configuration

Database Connection

The API uses MongoDB as its primary database with Motor (async driver). Configure the connection using the MONGO_URI environment variable:
MONGO_URI=mongodb://localhost:27017
For production deployments, use MongoDB Atlas or a self-hosted MongoDB instance:
MONGO_URI=mongodb+srv://username:[email protected]/?retryWrites=true&w=majority
The application connects to MongoDB during the FastAPI lifespan event and automatically creates required database indexes.

Database Structure

The API uses a database named ShortURL with two collections:
URLMap
collection
Stores URL mappings with short codes, passwords, and target URLs
  • Index: url_code (unique)
  • Documents: url_code, url_pass (hashed), url, _id
URLStats
collection
Tracks URL statistics and state
  • Index: url_code (unique)
  • Documents: url_code, url_hits, url_created_at, url_state

Automatic Index Creation

Indexes are created automatically on application startup (see main.py:26-27):
await app.URLMap.create_index("url_code", unique=True)
await app.URLStats.create_index("url_code", unique=True)
Ensure your MongoDB user has permissions to create indexes, especially in production environments.

CORS Configuration

The API includes CORS middleware to control cross-origin requests.

Allowed Origins

Configure allowed origins using the ALLOWED_ORIGINS environment variable:
# Allow all origins (development only)
ALLOWED_ORIGINS=*
The ALLOWED_ORIGINS variable accepts a comma-separated list of domains. If not set, it defaults to * (allow all).

CORS Settings

The API is configured with the following CORS settings (see main.py:35-41):
  • allow_credentials: true - Allows cookies and authentication headers
  • allow_methods: ["*"] - Allows all HTTP methods
  • allow_headers: ["*"] - Allows all headers
For production deployments, never use ALLOWED_ORIGINS=*. Always specify exact domain origins to prevent unauthorized access.

Server Startup

Uvicorn Configuration

Run the API using Uvicorn with recommended production settings:
uvicorn main:app --reload --host 0.0.0.0 --port 8000

Worker Processes

For production deployments, use multiple workers based on CPU cores:
# Formula: (2 x CPU cores) + 1
uvicorn main:app --workers 4 --host 0.0.0.0 --port 8000
Use --workers 1 during development to simplify debugging. Increase workers in production for better concurrency.

Health Check Endpoint

The API provides a health check endpoint at /health for monitoring database connectivity.

Usage

The health check pings the MongoDB database and returns status:
curl http://localhost:8000/health
Success Response:
{
  "message": "Database is active"
}
Failure Response:
{
  "detail": "Database connection failed: <error message>"
}
Integrate the /health endpoint with your monitoring tools, load balancers, or orchestration platforms (Kubernetes, Docker Swarm) for automated health checks.

Production Deployment Considerations

Security Checklist

  • Store all secrets in environment variables, never in code
  • Use a secret management service (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault)
  • Rotate SECRET_KEY periodically
  • Never commit .env files to version control
  • Set ALLOWED_ORIGINS to specific domains only
  • Remove wildcard (*) origins in production
  • Use HTTPS for all allowed origins
  • Verify CORS settings before deployment
  • Use strong MongoDB authentication credentials
  • Enable MongoDB encryption at rest and in transit
  • Use connection string with SSL/TLS (ssl=true parameter)
  • Restrict database user permissions (no admin access)
  • Enable MongoDB IP whitelist for your application servers
  • Configure URL_BLACKLIST to prevent malicious domains
  • Include known phishing domains, malware sites, and spam sources
  • Update the blacklist regularly
  • Monitor for abuse patterns

Performance Tuning

1. Database Optimization

Connection Pooling
optimization
Motor (AsyncIOMotorClient) uses connection pooling by default. For high-traffic deployments, configure pool size:
MONGO_URI=mongodb://localhost:27017/?maxPoolSize=50&minPoolSize=10
Database Indexes
optimization
Indexes on url_code are created automatically. Monitor index performance:
// MongoDB shell
db.URLMap.getIndexes()
db.URLStats.getIndexes()

2. Background Tasks

The API uses FastAPI’s BackgroundTasks for non-blocking hit tracking (see main.py:238):
background_tasks.add_task(update_hits_sync, url_code)
Hit counting runs in the background to avoid blocking redirect responses. This improves redirect latency significantly.

3. Async Operations

All database operations use async/await for optimal concurrency:
entry = await app.URLMap.find_one({"url_code": url_code})
await app.URLStats.update_one({"url_code": url_code}, {"$inc": {"url_hits": 1}})
Async operations allow the API to handle thousands of concurrent requests without blocking.

Monitoring and Logging

  • Monitor /health endpoint status
  • Track response times for redirect endpoint (/{url_code})
  • Monitor database connection pool usage
  • Set up alerts for 4xx/5xx error rates
  • Track MongoDB query performance

Logging Configuration

Uvicorn provides access logs by default. For production, configure structured logging:
uvicorn main:app --log-config logging.json --access-log

Deployment Platforms

Docker Deployment

Example Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Cloud Platforms

The API is compatible with:
  • AWS: Elastic Beanstalk, ECS, Lambda (with Mangum)
  • Google Cloud: Cloud Run, App Engine, GKE
  • Azure: App Service, Container Instances, AKS
  • Heroku: Direct deployment with Procfile
  • Railway: One-click deployment
For serverless deployments (AWS Lambda), use Mangum adapter to wrap the FastAPI app.

Base URL Configuration

Set the base URL for generated short links using SURL_BASE:
SURL_BASE=https://short.example.com
This affects the short_url returned by the /create endpoint (see main.py:91):
{
  "message": "URL created",
  "short_url": "https://short.example.com/abc123"
}
Ensure SURL_BASE matches your actual domain to avoid broken short links.

Build docs developers (and LLMs) love