Celery provides asynchronous task processing for FKApi, enabling background jobs like data scraping and scheduled tasks. This guide covers installation, configuration, and usage.Documentation Index
Fetch the complete documentation index at: https://docs.fkapi.sunr4y.dev/llms.txt
Use this file to discover all available pages before exploring further.
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
Linux (Ubuntu/Debian)
macOS
Windows
Option 1: Using Memurai (Recommended)Option 3: Using WSL2
- Download from https://www.memurai.com/
- Install and start the service
- Redis will run on
localhost:6379
# Activate virtual environment
source venv/bin/activate # Linux/Mac
# or
venv\Scripts\activate # Windows
# Install Celery packages
pip install celery[redis]==5.4.0
pip install django-celery-beat==2.6.0
pip install flower==2.0.1
pip install django-redis==5.4.0
These packages are already included in
requirements.txt, so if you installed all dependencies, you already have Celery.# Enable Celery
ENABLE_CELERY=True
# Redis configuration
REDIS_URL=redis://localhost:6379/1
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fkapi.settings")
app = Celery("fkapi")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
Running Celery
Starting Workers
Celery workers process async tasks. Start a worker with:Worker Options Explained
Worker Options Explained
--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:Starting Flower (Monitoring)
Flower provides a web UI for monitoring Celery:- 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 insettings.py:
Modifying Schedules
You can modify schedules in several ways:- Django Admin
- Settings File
- Go to http://localhost:8000/admin/
- Navigate to Periodic Tasks
- Add or edit tasks
- Changes take effect immediately
Task Examples
Creating a Task
Define tasks in your Django app’stasks.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:- Start Flower:
celery -A fkapi flower --port=5555 - Open http://localhost:5555
- 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:- Check worker is running:
celery -A fkapi inspect active - Check for errors in worker logs
- Verify task is registered:
celery -A fkapi inspect registered - Check Redis connection:
redis-cli ping
ModuleNotFoundError
Error:ModuleNotFoundError: No module named 'celery'
Solution:
Worker Crashes
Error: Worker exits unexpectedly Solution:- Check worker logs for errors
- Increase worker timeout
- Check database connection
- Verify memory availability
- Check for task deadlocks
Tasks Slow or Hanging
Error: Tasks take too long or never complete Solution:- Check database performance
- Add timeouts to external API calls
- Monitor Redis memory usage
- Increase worker concurrency
- Profile task code for bottlenecks
Production Deployment
For production, run Celery as a system service:Systemd Service (Linux)
Create/etc/systemd/system/celery.service:
Docker Deployment
See the Docker guide for containerized deployment with docker-compose.Best Practices
Task Design
Task Design
- Keep tasks small and focused
- Make tasks idempotent (safe to retry)
- Handle errors gracefully
- Add logging for debugging
- Set task timeouts
Performance
Performance
- Use appropriate concurrency settings
- Monitor Redis memory usage
- Use task routing for different priorities
- Implement rate limiting for external APIs
- Profile slow tasks
Reliability
Reliability
- Configure task retries
- Use result backends for important tasks
- Monitor task success rates
- Set up alerting for failures
- Back up Redis data in production
Security
Security
- 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