How to Fix Celery Worker Memory Leaks (Step-by-Step Guide)
Fix Celery worker memory leaks: diagnose with tracemalloc and memray, then use max_tasks_per_child, max_memory_per_child, iterator(), and leaner tasks.
Introduce
It usually starts quietly. A Celery worker starts at 150 MB. A day later it is at 600 MB. By the weekend it is at 2 GB, the container is killed with an out-of-memory error, tasks get redelivered, and someone gets paged at 3 a.m.
Memory that grows over time in a long-running worker is one of the most common production problems in Celery. The tricky part is that not every case is a true "leak". Some are real bugs, some are normal Python memory behavior, and some are simply tasks that load too much data. Each one needs a different fix.
This guide explains why Celery workers grow, how to tell the causes apart, how to find the exact lines of code responsible, and how to fix the problem both at the root and with safety nets that keep production stable while you do.
First: Is It Really a Leak?
Before changing anything, look at the shape of the memory graph for a single worker process.
| Pattern | What it usually means |
|---|---|
| Climbs steadily with every task and never levels off | A true leak: objects are being kept alive |
| Jumps on a certain task, then stays high | A high-water mark: one heavy task loaded a lot of data, and Python did not give the memory back |
| Rises, then plateaus at a stable level | Normal warm-up: caches and imports filled, no real leak |
| Sudden spikes that match big jobs | Tasks that load too much at once, not a leak |
Two facts about Python help here:
- Python often does not return freed memory to the operating system. Even after you delete a large object, the process may keep that memory reserved for reuse. The resident memory (RSS) of the process stays high even though Python considers the memory free.
- Memory fragmentation is real. A long-running process that allocates and frees objects of many sizes can end up with small gaps it cannot reuse, so RSS drifts upward over time.
So "memory never goes down" does not automatically mean "there is a leak". What matters is whether it keeps growing without bound.
Why Prefork Workers Make It Worse
By default, Celery uses the prefork pool. The main process starts several child processes, and each child runs tasks. Every child has its own memory.
- With
--concurrency=8, you have eight separate processes. If each grows to 500 MB, the worker uses 4 GB, not 500 MB. - Long-lived children accumulate fragmentation and any leaked objects, because they are never restarted unless you tell Celery to.
- When the container hits its memory limit, the kernel kills a process, and any task it was running is lost or redelivered.
This is why the most effective practical fixes are about recycling children, covered below.
Step 1: Measure Memory per Task
You cannot fix what you cannot see. Start by logging the memory of each worker process around every task, using Celery signals and psutil:
## tasks_monitoring.py
import logging
import os
import psutil
from celery.signals import task_postrun, task_prerun
logger = logging.getLogger(__name__)
_process = psutil.Process(os.getpid())
_before = {}
@task_prerun.connect
def memory_before(task_id=None, **kwargs):
_before[task_id] = _process.memory_info().rss
@task_postrun.connect
def memory_after(task_id=None, task=None, **kwargs):
start = _before.pop(task_id, None)
now = _process.memory_info().rss
delta_mb = (now - start) / 1024 / 1024 if start else 0
logger.info(
"task=%s rss_mb=%.1f delta_mb=%.1f",
task.name, now / 1024 / 1024, delta_mb,
)
Send these logs to your logging system and look for two things: which task names have a consistently positive delta_mb, and which ones cause large jumps. Often a single task type is responsible for most of the growth, which narrows the search enormously.
If you use Flower or Prometheus exporters, also graph the RSS of each worker process over days, not hours. Slow leaks only show up on long time scales.
Step 2: Find the Exact Cause with tracemalloc
Python's built-in tracemalloc module can show which lines of code allocated the memory that is still in use. Take a snapshot, run tasks, take another, and compare:
## worker_debug.py
import tracemalloc
from celery.signals import task_postrun, worker_process_init
_baseline = None
_counter = 0
@worker_process_init.connect
def start_tracing(**kwargs):
global _baseline
tracemalloc.start(10) # keep 10 stack frames
_baseline = tracemalloc.take_snapshot()
@task_postrun.connect
def report_growth(**kwargs):
global _counter
_counter += 1
if _counter % 200 != 0:
return
snapshot = tracemalloc.take_snapshot()
stats = snapshot.compare_to(_baseline, "lineno")
for stat in stats[:10]:
print(stat)
The output lists lines of code with the amount of memory they added since the baseline, for example orders/tasks.py:42: size=312 MiB (+310 MiB), count=1200000 (+1199000). That points straight at the allocation that never gets released.
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
Two cautions. tracemalloc slows the process and uses extra memory, so use it in staging or on a single debug worker, never across production. And it only tracks Python allocations, not memory used by C extensions.
For deeper profiling, use memray. It is a memory profiler that also tracks native allocations, which matters if you use libraries like pandas, NumPy, Pillow, or lxml. Running the worker with the solo pool keeps everything in a single process, which makes profiling simpler:
memray run -o worker.bin -m celery -A config worker --pool=solo --loglevel=info
memray flamegraph worker.bin
Run the suspect task many times, stop the worker, and open the flame graph to see which call paths hold the most memory.
objgraph is another useful tool. It can show which object types are growing in count, for example objgraph.show_growth() printing that a certain class keeps gaining instances between tasks.
The Most Common Causes (and Their Fixes)
1. DEBUG = True in the Worker
This is a classic Django and Celery trap. When DEBUG is True, Django records every SQL query in connection.queries. In a web request, that list is reset after each request. In a long-running worker, it keeps growing as tasks run. Recent Django versions cap the log at a fixed size, but it still holds a lot of memory per process.
Fix: make sure workers run with DEBUG = False, and check which settings file your Celery process actually loads.
2. Loading Whole Querysets into Memory
## Loads every row and caches the result inside the queryset
for order in Order.objects.filter(status="paid"):
process(order)
Django caches the full result set while you iterate. For a few thousand rows that is fine, but for millions it is a memory spike that your worker then keeps as its high-water mark.
Fix: stream the data and use lighter objects.
qs = (
Order.objects.filter(status="paid")
.only("id", "total", "customer_id")
)
for order in qs.iterator(chunk_size=2000):
process(order)
Even better, split the work into small chunks by ID range so each task handles only a bounded slice. Also use values_list() when you do not need model instances. Note that iterator() uses server-side cursors on PostgreSQL, which can misbehave behind some connection poolers in transaction mode, so check DISABLE_SERVER_SIDE_CURSORS in that setup.
3. Module-Level Caches That Only Grow
_seen_ids = set() # grows forever
_cache = {} # grows forever
@lru_cache(maxsize=None) # unbounded cache
def get_price(product_id):
...
In a web app, a process might be recycled often enough that this never matters. A Celery child can run for days. Every key you add stays until the process dies.
Fix: bound every cache. Use lru_cache(maxsize=1000), a TTL cache, or store shared state in Redis instead of process memory. Treat any global mutable list, dict, or set in task code as suspicious.
4. Huge Task Arguments and Results
Passing a big list or a large payload as a task argument means the message sits in worker memory, and the deserialized object is kept while the task runs. Returning a big result stores it in your result backend and in memory along the way.
## Avoid
process_orders.delay(list_of_100000_dicts)
## Prefer
process_orders.delay(start_id, end_id)
Pass IDs or ranges and let the task read its own data. If you never read task results, turn them off:
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
CELERY_TASK_IGNORE_RESULT = True
CELERY_RESULT_EXPIRES = 3600
5. Prefetching Too Many Messages
With the default worker_prefetch_multiplier of 4, each child reserves several messages ahead of time. If your messages are large, or each task is heavy, a worker can hold a lot of memory just waiting. For long tasks, set it to 1:
CELERY_WORKER_PREFETCH_MULTIPLIER = 1
6. Reading Whole Files and Responses
Loading a big CSV, JSON file, or HTTP response into memory in one go inflates the process.
## Reads everything at once
data = requests.get(url).content
## Streams instead
with requests.get(url, stream=True, timeout=30) as r:
for chunk in r.iter_content(chunk_size=1024 * 1024):
handle(chunk)
With pandas, read in chunks (pd.read_csv(path, chunksize=50_000)), process each chunk, and let it go. For exports, write rows to the file as you go instead of building the full content first.
7. Objects Kept Alive by References
A leak in Python usually means something still holds a reference. Common culprits:
- A list that you append to inside a task but defined at module level.
- Signal receivers or callbacks that capture large objects in a closure.
- Exceptions stored with their tracebacks, which keep local variables alive.
- Custom logging handlers that buffer records.
- Class attributes used as accumulators.
Fix: keep task state local to the function, avoid appending to anything defined outside it, and del large objects as soon as you are done with them, especially inside loops.
8. C Extension Leaks and Unclosed Resources
Some libraries allocate memory outside Python's control, such as image libraries, XML parsers, and some database or crypto bindings. tracemalloc will not see it, but memray will. Also check for unclosed file handles, sockets, and HTTP sessions: create a requests.Session once and reuse it, or use a context manager, instead of building new clients inside a loop and abandoning them. Close PIL images with with Image.open(...).
The Safety Net: Recycle Worker Processes
Even after you fix the code, it is wise to keep a safety net, because slow growth and fragmentation can come back. Celery has two settings that replace a child process after a limit, which resets its memory to the baseline.
## settings.py (with a CELERY_ namespace)
CELERY_WORKER_MAX_TASKS_PER_CHILD = 500
CELERY_WORKER_MAX_MEMORY_PER_CHILD = 600_000 # in KiB, about 600 MB
Or on the command line:
celery -A config worker --concurrency=4 \
--max-tasks-per-child=500 \
--max-memory-per-child=600000
How they differ:
worker_max_tasks_per_childreplaces a child after it has run N tasks. It is simple and predictable, and good when growth is roughly proportional to the number of tasks.worker_max_memory_per_childreplaces a child once its resident memory exceeds a limit, measured in kibibytes. If a task pushes the process over the limit, the task is allowed to finish, and the child is replaced afterward. This targets the actual problem directly, which is why many teams prefer it.
Both only apply to the prefork pool. They do not work with gevent, eventlet, or threads pools.
How to choose the numbers:
- For
max_memory_per_child, start from your container limit. If a container has 4 GB and--concurrency=4, each child can use roughly 800 to 900 MB at most, minus overhead for the parent process. A limit around 600 MB per child leaves headroom. - For
max_tasks_per_child, look at your memory-per-task logs from Step 1 and pick a value that recycles the process well before it gets large. A few hundred to a few thousand is typical. - Do not set them too low. Every restart re-imports your Django app, which can take seconds and re-opens database connections. Restarting after every handful of tasks adds real overhead.
This is a mitigation, not a cure. It makes the symptom harmless while you work on the cause, and it protects you from the next leak you have not found yet.
Tune the Allocator (Advanced)
If your measurements show fragmentation rather than a true leak, the memory allocator can matter, especially on Linux with glibc. Two options teams try:
Free tech newsletter
FreeFree to join — no card, no paywall. Weekly AI, cloud & tooling insights.
- Limit malloc arenas with the environment variable
MALLOC_ARENA_MAX=2. This can reduce fragmentation in multi-threaded processes, at a small cost in allocation speed. - Use jemalloc instead of glibc's allocator, by preloading it. Some teams see noticeably flatter memory graphs.
Neither is guaranteed to help, so change one thing at a time and compare the memory graph over several days. Treat this as a last step after fixing the code.
Plan for the Worst Case: OOM Kills
If a worker is killed for using too much memory, the task it was running is affected:
- With the default early acknowledgement, the task may be lost.
- With
acks_late=Trueandtask_reject_on_worker_lost=True, the task is redelivered and may run again.
Redelivery means a task that causes an out-of-memory kill can get re-run, run out of memory again, and loop. To stay safe:
- Keep tasks idempotent, so a re-run is harmless.
- Set
max_retriesand make sure failing tasks eventually stop. - Alert when workers restart unexpectedly, for example by tracking container restart counts or OOMKilled events.
- Set container memory limits deliberately, so one runaway child does not take down the host.
Quick Diagnosis Table
| Symptom | Likely cause | Fix |
|---|---|---|
| Memory grows steadily with every task | Real leak: global lists, caches, references | Find with tracemalloc or memray, bound the cache |
| Memory jumps after one specific task | Task loads too much data | iterator(), chunking, values_list(), streaming |
| Memory grows only in workers, not in web | DEBUG = True |
Set DEBUG = False for workers |
| Memory high but flat | Normal high-water mark or fragmentation | Recycle with max_memory_per_child |
| Many workers, total memory too large | High concurrency times per-child memory | Lower concurrency, recycle children |
| Idle workers hold lots of memory | Prefetch of large messages | prefetch_multiplier = 1, smaller payloads |
| Growth even with clean Python code | C extension or allocator behavior | Profile with memray, try MALLOC_ARENA_MAX or jemalloc |
Related Reading: Keep Your Workers Lean and Reliable
Memory problems rarely appear alone. These guides cover the neighboring issues:
- If your tasks process huge datasets: How to Process Millions of Records Using Celery explains chunking, worker lanes, and
ignore_result, which keep each task's memory bounded by design. - If you want the Django-specific version of that pattern: How to Process 5 Million Records with Django and Celery shows a dispatcher and chunk worker built on the Django ORM.
- If querysets are inflating your task memory: Django ORM Optimization for Millions of Records covers
only(),iterator(), and indexes, the same habits that stop a task from loading everything at once. - If a recycled or killed worker may re-run tasks: Celery: How to Prevent Duplicate Task Execution explains idempotency and locks, which make OOM redelivery safe.
- If restarts cause failures you need to ride out: Celery Retry with Exponential Backoff in Django shows how to retry the right errors without causing retry storms.
- If child recycling multiplies database connections: Django Database Connection Pooling with PostgreSQL explains how to cap connections across many worker processes.
- If a task builds big files in memory: How to Export Large CSV Files in Django Without Memory Errors shows how to stream large outputs instead of holding them in memory.
A Practical Checklist
Work through this in order when a worker's memory keeps growing:
- Confirm the pattern: steady growth, a high-water mark, or a plateau
- Log RSS before and after each task to find the guilty task names
- Check that workers run with
DEBUG = False - Look for unbounded globals, caches, and
lru_cache(maxsize=None) - Replace full-queryset loops with
iterator()and chunked ID ranges - Stream files and HTTP responses, and read data in chunks
- Pass IDs instead of large payloads, and enable
ignore_resultif you do not read results - Set
prefetch_multiplier = 1for heavy tasks - Profile with tracemalloc or memray in staging
- Add
max_memory_per_childandmax_tasks_per_childas a safety net, sized from your container limit - Make tasks idempotent so OOM redelivery is harmless
- Watch memory graphs over days to confirm the fix
Conclusion
Celery worker memory leaks are almost always one of a few things: tasks that load too much data, objects kept alive by globals and caches, DEBUG mode left on, or normal Python memory behavior in a process that never restarts. The path to a fix is consistent: measure per task, find the exact allocation with tracemalloc or memray, remove the cause, and keep a safety net in place.
Use worker_max_memory_per_child and worker_max_tasks_per_child to make sure no single process can grow without limit, and design tasks to be small, bounded, and idempotent. Do that, and a worker that used to creep toward an out-of-memory kill becomes a steady, predictable part of your system.
Frequently Asked Questions
Why does my Celery worker memory keep growing?
Common causes include tasks that load large querysets or files into memory, global lists and caches that never shrink, DEBUG = True storing every SQL query, large task arguments or results, and normal Python memory fragmentation in long-lived processes. Measure memory per task to tell them apart.
What is the difference between worker_max_tasks_per_child and worker_max_memory_per_child?
worker_max_tasks_per_child replaces a child process after it has run a set number of tasks. worker_max_memory_per_child replaces it after its resident memory passes a limit in KiB. If one task pushes a child over the memory limit, the task finishes first and the child is replaced afterward. Both work only with the prefork pool.
Is a Celery worker memory leak always a bug in my code? No. Python often keeps freed memory reserved instead of returning it to the operating system, so memory can stay high without a true leak. A real leak is memory that keeps climbing without leveling off. Check the shape of the graph before assuming a bug.
How do I find which task is leaking memory in Celery?
Log process RSS in task_prerun and task_postrun signals to see which task names increase memory. Then use tracemalloc to compare snapshots and find the lines of code that hold the memory, or use memray for native allocations from C extensions.
Does DEBUG = True cause memory leaks in Celery workers?
It can cause steady memory growth. With DEBUG on, Django records every SQL query on the connection, and in a long-running worker that log is not cleared between tasks like it is between web requests. Always run workers with DEBUG = False.
What happens to a task when a Celery worker is killed for running out of memory?
With default settings the task can be lost. With acks_late=True and task_reject_on_worker_lost=True, it is redelivered and may run again, which is why tasks should be idempotent and have a finite retry limit.
Do max_tasks_per_child and max_memory_per_child work with gevent or eventlet? No. They only apply to the prefork pool. With gevent, eventlet, or threads pools, you need to fix the cause in code or restart the worker process through your process manager or orchestrator.
