Celery monitoring
@claude prepare a plan and write it here on how we could introduce celery monitoring
Claude finished @marcoacierno's task —— View job
Celery Monitoring Plan
I've analyzed the current Celery setup and prepared a comprehensive plan for introducing monitoring capabilities.
Current State Analysis
Existing Setup:
- Celery Version: 5.4.0
- Broker & Backend: Redis (separate databases for broker and results)
- Workers:
- Standard worker (ECS, 1 instance)
- Heavy processing worker (Fargate, auto-scaled, 4 vCPU/16GB RAM)
- Beat scheduler (for periodic tasks)
- Tasks: ~31 tasks across 12 modules including:
- Video upload processing (YouTube integration)
- Email notifications
- File processing
- Membership checks
- Heavy processing workload management
- Infrastructure: AWS ECS/Fargate with CloudWatch logging
- Existing Monitoring:
- Sentry integration with CeleryIntegration (monitoring beat tasks)
- Custom task locking mechanism (
OnlyOneAtTimeTask) - Auto-scaling logic for heavy processing workers
- Workers run with
-Eflag (events enabled)
Proposed Monitoring Plan
1. Monitoring Tool Recommendations
Option A: Flower (Recommended for Quick Start)
Pros:
- Official Celery monitoring tool
- Real-time web dashboard
- Built-in support for task history, worker management
- Simple to deploy
- Free and open-source
Cons:
- Basic authentication (would need enhancement)
- No long-term metrics retention
- Limited alerting capabilities
Implementation:
# Add to pyproject.toml dependencies
flower>=2.0.0
# Create new ECS task definition for Flower
command = ["celery", "-A", "pycon", "flower", "--port=5555"]
Option B: Prometheus + Grafana (Recommended for Production)
Pros:
- Industry-standard metrics collection
- Excellent visualization with Grafana
- Long-term metrics retention
- Powerful alerting capabilities
- Integration with existing infrastructure
Cons:
- More complex setup
- Additional infrastructure costs
- Requires learning Prometheus query language
Implementation:
# Add to pyproject.toml
prometheus-client>=0.19.0
celery-exporter>=1.5.0 # or implement custom exporter
Option C: Enhanced Sentry Monitoring (Recommended for Error Tracking)
Current State: Already using Sentry with CeleryIntegration(monitor_beat_tasks=True)
Enhancement:
- Enable Celery Cron Monitoring for all periodic tasks
- Add performance monitoring for slow tasks
- Implement custom context for better error tracking
2. Key Metrics to Track
Worker Metrics
- Worker health/status (up/down)
- Active workers count
- Worker memory/CPU usage (via CloudWatch)
- Task prefetch count
- Workers idle time
Task Metrics
- Task success/failure rates
- Task execution time (p50, p95, p99)
- Task retry counts
- Tasks pending in queue by queue name
- Task timeout incidents
- Tasks by state (pending, running, success, failure, retry)
Queue Metrics
- Queue length by queue name (
default,heavy_processing) - Message processing rate
- Queue growth rate
- Queue latency (time from submission to start)
Business Metrics
- Video upload success/failure rates
- Email delivery metrics
- Heavy processing worker spawn/shutdown events
- Lock contention on
OnlyOneAtTimeTasktasks
3. Implementation Steps
Phase 1: Quick Wins (1-2 days)
-
Deploy Flower for immediate visibility
- Create Flower ECS task definition
- Configure authentication (use
--basic-authwith env vars) - Set up internal ALB for access
- Deploy to staging first
-
Enhance Sentry monitoring
- Add task-level context to errors
- Enable performance monitoring for key tasks
- Set up Cron Monitoring for periodic tasks
from sentry_sdk.crons import monitor @app.task @monitor(monitor_slug='process-schedule-items-videos') def process_schedule_items_videos_to_upload(): ... -
Add structured logging
- Log task start/finish with timing
- Log queue depths periodically
- Include correlation IDs for tracing
Phase 2: Production-Grade Monitoring (1 week)
-
Deploy Prometheus + Grafana
- Set up Prometheus server (ECS or AWS Managed Prometheus)
- Install
celery-exporteror implement custom metrics endpoint - Create Grafana dashboards
- Configure alerts
-
CloudWatch Integration
- Create CloudWatch custom metrics for:
- Queue lengths
- Task success/failure rates
- Worker health
- Set up CloudWatch Alarms for critical metrics
- Create CloudWatch Dashboard
- Create CloudWatch custom metrics for:
-
Custom Metrics Collection
# backend/pycon/celery_monitoring.py from celery.signals import task_prerun, task_postrun, task_failure from prometheus_client import Counter, Histogram, Gauge task_started = Counter('celery_task_started_total', 'Tasks started', ['task_name']) task_completed = Counter('celery_task_completed_total', 'Tasks completed', ['task_name', 'status']) task_duration = Histogram('celery_task_duration_seconds', 'Task duration', ['task_name']) queue_length = Gauge('celery_queue_length', 'Queue length', ['queue_name'])
Phase 3: Advanced Features (Ongoing)
-
Alerting Rules
- Alert if queue length exceeds threshold
- Alert if task failure rate > 5%
- Alert if no workers active
- Alert if task execution time > SLA
- Alert if heavy processing worker fails to start
-
Custom Dashboards
- Executive dashboard (high-level metrics)
- Operations dashboard (detailed worker/task metrics)
- Business metrics dashboard (uploads, emails, etc.)
-
Distributed Tracing
- Add OpenTelemetry for request tracing
- Trace tasks from API call → Celery task → completion
4. Infrastructure Requirements
For Flower (Option A)
- ECS Task (1 container, minimal resources: 256 CPU / 512 MB)
- Internal ALB or security group rules
- Environment variables for authentication
- Cost: ~$15-20/month
For Prometheus + Grafana (Option B)
- Prometheus server (ECS or AWS Managed: ~$50/month)
- Grafana instance (ECS or AWS Managed: ~$50/month)
- Storage for metrics (S3 or EBS)
- Total cost: ~$100-150/month
For Enhanced Sentry (Option C)
- Already using Sentry
- May increase Sentry event volume (monitor billing)
- No additional infrastructure
5. Security Considerations
- Authentication: All monitoring UIs must have authentication
- Network Security: Monitoring endpoints should be internal-only or VPN-access
- Secrets Management: Store credentials in AWS Secrets Manager
- RBAC: Implement role-based access for different teams
- Data Retention: Define retention policies for metrics (30-90 days recommended)
6. Recommended Approach
Start with a hybrid approach:
-
Immediate (Week 1):
- Deploy Flower for quick visibility ✅
- Enhance Sentry with Cron Monitoring ✅
- Add structured logging ✅
-
Short-term (Weeks 2-3):
- Implement custom CloudWatch metrics ✅
- Create CloudWatch alarms ✅
- Build initial dashboards ✅
-
Long-term (Month 2+):
- Evaluate Prometheus + Grafana based on needs ✅
- Implement advanced alerting ✅
- Add distributed tracing if needed ✅
7. Success Metrics
- Reduced mean time to detection (MTTR) for task failures
- Visibility into queue health and worker capacity
- Proactive alerts before user-facing issues
- Historical metrics for capacity planning
- Better debugging with correlation IDs and tracing
Next Steps
Would you like me to:
- Implement Phase 1 (Flower + Enhanced Sentry)?
- Create Terraform configurations for the monitoring infrastructure?
- Build CloudWatch dashboards and alarms first?
- Start with Prometheus + Grafana directly?
Let me know which approach you'd prefer, and I can begin implementation!