Troubleshooting guide
RecursionError: maximum recursion depth exceeded in Python
Python stops a call chain at 1,000 frames by default. Usually that indicates a bug where a function ends up calling itself by accident.
3 min read10 sectionsUpdated
On this page
Common causes
- A property setter that assigns to itself, such as setting
self.nameinside thenamesetter. __getattr__reading an attribute that is not set yet.- Two functions calling each other.
- Missing or unreachable base case.
- Serialising circular references, such as ORM relationships.
- Decorators applied many times during a reload.
import sys, traceback
print(sys.getrecursionlimit())
try:
run()
except RecursionError:
tb = traceback.format_exc().splitlines()
print("\n".join(tb[:12])) # the entry point
print("\n".join(tb[-12:])) # the repeating cycle
# Faulthandler helps when the interpreter itself crashes
# python -X faulthandler app.pyFixes
Store the value under another name: self._name within the name property. In __getattr__, use object.__getattribute__ for internal fields, and avoid touching attributes that may not exist yet. Add or fix the base case. Use an explicit stack for walking deep trees. For circular data, exclude back-references or use a serialiser that handles depth. sys.setrecursionlimit is appropriate only when legitimate depth is slightly over the limit.
Rewriting recursion as iteration
Traversing a deep tree recursively can be turned into a loop with a list used as a stack: push the root, then repeatedly pop a node, process it, and push its children. This uses heap memory, which is plentiful, in place of the limited C stack. Python does not perform tail-call optimisation, so a tail-recursive style provides no benefit. Raising the recursion limit too far risks a hard interpreter crash from a real stack overflow, which produces no Python traceback at all and is much harder to debug.
Catch it automatically
Error tracking groups these by the cycle's location, so a single bug appears as one issue with a count and a first-seen release. See OpenTelemetry for Python to send exceptions automatically.
Related reading
- PHP maximum execution time exceeded: how to fix it: Fix PHP Maximum execution time of 30 seconds exceeded: why external waits may not count, which timeouts line up with Nginx, and how to move long work away.
- GC overhead limit exceeded in Java: how to fix it: Fix java.lang.OutOfMemoryError: GC overhead limit exceeded. Enable GC logs, take a heap dump, find what fills the heap and size the JVM for containers.
- ModuleNotFoundError in Python: how to fix it: Fix Python ModuleNotFoundError: wrong virtual environments, pip installing to another interpreter, sys.path issues and packaging mistakes in Docker builds.
- RabbitMQ monitoring: queues, consumers and alarms: Monitor RabbitMQ: queue depth and message rates, unacknowledged messages, consumer counts, memory and disk alarms, and connection churn, with commands.
- java.lang.OutOfMemoryError: causes and fixes: Every kind of java.lang.OutOfMemoryError explained: Java heap space, GC overhead, Metaspace, unable to create native thread and direct buffer memory.
- java.lang.StackOverflowError: causes and how to fix it: Fix java.lang.StackOverflowError: read the repeating frames, find runaway recursion, circular toString and JSON mappings, and know when -Xss is appropriate.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.