Initial commit: Test GLM project

This commit is contained in:
anor
2026-02-04 16:54:36 +10:00
commit 2ed8e1112c
85 changed files with 23511 additions and 0 deletions
+87
View File
@@ -0,0 +1,87 @@
# Subtask: Database Schema Design
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-01
**Dependencies**: None
## Description
Design and implement the database schema for URL storage, including tables for URLs, analytics, and rate limiting. Support 10M URLs with proper indexing for fast lookups.
## Requirements
- Store original URLs, short codes, custom aliases
- Support link expiration with TTL
- Track creation timestamp and access counts
- Handle duplicate URL detection efficiently
- Support composite indexes for common query patterns
## Technical Specifications
### Technology Stack
- **Database**: PostgreSQL (for ACID guarantees and complex queries)
- **Connection Pooling**: pgbouncer or connection pooler
### Schema Tables
```sql
-- URLs table
CREATE TABLE urls (
id BIGSERIAL PRIMARY KEY,
short_code VARCHAR(8) UNIQUE NOT NULL,
original_url TEXT NOT NULL,
custom_alias BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
expires_at TIMESTAMP WITH TIME ZONE,
access_count BIGINT DEFAULT 0,
checksum VARCHAR(64) -- For duplicate detection
);
-- Indexes
CREATE INDEX idx_short_code ON urls(short_code);
CREATE INDEX idx_checksum ON urls(checksum);
CREATE INDEX idx_expires_at ON urls(expires_at) WHERE expires_at IS NOT NULL;
-- Analytics table (separate for performance)
CREATE TABLE url_analytics (
id BIGSERIAL PRIMARY KEY,
url_id BIGINT REFERENCES urls(id) ON DELETE CASCADE,
clicked_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
user_agent TEXT,
ip_address INET,
country_code CHAR(2),
city VARCHAR(100),
referrer TEXT
);
CREATE INDEX idx_url_id_clicked ON url_analytics(url_id, clicked_at DESC);
-- Rate limiting table
CREATE TABLE rate_limits (
id BIGSERIAL PRIMARY KEY,
identifier VARCHAR(255) NOT NULL, -- IP or API key
action VARCHAR(50) NOT NULL, -- 'create', 'redirect'
window_start TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
request_count INTEGER DEFAULT 1,
PRIMARY KEY (identifier, action, window_start)
);
```
### Data Structures
- **checksum**: SHA-256 hash of original URL for duplicate detection
- **short_code**: Base62 encoded ID (6-8 characters)
## Acceptance Criteria
- [ ] Schema SQL file created with all tables and indexes
- [ ] Migration script for schema creation
- [ ] Foreign key constraints properly defined
- [ ] Indexes cover all query patterns (short_code lookup, duplicate detection, expiration cleanup)
- [ ] Support for 10M+ rows without performance degradation
## Notes
- **Trade-off**: Chose SQL over NoSQL for strong consistency and transaction support
- **Scaling**: Consider partitioning by date for analytics table at 100M+ rows
- **Cleanup**: Need background job for expired URL deletion (subtask dependency)
## Edge Cases
- What happens when URL exceeds maximum length? (TEXT type handles this)
- Concurrent inserts with same checksum? (UNIQUE constraint + application logic)
- Timezone handling for expiration? (Always use UTC internally)
+73
View File
@@ -0,0 +1,73 @@
# Subtask: Base62 Encoding/Decoding
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-02
**Dependencies**: None (can be implemented in parallel with 001-01)
## Description
Implement Base62 encoding/decoding for converting numeric IDs to short codes. This is a pure algorithm component with no external dependencies.
## Requirements
- Convert integer ID to Base62 string (0-9, a-z, A-Z)
- Convert Base62 string back to integer ID
- Support IDs up to 10^12 (10M URLs with buffer)
- Handle leading zeros correctly
- No external dependencies for core logic
## Technical Specifications
### Algorithm
```python
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASE = 62
def encode(num: int) -> str:
"""Convert integer to Base62 string."""
if num == 0:
return ALPHABET[0]
result = []
while num > 0:
num, remainder = divmod(num, BASE)
result.append(ALPHABET[remainder])
return ''.join(reversed(result))
def decode(short_code: str) -> int:
"""Convert Base62 string to integer."""
result = 0
for char in short_code:
result = result * BASE + ALPHABET.index(char)
return result
```
### Complexity Analysis
- **Time**: O(log₆₂(n)) for both operations
- **Space**: O(log₆₂(n)) for output string
### Code Length Constraints
- Target: <50 lines (Simplicity First principle)
- Single file module: `base62.py`
## Acceptance Criteria
- [ ] encode(0) returns "0"
- [ ] encode(12345) returns correct Base62 string
- [ ] decode(encode(12345)) == 12345 for all test values
- [ ] Handles edge cases: 0, negative numbers (raise error), max value
- [ ] Unit tests with 100% coverage
- [ ] No external dependencies (stdlib only)
- [ ] <50 lines of code
## Notes
- **Why Base62**: URL-safe, compact (~62^8 = 218 trillion combinations with 8 chars)
- **Case sensitivity**: URLs are case-sensitive, which is standard
- **Alternative considered**: Base57 (excluding ambiguous chars like 0/O/l/1) - rejected for simplicity
## Edge Cases
- Empty string input → raise ValueError
- Invalid characters in input → raise ValueError
- Negative numbers → raise ValueError
- Overflow for very large numbers → Python handles big ints natively
## Performance
- Encoding/decoding should be <1μs per operation
- No memory allocations in tight loops (use list comprehension)
+101
View File
@@ -0,0 +1,101 @@
# Subtask: Short Code Generation with Collision Handling
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-03
**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-02 (Base62 Encoding)
## Description
Implement unique short code generation using database sequence IDs with Base62 encoding. Handle hash collisions gracefully when generating codes from URL hashes.
## Requirements
- Generate 6-8 character short codes
- Handle collisions gracefully (retry with different encoding)
- Support custom alias validation
- Detect duplicate URLs using checksum
- Ensure uniqueness at scale (10M URLs)
## Technical Specifications
### Code Generation Strategies
#### Strategy 1: Sequential ID-based (Primary)
```python
def generate_short_code(url_id: int) -> str:
"""Generate short code from sequential database ID."""
return base62_encode(url_id)
```
- **Pros**: Guaranteed unique, simple, collision-free
- **Cons**: Predictable (sequential), requires database roundtrip
#### Strategy 2: Hash-based with Collision Handling (Fallback)
```python
def generate_from_url_hash(url: str, attempt: int = 0) -> str:
"""Generate short code from URL hash with collision handling."""
# SHA-256 hash + salt for collision resolution
salt = f"_{attempt}" if attempt > 0 else ""
hash_val = hashlib.sha256(f"{url}{salt}".encode()).digest()
# Take first 6 bytes and encode
num = int.from_bytes(hash_val[:6], 'big')
return base62_encode(num)[:8]
```
### Collision Handling Logic
```python
def create_short_code(original_url: str, custom_alias: str = None) -> str:
"""Create unique short code with collision handling."""
# 1. Check for duplicate URL
checksum = hashlib.sha256(original_url.encode()).hexdigest()
existing = db.query("SELECT short_code FROM urls WHERE checksum = %s", checksum)
if existing:
return existing[0]['short_code'] # Return existing code
# 2. Handle custom alias
if custom_alias:
if not is_valid_alias(custom_alias):
raise ValueError("Invalid custom alias")
if db.exists("SELECT 1 FROM urls WHERE short_code = %s", custom_alias):
raise ValueError("Alias already taken")
return custom_alias
# 3. Generate ID-based code (primary strategy)
url_id = db.insert("INSERT INTO urls (original_url, checksum) VALUES (%s, %s) RETURNING id",
original_url, checksum)
return base62_encode(url_id)
```
### Custom Alias Validation
```python
def is_valid_alias(alias: str) -> bool:
"""Validate custom alias format."""
return bool(re.match(r'^[a-zA-Z0-9]{4,20}$', alias))
```
## Data Structures
- **checksum**: SHA-256 hash of URL for duplicate detection
- **collision_retry_count**: Track collision attempts for monitoring
## Acceptance Criteria
- [ ] Generated codes are 6-8 characters
- [ ] No duplicate short codes in database (verified by UNIQUE constraint)
- [ ] Duplicate URLs return existing short code
- [ ] Custom aliases validated for format and uniqueness
- [ ] Collision handling retries up to 3 times with different salts
- [ ] Unit tests cover: normal case, duplicate URL, custom alias, collision
## Notes
- **Why sequential ID as primary**: Simpler, predictable length, no collisions
- **Hash-based as alternative**: For future distributed generation needs
- **Trade-off**: Sequential IDs are guessable but acceptable for public URLs
## Edge Cases
- URL longer than database limit → truncate before hashing
- Special characters in custom alias → regex validation
- Database connection failure during insert → retry logic
- Concurrent duplicate URL inserts → UNIQUE constraint + application retry
## Performance
- Duplicate check: O(1) with checksum index
- Insert: <10ms with proper connection pooling
- Custom alias check: O(1) with short_code index
+114
View File
@@ -0,0 +1,114 @@
# Subtask: URL Shortening API (Create Endpoint)
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-04
**Dependencies**: Decomp/001-01 (Database), Decomp/001-03 (Code Generation)
## Description
Implement HTTP API for creating short URLs. This is the main entry point for users to shorten URLs.
## Requirements
- RESTful POST endpoint for creating short URLs
- Support custom alias parameter
- Return short URL and metadata
- Rate limiting for abuse prevention
- Input validation and error handling
- <200ms response time p95
## Technical Specifications
### API Endpoint
```http
POST /api/v1/shorten
Content-Type: application/json
{
"url": "https://example.com/very/long/url",
"custom_alias": "mylink" // optional
}
Response 201 Created:
{
"short_code": "abc123",
"short_url": "https://short.est/abc123",
"original_url": "https://example.com/very/long/url",
"created_at": "2025-02-04T10:30:00Z",
"expires_at": null // or ISO timestamp if set
}
Errors:
400 Bad Request - Invalid URL or alias
409 Conflict - Custom alias already taken
422 Unprocessable Entity - URL validation failed
429 Too Many Requests - Rate limit exceeded
```
### Request Validation
```python
def validate_shorten_request(data: dict) -> tuple[bool, str | None]:
"""Validate request payload."""
url = data.get('url')
if not url:
return False, "URL is required"
# URL format validation
try:
result = urlparse(url)
if not all([result.scheme, result.netloc]):
return False, "Invalid URL format"
if result.scheme not in ['http', 'https']:
return False, "Only HTTP/HTTPS URLs allowed"
except Exception:
return False, "Invalid URL format"
# Custom alias validation
custom_alias = data.get('custom_alias')
if custom_alias and not is_valid_alias(custom_alias):
return False, "Invalid custom alias format"
return True, None
```
### Rate Limiting
```python
# Redis-based rate limiting
RATE_LIMIT = 10 requests per minute per IP
def check_rate_limit(identifier: str) -> bool:
"""Check if identifier exceeded rate limit."""
key = f"ratelimit:{identifier}:{datetime.utcnow().strftime('%Y%m%d%H%M')}"
count = redis.incr(key)
redis.expire(key, 60) # 1 minute window
return count <= RATE_LIMIT
```
## Acceptance Criteria
- [ ] POST /api/v1/shorten endpoint functional
- [ ] Returns 201 with valid response body
- [ ] Validates URL format (scheme, structure)
- [ ] Validates custom alias format
- [ ] Rate limiting enforced (10 req/min per IP)
- [ ] Error responses with proper status codes
- [ ] <200ms p95 latency (excluding rate limit checks)
- [ ] Unit tests + integration tests
## Notes
- **Framework**: Use FastAPI or Flask (async preferred)
- **Rate limiting**: Redis for distributed scenarios
- **Logging**: Log all URL creations for analytics
- **Monitoring**: Track response times, error rates
## Edge Cases
- URL with Unicode characters → punycode encoding
- URL with fragments/hash → preserve in original_url
- Empty request body → 400 error
- Malformed JSON → 400 error
- Database timeout → 503 error
## Performance Optimization
- Connection pooling for database
- Async I/O for database queries
- Cache frequent URLs in Redis (optional optimization)
+159
View File
@@ -0,0 +1,159 @@
# Subtask: URL Redirect Endpoint
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-05
**Dependencies**: Decomp/001-01 (Database), Decomp/001-03 (Code Generation)
## Description
Implement HTTP redirect endpoint that resolves short codes to original URLs. This is the most performance-critical path (<50ms p95).
## Requirements
- Resolve short code to original URL
- Return HTTP 301 (permanent) or 302 (temporary) redirect
- Check link expiration (TTL)
- Record analytics for each redirect
- Cache hot URLs for performance
- <50ms p95 latency
## Technical Specifications
### API Endpoint
```http
GET /{short_code}
Response 301 Moved Permanently (or 302):
Location: {original_url}
Response 404 Not Found:
{
"error": "Short URL not found or expired"
}
Response 410 Gone:
{
"error": "Short URL has expired"
}
```
### Redirect Logic
```python
async def redirect_handler(short_code: str, request):
"""Handle redirect requests with caching and analytics."""
# 1. Check cache first (Redis)
cache_key = f"url:{short_code}"
cached = await redis.get(cache_key)
if cached:
data = json.loads(cached)
await record_analytics(data['url_id'], request)
return RedirectResponse(data['original_url'], status_code=301)
# 2. Query database
url_data = await db.fetch_one(
"SELECT id, original_url, expires_at FROM urls WHERE short_code = $1",
short_code
)
if not url_data:
raise HTTPException(404, "Short URL not found")
# 3. Check expiration
if url_data['expires_at'] and url_data['expires_at'] < datetime.utcnow():
raise HTTPException(410, "Short URL has expired")
# 4. Cache result (5 minute TTL)
await redis.setex(cache_key, 300, json.dumps({
'url_id': url_data['id'],
'original_url': url_data['original_url']
}))
# 5. Record analytics (async, non-blocking)
await record_analytics(url_data['id'], request)
# 6. Return redirect
return RedirectResponse(url_data['original_url'], status_code=301)
```
### Analytics Recording
```python
async def record_analytics(url_id: int, request):
"""Record click analytics asynchronously."""
try:
user_agent = request.headers.get('user-agent', '')
ip_address = request.client.host
referrer = request.headers.get('referer', '')
# Queue for batch insert (use message queue or buffer)
await analytics_queue.put({
'url_id': url_id,
'clicked_at': datetime.utcnow(),
'user_agent': user_agent,
'ip_address': ip_address,
'referrer': referrer
})
except Exception:
# Analytics failure should not break redirect
pass
```
### Caching Strategy
```python
# Redis cache configuration
CACHE_TTL = 300 # 5 minutes
CACHE_WARMUP = True # Pre-populate cache for known hot URLs
async def warmup_cache():
"""Pre-populate cache for frequently accessed URLs."""
hot_urls = await db.fetch_all(
"""SELECT short_code, original_url, id
FROM urls
WHERE access_count > 100
ORDER BY access_count DESC
LIMIT 1000"""
)
for url in hot_urls:
await redis.setex(
f"url:{url['short_code']}",
CACHE_TTL,
json.dumps({'url_id': url['id'], 'original_url': url['original_url']})
)
```
## Acceptance Criteria
- [ ] GET /{short_code} returns 301/302 redirect
- [ ] Resolves short codes to original URLs
- [ ] Returns 404 for non-existent codes
- [ ] Returns 410 for expired URLs
- [ ] Records analytics for each redirect
- [ ] Cache hit rate >80% for hot URLs
- [ ] <50ms p95 latency (measured with load test)
- [ ] Analytics failure doesn't break redirect
## Notes
- **301 vs 302**: Use 301 for permanent redirects (allows browser caching)
- **Cache strategy**: LRU eviction, 5-minute TTL balances freshness and performance
- **Analytics decoupling**: Async queue ensures analytics don't block redirect
- **Performance bottleneck**: Database query → cache critical
## Edge Cases
- Short code with special characters → 404 (validation)
- Expired URL → 410 Gone
- Database timeout → serve from stale cache if available
- Analytics queue full → drop analytics, don't block redirect
- IP address spoofing → log X-Forwarded-For header if present
## Performance Targets
- Cache hit: <5ms
- Cache miss (DB): <50ms
- Analytics recording: <1ms (async, non-blocking)
- Throughput: 100K requests/second (with caching)
## Monitoring
- Track cache hit/miss ratio
- Monitor p50/p95/p99 latency
- Alert on latency >100ms
- Track error rates (404, 410)
+127
View File
@@ -0,0 +1,127 @@
# Subtask: Analytics Recording and Storage
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-06
**Dependencies**: Decomp/001-01 (Database Schema)
## Description
Implement analytics recording system for tracking URL clicks. Must handle high-volume writes (100K req/sec) without blocking redirect requests.
## Requirements
- Record click data: timestamp, user-agent, IP, referrer
- Batch inserts for performance (not row-by-row)
- Non-blocking operation (async queue)
- Handle geo-location lookup (optional)
- Survive database failures gracefully
- Support analytics queries
## Technical Specifications
### Data Collection Architecture
```python
# Async queue for buffering analytics events
class AnalyticsBuffer:
def __init__(self, max_size=10000, flush_interval=5):
self.buffer = []
self.max_size = max_size
self.flush_interval = flush_interval # seconds
self.lock = asyncio.Lock()
async def add(self, event: dict):
"""Add event to buffer, flush if full."""
async with self.lock:
self.buffer.append(event)
if len(self.buffer) >= self.max_size:
await self._flush()
async def _flush(self):
"""Batch insert all buffered events."""
if not self.buffer:
return
try:
await db.execute_many(
"""INSERT INTO url_analytics (url_id, clicked_at, user_agent, ip_address, referrer)
VALUES ($1, $2, $3, $4, $5)""",
self.buffer
)
self.buffer.clear()
except Exception as e:
# Log error but don't crash
logger.error(f"Analytics flush failed: {e}")
# Keep buffer to retry later
```
### Geo-location Lookup (Optional Enhancement)
```python
async def enrich_geo_location(event: dict) -> dict:
"""Add geo-location data to analytics event."""
try:
ip = event.get('ip_address')
if not ip or ip in ('127.0.0.1', '::1'):
return event
# Use MaxMind GeoLite2 or similar
geo_data = await geoip_lookup(ip)
event['country_code'] = geo_data.get('country_code')
event['city'] = geo_data.get('city')
except Exception:
pass # Geo-location failure not critical
return event
```
### Background Worker
```python
async def analytics_worker():
"""Background task to periodically flush analytics buffer."""
buffer = AnalyticsBuffer()
while True:
try:
await asyncio.sleep(buffer.flush_interval)
await buffer.flush()
except Exception as e:
logger.error(f"Analytics worker error: {e}")
```
## Acceptance Criteria
- [ ] Analytics events captured for all redirects
- [ ] Batch inserts (not single-row)
- [ ] Non-blocking operation (redirect latency unaffected)
- [ ] Survives database failures (drop events, don't crash)
- [ ] Flush interval: 5 seconds or 10K events
- [ ] Unit tests for buffer overflow and error handling
## Notes
- **Why async queue**: Decouples redirect latency from analytics write speed
- **Batch size**: 10K events balances memory usage and DB efficiency
- **Flush interval**: 5 seconds limits data loss on failure
- **Trade-off**: Accept data loss on crash vs. synchronous writes (chosen async)
## Alternative: Message Queue (Scale-up Path)
For 1M+ events/sec, replace in-memory buffer with:
- Redis Streams
- Kafka
- RabbitMQ
## Edge Cases
- Buffer overflow → flush immediately, drop if still full
- Database connection lost → keep buffering, alert, drop when full
- Malformed user-agent → store as-is, don't validate
- IPv6 addresses → store in INET column (PostgreSQL handles this)
- Private IP ranges → skip geo-location lookup
## Performance Targets
- Memory usage: <100MB for 10K event buffer
- Flush time: <1 second for 10K batch insert
- Zero impact on redirect latency
## Monitoring
- Buffer size alerts
- Flush success/failure rate
- Events per second throughput
- Database insert latency
+130
View File
@@ -0,0 +1,130 @@
# Subtask: QR Code Generation
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-07
**Dependencies**: Decomp/001-03 (Code Generation), Decomp/001-04 (Create API)
## Description
Generate QR codes for short URLs. QR codes should be generated on-demand and cached.
## Requirements
- Generate QR code image (PNG format) for short URLs
- Support configurable size (default 200x200px)
- Cache generated QR codes
- Serve via dedicated endpoint
- Handle QR code with logo (optional enhancement)
## Technical Specifications
### API Endpoint
```http
GET /api/v1/qr/{short_code}?size=200
Response 200 OK:
Content-Type: image/png
<binary PNG data>
Response 404 Not Found:
{
"error": "Short URL not found"
}
```
### QR Code Generation
```python
import qrcode
from io import BytesIO
async def generate_qr_code(short_url: str, size: int = 200) -> bytes:
"""Generate QR code for URL."""
# Validate size parameter
if not 50 <= size <= 1000:
raise ValueError("Size must be between 50 and 1000")
# Create QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=max(1, size // 25), # Approximate scaling
border=4,
)
qr.add_data(short_url)
qr.make(fit=True)
# Generate image
img = qr.make_image(fill_color="black", back_color="white")
# Resize to exact dimensions
img = img.resize((size, size), resample=0)
# Convert to bytes
buffer = BytesIO()
img.save(buffer, format='PNG')
return buffer.getvalue()
```
### Caching Strategy
```python
async def get_qr_code(short_code: str, size: int = 200) -> bytes:
"""Get QR code from cache or generate new one."""
cache_key = f"qr:{short_code}:{size}"
# Check cache
cached = await redis.get(cache_key)
if cached:
return cached
# Verify short code exists
url_data = await db.fetch_one(
"SELECT short_code FROM urls WHERE short_code = $1",
short_code
)
if not url_data:
raise HTTPException(404, "Short URL not found")
# Generate QR code
short_url = f"{BASE_URL}/{short_code}"
qr_data = await generate_qr_code(short_url, size)
# Cache for 24 hours
await redis.setex(cache_key, 86400, qr_data)
return qr_data
```
## Acceptance Criteria
- [ ] GET /api/v1/qr/{short_code} returns PNG image
- [ ] QR code scans to correct short URL
- [ ] Size parameter validated (50-1000px)
- [ ] QR codes cached in Redis (24 hour TTL)
- [ ] Returns 404 for non-existent short codes
- [ ] Unit tests for QR generation and caching
## Notes
- **Library**: `qrcode` (pip install qrcode[pil])
- **Cache duration**: 24 hours (QR codes don't change)
- **Error correction**: L (7%) for smallest size
- **Trade-off**: Generate on-demand vs. pre-generate (on-demand chosen for flexibility)
## Edge Cases
- Invalid size parameter → 400 error
- Short URL longer than QR capacity → use higher version QR
- Concurrent generation → use cache lock or accept duplicate work
- QR library failure → 500 error
## Performance Targets
- Generation time: <100ms
- Cache hit: <10ms (Redis fetch)
- Memory per QR: ~10KB (200x200 PNG)
## Optional Enhancements
- Logo in center (requires higher error correction)
- Different colors
- Vector format (SVG) for print
- Bulk generation for analytics
+225
View File
@@ -0,0 +1,225 @@
# Subtask: Analytics Query API
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-08
**Dependencies**: Decomp/001-01 (Database), Decomp/001-06 (Analytics Recording)
## Description
Implement API endpoints for querying URL analytics. Provide statistics, click history, and aggregated data.
## Requirements
- Get click count for a short URL
- Get click history with pagination
- Aggregate analytics by day/country/device
- Support date range filtering
- <500ms response time p95
## Technical Specifications
### API Endpoints
```http
# Get URL statistics
GET /api/v1/stats/{short_code}
Response 200 OK:
{
"short_code": "abc123",
"original_url": "https://example.com",
"created_at": "2025-02-01T10:00:00Z",
"total_clicks": 1234,
"last_clicked": "2025-02-04T15:30:00Z",
"expires_at": null
}
# Get click history with pagination
GET /api/v1/analytics/{short_code}?page=1&limit=50&start_date=2025-02-01&end_date=2025-02-04
Response 200 OK:
{
"short_code": "abc123",
"total_clicks": 1234,
"page": 1,
"limit": 50,
"total_pages": 25,
"clicks": [
{
"clicked_at": "2025-02-04T15:30:00Z",
"user_agent": "Mozilla/5.0...",
"country_code": "US",
"city": "San Francisco",
"referrer": "https://google.com"
}
]
}
# Get aggregated statistics
GET /api/v1/analytics/{short_code}/aggregate?group_by=day&start_date=2025-02-01
Response 200 OK:
{
"short_code": "abc123",
"aggregation": "day",
"data": [
{"date": "2025-02-01", "clicks": 150},
{"date": "2025-02-02", "clicks": 230},
{"date": "2025-02-03", "clicks": 456},
{"date": "2025-02-04", "clicks": 398}
]
}
```
### Query Implementation
```python
async def get_url_stats(short_code: str) -> dict:
"""Get basic statistics for a short URL."""
url_data = await db.fetch_one(
"""SELECT short_code, original_url, created_at, expires_at, access_count
FROM urls WHERE short_code = $1""",
short_code
)
if not url_data:
raise HTTPException(404, "Short URL not found")
last_click = await db.fetch_one(
"""SELECT clicked_at FROM url_analytics
WHERE url_id = $1
ORDER BY clicked_at DESC LIMIT 1""",
url_data['id']
)
return {
"short_code": url_data['short_code'],
"original_url": url_data['original_url'],
"created_at": url_data['created_at'].isoformat(),
"total_clicks": url_data['access_count'],
"last_clicked": last_click['clicked_at'].isoformat() if last_click else None,
"expires_at": url_data['expires_at'].isoformat() if url_data['expires_at'] else None
}
async def get_click_history(short_code: str, page: int = 1, limit: int = 50,
start_date: str = None, end_date: str = None) -> dict:
"""Get paginated click history."""
# Build query with filters
conditions = ["url_id = (SELECT id FROM urls WHERE short_code = $1)"]
params = [short_code]
param_count = 1
if start_date:
param_count += 1
conditions.append(f"clicked_at >= ${param_count}")
params.append(start_date)
if end_date:
param_count += 1
conditions.append(f"clicked_at <= ${param_count}")
params.append(end_date)
where_clause = " AND ".join(conditions)
# Get total count
total = await db.fetch_one(
f"SELECT COUNT(*) as count FROM url_analytics WHERE {where_clause}",
*params
)
total_clicks = total['count']
total_pages = (total_clicks + limit - 1) // limit
# Get paginated results
offset = (page - 1) * limit
clicks = await db.fetch_all(
f"""SELECT clicked_at, user_agent, country_code, city, referrer
FROM url_analytics
WHERE {where_clause}
ORDER BY clicked_at DESC
LIMIT ${param_count + 1} OFFSET ${param_count + 2}""",
*params, limit, offset
)
return {
"short_code": short_code,
"total_clicks": total_clicks,
"page": page,
"limit": limit,
"total_pages": total_pages,
"clicks": [dict(click) for click in clicks]
}
async def get_aggregated_clicks(short_code: str, group_by: str = 'day',
start_date: str = None, end_date: str = None) -> dict:
"""Get aggregated click statistics."""
# Map group_by to SQL date truncation
trunc_map = {
'day': "DATE_TRUNC('day', clicked_at)",
'hour': "DATE_TRUNC('hour', clicked_at)",
'month': "DATE_TRUNC('month', clicked_at)"
}
if group_by not in trunc_map:
raise HTTPException(400, f"Invalid group_by: {group_by}")
date_trunc = trunc_map[group_by]
# Build query
conditions = ["url_id = (SELECT id FROM urls WHERE short_code = $1)"]
params = [short_code]
param_count = 1
if start_date:
param_count += 1
conditions.append(f"clicked_at >= ${param_count}")
params.append(start_date)
if end_date:
param_count += 1
conditions.append(f"clicked_at <= ${param_count}")
params.append(end_date)
where_clause = " AND ".join(conditions)
query = f"""
SELECT {date_trunc} as period, COUNT(*) as clicks
FROM url_analytics
WHERE {where_clause}
GROUP BY period
ORDER BY period ASC
"""
results = await db.fetch_all(query, *params)
return {
"short_code": short_code,
"aggregation": group_by,
"data": [{"date": r['period'].isoformat(), "clicks": r['clicks']} for r in results]
}
```
## Acceptance Criteria
- [ ] GET /api/v1/stats/{short_code} returns URL statistics
- [ ] GET /api/v1/analytics/{short_code} returns paginated click history
- [ ] GET /api/v1/analytics/{short_code}/aggregate returns aggregated data
- [ ] Date range filtering works correctly
- [ ] Pagination works correctly (page, limit, total_pages)
- [ ] Group by day/hour/month supported
- [ ] <500ms p95 response time
- [ ] Unit tests for all endpoints
## Notes
- **Database indexes**: Composite index on (url_id, clicked_at) critical for performance
- **Pagination**: Cursor-based pagination better for large datasets (future enhancement)
- **Caching**: Cache stats endpoint (5 minute TTL)
## Edge Cases
- URL with no clicks → return 0 total_clicks
- Page beyond total_pages → return empty array
- Invalid date format → 400 error
- Group by not supported → 400 error
## Performance Optimization
- Materialized view for aggregated stats (if query is slow)
- Query timeout: 5 seconds
- Limit max results: 10,000 per query
+182
View File
@@ -0,0 +1,182 @@
# Subtask: Redis Caching Layer
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-09
**Dependencies**: None (can be implemented in parallel)
## Description
Implement Redis caching layer for URL lookups to achieve <50ms p95 latency. Handle cache warming, eviction, and failure scenarios.
## Requirements
- Cache short URL → original URL mapping
- Cache hit rate >80%
- TTL-based eviction (5 minutes for hot URLs)
- Graceful degradation on Redis failure
- Connection pooling and retry logic
## Technical Specifications
### Cache Configuration
```python
import redis.asyncio as redis
from typing import Optional
class URLCache:
def __init__(self, redis_url: str = "redis://localhost:6379"):
self.pool = redis.ConnectionPool.from_url(
redis_url,
max_connections=50,
retry_on_timeout=True,
retry_on_error=[redis.ConnectionError, redis.TimeoutError],
socket_timeout=2,
socket_connect_timeout=2
)
self.redis = redis.Redis(connection_pool=self.pool)
self.default_ttl = 300 # 5 minutes
async def get_url(self, short_code: str) -> Optional[dict]:
"""Get URL from cache."""
try:
data = await self.redis.get(f"url:{short_code}")
return json.loads(data) if data else None
except Exception as e:
logger.warning(f"Cache get failed: {e}")
return None # Degrade gracefully
async def set_url(self, short_code: str, url_data: dict, ttl: int = None):
"""Set URL in cache."""
try:
ttl = ttl or self.default_ttl
await self.redis.setex(
f"url:{short_code}",
ttl,
json.dumps(url_data)
)
except Exception as e:
logger.warning(f"Cache set failed: {e}")
# Don't raise, cache failure is non-critical
async def invalidate(self, short_code: str):
"""Invalidate cache entry."""
try:
await self.redis.delete(f"url:{short_code}")
except Exception as e:
logger.warning(f"Cache invalidation failed: {e}")
async def get_multi(self, short_codes: list[str]) -> dict[str, dict]:
"""Batch get multiple URLs from cache."""
try:
keys = [f"url:{code}" for code in short_codes]
values = await self.redis.mget(keys)
return {
code: json.loads(v)
for code, v in zip(short_codes, values)
if v is not None
}
except Exception as e:
logger.warning(f"Batch cache get failed: {e}")
return {}
async def close(self):
"""Close connections."""
await self.redis.close()
await self.pool.disconnect()
```
### Cache Warming Strategy
```python
async def warmup_cache(cache: URLCache, db):
"""Pre-populate cache with hot URLs."""
# Get top 1000 URLs by access count
hot_urls = await db.fetch_all("""
SELECT id, short_code, original_url, access_count
FROM urls
WHERE access_count > 10
ORDER BY access_count DESC
LIMIT 1000
""")
# Pipeline for faster bulk loading
pipe = cache.redis.pipeline()
for url in hot_urls:
key = f"url:{url['short_code']}"
data = json.dumps({
'url_id': url['id'],
'original_url': url['original_url']
})
pipe.setex(key, cache.default_ttl, data)
await pipe.execute()
logger.info(f"Warmed up cache with {len(hot_urls)} URLs")
```
### Cache-Aside Pattern Integration
```python
async def get_url_with_cache(short_code: str, cache: URLCache, db):
"""Get URL using cache-aside pattern."""
# 1. Try cache first
cached = await cache.get_url(short_code)
if cached:
return cached['original_url'], True # True = cache hit
# 2. Cache miss: query database
url_data = await db.fetch_one(
"SELECT id, original_url, expires_at FROM urls WHERE short_code = $1",
short_code
)
if not url_data:
return None, False
# Check expiration
if url_data['expires_at'] and url_data['expires_at'] < datetime.utcnow():
return None, False
# 3. Populate cache for next request
await cache.set_url(short_code, {
'url_id': url_data['id'],
'original_url': url_data['original_url']
})
return url_data['original_url'], False # False = cache miss
```
## Acceptance Criteria
- [ ] URLCache class implemented with async methods
- [ ] Cache hit rate >80% for hot URLs
- [ ] Graceful degradation on Redis failure (return None, don't crash)
- [ ] Connection pooling configured (max 50 connections)
- [ ] Cache warming function implemented
- [ ] TTL properly configured (5 minutes default)
- [ ] Unit tests for cache hit/miss scenarios
## Notes
- **Why Redis**: Fast in-memory store, supports TTL, distributed
- **Cache-aside**: Simple pattern, avoids stale data issues
- **Graceful degradation**: System works even if Redis is down
- **Trade-off**: Accept stale data for 5 minutes vs. cache invalidation overhead
## Failure Scenarios
- Redis connection lost → return cache miss, query DB
- Redis timeout → log warning, continue without cache
- OOM error → Redis evicts oldest keys (LRU), acceptable
- Network partition → continue without cache
## Performance Targets
- Cache GET: <5ms p95
- Cache SET: <10ms p95
- Batch GET (100 keys): <50ms p95
- Memory usage: <1GB for 100K cached URLs
## Monitoring
- Cache hit/miss ratio (target >80%)
- Redis connection errors
- Memory usage
- Eviction rate
- Command execution times
+196
View File
@@ -0,0 +1,196 @@
# Subtask: Rate Limiting Implementation
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-10
**Dependencies**: Decomp/001-09 (Redis Cache) - uses Redis for distributed rate limiting
## Description
Implement rate limiting to prevent abuse of the URL shortening service. Support different limits for different actions (create vs. redirect).
## Requirements
- Rate limit URL creation (10 per minute per IP)
- Rate limit redirects (100 per second per IP)
- Support API key-based rate limiting (higher limits)
- Distributed (works across multiple instances)
- Sliding window algorithm
- Return proper HTTP headers (X-RateLimit-*)
## Technical Specifications
### Rate Limiting Configuration
```python
from dataclasses import dataclass
from enum import Enum
class Action(Enum):
CREATE = "create"
REDIRECT = "redirect"
@dataclass
class RateLimit:
requests: int
window: int # seconds
RATE_LIMITS = {
Action.CREATE: RateLimit(requests=10, window=60), # 10/min
Action.REDIRECT: RateLimit(requests=100, window=1), # 100/sec
}
API_KEY_LIMITS = {
Action.CREATE: RateLimit(requests=100, window=60), # 100/min
Action.REDIRECT: RateLimit(requests=1000, window=1), # 1000/sec
}
```
### Sliding Window Implementation
```python
class RateLimiter:
def __init__(self, redis: redis.Redis):
self.redis = redis
async def check_rate_limit(
self,
identifier: str, # IP address or API key
action: Action,
api_key: str = None
) -> tuple[bool, dict]:
"""
Check if request is within rate limit.
Returns (allowed, rate_limit_info)
"""
# Get limits
limits = API_KEY_LIMITS if api_key else RATE_LIMITS
limit = limits[action]
# Sliding window key
key = f"ratelimit:{action.value}:{identifier}"
now = time.time()
window_start = now - limit.window
# Clean up old entries and count current window
pipe = self.redis.pipeline()
pipe.zremrangebyscore(key, 0, window_start)
pipe.zcard(key)
pipe.zadd(key, {str(now): now})
pipe.expire(key, limit.window)
results = await pipe.execute()
current_count = results[1]
remaining = max(0, limit.requests - current_count - 1)
reset_at = now + limit.window
allowed = current_count < limit.requests
return allowed, {
"limit": limit.requests,
"remaining": remaining,
"reset": int(reset_at)
}
async def is_allowed(self, identifier: str, action: Action, api_key: str = None) -> bool:
"""Simple check without returning info."""
allowed, _ = await self.check_rate_limit(identifier, action, api_key)
return allowed
```
### Middleware Integration
```python
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
async def rate_limit_middleware(request: Request, call_next):
"""Rate limiting middleware."""
# Extract identifier
api_key = request.headers.get("X-API-Key")
identifier = api_key or request.client.host
# Determine action based on path
if request.url.path == "/api/v1/shorten" and request.method == "POST":
action = Action.CREATE
elif request.url.path.startswith("/api/v1/"):
action = Action.REDIRECT # Analytics, stats, etc.
else:
# Redirect paths (/{short_code}) - no rate limiting
return await call_next(request)
# Check rate limit
limiter = request.app.state.rate_limiter
allowed, info = await limiter.check_rate_limit(identifier, action, api_key)
# Add rate limit headers
headers = {
"X-RateLimit-Limit": str(info["limit"]),
"X-RateLimit-Remaining": str(info["remaining"]),
"X-RateLimit-Reset": str(info["reset"])
}
if not allowed:
return JSONResponse(
status_code=429,
content={"error": "Rate limit exceeded", "retry_after": info["reset"]},
headers=headers
)
response = await call_next(request)
response.headers.update(headers)
return response
```
### Request Extraction Helper
```python
def extract_identifier(request: Request) -> tuple[str, str | None]:
"""
Extract rate limit identifier from request.
Returns (identifier, api_key)
"""
# Check for API key first
api_key = request.headers.get("X-API-Key")
if api_key:
return api_key, api_key
# Fall back to IP address
# Check for forwarded headers (behind proxy)
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
return forwarded_for.split(",")[0].strip(), None
return request.client.host, None
```
## Acceptance Criteria
- [ ] RateLimiter class with sliding window algorithm
- [ ] CREATE action limited to 10/min per IP (100/min with API key)
- [ ] REDIRECT action limited to 100/sec per IP (1000/sec with API key)
- [ ] X-RateLimit-* headers returned on all responses
- [ ] 429 status code when limit exceeded
- [ ] Works across multiple instances (Redis-backed)
- [ ] Unit tests for rate limit logic
## Notes
- **Why sliding window**: More accurate than fixed window, simpler than token bucket
- **Why Redis sorted sets**: Efficient for time-series data, ZREM range for cleanup
- **API key support**: Allows premium users higher limits
- **Trade-off**: Exact vs. approximate (sliding window is exact but more expensive)
## Edge Cases
- Clock skew → use Redis time, not client time
- Distributed systems → Redis provides single source of truth
- Burst traffic → sliding window handles better than fixed window
- API key leaking → consider adding HMAC signature
## Alternative Algorithms
- **Token Bucket**: Allows burst, more complex
- **Fixed Window**: Simpler but allows double requests at boundary
- **Leaky Bucket**: Smooths traffic, harder to implement
## Monitoring
- Rate limit hit rate (percentage of requests limited)
- API key usage distribution
- Top offenders by IP
- Redis sorted set size
+215
View File
@@ -0,0 +1,215 @@
# Subtask: Background Jobs and Cleanup
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-11
**Dependencies**: Decomp/001-01 (Database), Decomp/001-06 (Analytics)
## Description
Implement background job system for periodic tasks: expired URL cleanup, analytics aggregation, cache warming, and maintenance tasks.
## Requirements
- Clean up expired URLs periodically
- Archive old analytics data
- Warm up cache with hot URLs
- Database maintenance (VACUUM, ANALYZE)
- Job scheduling and monitoring
## Technical Specifications
### Job Framework
```python
import asyncio
from datetime import datetime, timedelta
from typing import Callable
class JobScheduler:
def __init__(self):
self.jobs = []
self.running = False
def schedule(self, interval: int, job: Callable, name: str):
"""Schedule a periodic job."""
self.jobs.append({
'name': name,
'interval': interval,
'job': job,
'last_run': None
})
async def start(self):
"""Start all scheduled jobs."""
self.running = True
tasks = [asyncio.create_task(self._run_job(job)) for job in self.jobs]
await asyncio.gather(*tasks)
async def _run_job(self, job_config: dict):
"""Run a single job periodically."""
while self.running:
try:
await job_config['job']()
job_config['last_run'] = datetime.utcnow()
await asyncio.sleep(job_config['interval'])
except Exception as e:
logger.error(f"Job {job_config['name']} failed: {e}")
await asyncio.sleep(60) # Wait before retry
async def stop(self):
"""Stop all jobs."""
self.running = False
```
### Expired URL Cleanup
```python
async def cleanup_expired_urls():
"""Delete expired URLs and their analytics."""
deleted_count = await db.execute("""
DELETE FROM urls
WHERE expires_at IS NOT NULL
AND expires_at < NOW()
RETURNING id
""")
if deleted_count > 0:
logger.info(f"Cleaned up {deleted_count} expired URLs")
# Note: Analytics are deleted via ON DELETE CASCADE
```
### Analytics Data Archival
```python
async def archive_old_analytics():
"""
Archive analytics older than 90 days to separate table or cold storage.
For simplicity, we'll move to an archive table.
"""
cutoff_date = datetime.utcnow() - timedelta(days=90)
# Create archive table if not exists
await db.execute("""
CREATE TABLE IF NOT EXISTS url_analytics_archive (
LIKE url_analytics INCLUDING ALL
)
""")
# Move old data to archive
moved_count = await db.execute("""
WITH archived AS (
DELETE FROM url_analytics
WHERE clicked_at < $1
RETURNING *
)
INSERT INTO url_analytics_archive
SELECT * FROM archived
RETURNING *
""", cutoff_date)
if moved_count > 0:
logger.info(f"Archived {moved_count} old analytics records")
# Optional: VACUUM to reclaim space
await db.execute("VACUUM ANALYZE url_analytics")
```
### Cache Warming Job
```python
async def periodic_cache_warmup():
"""Periodically warm up cache with hot URLs."""
try:
await warmup_cache(cache, db)
logger.info("Cache warmup completed")
except Exception as e:
logger.error(f"Cache warmup failed: {e}")
```
### Database Maintenance
```python
async def database_maintenance():
"""Run periodic database maintenance."""
try:
# Update statistics for query planner
await db.execute("ANALYZE urls")
await db.execute("ANALYZE url_analytics")
# Clean up dead tuples (VACUUM)
await db.execute("VACUUM ANALYZE")
logger.info("Database maintenance completed")
except Exception as e:
logger.error(f"Database maintenance failed: {e}")
```
### Job Scheduling Configuration
```python
def setup_scheduler(scheduler: JobScheduler):
"""Configure all scheduled jobs."""
# Expired URL cleanup - every hour
scheduler.schedule(
interval=3600,
job=cleanup_expired_urls,
name="cleanup_expired_urls"
)
# Analytics archival - daily at 2 AM
scheduler.schedule(
interval=86400, # 24 hours
job=archive_old_analytics,
name="archive_old_analytics"
)
# Cache warmup - every 10 minutes
scheduler.schedule(
interval=600,
job=periodic_cache_warmup,
name="cache_warmup"
)
# Database maintenance - weekly
scheduler.schedule(
interval=604800, # 7 days
job=database_maintenance,
name="database_maintenance"
)
```
## Acceptance Criteria
- [ ] JobScheduler class implemented
- [ ] Expired URLs cleaned up hourly
- [ ] Old analytics (>90 days) archived daily
- [ ] Cache warmed up every 10 minutes
- [ ] Database maintenance runs weekly
- [ ] Jobs handle failures gracefully (retry after 60 seconds)
- [ ] Logging for job execution and failures
- [ ] Unit tests for each job function
## Notes
- **Why async jobs**: Non-blocking, can run alongside API server
- **Why CASCADE delete**: Analytics auto-delete when URL deleted
- **Archive strategy**: Separate table for cold data (can be moved to S3 later)
- **VACUUM timing**: Run during low traffic (weekly)
## Edge Cases
- Database connection lost → retry after delay
- VACUUM locks table → run during maintenance window
- Archive table doesn't exist → create on first run
- Large data volume → batch deletes (1000 at a time)
## Alternative: External Job Scheduler
For production, consider:
- **Celery Beat**: More robust, distributed
- **Kubernetes CronJob**: Container-native
- **AWS EventBridge**: Cloud-native
- **cron**: Simple but no monitoring
## Monitoring
- Job execution timestamps
- Job failure rates
- Records affected per job
- Job duration (alert if >5 minutes)
+276
View File
@@ -0,0 +1,276 @@
# Subtask: Health Check and Monitoring
**Parent Task**: Decomp/001
**Subtask ID**: Decomp/001-12
**Dependencies**: All previous subtasks
## Description
Implement health check endpoints and monitoring for the service. Support readiness/liveness probes, dependency health checks, and metrics collection.
## Requirements
- Health check endpoint (/health)
- Readiness check (database, redis connectivity)
- Liveness check (basic service status)
- Metrics endpoint (Prometheus format)
- Dependency health monitoring
## Technical Specifications
### Health Check Endpoints
```http
# Liveness probe - is the service running?
GET /health/live
Response 200 OK:
{"status": "alive"}
# Readiness probe - is the service ready to serve traffic?
GET /health/ready
Response 200 OK:
{
"status": "ready",
"checks": {
"database": "ok",
"redis": "ok",
"analytics_queue": "ok"
}
}
Response 503 Service Unavailable:
{
"status": "not_ready",
"checks": {
"database": "failed",
"redis": "ok",
"analytics_queue": "ok"
},
"failed_checks": ["database"]
}
# Detailed health with metrics
GET /health
Response 200 OK:
{
"status": "healthy",
"version": "1.0.0",
"uptime_seconds": 3600,
"checks": {
"database": {"status": "ok", "latency_ms": 5},
"redis": {"status": "ok", "latency_ms": 2},
"analytics_queue": {"status": "ok", "queue_size": 123}
},
"metrics": {
"total_urls": 1234567,
"total_clicks": 98765432,
"cache_hit_rate": 0.87,
"active_connections": 42
}
}
```
### Health Check Implementation
```python
from datetime import datetime
from time import time
class HealthChecker:
def __init__(self, db, redis, analytics_queue):
self.db = db
self.redis = redis
self.analytics_queue = analytics_queue
self.start_time = time()
async def check_liveness(self) -> dict:
"""Basic liveness check."""
return {"status": "alive"}
async def check_readiness(self) -> dict:
"""Check if all dependencies are ready."""
checks = {}
failed = []
# Database check
try:
start = time()
await self.db.fetch_one("SELECT 1")
checks["database"] = "ok"
except Exception as e:
checks["database"] = f"failed: {str(e)}"
failed.append("database")
# Redis check
try:
start = time()
await self.redis.ping()
checks["redis"] = "ok"
except Exception as e:
checks["redis"] = f"failed: {str(e)}"
failed.append("redis")
# Analytics queue check
try:
queue_size = await self.analytics_queue.qsize()
checks["analytics_queue"] = "ok"
except Exception as e:
checks["analytics_queue"] = f"failed: {str(e)}"
failed.append("analytics_queue")
if failed:
return {
"status": "not_ready",
"checks": checks,
"failed_checks": failed
}
return {
"status": "ready",
"checks": checks
}
async def check_detailed(self) -> dict:
"""Detailed health check with metrics."""
checks = {}
metrics = {}
# Database health with latency
try:
start = time()
await self.db.fetch_one("SELECT 1")
db_latency = (time() - start) * 1000
# Get some metrics
url_count = await self.db.fetch_one("SELECT COUNT(*) as count FROM urls")
click_count = await self.db.fetch_one("SELECT SUM(access_count) as count FROM urls")
checks["database"] = {"status": "ok", "latency_ms": round(db_latency, 2)}
metrics["total_urls"] = url_count['count']
metrics["total_clicks"] = click_count['count'] or 0
except Exception as e:
checks["database"] = {"status": "failed", "error": str(e)}
# Redis health with latency
try:
start = time()
await self.redis.ping()
redis_latency = (time() - start) * 1000
# Get cache info
info = await self.redis.info('stats')
hit_rate = info.get('keyspace_hits', 0) / max(1, info.get('keyspace_hits', 0) + info.get('keyspace_misses', 0))
checks["redis"] = {"status": "ok", "latency_ms": round(redis_latency, 2)}
metrics["cache_hit_rate"] = round(hit_rate, 3)
except Exception as e:
checks["redis"] = {"status": "failed", "error": str(e)}
# Analytics queue
try:
queue_size = await self.analytics_queue.qsize()
checks["analytics_queue"] = {"status": "ok", "queue_size": queue_size}
except Exception as e:
checks["analytics_queue"] = {"status": "failed", "error": str(e)}
uptime = time() - self.start_time
return {
"status": "healthy" if all(c.get("status") == "ok" for c in checks.values()) else "degraded",
"version": os.getenv("APP_VERSION", "1.0.0"),
"uptime_seconds": round(uptime, 2),
"checks": checks,
"metrics": metrics
}
```
### Prometheus Metrics Endpoint
```http
GET /metrics
Response 200 OK (text/plain):
# HELP url_shortener_urls_total Total number of URLs
# TYPE url_shortener_urls_total gauge
url_shortener_urls_total 1234567
# HELP url_shortener_clicks_total Total number of clicks
# TYPE url_shortener_clicks_total gauge
url_shortener_clicks_total 98765432
# HELP url_shortener_cache_hits Cache hits
# TYPE url_shortener_cache_hits counter
url_shortener_cache_hits 87654321
# HELP url_shortener_cache_misses Cache misses
# TYPE url_shortener_cache_misses counter
url_shortener_cache_misses 12345678
# HELP url_shortener_request_latency_seconds Request latency
# TYPE url_shortener_request_latency_seconds histogram
url_shortener_request_latency_seconds_bucket{le="0.005"} 12345
url_shortener_request_latency_seconds_bucket{le="0.01"} 23456
...
url_shortener_request_latency_seconds_bucket{le="+Inf"} 99999
url_shortener_request_latency_seconds_sum 456.78
url_shortener_request_latency_seconds_count 99999
# HELP url_shortener_rate_limit_exceeded Rate limit exceeded
# TYPE url_shortener_rate_limit_exceeded counter
url_shortener_rate_limit_exceeded 1234
```
### Metrics Implementation
```python
from prometheus_client import Counter, Histogram, Gauge, generate_latest
# Define metrics
url_count = Gauge('url_shortener_urls_total', 'Total number of URLs')
click_count = Gauge('url_shortener_clicks_total', 'Total number of clicks')
cache_hits = Counter('url_shortener_cache_hits', 'Cache hits')
cache_misses = Counter('url_shortener_cache_misses', 'Cache misses')
request_latency = Histogram('url_shortener_request_latency_seconds', 'Request latency')
rate_limit_exceeded = Counter('url_shortener_rate_limit_exceeded', 'Rate limit exceeded')
async def metrics_handler():
"""Prometheus metrics endpoint."""
# Update gauges from database
urls = await db.fetch_one("SELECT COUNT(*) as count FROM urls")
url_count.set(urls['count'])
clicks = await db.fetch_one("SELECT SUM(access_count) as count FROM urls")
click_count.set(clicks['count'] or 0)
return Response(content=generate_latest(), media_type="text/plain")
```
## Acceptance Criteria
- [ ] GET /health/live returns 200 with {"status": "alive"}
- [ ] GET /health/ready returns 200 when all dependencies OK, 503 otherwise
- [ ] GET /health returns detailed status with metrics
- [ ] GET /metrics returns Prometheus format metrics
- [ ] Health checks have <100ms timeout for each dependency
- [ ] Liveness check always succeeds (no external dependencies)
- [ ] Readiness check fails fast on dependency issues
## Notes
- **Kubernetes probes**: Use /health/live for liveness, /health/ready for readiness
- **Timeout**: Each health check should timeout within 100ms
- **Circuit breaker**: Mark service unhealthy after 3 consecutive failures
- **Metrics**: Use prometheus_client for standard metrics
## Edge Cases
- Database timeout → mark as failed, don't block
- Redis down → continue serving (with degraded performance)
- High queue size → alert but don't fail readiness
- Partial metrics available → return what's available
## Monitoring Checklist
- Uptime (should be 99.9%+)
- Response times (p50, p95, p99)
- Error rates (4xx, 5xx)
- Cache hit rate (>80% target)
- Queue sizes
- Database connection pool usage