Diagnostic Queries
Symptoms
Server-side recursion went deeper than max_stack_depth allows — typically deeply nested function calls or runaway recursive SQL/PL/pgSQL. PostgreSQL raises SQLSTATE 54001 (statement_too_complex).
- A HINT suggests increasing
max_stack_depthif safe. - Often from infinite or very deep recursion.
- Guards against crashing the backend via stack overflow.
What the server log shows
ERROR: stack depth limit exceeded
HINT: Increase the configuration parameter max_stack_depth (currently 2048kB), after ensuring the platform's stack depth limit is adequate.
Why PostgreSQL raises this — what the manual says
Section 19.4.1 Memory (max_stack_depth):
“Specifies the maximum safe depth of the server’s execution stack.”
PostgreSQL checks execution stack depth against max_stack_depth. When recursion or nesting exceeds it, the statement is aborted with 54001 rather than risking a stack overflow that would crash the backend.
Common causes
- Infinite or unbounded recursion in a function or recursive CTE.
- Very deeply nested function/trigger calls.
- A recursive query missing a proper termination condition.
Relevant GUC parameters
| Parameter | Default | Effect |
|---|---|---|
max_stack_depth |
2MB | Maximum safe server stack depth; must stay below the OS ulimit -s. |
How to fix it
- Add a termination/base case to recursive functions or CTEs.
- Refactor deep recursion into iteration.
- If legitimately deep, raise
max_stack_depth— but keep it below the OSulimit -s.
Related & next steps
Reference: PostgreSQL 18 Section 20.4 “Resource Consumption”.
Thanks — noted. This helps keep the database accurate.