Celery Basics
This chapter turns task calls into an explicit distributed protocol covering serialization, broker delivery, worker reservation, acknowledgments, result state, periodic scheduling, and operational visibility.
- Explain Task definition & calling by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Brokers & result backends by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Celery Beat (periodic tasks) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Monitoring by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Complete Django integration by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Celery Basics, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the distributed learning arc appropriate to this subject.
The problem this chapter solves
This chapter turns task calls into an explicit distributed protocol covering serialization, broker delivery, worker reservation, acknowledgments, result state, periodic scheduling, and operational visibility.
It keeps slow, retryable, scheduled, or bursty work away from request latency and lets workers scale independently.
Learning outcomes
- Explain Task definition & calling by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Brokers & result backends by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Celery Beat (periodic tasks) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Monitoring by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Complete Django integration by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
A producer serializes a task signature to a broker. A worker reserves a message, executes the registered task, acknowledges according to policy, and optionally writes state to a result backend. Delivery and execution can be repeated after failures, so observable exactly-once behavior must be created with idempotency or transactional guards. In Celery Basics, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- The producer validates a small task message and publishes the registered task name, identity, arguments, headers, and delivery options to the broker.
- A worker reserves and deserializes the message, executes the task under acknowledgment and time-limit policy, and records domain progress separately from optional result metadata.
- Success acknowledges according to policy; a transient failure schedules a bounded retry with the same logical operation identity; terminal failure enters the owned error or dead-letter path.
- Idempotency storage or a database constraint prevents repeated delivery from creating a second logical effect.
- Tests drive success, retry, crash-after-side-effect, expiry, and worker restart while metrics expose backlog age, runtime, retries, and terminal failures.
Memory and performance lens
Worker child processes retain imported application state and task allocations. Large task arguments inflate broker and worker memory; pass stable identifiers and load data inside the task. Configure prefetch and worker recycling to control unfair reservations and leaks. For Celery Basics, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Celery Basics, measure publish-to-complete latency, retries, duplicate effects, oldest work age, queue depth or partition lag, throughput, and recovery time rather than optimizing from source-code appearance.
1. Task definition & calling
The Task definition & calling unit begins with @app.task vs @shared_task: A Celery task is a registered message-handling contract; delay is shorthand while apply_async exposes routing, ETA, expiry, and options. Pass small JSON-compatible arguments and track a domain job record when user-visible state matters. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Task definition & calling
| Concept | Meaning | Engineering decision |
|---|---|---|
| @app.task vs @shared_task | A Celery task is a registered message-handling contract; delay is shorthand while apply_async exposes routing, ETA, expiry, and options. | Pass small JSON-compatible arguments and track a domain job record when user-visible state matters. |
| delay() vs apply_async() (countdown/eta/expires) | A Celery task is a registered message-handling contract; delay is shorthand while apply_async exposes routing, ETA, expiry, and options. | Pass small JSON-compatible arguments and track a domain job record when user-visible state matters. |
| task states: PENDING→STARTED→SUCCESS/FAILURE | A Celery task is a registered message-handling contract; delay is shorthand while apply_async exposes routing, ETA, expiry, and options. | Pass small JSON-compatible arguments and track a domain job record when user-visible state matters. |
Message and failure lifecycle: Task definition & calling
@app.task vs @shared_task. The producer serializes task name, IDs, arguments, and headers. Worker and backend state may be absent or eventually updated; PENDING can mean unknown, not queued.
delay() vs apply_async() (countdown/eta/expires). The producer serializes task name, IDs, arguments, and headers. Worker and backend state may be absent or eventually updated; PENDING can mean unknown, not queued.
task states: PENDING→STARTED→SUCCESS/FAILURE. The producer serializes task name, IDs, arguments, and headers. Worker and backend state may be absent or eventually updated; PENDING can mean unknown, not queued.
Read these as one system: @app.task vs @shared_task establishes the starting contract, delay() vs apply_async() (countdown/eta/expires) changes how that contract is executed or represented, and task states: PENDING→STARTED→SUCCESS/FAILURE exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Task definition & calling
1@shared_task(autoretry_for=(TimeoutError,), retry_backoff=True)2def deliver(job_id: str): ...This Task definition & calling slice makes @app.task vs @shared_task observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward task states: PENDING→STARTED→SUCCESS/FAILURE, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Task definition & calling
| Risk | Why it matters |
|---|---|
| @app.task vs @shared_task | Waiting synchronously on a task result inside a request defeats decoupling and can deadlock workflows. |
| delay() vs apply_async() (countdown/eta/expires) | Waiting synchronously on a task result inside a request defeats decoupling and can deadlock workflows. |
| task states: PENDING→STARTED→SUCCESS/FAILURE | Waiting synchronously on a task result inside a request defeats decoupling and can deadlock workflows. |
Failure-recovery drill: Task definition & calling
- Foundation: implement or demonstrate @app.task vs @shared_task with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine @app.task vs @shared_task with delay() vs apply_async() (countdown/eta/expires). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for task states: PENDING→STARTED→SUCCESS/FAILURE. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Brokers & result backends
The Brokers & result backends unit begins with Redis broker: config + pooling: The broker transports work; the result backend stores task metadata or return values. They solve different problems. Expire unneeded results and encrypt or avoid sensitive payloads. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Brokers & result backends
| Concept | Meaning | Engineering decision |
|---|---|---|
| Redis broker: config + pooling | The broker transports work; the result backend stores task metadata or return values. They solve different problems. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| CELERY_BROKER_URL and CELERY_RESULT_BACKEND | The broker transports work; the result backend stores task metadata or return values. They solve different problems. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| AsyncResult: state/result/get()/ready() | The broker transports work; the result backend stores task metadata or return values. They solve different problems. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| result_expires setting | The broker transports work; the result backend stores task metadata or return values. They solve different problems. | Expire unneeded results and encrypt or avoid sensitive payloads. |
Message and failure lifecycle: Brokers & result backends
Redis broker: config + pooling. Delivery guarantees follow broker acknowledgment and visibility rules. AsyncResult is a client view over backend state, not a durable business record.
CELERY_BROKER_URL and CELERY_RESULT_BACKEND. Delivery guarantees follow broker acknowledgment and visibility rules. AsyncResult is a client view over backend state, not a durable business record.
AsyncResult: state/result/get()/ready(). Delivery guarantees follow broker acknowledgment and visibility rules. AsyncResult is a client view over backend state, not a durable business record.
result_expires setting. Delivery guarantees follow broker acknowledgment and visibility rules. AsyncResult is a client view over backend state, not a durable business record.
Read these as one system: Redis broker: config + pooling establishes the starting contract, CELERY_BROKER_URL and CELERY_RESULT_BACKEND changes how that contract is executed or represented, and result_expires setting exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Brokers & result backends
1@shared_task(bind=True, autoretry_for=(TransientError,), retry_backoff=True, max_retries=5)2def redis_broker_config_pooling(self, entity_id: str) -> dict[str, str]:3 result = service.execute(entity_id)4 return {"status": "completed", "result_id": result.id}This Brokers & result backends slice makes Redis broker: config + pooling observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward result_expires setting, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Brokers & result backends
| Risk | Why it matters |
|---|---|
| Redis broker: config + pooling | Do not use a result backend as the only system of record. |
| CELERY_BROKER_URL and CELERY_RESULT_BACKEND | Do not use a result backend as the only system of record. |
| AsyncResult: state/result/get()/ready() | Do not use a result backend as the only system of record. |
| result_expires setting | Do not use a result backend as the only system of record. |
Failure-recovery drill: Brokers & result backends
- Foundation: implement or demonstrate Redis broker: config + pooling with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Redis broker: config + pooling with CELERY_BROKER_URL and CELERY_RESULT_BACKEND. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for result_expires setting. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Celery Beat (periodic tasks)
The Celery Beat (periodic tasks) unit begins with crontab() syntax examples: Beat is a scheduler that publishes due tasks; workers still execute them. Make periodic tasks idempotent and protect against overlapping runs. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Celery Beat (periodic tasks)
| Concept | Meaning | Engineering decision |
|---|---|---|
| crontab() syntax examples | Beat is a scheduler that publishes due tasks; workers still execute them. | Make periodic tasks idempotent and protect against overlapping runs. |
| django-celery-beat DB scheduler | Beat is a scheduler that publishes due tasks; workers still execute them. | Make periodic tasks idempotent and protect against overlapping runs. |
| PeriodicTask model: enable/disable via admin | Beat is a scheduler that publishes due tasks; workers still execute them. | Make periodic tasks idempotent and protect against overlapping runs. |
Message and failure lifecycle: Celery Beat (periodic tasks)
crontab() syntax examples. Only one active scheduler should own a schedule unless the scheduler itself coordinates leadership. Database schedulers turn rows into publish decisions.
django-celery-beat DB scheduler. Only one active scheduler should own a schedule unless the scheduler itself coordinates leadership. Database schedulers turn rows into publish decisions.
PeriodicTask model: enable/disable via admin. Only one active scheduler should own a schedule unless the scheduler itself coordinates leadership. Database schedulers turn rows into publish decisions.
Read these as one system: crontab() syntax examples establishes the starting contract, django-celery-beat DB scheduler changes how that contract is executed or represented, and PeriodicTask model: enable/disable via admin exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Celery Beat (periodic tasks)
1@shared_task(bind=True, autoretry_for=(TransientError,), retry_backoff=True, max_retries=5)2def crontab_syntax_examples(self, entity_id: str) -> dict[str, str]:3 result = service.execute(entity_id)4 return {"status": "completed", "result_id": result.id}This Celery Beat (periodic tasks) slice makes crontab() syntax examples observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward PeriodicTask model: enable/disable via admin, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Celery Beat (periodic tasks)
| Risk | Why it matters |
|---|---|
| crontab() syntax examples | Multiple beat instances can duplicate work. |
| django-celery-beat DB scheduler | Multiple beat instances can duplicate work. |
| PeriodicTask model: enable/disable via admin | Multiple beat instances can duplicate work. |
Failure-recovery drill: Celery Beat (periodic tasks)
- Foundation: implement or demonstrate crontab() syntax examples with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine crontab() syntax examples with django-celery-beat DB scheduler. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for PeriodicTask model: enable/disable via admin. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Monitoring
The Monitoring unit begins with Flower real-time UI: Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. Alert on sustained backlog age and failure rate, not on a single retry. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Monitoring
| Concept | Meaning | Engineering decision |
|---|---|---|
| Flower real-time UI | Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. | Alert on sustained backlog age and failure rate, not on a single retry. |
| task events and task_id tracking | Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. | Alert on sustained backlog age and failure rate, not on a single retry. |
| Prometheus metrics for Celery | Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. | Alert on sustained backlog age and failure rate, not on a single retry. |
Message and failure lifecycle: Monitoring
Flower real-time UI. Workers emit an event stream when enabled; exporters translate broker and process state into metrics.
task events and task_id tracking. Workers emit an event stream when enabled; exporters translate broker and process state into metrics.
Prometheus metrics for Celery. Workers emit an event stream when enabled; exporters translate broker and process state into metrics.
Read these as one system: Flower real-time UI establishes the starting contract, task events and task_id tracking changes how that contract is executed or represented, and Prometheus metrics for Celery exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Monitoring
1@shared_task(bind=True, autoretry_for=(TransientError,), retry_backoff=True, max_retries=5)2def flower_real_time_ui(self, entity_id: str) -> dict[str, str]:3 result = service.execute(entity_id)4 return {"status": "completed", "result_id": result.id}This Monitoring slice makes Flower real-time UI observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Prometheus metrics for Celery, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Monitoring
| Risk | Why it matters |
|---|---|
| Flower real-time UI | Event monitoring adds overhead and may be incomplete; reconcile with domain records. |
| task events and task_id tracking | Event monitoring adds overhead and may be incomplete; reconcile with domain records. |
| Prometheus metrics for Celery | Event monitoring adds overhead and may be incomplete; reconcile with domain records. |
Failure-recovery drill: Monitoring
- Foundation: implement or demonstrate Flower real-time UI with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Flower real-time UI with task events and task_id tracking. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Prometheus metrics for Celery. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Complete Django integration
The Complete Django integration unit begins with config/celery.py application bootstrap: Django's Celery bootstrap creates one Celery application, loads Django settings, and exposes it early enough for shared-task decorators to bind to the correct app. Keep bootstrap declarative, avoid connecting to services at import time, and verify worker startup plus task registration in CI. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Guarantees before APIs: Complete Django integration
| Concept | Meaning | Engineering decision |
|---|---|---|
| config/celery.py application bootstrap | Django's Celery bootstrap creates one Celery application, loads Django settings, and exposes it early enough for shared-task decorators to bind to the correct app. | Keep bootstrap declarative, avoid connecting to services at import time, and verify worker startup plus task registration in CI. |
| autodiscover_tasks and Django settings namespace | autodiscover_tasks() imports conventional task modules from installed Django apps, while a settings namespace maps prefixed Django settings to Celery options. | Put task definitions in predictable modules, keep imports side-effect-light, and document broker, serializer, timezone, acknowledgement, and routing settings. |
| worker/beat/Flower process commands | Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. | Alert on sustained backlog age and failure rate, not on a single retry. |
| Redis visibility and connection-pool settings | When Redis is a Celery broker, visibility timeout controls redelivery of reserved but unacknowledged messages, while connection-pool limits bound broker sockets per process. | Set the timeout above expected task runtime or use task designs that checkpoint safely, bound pools across all processes, and monitor redelivery plus connection pressure. |
Message and failure lifecycle: Complete Django integration
config/celery.py application bootstrap. The module sets the Django settings environment, constructs Celery, imports configuration from the chosen namespace, and discovers registered tasks. Importing it from the project package makes worker and web processes share configuration.
autodiscover_tasks and Django settings namespace. Celery asks Django's app registry for configurations and imports each tasks module; namespace='CELERY' converts keys such as CELERY_TASK_ACKS_LATE into Celery configuration.
worker/beat/Flower process commands. Workers emit an event stream when enabled; exporters translate broker and process state into metrics.
Redis visibility and connection-pool settings. A worker reserves a message into an unacknowledged structure; if acknowledgement does not arrive before the visibility window, the broker transport can make it available again. Each worker/web process owns its client pool.
Read these as one system: config/celery.py application bootstrap establishes the starting contract, autodiscover_tasks and Django settings namespace changes how that contract is executed or represented, and Redis visibility and connection-pool settings exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A recoverable implementation slice: Complete Django integration
1@shared_task(bind=True, autoretry_for=(TransientError,), retry_backoff=True, max_retries=5)2def config_celery_py_application_bootstrap(self, entity_id: str) -> dict[str, str]:3 result = service.execute(entity_id)4 return {"status": "completed", "result_id": result.id}This Complete Django integration slice makes config/celery.py application bootstrap observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Redis visibility and connection-pool settings, predict its behavior for empty, invalid, repeated, and large input.
Duplicate, ordering, and outage traps: Complete Django integration
| Risk | Why it matters |
|---|---|
| config/celery.py application bootstrap | Creating multiple app objects or importing models before Django setup causes missing tasks, circular imports, and inconsistent configuration. |
| autodiscover_tasks and Django settings namespace | A task module outside discovery or a misspelled setting can leave producers sending names workers never registered. |
| worker/beat/Flower process commands | Event monitoring adds overhead and may be incomplete; reconcile with domain records. |
| Redis visibility and connection-pool settings | A timeout shorter than legitimate work duplicates long tasks; an enormous timeout delays recovery after a worker dies. |
Failure-recovery drill: Complete Django integration
- Foundation: implement or demonstrate config/celery.py application bootstrap with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine config/celery.py application bootstrap with autodiscover_tasks and Django settings namespace. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Redis visibility and connection-pool settings. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from celery import Celery2from celery.schedules import crontab3
4app = Celery("reports")5app.conf.update(6 broker_url="redis://redis:6379/0",7 result_backend="redis://redis:6379/1",8 result_expires=3600,9 beat_schedule={10 "daily-summary": {11 "task": "reports.daily_summary",12 "schedule": crontab(hour=9, minute=0),13 }14 },15)16
17@app.task(bind=True, autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=4)18def build_report(self, report_id: str) -> str:19 report = load_report(report_id)20 if report.status == "complete":21 return report.location22 return generate_and_store(report)Expected result
1Beat publishes the scheduled task; repeated report delivery returns the already completed location.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from celery import Celery | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from celery.schedules import crontab | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | app = Celery("reports") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 5 | app.conf.update( | Implements the next python statement in the example's data flow. |
| 6 | broker_url="redis://redis:6379/0", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 7 | result_backend="redis://redis:6379/1", | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 8 | result_expires=3600, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | beat_schedule={ | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | "daily-summary": { | Implements the next python statement in the example's data flow. |
| 11 | "task": "reports.daily_summary", | Implements the next python statement in the example's data flow. |
| 12 | "schedule": crontab(hour=9, minute=0), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 13 | } | Implements the next python statement in the example's data flow. |
| 14 | }, | Implements the next python statement in the example's data flow. |
| 15 | ) | Implements the next python statement in the example's data flow. |
| 17 | @app.task(bind=True, autoretry_for=(TimeoutError,), retry_backoff=True, max_retries=4) | Applies a decorator or framework annotation before the following definition is bound. |
| 18 | def build_report(self, report_id: str) -> str: | Defines a function; its parameters form the explicit input boundary. |
| 19 | report = load_report(report_id) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 20 | if report.status == "complete": | Evaluates the condition and enters this branch only when it is truthy. |
| 21 | return report.location | Returns the observable result to the caller and ends this invocation. |
| 22 | return generate_and_store(report) | Returns the observable result to the caller and ends this invocation. |
Step-by-step execution
- The producer validates a small task message and publishes the registered task name, identity, arguments, headers, and delivery options to the broker.
- A worker reserves and deserializes the message, executes the task under acknowledgment and time-limit policy, and records domain progress separately from optional result metadata.
- Success acknowledges according to policy; a transient failure schedules a bounded retry with the same logical operation identity; terminal failure enters the owned error or dead-letter path.
- Idempotency storage or a database constraint prevents repeated delivery from creating a second logical effect.
- Tests drive success, retry, crash-after-side-effect, expiry, and worker restart while metrics expose backlog age, runtime, retries, and terminal failures.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Task definition & calling | Waiting synchronously on a task result inside a request defeats decoupling and can deadlock workflows. | Pass small JSON-compatible arguments and track a domain job record when user-visible state matters. |
| Brokers & result backends | Do not use a result backend as the only system of record. | Expire unneeded results and encrypt or avoid sensitive payloads. |
| Celery Beat (periodic tasks) | Multiple beat instances can duplicate work. | Make periodic tasks idempotent and protect against overlapping runs. |
| Monitoring | Event monitoring adds overhead and may be incomplete; reconcile with domain records. | Alert on sustained backlog age and failure rate, not on a single retry. |
| Complete Django integration | Creating multiple app objects or importing models before Django setup causes missing tasks, circular imports, and inconsistent configuration. | Keep bootstrap declarative, avoid connecting to services at import time, and verify worker startup plus task registration in CI. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Async Report Generator project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Task definition & calling: @app.task vs @shared_task
- To do: Task definition & calling: delay() vs apply_async() (countdown/eta/expires)
- To do: Task definition & calling: task states: PENDING→STARTED→SUCCESS/FAILURE
- To do: Brokers & result backends: Redis broker: config + pooling
- To do: Brokers & result backends: CELERY_BROKER_URL and CELERY_RESULT_BACKEND
- To do: Brokers & result backends: AsyncResult: state/result/get()/ready()
- To do: Brokers & result backends: result_expires setting
- To do: Celery Beat (periodic tasks): crontab() syntax examples
- To do: Celery Beat (periodic tasks): django-celery-beat DB scheduler
- To do: Celery Beat (periodic tasks): PeriodicTask model: enable/disable via admin
- To do: Monitoring: Flower real-time UI
- To do: Monitoring: task events and task_id tracking
- To do: Monitoring: Prometheus metrics for Celery
- To do: Complete Django integration: config/celery.py application bootstrap
- To do: Complete Django integration: autodiscover_tasks and Django settings namespace
- To do: Complete Django integration: worker/beat/Flower process commands
- To do: Complete Django integration: Redis visibility and connection-pool settings
Quick revision
- Task definition & calling: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Brokers & result backends: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Celery Beat (periodic tasks): connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Monitoring: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Complete Django integration: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?