Initial commit: Test GLM project
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user