Skip to main content
Celery provides asynchronous task processing for FKApi, enabling background jobs like data scraping and scheduled tasks. This guide covers installation, configuration, and usage.

Overview

Celery is completely optional for FKApi. The system automatically falls back to threading if Celery is not available. However, Celery is recommended for production as it provides:
  • Better performance for background tasks
  • Task scheduling with Celery Beat
  • Task monitoring with Flower
  • Distributed task processing
  • Task retry and error handling

When to Use Celery

Use Celery

  • Production deployments
  • Scheduled tasks (daily scraping)
  • High-traffic environments
  • Task monitoring required

Skip Celery

  • Development/testing
  • Low-traffic deployments
  • Simpler setup preferred
  • No scheduled tasks needed

Architecture

FKApi uses Celery with the following components:
  • Redis: Message broker and result backend
  • Celery Worker: Processes async tasks
  • Celery Beat: Scheduler for periodic tasks
  • Flower: Web-based monitoring dashboard

Prerequisites

Before installing Celery, ensure you have:
  • Redis installed and running
  • Python 3.10 or higher
  • FKApi base installation complete

Installation

Running Celery

Starting Workers

Celery workers process async tasks. Start a worker with:
  • --loglevel=info: Set logging level (debug, info, warning, error, critical)
  • --pool=threads: Use thread pool (required for Windows)
  • --concurrency=4: Number of worker threads (adjust based on CPU cores)
  • -A fkapi: Name of the Celery app

Starting Beat Scheduler

Celery Beat schedules periodic tasks. Start the scheduler with:
The DatabaseScheduler stores schedules in the database, allowing runtime configuration through Django admin.

Starting Flower (Monitoring)

Flower provides a web UI for monitoring Celery:
Access the dashboard at: http://localhost:5555 Flower shows:
  • Active workers
  • Running tasks
  • Task history
  • Success/failure rates
  • Worker resource usage

Running All Services

For development, you’ll need to run three separate processes:

Scheduled Tasks

FKApi includes scheduled tasks configured in settings.py:

Modifying Schedules

You can modify schedules in several ways:
  1. Go to http://localhost:8000/admin/
  2. Navigate to Periodic Tasks
  3. Add or edit tasks
  4. Changes take effect immediately

Task Examples

Creating a Task

Define tasks in your Django app’s tasks.py:

Calling a Task

Call tasks asynchronously from your views or API endpoints:

Fallback to Threading

If Celery is not available, FKApi automatically uses threading:

Monitoring

Command Line

Monitor Celery from the command line:

Flower Dashboard

Flower provides comprehensive monitoring:
  1. Start Flower: celery -A fkapi flower --port=5555
  2. Open http://localhost:5555
  3. View:
    • Tasks: History of all tasks
    • Workers: Active workers and their status
    • Monitor: Real-time task execution
    • Broker: Redis connection stats

Troubleshooting

Redis Connection Failed

Error: Error: Redis is not running Solution:

Tasks Not Executing

Error: Tasks appear in queue but don’t execute Solution:
  1. Check worker is running: celery -A fkapi inspect active
  2. Check for errors in worker logs
  3. Verify task is registered: celery -A fkapi inspect registered
  4. Check Redis connection: redis-cli ping

ModuleNotFoundError

Error: ModuleNotFoundError: No module named 'celery' Solution:

Worker Crashes

Error: Worker exits unexpectedly Solution:
  1. Check worker logs for errors
  2. Increase worker timeout
  3. Check database connection
  4. Verify memory availability
  5. Check for task deadlocks

Tasks Slow or Hanging

Error: Tasks take too long or never complete Solution:
  1. Check database performance
  2. Add timeouts to external API calls
  3. Monitor Redis memory usage
  4. Increase worker concurrency
  5. Profile task code for bottlenecks

Production Deployment

For production, run Celery as a system service:

Systemd Service (Linux)

Create /etc/systemd/system/celery.service:
Enable and start:

Docker Deployment

See the Docker guide for containerized deployment with docker-compose.

Best Practices

  • Keep tasks small and focused
  • Make tasks idempotent (safe to retry)
  • Handle errors gracefully
  • Add logging for debugging
  • Set task timeouts
  • Use appropriate concurrency settings
  • Monitor Redis memory usage
  • Use task routing for different priorities
  • Implement rate limiting for external APIs
  • Profile slow tasks
  • Configure task retries
  • Use result backends for important tasks
  • Monitor task success rates
  • Set up alerting for failures
  • Back up Redis data in production
  • Use strong Redis passwords
  • Limit Redis network access
  • Validate task inputs
  • Use encrypted connections in production
  • Keep Celery and Redis updated

Next Steps

Docker Deployment

Deploy with docker-compose for simplified management

Monitoring

Set up Prometheus and Grafana for metrics