Every Python team eventually meets the same problem: a web request needs to do something slow — send a batch of emails, transcode a video, call a third-party API that times out half the time — and doing it inline means the user stares at a spinner. celery is the answer most of the ecosystem converged on: producers push serialized function calls to a broker, workers pull them off and execute them, and results land in a backend your code can poll. It is widely recognized as the de facto job runner for Django and Flask deployments, hardened by a decade of production use.
The pain starts when something misbehaves. A task silently never runs. A chord body never fires even though every header item finished. A worker goes quiet at 3 a.m. and the only symptom is a flat graph. At that point the tutorial-level mental model stops helping; you need to know what the code actually does. This post is a tour of the real source tree of celery on its default branch main — version 5.7.0 at the time of writing — with every symbol and line number taken from an actual checkout, not from memory.
Two diagrams anchor the tour. The overview shows the four load-bearing layers — app core, canvas composites, worker runtime, and the state layer of result backends and beat. The detail diagram names the concrete classes and files so you can jump straight into the source.
celery at a glance: from the app factory through canvas composites into the worker's event loop and pools, with results flowing back through the backend. Click any node to open the source on GitHub.
Reading the overview from left to right, these anchors are worth committing to memory, each verified against the current tree:
Celery, L376 — the application class every queue, connection and task hangs off. Despite its 1,832-line file, importingceleryitself stays cheap because the package rebuilds itself as a lazy module.task(), L652 — the decorator behind@app.task. It returns aPromiseProxyso the actualTaskobject is only materialized when the app is finalized.Task.retry, L817 — re-sends the message and raises aRetryexception. Defaults live a few hundred lines up:max_retries = 3anddefault_retry_delay = 3 * 60.add_autoretry_behaviour, L8 — the machinery behindautoretry_for=(...), wrappingrunwith an exponential-backoff countdown computed per attempt.Signature, L386 — a task call as a serializable dict._chain,groupand_chordare all built on it;_chordstarts at L2325.asynloop, L65 — the worker’s non-blocking event loop, driven by Kombu’s hub;synloopat L161 is the blocking fallback.TaskPool, L149 — the prefork pool built on billiard, a fork ofmultiprocessingtuned for task execution.RedisBackend, L481 — the most deployed result backend, layered over the key-value store family incelery/backends/base.py.
The detail view: concrete classes and files, and how a task message travels from apply_async through AMQP into the consumer, strategy, loops and a pool, while results flow back through the backend layer.
The app that pretends to be a module
The first surprise is that celery/__init__.py is only 176 lines and almost none of it is real code. The package ends with recreate_module (L153), which rebuilds celery as a lazy facade: a mapping (L155) says which submodule owns which public name — Celery and shared_task from celery.app, Task from celery.app.task, chain, chord, group and friends from celery.canvas. Nothing imports until you touch the attribute — a deliberate startup-latency win for a library loaded at every process start.
Registration is equally lazy. The task() decorator at L652 of celery/app/base.py wraps your function in a PromiseProxy (L706); the real Task object is created by _task_from_fun only when finalize() runs (L850). That is why touching a task attribute too early can resolve against a half-configured app — the proxy defers binding on purpose.
One more early-import trick: maybe_patch_concurrency (L119) inspects sys.argv for -P eventlet or -P gevent and applies monkey-patching (_patch_eventlet at L103, _patch_gevent at L112) before anything else loads. The module even saves the original os.write (L24), because signal handlers inside the eventlet hub must not call the patched blocking version.
Canvas: task calls that compose
celery/canvas.py is the largest file in the package at 2,972 lines. The base abstraction, Signature(dict) (L386), is literally a dictionary subclass: a task name, arguments and options that can be JSON-serialized, sent over the wire, and rebuilt on the other side. Around it sit three composition primitives. _chain (L1104, exposed as chain at L1606) runs signatures in sequence. group (L1825) fans signatures out in parallel via _apply_tasks (L2111) and returns a joinable GroupResult. _chord (L2325) is the hard one: run a header group, then feed the collected results into a body signature.
The chord implementation shows how much edge-case engineering hides behind the API. Its run method (L2657) documents that an empty header executes the body immediately, that chains must not be passed to header tasks, and that nested chains must be unrolled (_unroll_chords, L2701) before freezing, or the whole remaining tail gets embedded in every inner chord header. If you ever debug a chord that deadlocks under load, this is where the fix will be.
The worker: bootsteps and two event loops
The worker side starts with WorkController (L64 in celery/worker/worker.py), but its real shape is a blueprint of bootsteps — small components with start/stop semantics in celery/worker/components.py: Timer (L32), Hub (L56), Pool (L101), Beat (L181) and the Consumer step (L221). The Pool bootstep requires the Hub (L115), instantiates the pool with options like maxtasksperchild and timeouts (L154), and wires a LaxBoundedSemaphore so the main loop stops reading messages when the pool is saturated (L147).
celery/worker/consumer/consumer.py (1,068 lines) owns the broker conversation. Its start loop (L406) runs the blueprint and restarts it on recoverable connection errors, guarded by a restart-frequency limiter that sleeps when restarts come too fast (L413). Incoming messages resolve through the strategy default (L100 in celery/worker/strategy.py), which builds a Request (L68 in celery/worker/request.py) and honors rate limits (L122).
The inner loop lives in celery/worker/loops.py, just 231 lines. asynloop (L65) is the optimized path: it registers callbacks with Kombu’s hub, creates a generator-based loop (L113), and batches QoS updates so remote control commands keep priority (L126). synloop (L161) is the documented fallback: a plain while-loop around drain_events(timeout=2.0) (L192). Both loops check heartbeat_error sentinels each cycle, so a heartbeat failure raises instead of stalling silently.
From fork() to spawn(): what the numbers say
The concurrency story is told by celery/concurrency/. A small factory defines the ALIASES table (L11) mapping prefork, solo, threads, eventlet and gevent to their TaskPool classes, plus a CELERY_CUSTOM_WORKER_POOL hook (L34) for out-of-tree pools. The prefork pool (L149) defaults to billiard’s AsynPool (L152), the asynchronous pool at celery/concurrency/asynpool.py L489. Its on_start (L158) is where a quiet modernization happened: when the legacy forking_enable path is disabled, the pool sets FORKED_BY_MULTIPROCESSING = 1 and switches to set_start_method('spawn', force=True) (L174), because the legacy execv path depended on a C extension absent on CPython 3. Each pool is constructed with enable_timeouts=True and synack=False (L182).
The solo pool is delightfully honest about itself: 33 lines, self.limit = 1 (L19), blocking inline execution for debugging. The threads pool wraps ThreadPoolExecutor (L4 in celery/concurrency/thread.py); the eventlet and gevent pools (L90 and L94) lean on the monkey-patching done back in the app module. Windows forces the threaded path — the Pool bootstep computes threaded = not w.use_eventloop or IS_WINDOWS (L143).
A few numbers worth knowing: retries default to 3 attempts with a 180-second delay (L266 and L270 of celery/app/task.py); autoretry backoff is capped at 600 seconds by default (retry_backoff_max, L25 of celery/app/autoretry.py) and uses full jitter via get_exponential_backoff_interval (L543 of celery/utils/time.py). The package ships 161 Python files, 22 of them in celery/backends/ — from Redis and RPC to S3, GCS and MongoDB. The command line you type after pip install is built on click: celery/bin/celery.py imports it at L8, and requirements/default.txt pins click>=8.3.1,<9.0. We covered that library’s dispatch design before in our click source tour.
Results: push versus pull
celery/backends/base.py is the second-largest file at 1,901 lines, and it is a taxonomy in code. The abstract Backend (L215) defines the lifecycle: mark_as_done (L307), mark_as_failure (L315), store_result (L894), get_task_meta (L990). The key-value family (BaseKeyValueStoreBackend, L1380, and the sync-merged KeyValueStoreBackend, L1879) is what most real backends inherit. There is even a DisabledBackend (L1883) for callers who fire tasks and never read results — the default when none is configured.
The consumer-facing side is celery/result.py (1,181 lines): AsyncResult (L70) with its get (L191) and ready (L371), GroupResult (L950) for joining group children, and EagerResult (L1046) for always_eager test mode. The interesting engineering is in Redis-based setups: RedisBackend (L481) does not just poll — it attaches a ResultConsumer (L210) that subscribes to a pub/sub channel, so a thread blocked in get() is woken by a push instead of hammering the server at an interval. That is why Redis-backed waits feel instant while database-backed waits tick. The class also grows SentinelBackend (L1119) for Sentinel topologies and set_chord_size (L871) for chord bookkeeping.
When a prefork child looks wedged, sampling tools like py-spy can attach to the live process and show which stack frame is stuck — often faster than any worker log.
Honest Limits
The beat scheduler is a single-process heapq loop. Scheduler.tick (L343 of celery/beat.py) pops due entries and sends them; PersistentScheduler (L566) persists entries across restarts, and Service (L1009) owns the lifecycle. Nothing coordinates two beat processes — run two, and every periodic task fires twice. The syntax is expressive (crontab at L354 of celery/schedules.py, its own parser at L227, plus a solar schedule at L752 keyed to sunrise and sunset), yet beat checks due-ness on its own clock, so a sleep-deprived machine drifts.
Delivery semantics deserve respect too. celery is at-least-once: a worker killed mid-task can re-run it after redelivery, and Task.retry re-sends by design. Idempotency is your job. Broker and backend are separate systems with no shared transaction, so a task can be acknowledged while its result write fails. And the builder behind the wire format is as_task_v2 (L370 of celery/app/amqp.py) — keep task_serializer to JSON unless you control every producer, because arbitrary pickle from a compromised broker is a real attack vector celery documents at length.
Finally, the asynchronous loop only runs where the transport supports it; elsewhere you drop to Enjoyed this post? Never miss out on future posts by following us synloop and its two-second blocking drains — fine for development, a throughput ceiling under load. None of these limits are hidden; they are visible in the source we just walked, comment-cited and issue-numbered. That is the case for reading the tree: the failure modes you will hit in production are already in these files, waiting for you to look before the 3 a.m. page does it for you.