System Design: URL Shortener from Scratch
A URL shortener design exercise with collision-safe code allocation, redirect caching semantics, abuse controls, and an explicit capacity worksheet.
This URL shortener design exercise shows why a hash or random generator cannot guarantee unique codes, and implements collision retry against a unique database constraint. It calculates base62 namespace sizes, sizes redirect traffic from explicit assumptions, and explains how 301/302 semantics and Cache-Control affect destination changes. The abuse section covers phishing, malware, and the limits of a public redirect service.
System Design: URL Shortener from Scratch
This is a hypothetical URL shortener design exercise. It focuses on creating a code-to-destination mapping, serving redirects, and controlling abuse; its traffic values are inputs to recalculate, not production measurements.
This case study applies common URL-shortening requirements without describing any provider’s internal architecture.
Introduction
Functional Requirements
Users need to:
- Shorten a long URL into a compact link
- Access the short URL and get redirected to the original
- Optionally set expiration dates
- Optionally customize the short code
- View statistics on link usage
Non-Functional Requirements
Treat the following as target assumptions for the exercise:
- Fast: Redirects under 100ms
- Available: Handle service disruptions gracefully
- Scalable: Millions of links, billions of redirects
- Durable: No lost links
Capacity worksheet
Use explicit example inputs: 1,000,000 new links per day, 100 redirects per created link per day, 500 bytes of stored mapping data per link, five years of retention, a 10× peak-to-average traffic factor, and a 3× multiplier for index and replica overhead. These are exercise assumptions, not service measurements.
- Redirects/day:
1,000,000 × 100 = 100,000,000. - Average redirect rate:
100,000,000 / 86,400 ≈ 1,157requests/second. - Assumed peak rate:
1,157 × 10 ≈ 11,570requests/second. - Retained mappings:
1,000,000 × 365 × 5 = 1.825 billion. - Storage:
1.825 billion × 500 bytes ≈ 912.5 GBraw, or about2.74 TBafter the assumed 3× overhead.
Replace the redirect ratio, peak multiplier, record size, retention, and replication/index overhead with measured workload and storage-engine values before sizing infrastructure.
Core Components
Short Code Generation
A short code must be URL-safe and unique within the service. Randomness can make codes harder to guess, but it does not prevent collisions. Enforce uniqueness with a database constraint and retry when an insert loses the race.
A seven-character base62 code space contains 62^7 = 3,521,614,606,208 possible values (about 3.52 trillion). That is a namespace size, not a guarantee that a code will be unique. As the number of allocated codes grows, collisions become more likely; atomic conflict handling remains necessary.
import secrets
import string
ALPHABET = string.ascii_letters + string.digits
CODE_WIDTH = 7
CODE_SPACE = len(ALPHABET) ** CODE_WIDTH
def encode_base62(value: int, width: int = CODE_WIDTH) -> str:
chars = []
while value:
value, remainder = divmod(value, len(ALPHABET))
chars.append(ALPHABET[remainder])
return "".join(reversed(chars)).rjust(width, ALPHABET[0])
def create_short_url(db, destination: str) -> str:
for _ in range(8):
code = encode_base62(secrets.randbelow(CODE_SPACE))
row = db.fetch_one(
"""
INSERT INTO short_urls (code, destination_url)
VALUES (%s, %s)
ON CONFLICT (code) DO NOTHING
RETURNING code
""",
(code, destination),
)
if row is not None:
return code
raise RuntimeError("could not allocate a unique code; retry the request")
The code column needs a unique constraint. A conflict means another request claimed the same code first; retry with a new candidate. Limit retries and return a retryable error if the allocator is unhealthy. If using a preallocated key generator instead, reserve disjoint ranges or atomically claim each key before returning it; a counter alone is not safe when multiple generators allocate concurrently.
This pattern handles uniqueness, not URL safety. Validate the destination and apply the abuse checks described later before storing or returning a short link.
Base62 Encoding
Base62 uses characters 0-9, A-Z, a-z giving 62 characters per position:
| Length | Namespace size (62^length) |
Approximate combinations |
|---|---|---|
| 6 | 56,800,235,584 | 56.8 billion |
| 7 | 3,521,614,606,208 | 3.52 trillion |
| 8 | 218,340,105,584,896 | 218.34 trillion |
Under the worksheet’s 1.825 billion retained-link assumption, seven characters use about 0.052% of the namespace. That sizing does not eliminate random collisions; the unique constraint and retry-on-conflict insert handle them.
Data Model
Relational Schema
CREATE TABLE urls (
id BIGSERIAL PRIMARY KEY,
short_code VARCHAR(12) NOT NULL UNIQUE,
original_url TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE,
is_custom BOOLEAN DEFAULT FALSE,
creator_id BIGINT,
click_count BIGINT DEFAULT 0,
is_active BOOLEAN DEFAULT TRUE,
CONSTRAINT urls_short_code_idx UNIQUE (short_code)
);
CREATE INDEX idx_urls_short_code ON urls(short_code);
CREATE INDEX idx_urls_creator ON urls(creator_id);
CREATE INDEX idx_urls_expires ON urls(expires_at) WHERE expires_at IS NOT NULL;
NoSQL Alternative (DynamoDB)
{
"TableName": "urls",
"KeySchema": [{ "AttributeName": "short_code", "KeyType": "HASH" }],
"AttributeDefinitions": [
{ "AttributeName": "short_code", "AttributeType": "S" },
{ "AttributeName": "creator_id", "AttributeType": "N" }
],
"GlobalSecondaryIndexes": [
{
"IndexName": "creator-index",
"KeySchema": [{ "AttributeName": "creator_id", "KeyType": "HASH" }],
"Projection": { "ProjectionType": "ALL" },
"ProvisionedThroughput": {
"ReadCapacityUnits": 100,
"WriteCapacityUnits": 50
}
}
],
"ProvisionedThroughput": {
"ReadCapacityUnits": 1000,
"WriteCapacityUnits": 500
}
}
Caching Strategy
Redirect latency is critical. Cache aggressively.
Cache Structure
# Redis cache key pattern
cache_key = f"url:{short_code}"
# Cache value
cache_value = {
"original_url": "https://example.com/very/long/path",
"expires_at": "2027-01-01T00:00:00Z",
"is_active": True
}
Cache TTL Strategy
CACHE_TTL = {
"frequently_accessed": 3600, # 1 hour for popular links
"recently_created": 300, # 5 minutes for new links
"custom": 86400, # 24 hours for custom links
"expired": 60 # 1 minute for recently expired
}
Write-Through Cache
async def create_short_url(url: str, custom_code: str = None) -> str:
short_code = custom_code or generate_short_code(url)
# Write to database
await db.urls.create({
"short_code": short_code,
"original_url": url,
"is_custom": custom_code is not None
})
# Write to cache
await cache.set(f"url:{short_code}", {
"original_url": url,
"expires_at": None,
"is_active": True
}, ttl=CACHE_TTL["recently_created"])
return short_code
Cache Miss Handling
async def get_original_url(short_code: str) -> Optional[str]:
# Check cache first
cached = await cache.get(f"url:{short_code}")
if cached:
return cached["original_url"]
# Cache miss - fetch from database
url_record = await db.urls.get(short_code=short_code)
if not url_record:
return None
# Populate cache
await cache.set(f"url:{short_code}", {
"original_url": url_record.original_url,
"expires_at": url_record.expires_at,
"is_active": url_record.is_active
}, ttl=CACHE_TTL["recently_created"])
return url_record.original_url
Redirect Logic
HTTP Redirect Types
| Status | Meaning | Cache and method considerations |
|---|---|---|
| 301 | Permanent move | Heuristically cacheable; a client or intermediary may retain the mapping unless cache controls say otherwise. |
| 302 | Temporary move | Not heuristically cacheable, but explicit freshness directives can still permit caching. |
| 303 | See another resource with GET | Useful after a non-GET request when the follow-up should use GET. |
| 307 / 308 | Temporary / permanent move | Preserve the original method and request body. |
Choose the status from the product’s mapping lifecycle, not from an analytics requirement. For a destination users may edit, a 302 with Cache-Control: no-store avoids clients retaining an obsolete redirect; a bounded max-age is another option if the service can invalidate caches. A 301 signals a permanent move and can be cached heuristically. Click tracking should be recorded server-side regardless of redirect status. See RFC 9110 and RFC 9111 for HTTP semantics and cache controls.
Redirect Handler
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/{short_code}")
async def redirect_to_original(short_code: str):
# Check for special paths
if short_code in ["health", "metrics", "docs"]:
raise HTTPException(status_code=404)
# Validate short code format
if not is_valid_short_code(short_code):
raise HTTPException(status_code=400, detail="Invalid short code")
# Get original URL
original_url = await get_original_url(short_code)
if not original_url:
raise HTTPException(status_code=404, detail="URL not found")
# Track click asynchronously
asyncio.create_task(track_click(short_code))
return RedirectResponse(
url=original_url,
status_code=status.HTTP_302_FOUND,
headers={"Cache-Control": "no-store"}
)
Rate Limiting
Prevent abuse with rate limits per IP:
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
@app.post("/shorten")
@limiter.limit("10/minute")
async def create_short_url(request: Request, url: str = Body(...)):
# Validate URL
if not is_valid_url(url):
raise HTTPException(status_code=400, detail="Invalid URL")
# Check if already shortened by this user
existing = await find_existing_mapping(url, request.client.host)
if existing:
return {"short_url": f"https://short.ly/{existing.short_code}"}
short_code = await create_mapping(url)
return {"short_url": f"https://short.ly/{short_code}"}
High Availability Design
Database High Availability
-- PostgreSQL synchronous replication
ALTER SYSTEM SET synchronous_commit = on;
ALTER SYSTEM SET synchronous_standby_names = '*';
-- Read replicas for redirects
CREATE PUBLICATION url_shares FOR TABLE urls;
-- On replica
CREATE SUBSCRIPTION url_sub CONNECTION 'host=primary port=5432 dbname=urlshort' PUBLICATION url_shares;
Multiple Redis Instances
from rediscluster import RedisCluster
# Redis Cluster configuration
rc = RedisCluster(
startup_nodes=[
{"host": "redis-1", "port": 6379},
{"host": "redis-2", "port": 6379},
{"host": "redis-3", "port": 6379}
],
decode_responses=True
)
async def get_original_url(short_code: str) -> Optional[str]:
# Consistent hashing handles failover automatically
cached = await rc.get(f"url:{short_code}")
return json.loads(cached)["original_url"] if cached else None
Geographic Distribution
Deploy redirector clusters in multiple regions:
# Route 53 latency routing
- Name: short.ly
Type: A
SetIdentifier: us-east-1
Region: us-east-1
AliasTarget:
DNSName: dualstack.api-elb-us-east-1.amazonaws.com
EvaluateTargetHealth: true
# EU redirector
- Name: short.ly
Type: A
SetIdentifier: eu-west-1
Region: eu-west-1
AliasTarget:
DNSName: dualstack.api-elb-eu-west-1.amazonaws.com
EvaluateTargetHealth: true
Users are routed to the nearest cluster based on latency.
Analytics Pipeline
Track clicks without slowing redirects:
async def track_click(short_code: str):
# Fire and forget - don't await
asyncio.ensure_future(
kafka.send("clicks", {
"short_code": short_code,
"timestamp": datetime.utcnow().isoformat(),
"user_agent": request.headers.get("user-agent"),
"referer": request.headers.get("referer"),
"ip_hash": hash_ip(request.client.host)
})
)
Click Analytics Consumer
async def process_clicks():
consumer = KafkaConsumer("clicks", bootstrap_servers=["kafka:9092"])
for message in consumer:
event = json.loads(message.value)
# Update click count in background
await db.query("""
UPDATE urls
SET click_count = click_count + 1
WHERE short_code = $1
""", event["short_code"])
# Update analytics warehouse
await warehouse.insert("click_events", event)
Complete API Specification
Endpoints
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/v1/shorten | Create short URL |
| GET | /{short_code} | Redirect to original |
| GET | /api/v1/links/{short_code} | Get link info |
| GET | /api/v1/links/{short_code}/stats | Get click statistics |
| DELETE | /api/v1/links/{short_code} | Delete a link |
| PUT | /api/v1/links/{short_code} | Update link settings |
Request/Response Examples
# Create short URL
curl -X POST https://short.ly/api/v1/shorten \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/very/long/path/that/needs/shortening"}'
# Response
{
"short_code": "xV2bP9qK",
"short_url": "https://short.ly/xV2bP9qK",
"original_url": "https://example.com/very/long/path/that/needs/shortening",
"created_at": "2026-03-22T10:30:00Z",
"expires_at": null
}
Abuse Prevention and Security
Malicious URL Detection
URL shorteners are frequently abused for phishing, malware distribution, and spam. Use layered safeguards; the example below treats syntax checks separately from reputation and content signals.
A shortener intentionally redirects to a destination chosen by its creator, so the abuse boundary is controlling which destinations it will publish and how quickly it can block them. Accept only validated absolute http or https URLs; do not build a redirect from a request’s next parameter or an untrusted Host header. Check reputation and malware signals, provide reporting and takedown, and consider a preview or warning page for links with risk signals. Do not treat a suspicious top-level domain alone as proof of abuse.
If a scanner fetches submitted URLs, run it in an isolated worker with no access to private networks or cloud metadata endpoints. Re-check DNS results and every redirect hop so a public hostname cannot redirect the scanner into an internal address. A destination that changes to a phishing or malware site should be blockable at the redirect path, including cache and CDN entries.
class MaliciousURLDetector:
"""Detect potentially malicious URLs before shortening"""
def __init__(self, threat_intel_client: ThreatIntelClient):
self.threat_intel = threat_intel_client
async def check_url(self, url: str) -> ThreatAssessment:
checks = await asyncio.gather(
self._check_domain_reputation(url),
self._check_url_pattern(url),
self._check_content_scan(url),
self._check_google_safe_browsing(url)
)
if any(check.threat for check in checks):
return ThreatAssessment(
threat=True,
reason="URL flagged by security checks",
severity="high"
)
return ThreatAssessment(threat=False)
async def _check_url_pattern(self, url: str) -> CheckResult:
parsed = urlparse(url)
# Reject malformed redirect targets; reputation signals need context.
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
return CheckResult(threat=True, reason="Invalid absolute HTTP(S) URL")
return CheckResult(threat=False)
Rate Limiting Tiers
RATE_LIMITS = {
"anonymous": {"shorten": "5/hour", "redirect": "100/hour"},
"authenticated_free": {"shorten": "100/hour", "redirect": "1000/hour"},
"authenticated_pro": {"shorten": "10000/hour", "redirect": "100000/hour"},
}
# These example limits need tuning from abuse reports and service capacity.
@app.middleware
async def rate_limit_middleware(request: Request, call_next):
user_tier = get_user_tier(request)
operation = "redirect" if request.method == "GET" else "shorten"
if user_tier == "anonymous":
# Rate limit by IP
identity = f"ip:{request.client.host}"
else:
user_id = get_user_id(request)
identity = f"user:{user_id}"
if not await rate_limiter.check_limit(identity, RATE_LIMITS[user_tier][operation]):
raise HTTPException(status_code=429, detail="Rate limit exceeded")
return await call_next(request)
Spam Link Prevention
async def create_short_url(url: str, user_id: int = None) -> ShortUrl:
# Validate URL format
if not is_valid_url(url):
raise HTTPException(status_code=400, detail="Invalid URL format")
# Check for known spam domains
if await spam_database.is_spam_domain(extract_domain(url)):
raise HTTPException(status_code=403, detail="URL blocked")
# Require authentication for custom codes
if custom_code and not user_id:
raise HTTPException(status_code=401, detail="Authentication required for custom codes")
# Create short URL
return await url_service.create(url, custom_code, user_id)
Failure Scenarios and Mitigations
These responses depend on the chosen storage, cache, and abuse-review services; validate them with the system’s actual failure modes.
| Failure scenario | User-visible effect | Response to design and test |
|---|---|---|
| Redirect cache unavailable | Database read load rises; latency may increase | Fall back only within database capacity; monitor cache errors and database saturation |
| Unique-code conflicts continue | Link creation retries or fails | Retry a bounded number of times against the unique constraint, then return a retryable error; never store an unchecked code |
| Mapping database unavailable | New links cannot be confirmed; redirects may miss | Reject creation without a durable write; define whether cached reads can serve and how stale they may be |
| DNS or domain configuration failure | The short-link hostname may be unreachable | Monitor external resolution and keep a tested recovery procedure for the domain and records |
| Reputation scanner unavailable | Abuse checks cannot finish normally | Apply an explicit fail-open, queue, or fail-closed policy and test its security and availability consequences |
Cache Failure Handling
async def get_original_url(short_code: str) -> Optional[str]:
record = None
try:
# Cache and database adapters return the same mapping fields.
cached = await redis.get(f"url:{short_code}")
if cached:
record = json.loads(cached)
except RedisConnectionError:
# Cache unavailable; use the database only if it has capacity.
pass
if record is None:
record = await db.urls.get(short_code=short_code)
if not record:
return None
expires_at = parse_expiration(record["expires_at"])
if not record["is_active"] or (expires_at is not None and expires_at <= clock.now()):
return None
return record["original_url"]
Here, parse_expiration converts either adapter’s timestamp into a timezone-aware value, and clock.now() is an injected clock. That keeps cache and database paths on the same validity check.
Hypothetical Failure Exercises
Use these hypothetical cases to test the design’s failure behavior.
The redirect database is unavailable
Creation requests should fail clearly if the service cannot confirm that a code-to-destination mapping was stored. Existing redirects can continue only if a trusted cache or read path has the mapping; define how stale that data may be and what happens when it misses. Do not assume a read replica can be promoted safely without checking the database’s replication and failover guarantees.
A destination is changed or taken down
A CDN or browser may retain a redirect after the origin mapping changes, especially for a permanent redirect or an explicit freshness lifetime. Test the selected status, cache headers, and invalidation path together. For abuse takedowns, verify that both origin and edge caches stop serving the old destination within the documented response window.
Abuse scanning is slow or unavailable
Decide whether link creation should wait, queue for review, or reject while reputation checks are unavailable. Test that an untrusted destination cannot be fetched by the scanner from private network ranges or cloud metadata endpoints, and that a block decision invalidates cached redirects.
Common Pitfalls / Anti-Patterns
Pitfall 1: Treating unpredictable codes as authorization
Sequential IDs make enumeration easier and reveal allocation order. Random codes reduce that signal, but a short code is still a public bearer link; it must not protect private content by itself.
Generate a cryptographically random base62 candidate, enforce a unique database constraint, and retry a conflict. In the worksheet’s hypothetical 1.825 billion retained links, seven-character codes occupy about 0.052% of the 3.52-trillion namespace. That is a sizing input, not a guarantee against guessing. Rate-limit lookups and creations, avoid revealing whether a code exists when that matters, and require authentication for destinations that are not meant to be public.
Pitfall 2: Leaving stale redirects after expiration or takedown
An expired or reported destination can remain reachable through a cached mapping. Check the active state and expiration before returning a redirect, and set cache freshness so it cannot outlive the mapping’s expiration. For edits or abuse takedowns, invalidate origin and edge caches or use a short, explicit freshness window that meets the product’s revocation objective. Test the stale window instead of calling a fixed TTL safe for every link.
Pitfall 3: Sizing the cache from an assumed hit rate
A cache miss sends another request to the mapping store. Estimate that load with redirect requests per second × (1 - cache hit ratio), then measure it under the expected key distribution and failure conditions. For the worksheet’s hypothetical peak of about 11,574 redirects per second, a measured 30% miss rate would mean roughly 3,472 mapping reads per second; those values are scenario inputs, not benchmark results.
Cache the destination and the metadata needed to decide whether a redirect is still valid. Keep click analytics on an asynchronous path where the delivery guarantees allow it; storing a mutable click count in the redirect cache can create a separate consistency problem. Use observed traffic to decide whether warming hot keys helps.
Observability Checklist
Metrics to Capture
url_redirects_total(counter) - By short_code prefix, status codeurl_shortens_total(counter) - By user_tier, custom vs autoredirect_latency_seconds(histogram) - P50, P95, P99cache_hit_ratio(gauge) - Cache efficiencymalicious_url_attempts_total(counter) - Blocked attempts by typecode_allocation_conflicts_total(counter) - Unique-constraint retries and exhausted attempts
Logs to Emit
{
"timestamp": "2026-03-22T10:30:00Z",
"event": "redirect",
"short_code": "xV2bP9qK",
"status": 302,
"latency_ms": 12,
"cache_hit": true,
"user_ip_hash": "abc123"
}
Alerts to Configure
| Alert | Threshold | Severity |
|---|---|---|
| Redirect latency P99 > 200ms | 200ms | Warning |
| Cache hit ratio < 50% | 50% | Warning |
| Code allocation retry spike | Set from observed baseline | Warning |
| Malicious attempts spike | > 100/min | Warning |
| DB connection pool > 80% | 80% | Warning |
These thresholds are example starting points. Set alert conditions from the service’s SLOs, tested capacity, and abuse response needs.
Security Checklist
- Accept only validated absolute HTTP or HTTPS destinations
- Keep scanner requests away from private networks and cloud metadata endpoints
- Re-check DNS and every redirect hop made by a scanner
- Invalidate origin and edge caches after a destination takedown
- Do not block a destination solely because of its top-level domain
- TLS 1.3 for all connections
- URL validation and sanitization
- Malicious URL scanning (Google Safe Browsing API)
- Rate limiting per IP and per user
- Custom code length and character validation
- Authentication required for custom short codes
- Audit logging of all URL creations
- GDPR compliance for analytics data
- Regular security audits
Trade-off Analysis
| Design decision | Option A | Option B | How to choose |
|---|---|---|---|
| Code allocation | Random candidate plus unique constraint and bounded retry | Preallocated, atomically leased ranges | Start with the simpler path; consider leasing if measured insert contention justifies its operational cost |
| Code length | Six base62 characters: 56,800,235,584 values | Seven characters: 3,521,614,606,208 values | Choose from retained-link volume, acceptable code length, and guessing risk; conflicts still need handling |
| Redirect status | 301 permanent | 302 temporary | Match the mapping lifecycle; set explicit cache controls when destinations may change |
| Cache | Destination only | Destination plus redirect metadata | Include fields needed for active and expiry checks; keep analytics consistency separate |
| Custom codes | Authenticated claim | Anonymous claim | Apply uniqueness, reserved-path, abuse, and ownership rules appropriate to the product |
| Click analytics | Synchronous write | Queued event | Choose based on redirect latency and whether losing or delaying events is acceptable |
| Storage | Relational mapping table | Partitioned or distributed key-value store | Decide from query needs, write/read volume, failure model, and operator experience—not a fixed row-count threshold |
A preallocated key generator can reduce allocation work, but it adds a service and a lease-recovery problem. If it is used, reserve disjoint ranges atomically and never return possibly issued codes to the pool without proving they were unused. Do not fall back from allocator failure to an unchecked hash.
Interview Questions
A random or hashed code can collide, so generation alone cannot establish uniqueness. Store codes behind a unique constraint and retry a new random candidate when an insert loses the conflict. If using a preallocated generator, reserve keys atomically and do not return a possibly issued key to the pool.
Base62 uses alphanumeric characters, so codes do not need URL escaping. Standard base64 includes characters such as `+`, `/`, and `=`; base64url is another option with a different alphabet. This exercise chooses seven base62 characters because `62^7` provides about 3.52 trillion candidates; choose length from expected retained links, URL length, and guessing risk.
With uniformly random seven-character codes, the approximate chance that one guess hits an allocated code is allocated codes divided by `62^7`. Under this exercise's 1.825-billion-link assumption, that is about 0.052% per guess if every retained code is active. That is not authorization: rate-limit guesses, avoid leaking existence where needed, and require authentication for private destinations.
Cache the destination and the metadata needed to check active state and expiration. Measure cache-hit rate and mapping-store latency under the expected key distribution; estimate miss traffic as redirect requests per second times `(1 - hit ratio)`. Set freshness and invalidation based on how quickly a destination change or takedown must take effect.
Check active state and expiration on both cache-hit and database paths before returning a redirect. A cached entry must not remain fresh past the link's expiration. For edits and takedowns, invalidate origin and edge entries or use a freshness window that meets the product's revocation objective. Choose a not-found or gone response deliberately.
A cache failure can send more reads to the database; redirects continue only if the database has capacity and the mapping is available. Use a bounded fallback or load-shedding policy, monitor the read path, and test the combined cache and database failure cases. A circuit breaker can stop repeated calls to an unhealthy cache, but it cannot create database capacity.
Validate absolute HTTP or HTTPS destinations, use reputation and malware signals, rate-limit creation, and provide reporting and takedown. Treat domain or URL-pattern heuristics as review signals rather than proof; a top-level domain alone should not decide a block. Run any URL fetch in an isolated worker, block private and metadata addresses, and re-check DNS and each redirect hop to prevent SSRF.
Custom codes need authentication — otherwise people squat on popular terms. Require login to claim a custom code, validate it meets your format rules (minimum length, allowed characters, not on the reserved list), and charge for it if you're running a business. Premium pricing alone deters most abuse.
The reserved list matters. Things like /admin, /health, /metrics — these should never be available as custom codes regardless of who asks.
PostgreSQL handles most URL shortener workloads fine. The short_code gets a unique index for fast lookups — this is the only query path that matters for redirects. Everything else (creator_id, expires_at) can live on secondary indexes.
At extreme scale — billions of URLs — PostgreSQL starts showing cracks. Cassandra and DynamoDB both scale horizontally without the manual sharding overhead. The query pattern is simple (look up by short_code), which maps well to partitioned NoSQL designs. You lose some query flexibility but gain almost unbounded horizontal scalability.
Do not wait for an analytics database write before returning the redirect if that delay conflicts with the latency target. A background task inside a web process can be lost during a restart, so use a durable queue when the product needs delivery beyond best effort.
Decide whether the redirect may be returned before the event is durably accepted. That choice sets the loss window. A consumer can batch analytics writes later, while dashboards should report their freshness and any dropped or delayed events.
Seven base62 characters provide `M = 62^7 = 3,521,614,606,208` possible codes. With `n = 1.825` billion retained links, occupancy is about `n/M = 0.052%`. Under uniform random allocation, the probability of at least one collision over all `n` independent draws is approximately `1 - exp(-n(n-1)/(2M))`, which is effectively 1 at this volume; the expected number of duplicate draws before retries is about 473,000 over five years. The average conflict rate is small, but unique-constraint retries are still required. These calculations use the worksheet assumptions, not a benchmark.
Start with random candidates, a unique database constraint, and bounded retries. A preallocated generator may help if measurements show allocation contention, but it adds range leasing, durable state, and recovery work. A hash plus salt still does not guarantee uniqueness; it must use the same conflict check. Do not silently fall back to an unchecked code when allocation fails.
You have two philosophies here. The first: deduplicate and return the existing short URL. If the same user submits the same URL twice, give them the same short code. This is efficient — fewer entries in your database — but it breaks the assumption that each short code belongs to one URL. It also means one user can "claim" a URL that another user wanted.
The second approach: treat each submission as unique, even for identical URLs. This preserves the one-to-one mapping and is simpler to reason about, but wastes keyspace on duplicates.
Most production systems do a hybrid: check if the submitting user already has a short code for that URL (deduplicate per user), but allow different users to create different short codes for the same long URL. The cache and database handling stays simple.
PostgreSQL handles millions of rows without complaint if you have the right indexes. The short_code unique index performs well even with hundreds of millions of entries. The problems start when you need to scale writes or distribute geographically.
Read replicas help with redirect read throughput — you can route reads to replicas and writes to primary. But there's a catch: replication lag means occasionally a brand-new URL might not be on a replica yet, so a redirect could 404 even though the URL was just created. Acceptable for most use cases, but something to monitor.
At billions of rows, table partitioning becomes necessary. You can partition by creation date, then route redirects to the right partition based on short code prefix. DynamoDB and Cassandra handle this scale natively with automatic partitioning, but you give up PostgreSQL's query flexibility.
Users in different regions expect instant redirects. If your primary database is in us-east-1, a user in Tokyo sees 100ms+ latency just for the database lookup before the redirect even starts.
The usual approach: regional Redis caches that replicate asynchronously. Writes go to the primary region and propagate to regional caches. The trade-off is eventual consistency — a URL created in us-east-1 might not be redirectable from eu-west for a few seconds.
For most URL shorteners, eventual consistency is fine. Users rarely create and immediately test from opposite sides of the world. The p99 latency improvement from regional caching outweighs the brief inconsistency window.
Custom codes bypass the random generation process, which means they can collide with system paths. If someone registers "/health" as a custom code, your redirect handler gets confused — that path is supposed to be your health check endpoint.
The reserved list must be enforced at creation time, not just checked at redirect time. Block /health, /metrics, /docs, /api/*, and any other internal paths. Also block codes that look like valid base62 but decode to ASCII — "admin" encoded in base62 is a real short code someone could claim.
Character validation matters too. A custom code containing SQL injection characters or path traversal sequences ("../../../etc/passwd") needs sanitization even if it passes your base62 filter. Validate strictly: alphanumeric only, minimum 4 characters, maximum 12.
The shortener's job is redirect, not reliability. You redirect to whatever URL the user provided — you're not responsible for that URL being up. But there are legitimate cases where you'd want to detect and handle dead links.
Some systems do proactive validation: when a URL is shortened, scan it to verify it responds without error. This adds creation latency and still doesn't guarantee the URL stays up. Not worth the complexity for most use cases.
For premium tiers, periodic revalidation makes sense. Check every hour whether premium short URLs still respond. If a link goes dead, alert the owner and optionally auto-expire the short code. This is a business feature, not a technical requirement.
Persist each range lease or atomic claim before a worker can issue its codes, and fence workers so a recovered process cannot reuse an old lease. If the allocator cannot tell whether a code was issued, quarantine it rather than returning it to the pool. Keep link creation retryable while the allocator is unavailable; a fallback generator must still use the uniqueness constraint.
A 301 represents a permanent move and can be heuristically cacheable; a 302 is temporary and is not heuristically cacheable, though explicit freshness controls can allow caching. If users can edit destinations, use a status and Cache-Control policy that match the change and takedown requirements. Record clicks server-side; the redirect status does not provide analytics. See [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html) and [RFC 9111](https://www.rfc-editor.org/rfc/rfc9111.html).
Start with measured creations per day, redirects per link, peak-to-average factor, stored bytes per record, retention, and storage overhead. In this exercise, 1 million links per day and 100 redirects per link per day imply 100 million redirects per day, about 1,157 requests per second on average, and about 11,570 at the assumed 10× peak. Five years at 500 bytes per mapping is about 912.5 GB raw; a hypothetical 3× index and replica multiplier gives about 2.74 TB. Replace every input with workload and database measurements before sizing infrastructure.
Further Reading
- Caching Strategies — Deep dive into Redis caching patterns
- Load Balancing — Geographic distribution and routing
- Database Scaling — Read replicas and partitioning
- Rate Limiting — Anti-abuse patterns
- Distributed Caching — Multi-node cache architectures
For more system design patterns, see our Caching Strategies guide which covers caching patterns used here. The Load Balancing guide covers geographic distribution.
Conclusion
The code-allocation path retries unique-constraint conflicts, while redirect freshness follows the mapping lifecycle. Cache and storage choices should follow measured traffic, failure tests, and the consistency needed for edits and takedowns. Analytics can run asynchronously when the product accepts its delivery guarantees.
Quick Recap Checklist
Before deploying your URL shortener to production, verify these essentials:
Core Functionality
- Random code generation with a unique constraint and bounded conflict retries
- Base62 encoding with 6-8 character output
- URL validation and sanitization
- Custom code reservation for system paths
- Expiration handling on every redirect
Performance
- Redis caching with write-through on create
- Cache freshness matches expiration, edit, and takedown requirements
- Database indexes on short_code for fast lookups
- Read replicas for redirect traffic
- Async analytics (fire-and-forget click tracking)
Availability
- Circuit breaker for cache failures
- Database fallback when cache unavailable
- Multi-region deployment with latency-based routing
- Recovery procedure for database and optional allocator failures
- Connection pool monitoring and auto-scaling
Security
- Rate limiting per IP and per user tier
- Malicious URL scanning (Safe Browsing API)
- Scanner fetches cannot reach private networks or cloud metadata endpoints
- Takedown decisions invalidate origin and edge cache entries
- Reputation heuristics do not block a destination solely because of its top-level domain
- Authentication required for custom codes
- Reserved path blocking at creation time
- TLS 1.3 for all connections
- Audit logging for URL creations
Observability
- Redirect latency histograms (P50, P95, P99)
- Cache hit ratio monitoring
- Code allocation conflict and retry rate
- Alert thresholds configured for all critical metrics
Category
Related Posts
System Design: Netflix Architecture for Global Streaming
A hypothetical streaming architecture exercise informed by public Open Connect material, with explicit assumptions for capacity, delivery, and playback design.
System Design: Twitter Feed Architecture and Scalability
A Twitter/X-like feed design exercise covering fan-out, timeline consistency, and capacity estimates from explicit workload assumptions.
Amazon Architecture: History and Service Design
Separate documented Amazon and AWS milestones from popular retellings, then apply the lesson about service boundaries to a current request flow.