5.5 KiB
5.5 KiB
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
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
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
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