1. What is Celery?
Celery is a Python distributed task queue system (Distributed Task Queue) used to submit tasks to the message broker (Message Broker) for execution by an independent Worker process.
For example, after the user uploads a copy of PDF, the backend needs:
- Save upload record.
- Parse PDF text.
- Split the text into Chunks.
- Call the Embedding model.
- Write vector to database.
If all steps are executed in the HTTP request, the user may need to wait for tens of seconds or even longer.
After using Celery, time-consuming operations can be handed over to the background Worker.
Django / DRF
│
Submit Task
│
▼
Redis Broker
│
▼
Celery Worker
│
┌─────────┼─────────┐
▼ ▼ ▼
Document parsing Embedding data synchronization
Parse docs Embedding Sync data
└─────────┼─────────┘
▼
PostgreSQL / MinIO
API only needs to complete request verification, data creation and task submission before returning a response.
Note: Celery asynchronous tasks are different from Python’s asyncio. Celery can run tasks in separate processes or on other machines without relying on async def.
2. Core components of Celery
| components | function |
|---|---|
| Task | Python function that needs to be executed |
| Producer | The party that submitted the task, such as Django |
| Broker | Deliver and queue task messages such as Redis, RabbitMQ |
| Worker | Process that receives and executes tasks |
| Result Backend | Save task status and results |
| Beat | Scheduler that triggers tasks regularly |
Broker
Broker is responsible for delivering task messages.
For example:
process_document.delay(document_id)
Celery will serialize the task name, parameters and other information and send it through Broker.
Broker itself does not perform tasks.
Worker
Worker is an independently running Celery process, responsible for obtaining tasks and executing them.
A Worker can manage multiple concurrent execution units depending on the configuration.
Result Backend
Result Backend is used to save task execution status and results.
Common statuses include:
| Status | meaning |
|---|---|
| PENDING | No known outcome status yet |
| STARTED | Execution has started, corresponding tracking needs to be enabled |
| RETRY | Waiting to retry |
| SUCCESS | Executed successfully |
| FAILURE | Execution failed |
PENDING may also mean that task ID does not exist or the result has expired, so it cannot be judged based on it alone that the task must still be queued.
Broker and Result Backend can use the same Redis service but have different responsibilities.
3. Django project integration Celery
Assume that the Django project structure is:
backend/
├── manage.py
├── config/
│ ├── __init__.py
│ ├── settings.py
│ ├── celery.py
│ └── urls.py
└── documents/
├── models.py
├── views.py
└── tasks.py
Install dependencies
pip install "celery[redis]"
Create Celery App
At config/celery.py:
import os
from celery import Celery
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
"config.settings",
)
app = Celery("config")
app.config_from_object(
"django.conf:settings",
namespace="CELERY",
)
app.autodiscover_tasks()
Among them:
Celery("config"): Create Celery application.config_from_object(): Read Django Settings.namespace="CELERY": Configuration using theCELERY_prefix.autodiscover_tasks(): Automatically discovertasks.pywithin Django Apps.
At config/__init__.py:
from .celery import app as celery_app
__all__ = ("celery_app",)
Django Settings
CELERY_BROKER_URL = "redis://redis:6379/1"
CELERY_RESULT_BACKEND = "redis://redis:6379/2"
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TIMEZONE = "UTC"
CELERY_TASK_TRACK_STARTED = True
CELERY_RESULT_EXPIRES = 3600
redis here is the internal service name of Docker Compose.
The production environment needs to configure identity authentication and network isolation. If you do not need to save the task return value, you can also disable Result Backend to reduce additional storage overhead.
4. Definition and implementation Task
At documents/tasks.py:
from celery import shared_task
@shared_task
def process_document(document_id: int):
print(f"Processing document: {document_id}")
return {"document_id": document_id}
@shared_task allows tasks in Django App not to directly depend on specific Celery App instances.
delay()
Submit the task in View:
result = process_document.delay(123)
delay() is a shortcut for apply_async().
It sends the task to Broker, usually returning a AsyncResult object immediately, rather than waiting for the background function to complete.
task_id = result.id
apply_async()
If you need more control:
process_document.apply_async(
args=[123],
countdown=30,
)
Indicates that the task is scheduled to be executed in about 30 seconds.
You can also specify:
process_document.apply_async(
args=[123],
queue="documents",
)
countdown is not a strict real-time scheduling guarantee; for long-term scheduled tasks, priority should be given to a suitable scheduler rather than piling up a large number of long-term countdown tasks.
Do not call Task directly
process_document(123)
This typically executes the task synchronously within the current process rather than submitting a background task.
To distribute asynchronously, use:
process_document.delay(123)
5. Start Celery Worker
In development environment:
celery -A config worker --loglevel=info
Specify the number of concurrencies:
celery -A config worker \
--loglevel=info \
--concurrency=4
Specify queue:
celery -A config worker \
--loglevel=info \
--queues=documents
Note: The default Prefork Worker Pool relies on the process mechanism and is suitable for the Linux server; when developing on macOS or Windows, you need to choose a compatible running mode according to the platform.
Production environments typically run Worker through Docker Compose, a process manager, or a container orchestration system.
6. Practical applications in Django / DRF
Take users uploading documents as an example.
Business process:
POST /api/documents/
│
▼
Save files and database records
│
▼
Submit Celery Task
│
▼
HTTP 202 Accepted
│
▼
Worker parsing document
│
▼
Update Document Status
Define task status
For example Django Model:
class Document(models.Model):
class Status(models.TextChoices):
PENDING = "pending"
PROCESSING = "processing"
COMPLETED = "completed"
FAILED = "failed"
file = models.FileField(upload_to="documents/")
status = models.CharField(
max_length=20,
choices=Status.choices,
default=Status.PENDING,
)
error_message = models.TextField(blank=True)
The actual model also needs to add fields such as user association and creation time according to the project.
Task
from celery import shared_task
from .models import Document
@shared_task
def process_document(document_id):
document = Document.objects.get(pk=document_id)
document.status = Document.Status.PROCESSING
document.save(update_fields=["status"])
try:
# Parse document
# Split text
# Generate Embeddings
# Save processing results
...
except Exception as exc:
document.status = Document.Status.FAILED
document.error_message = str(exc)
document.save(
update_fields=["status", "error_message"]
)
raise
document.status = Document.Status.COMPLETED
document.save(update_fields=["status"])
The exception is reserved here for rethrowing so that Celery logs the task as failed. Production environments should not provide raw exceptions containing sensitive information directly to end users.
View Submit task
from django.db import transaction
def create_document(request):
with transaction.atomic():
document = Document.objects.create(
file=request.FILES["file"]
)
process_document.delay_on_commit(document.pk)
return {
"document_id": document.pk,
"status": "pending",
}
This is a business process diagram. Complete DRF View also requires Serializer, permission verification and response objects.
delay_on_commit(), available since Celery 5.4, is used to send tasks after a database transaction has successfully committed.
Note: It does not directly return Celery Task ID, nor does it guarantee that database commits and Broker releases will be atomic across systems in the event of a failure.
Why is it recommended to pass ID?
Not recommended:
process_document.delay(document)
Recommended:
process_document.delay(document.pk)
The reason is:
- Django Model Instance is not suitable as a JSON Task parameter.
- The task may be executed in another process or machine.
- The object's state may have changed.
- Passing simple, serializable data is more stable.
Worker should requery the current database status based on ID.
7. Task Retry: Retry after failure
Background tasks often call external services, such as:
- LLM API。
- Embedding API。
- Third party HTTP API.
- Object storage service.
These operations may fail due to timeouts, network errors, or service throttling.
Celery supports automatic retry:
import requests
from celery import shared_task
@shared_task(
autoretry_for=(
requests.exceptions.Timeout,
requests.exceptions.ConnectionError,
),
retry_backoff=True,
retry_jitter=True,
retry_kwargs={"max_retries": 3},
)
def fetch_external_data(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
Main parameters:
| parameters | function |
|---|---|
autoretry_for | Specify automatic retry exceptions |
retry_backoff | Use exponential backoff |
retry_jitter | Add randomness to retry delays |
max_retries | Maximum number of retries |
Do not retry all exceptions unconditionally.
For example:
- Temporary network failure: usually a good time to try again.
- API Rate Limit: Delayed retry may be appropriate.
- File format not supported: Retrying is usually not necessary.
- Data validation failed: Failure should be reported directly.
Idempotence (Idempotency)
Celery In certain failure, confirmation and retry scenarios, the same business task may be executed multiple times.
Therefore, it is important that Task should be designed to be idempotent operations whenever possible:
Repeated execution of the same business task should not produce repeated business results.
For example, when writing document Embeddings, you can combine unique constraints, Upsert or task status verification to avoid repeatedly creating the same Chunks.
8. Task status and result query
If Result Backend is enabled:
result = process_document.delay(123)
You can then query through task ID:
from celery.result import AsyncResult
result = AsyncResult(task_id)
print(result.state)
print(result.ready())
If you need to get results:
result.result
It is generally not recommended to call blocking in Web Request:
result.get()
Because this will wait for the task to complete, defeating the main point of using background tasks.
The more recommended method in the project
For tasks with clear business entities such as document processing and video conversion, it is generally recommended to save the business status to PostgreSQL:
Document
├── id
├── status
├── progress
├── error_message
└── processed_at
The front end can be accessed via:
GET /api/documents/123/
Query processing status.
This makes it easier to implement permission control, long-term business status and failure reason management than relying entirely on Celery Result Backend.
9. Celery Beat: scheduled task
Celery Beat is used to send tasks periodically as configured.
For example:
- Clean up expired records every day.
- Regularly synchronize third-party data.
- Statistics are updated hourly.
- Data aggregation is performed nightly.
Configuration
from celery.schedules import crontab
CELERY_BEAT_SCHEDULE = {
"cleanup-expired-records": {
"task": "documents.tasks.cleanup_expired_records",
"schedule": crontab(hour=3, minute=0),
},
}
Corresponding tasks:
from celery import shared_task
@shared_task
def cleanup_expired_records():
# Clean up expired records that meet the conditions
...
Start Beat:
celery -A config beat --loglevel=info
Beat is responsible for scheduling and not responsible for actually executing tasks. There must be Worker consuming these tasks.
Usually only one Beat instance responsible for the same schedule is run to avoid repeated scheduling.
For projects that need to manage periodic tasks in Django Admin, django-celery-beat can also be used.
10. Task Queues: Task queue division
A project can be divided into different queues based on task types.
For example RAG system:
Redis Broker
│
┌────────────┼────────────┐
▼ ▼ ▼
documents embeddings maintenance
│ │ │
Worker A Worker B Worker C
Specify queue
process_document.apply_async(
args=[123],
queue="documents",
)
Or configure task routing in Settings:
CELERY_TASK_ROUTES = {
"documents.tasks.process_document": {
"queue": "documents",
},
}
Start corresponding Worker:
celery -A config worker \
-Q documents \
--loglevel=info
This can prevent certain types of high-time-consuming tasks from continuing to occupy all Worker and affecting the execution of other tasks.
For small projects, a single queue is usually sufficient initially; split later when resource competition becomes apparent.
11. Docker Compose deployment
Celery Worker and Django typically use the same code and dependencies, but run different startup commands.
For example:
services:
web:
build: .
command: gunicorn config.wsgi:application --bind 0.0.0.0:8000
depends_on:
- redis
environment:
CELERY_BROKER_URL: redis://redis:6379/1
CELERY_RESULT_BACKEND: redis://redis:6379/2
worker:
build: .
command: celery -A config worker --loglevel=info
depends_on:
- redis
environment:
CELERY_BROKER_URL: redis://redis:6379/1
CELERY_RESULT_BACKEND: redis://redis:6379/2
beat:
build: .
command: celery -A config beat --loglevel=info
depends_on:
- redis
environment:
CELERY_BROKER_URL: redis://redis:6379/1
CELERY_RESULT_BACKEND: redis://redis:6379/2
redis:
image: redis:8
command: redis-server --appendonly yes
volumes:
- redis_data:/data
volumes:
redis_data:
This is a simplified configuration, assuming that the database, file storage, and other dependencies of the Django project have been configured separately.
The actual production environment also needs to deal with:
- Worker automatically restarts.
- Database health check with Redis.
- Graceful Shutdown。
- Task Time Limits。
- Logging and monitoring.
- Broker Authentication and persistence.
- Task backlog and failure recovery.
12. Frequently Asked Questions and Practical Suggestions
Is Celery suitable for all asynchronous operations?
Not suitable.
For example, a HTTP request needs to query several external interfaces concurrently, and must wait for all results to be returned before responding. This may be more suitable for asyncio or asynchronous HTTP Client.
Celery is more suitable for:
- Tasks that do not need to be completed immediately in the current request.
- Long background work.
- Tasks requiring retries and independent Worker.
- Periodic tasks.
- Task processing that requires horizontal scalability.
What is the relationship between Celery and Redis?
Celery is a task execution and scheduling framework.
Redis can act as Broker or Result Backend.
Redis does not automatically perform tasks, the actual Python function is run by Celery Worker.
Can I directly transfer files to Celery?
Delivering large file content is generally not recommended.
More reasonable is:
Upload files → MinIO / R2
↓
Save file reference
↓
Celery Task(file_id)
↓
Worker read file
This avoids putting large file contents into Broker messages.
Celery Is it guaranteed that the task will be executed only once?
It cannot be simply considered this way.
Actual processing needs to take into account message acknowledgments, Worker crashes, retries, and repeated executions.
Key business operations should incorporate idempotent design, database constraints, and business state control.
How to monitor Celery?
In the basic stage, you can observe the task execution through Worker Logs.
When you need more complete task monitoring, you can use Flower:
pip install flower
celery -A config flower
Flower can provide a visual interface for Worker, task status and some execution statistics. Production environments require restricted access.
Summary
| Knowledge points | importance |
|---|---|
| Task / Broker / Worker | core |
| Result Backend | important |
@shared_task | core |
delay() / apply_async() | core |
| Django Integration | core |
delay_on_commit() | core |
| Retry / Backoff | core |
| Idempotency | core |
| Task State / Result | important |
| Celery Beat | important |
| Task Queues / Routing | important |
| Docker Deployment | important |
| Flower / Monitoring | on demand |
Celery The five most important concepts:
- Task Queue: Separate time-consuming operations from HTTP requests and hand them over to the background Worker for execution.
- Broker & Worker: Broker is responsible for delivering tasks, and Worker is responsible for actual execution.
- Django Integration: Define the task through
@shared_taskand submit it usingdelay()ordelay_on_commit(). - Retry & Idempotency: Background tasks must consider failed retries and repeated executions.
- Task State Management: For long-term business processes, it is recommended to persist the business state to the database instead of only relying on the Celery result state.