5.9 KiB
5.9 KiB
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
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
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
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
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
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
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)