Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

PHP 8.3+ throws Maximum call stack size reached. Infinite recursion?

Your error

Fatal error: Uncaught Error: Maximum call stack size of 8306688 bytes (zend.max_allowed_stack_size - zend.reserved_stack_size) reached. Infinite recursion?1 more line it can show

Fix it fast

Most common cause, 1 of 3

Endless recursion through an internal function or a magic method

Follow the repeating frames to the call that leads back into the same function, and make sure every path through it reaches a stopping condition.

Fix
function depth(array $node): int
{
    if (empty($node['children'])) {
        return 1;          // the stopping condition
    }
    return 1 + max(array_map('depth', $node['children']));
}
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

PHP 8.3 and later throw Maximum call stack size of N bytes reached. Infinite recursion? before the stack overflows. Usually a recursion through callbacks or magic methods never ends; nested serialize() calls on cyclic objects do the same since 8.3.27 and 8.4.14. For deep but finite recursion, raise ulimit -s. Applies to PHP 8.3 to 8.6.

  • Applies to PHP 8.6.0, PHP 8.5.13, PHP 8.4.28, PHP 8.3.37, Linux, bash ulimit
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Print the PHP version, the shell's stack limit in KiB and the two stack settings. Then read the stack trace of the error: frames that repeat point to causes 1 or 2, a long but varied trace through a parser or tree walker points to cause 3.

Run this first
php -v | head -1
ulimit -s
php -i | grep -E "zend\.(max_allowed|reserved)_stack_size"

Then find the line you see in this list and open its fix:

  1. 1Endless recursion through an internal function or a magic methodThe same frames repeat all the way down the trace, and they include a callback runner such as array_map or usort, or a magic method such as __toString
  2. 2serialize() is called again inside __serialize() on a cyclic object graphThe trace alternates between serialize() and a __serialize() or Serializable::serialize() method, and it started after moving to 8.3.27 or 8.4.14
  3. 3The recursion is finite, but the process stack is too small for itThe trace is long but not a loop, the input is deeply nested, and the byte count in the message is close to ulimit -s times 1024

What does the error look like?

  • Fatal error: Uncaught Error: Maximum call stack size of 8306688 bytes (zend.max_allowed_stack_size - zend.reserved_stack_size) reached. Infinite recursion?
  • Maximum call stack size of 8339456 bytes reached. Infinite recursion?

Cause 1 of 3

Endless recursion through an internal function or a magic method

You seeThe same frames repeat all the way down the trace, and they include a callback runner such as array_map or usort, or a magic method such as __toString

Check

PHP 8.3 added the stack check so that runaway recursion ends in a catchable Error rather than a segmentation fault. According to the migration notes, the stack grows when uncontrolled recursion passes through internal functions or the magic methods __toString(), __clone(), __sleep() and __destruct(), so those frames are the ones to look for.

Check
php your-script.php 2>&1 | grep -E "^#[0-9]+ " | head -20

Fix

Follow the repeating frames to the call that leads back into the same function, and make sure every path through it reaches a stopping condition. For __toString(), check that it never casts $this, or an object that casts it back, to a string.

Fix
function depth(array $node): int
{
    if (empty($node['children'])) {
        return 1;          // the stopping condition
    }
    return 1 + max(array_map('depth', $node['children']));
}

Verify

The same command now finishes, and the trace no longer repeats the same frame.

Verify
php your-script.php; echo "exit: $?"

Confirmed by php.net

Did this fix it?

Cause 2 of 3

serialize() is called again inside __serialize() on a cyclic object graph

You seeThe trace alternates between serialize() and a __serialize() or Serializable::serialize() method, and it started after moving to 8.3.27 or 8.4.14

Check

PHP tracks objects it has already written only within one serialize() call. When __serialize() itself calls serialize() on children that point back to the parent, each inner call starts with an empty record, so the cycle never ends. Code like this that ran on 8.3.26 can fail after the 8.3.27 and 8.4.14 updates; the maintainers explained the per-call tracking and closed the report as expected behaviour.

Check
grep -rn -A6 "function __serialize" src | grep -E "(^|[^_])serialize\("

Fix

Return the data as a plain array from __serialize() and let the outer serialize() handle it in one pass, so PHP can see and reuse objects it has already stored. For a third-party library, update to a release that dropped the nested call.

Fix
public function __serialize(): array
{
    // before: return [serialize($this->toArray())];
    return $this->toArray();
}

public function __unserialize(array $data): void
{
    $this->fromArray($data);
}

Verify

serialize() of the object returns a string, and unserialize() of that string rebuilds it.

Verify
php -r 'require "vendor/autoload.php"; $o = new App\Search\ClassMetadata(); var_dump(unserialize(serialize($o)) instanceof App\Search\ClassMetadata);'

Confirmed by github.com

Did this fix it?

Cause 3 of 3

The recursion is finite, but the process stack is too small for it

You seeThe trace is long but not a loop, the input is deeply nested, and the byte count in the message is close to ulimit -s times 1024

Check

With zend.max_allowed_stack_size at its default of 0, PHP measures the real stack limit; on Linux the main thread's limit comes from RLIMIT_STACK, the value ulimit -s shows in KiB. A legitimate walk over deeply nested data can simply need more stack than that limit allows.

Check
ulimit -s
ulimit -H -s

Fix

Raise the soft stack limit for the shell that starts PHP, up to the hard limit, then run the command again; PHP picks up the larger limit on its own. Avoid zend.max_allowed_stack_size=-1 or a value larger than the real stack, because that only removes the safety check and brings back segmentation faults.

Fix
ulimit -S -s 65536      # 64 MiB, must not exceed ulimit -H -s
php artisan route:cache

Verify

ulimit -s prints the new value in that shell, and the command that failed now completes.

Verify
ulimit -s

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Add a unit test that serializes and unserializes every class with __serialize(), with at least one parent-child cycle in the fixture.
  • Turn deep recursive tree walks into loops with an explicit stack array when the input depth is not under your control.
  • Set the stack ulimit in the service or container definition of CLI workers that need more, instead of disabling PHP's check in php.ini.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: Spotless Laundry, EZ Estimater.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.