Memory Leaks in Django
Django's ORM, signal system, and middleware can all contribute to memory growth that eventually crashes your workers. Here are the most common leaks and their fixes.
DEBUG = True in Production
The number one cause. When DEBUG = True, Django stores every SQL query in django.db.connection.queries:
# settings.py — MUST be False in production
DEBUG = FalseUnbounded QuerySet Iteration
Loading millions of rows into memory:
# BAD — loads all objects at once
for obj in MyModel.objects.all():
process(obj)
# GOOD — use iterator with chunk_size
for obj in MyModel.objects.all().iterator(chunk_size=1000):
process(obj)Signals Accumulating Handlers
If you connect signals in a function that runs repeatedly without dispatch_uid:
# BAD — adds a new handler every time
post_save.connect(my_handler, sender=MyModel)
# GOOD — deduplicates with dispatch_uid
post_save.connect(my_handler, sender=MyModel, dispatch_uid='my_unique_handler')Middleware Storing Per-Request Data
class LeakyMiddleware:
_cache = {} # Class-level dict grows forever
def __call__(self, request):
self._cache[request.path] = datetime.now() # Never cleanedFix by using Django's cache framework or per-request storage.
Detecting Leaks
Use tracemalloc to find the source:
import tracemalloc
tracemalloc.start()
# ... run your code ...
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
print(stat)Bugsly tracks memory usage over time, alerting you when a Django worker's memory consumption trends upward — catching leaks before they cause OOM kills.
Try Bugsly Free
Track up to 100 issues per month on the free plan; events are not billed.
Get Started FreeRelated Articles
How to Fix Rangeerror in C# In Production
Learn how to diagnose and fix the rangeerror in C# in production. Includes code examples and prevention tips.
Read moreHow to Fix Validationerror in Vue.js When Deploying
A practical guide to resolving Validationerror in Vue.js when deploying, with real code examples and debugging tips.
Read moreHow to Fix Version Mismatch in Flutter
Fix Version Mismatch in your Flutter app. Understand the root cause and apply the right solution.
Read moreFix Connection Refused Error in Ruby
Learn how to fix the Connection Refused error in Ruby. Step-by-step guide with code examples and solutions. Quick, practical guide for developers.
Read moreFrom the same team
SEOBolt
Technical SEO and AI search audits with ready-to-apply fix plans.
Try SEOBolt →GrowFast
Domain in, qualified B2B leads out, with cold outreach and deliverability handled.
Try GrowFast →AutoShort
Turn a topic into a faceless short: AI script, voiceover and captions.
Try AutoShort →RemixViral
Paste a long video and get back the moments worth posting, cut vertical and captioned.
Try RemixViral →