pycon icon indicating copy to clipboard operation
pycon copied to clipboard

Celery monitoring

Open marcoacierno opened this issue 2 years ago • 2 comments

marcoacierno avatar Apr 10 '24 11:04 marcoacierno

@claude prepare a plan and write it here on how we could introduce celery monitoring

marcoacierno avatar Oct 01 '25 02:10 marcoacierno

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 -E flag (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 OnlyOneAtTimeTask tasks

3. Implementation Steps

Phase 1: Quick Wins (1-2 days)

  1. Deploy Flower for immediate visibility

    • Create Flower ECS task definition
    • Configure authentication (use --basic-auth with env vars)
    • Set up internal ALB for access
    • Deploy to staging first
  2. 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():
        ...
    
  3. 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)

  1. Deploy Prometheus + Grafana

    • Set up Prometheus server (ECS or AWS Managed Prometheus)
    • Install celery-exporter or implement custom metrics endpoint
    • Create Grafana dashboards
    • Configure alerts
  2. 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
  3. 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)

  1. 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
  2. Custom Dashboards

    • Executive dashboard (high-level metrics)
    • Operations dashboard (detailed worker/task metrics)
    • Business metrics dashboard (uploads, emails, etc.)
  3. 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:

  1. Immediate (Week 1):

    • Deploy Flower for quick visibility ✅
    • Enhance Sentry with Cron Monitoring ✅
    • Add structured logging ✅
  2. Short-term (Weeks 2-3):

    • Implement custom CloudWatch metrics ✅
    • Create CloudWatch alarms ✅
    • Build initial dashboards ✅
  3. 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:

  1. Implement Phase 1 (Flower + Enhanced Sentry)?
  2. Create Terraform configurations for the monitoring infrastructure?
  3. Build CloudWatch dashboards and alarms first?
  4. Start with Prometheus + Grafana directly?

Let me know which approach you'd prefer, and I can begin implementation!


View Job Run | View Branch

claude[bot] avatar Oct 01 '25 02:10 claude[bot]