Providing Flask URL shortener example
I'm producing a concise Flask app that generates Base62 short IDs with collision checking, caches redirects in Redis for low-latency lookups, and asynchronously logs click analytics (referrer, user-agent) to ClickHouse using a background thread pool.
Below is a minimal, end‑to‑end example of how you can implement a Flask URL shortener with Base62 IDs, collision handling, Redis caching for fast redirects, and asynchronous click logging to ClickHouse. This is a reference implementation—adjust for production concerns (auth, rate limits, config, retries, error handling, connection pooling, etc.).
Key Components
- Base62 encoding to generate short IDs from random integers.
- Collision handling by retrying if a generated short code already exists in your DB.
- Redis to cache short-code → URL lookups for sub‑millisecond latency.
- Click analytics logged asynchronously (referrer, user-agent, etc.) to ClickHouse using a background executor.
Setup
pip install flask redis clickhouse-driver sqlalchemy
Make sure Redis and ClickHouse are running and reachable (adjust host/port below).
app.py
import os
import random
import string
import time
from concurrent.futures import ThreadPoolExecutor
from flask import Flask, request, redirect, jsonify
from sqlalchemy import create_engine, Column, Integer, String, UniqueConstraint
from sqlalchemy.orm import sessionmaker, declarative_base
import redis
from clickhouse_driver import Client as CHClient
# ---------------------------
# Configuration
# ---------------------------
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 0
CLICKHOUSE_HOST = "localhost"
CLICKHOUSE_DB = "default"
CLICKHOUSE_TABLE = "clicks" # You must create this table in ClickHouse
DATABASE_URL = "sqlite:///urls.db" # Replace with Postgres/MySQL in production
SHORT_CODE_LENGTH = 7 # Adjust length as needed
MAX_ID_GENERATION_ATTEMPTS = 5
# ---------------------------
# Base62 utilities
# ---------------------------
BASE62_ALPHABET = string.digits + string.ascii_letters # 0-9 + A-Z + a-z
def base62_encode(num: int) -> str:
"""Encode a positive integer into a Base62 string."""
if num == 0:
return BASE62_ALPHABET[0]
base62 = []
while num > 0:
num, rem = divmod(num, 62)
base62.append(BASE62_ALPHABET[rem])
return ''.join(reversed(base62))
def generate_short_code(length=SHORT_CODE_LENGTH) -> str:
"""Generate a random Base62 short code of given length."""
# For stronger guarantees, you could use something like secrets.randbelow
# or a counter. This is a simple example:
val = random.getrandbits(length * 6) # approx 2^(length*6)
short_code = base62_encode(val)
# If the encoded string is shorter than desired, pad it (rarely needed).
if len(short_code) < length:
short_code = short_code.rjust(length, BASE62_ALPHABET[0])
return short_code[:length]
# ---------------------------
# Flask & database setup
# ---------------------------
app = Flask(__name__)
engine = create_engine(DATABASE_URL, echo=False)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()
class URLMap(Base):
__tablename__ = "url_map"
id = Column(Integer, primary_key=True, autoincrement=True)
short_code = Column(String(32), nullable=False, unique=True)
long_url = Column(String(2048), nullable=False)
__table_args__ = (UniqueConstraint('short_code', name='_short_code_uc'),)
Base.metadata.create_all(bind=engine)
# Redis client
r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
# ClickHouse client
ch_client = CHClient(host=CLICKHOUSE_HOST, database=CLICKHOUSE_DB)
# Thread pool for async logging
executor = ThreadPoolExecutor(max_workers=4)
# ---------------------------
# Helpers
# ---------------------------
def get_db_session():
return SessionLocal()
def get_long_url_from_cache(short_code: str):
return r.get(f"url:{short_code}")
def set_long_url_in_cache(short_code: str, long_url: str):
# Add a reasonable TTL. Adjust as you like or omit.
r.setex(f"url:{short_code}", 24 * 3600, long_url)
def log_click_async(short_code: str, referrer: str, user_agent: str, ip: str, ts: float):
"""Submit analytics logging to ClickHouse asynchronously."""
executor.submit(log_click, short_code, referrer, user_agent, ip, ts)
def log_click(short_code: str, referrer: str, user_agent: str, ip: str, ts: float):
"""Write click analytics to ClickHouse (blocking)."""
# Ensure your ClickHouse table "clicks" exists, e.g.:
# CREATE TABLE clicks (
# short_code String,
# referrer String,
# user_agent String,
# ip String,
# ts DateTime
# ) ENGINE = MergeTree() ORDER BY ts;
ch_client.execute(
"INSERT INTO clicks (short_code, referrer, user_agent, ip, ts) VALUES",
[(short_code, referrer or "", user_agent or "", ip or "", ts)]
)
def create_or_get_short_code(long_url: str):
"""Attempt to create a unique short code; handle collisions."""
session = get_db_session()
try:
for _ in range(MAX_ID_GENERATION_ATTEMPTS):
candidate = generate_short_code()
# Check if candidate is already in use
existing = session.query(URLMap).filter_by(short_code=candidate).first()
if not existing:
# Create new entry
new_entry = URLMap(short_code=candidate, long_url=long_url)
session.add(new_entry)
session.commit()
return candidate
# If we got here, we couldn't find a free short code
raise RuntimeError("Failed to generate unique short code after multiple attempts.")
except Exception:
session.rollback()
raise
finally:
session.close()
def resolve_short_code(short_code: str):
"""Resolve a short code to a long URL (with Redis cache)."""
# Check cache first
cached = get_long_url_from_cache(short_code)
if cached:
return cached.decode("utf-8")
# Otherwise fallback to DB
session = get_db_session()
try:
entry = session.query(URLMap).filter_by(short_code=short_code).first()
if entry:
set_long_url_in_cache(short_code, entry.long_url)
return entry.long_url
return None
finally:
session.close()
# ---------------------------
# Routes
# ---------------------------
@app.route("/shorten", methods=["POST"])
def shorten():
data = request.get_json()
if not data or "url" not in data:
return jsonify({"error": "Missing url"}), 400
long_url = data["url"].strip()
if not long_url.startswith(("http://", "https://")):
return jsonify({"error": "URL must start with http:// or https://"}), 400
try:
short_code = create_or_get_short_code(long_url)
return jsonify({"short_url": f"{request.host_url}{short_code}"})
except Exception as e:
# In production, log this properly
return jsonify({"error": str(e)}), 500
@app.route("/<short_code>", methods=["GET"])
def redirect_short_url(short_code):
long_url = resolve_short_code(short_code)
if not long_url:
return jsonify({"error": "Short URL not found"}), 404
# Collect analytics
referrer = request.headers.get("Referer", "")
user_agent = request.headers.get("User-Agent", "")
ip = request.remote_addr or ""
ts = time.time()
# Asynchronous logging
log_click_async(short_code, referrer, user_agent, ip, ts)
# Fast redirect
return redirect(long_url, code=302)
# ---------------------------
# Main
# ---------------------------
if __name__ == "__main__":
# For local debug only; in production use gunicorn/uwsgi, etc.
app.run(host="0.0.0.0", port=5000, debug=True)
Notes
-
ClickHouse table
Ensure you create the ClickHouse table before running:
CREATE TABLE IF NOT EXISTS clicks (
short_code String,
referrer String,
user_agent String,
ip String,
ts DateTime
) ENGINE = MergeTree() ORDER BY ts;
-
Redis
Make sure Redis is running locally or adjust REDIS_HOST/PORT accordingly.
-
Persistence
The example uses SQLite via SQLAlchemy for storing short_code -> long_url mappings. Swap in Postgres or MySQL for production.
-
Security & Compliance
This is a minimal example. Add authentication, rate limiting, validation, and privacy notices as needed—especially if logging user-agent/referrer.
-
Performance Tuning
- Use connection pooling for Redis and ClickHouse.
- Consider a more robust queueing system (e.g., Celery, RQ) for analytics if volume is high.
- Increase or tune thread pool size for logging throughput.
This provides the core functionality you asked for: Base62 IDs, collision handling, Redis caching for fast lookups, and asynchronous click analytics to ClickHouse.