nphp9 Jun 2025 07:42

PHP was designed on the shared nothing principle: each request gets a clean process, no memory shared between requests. Frameworks like Laravel rely on this.

With Swoole, Hyperf, and Octane, this changes. State can leak between requests. What patterns do people use to stay safe?

Replies (6)
dmitry_kv9 Jun 2025 08:03

The main rule: nothing mutable in static properties or global state. Service classes are fine if they are stateless. The problem is any class that stores request-specific data as an instance property in a singleton.

0
alex_petrov9 Jun 2025 09:30

In Hyperf, Coroutine::getContext() gives you a coroutine-local storage that is cleaned up when the coroutine ends. That is how it replaces things like superglobals and request-scoped state.

0
sergey_web9 Jun 2025 10:02

Authentication state is the most common leaker. If your auth middleware stores the user in a static property for convenience, the next request in the same worker will see the previous user. Caught this bug in production.

0
petr_sys9 Jun 2025 11:17

Octane flushes the service container between requests for scoped bindings, but singletons persist. Know which of your services are bound as singletons and audit them for mutable state.

0
vova9 Jun 2025 12:08

The safest rule: treat every service as if it runs in a worker that handles millions of requests in sequence. Any state that is not explicitly reset between requests will eventually cause a bug.

0
nphp9 Jun 2025 13:54

I wrote a static analysis rule for PHPStan that flags mutable static properties in classes registered as singletons. Catches about half the issues before they reach review.

0