Laravel Octane: Worker Lifecycle &amp; State Leakage | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Octane Worker Lifecycle, State Leakage, and Memory Management in Production

 Octane Worker Lifecycle, State Leakage, and Memory Management in Production
============================================================================

 Laravel Octane keeps workers alive between requests, which means static state, resolved singletons, and leaked closures silently corrupt responses. Learn exactly where leakage happens and how to prevent it.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 18 Jul 2026 · Updated 18 Jul 2026 · 4 min read

ShareCopy linkCopied

 ![Octane Worker Lifecycle, State Leakage, and Memory Management in Production](https://cdn.msaied.com/440/abbd7cbb286a5bd8ea53bee583d2c30f.png) 

  On this page +1. [Why Octane Changes Everything About Application State](#why-octane-changes-everything-about-application-state)
2. [The Worker Lifecycle in Detail](#the-worker-lifecycle-in-detail)
3. [Common Leakage Patterns](#common-leakage-patterns)
4. [1. Singletons That Accumulate State](#1-singletons-that-accumulate-state)
5. [2. Static Properties](#2-static-properties)
6. [3. Closures Captured in Long-Lived Objects](#3-closures-captured-in-long-lived-objects)
7. [Memory Management](#memory-management)
8. [Verifying Your Code Is Octane-Safe](#verifying-your-code-is-octane-safe)
9. [Key Takeaways](#key-takeaways)

 Why Octane Changes Everything About Application State
-----------------------------------------------------

Traditional PHP-FPM boots the framework on every request and discards all memory when the response is sent. Octane inverts this: a single worker process boots Laravel **once** and then handles thousands of requests in that same process. The performance gain is real — but the contract your code must honour changes completely.

Understanding the worker lifecycle is the prerequisite for running Octane safely.

The Worker Lifecycle in Detail
------------------------------

With Swoole or RoadRunner, Octane's boot sequence looks like this:

1. **Worker boot** — `Application::boot()` runs, all service providers fire, singletons are resolved and cached in the container.
2. **Request loop** — for each incoming request Octane clones a "sandbox" application, binds fresh `Request`, `Auth`, `Session`, and a handful of other stateful services, then dispatches through the kernel.
3. **Flush** — after the response is sent, Octane fires `RequestHandled` and resets the services registered in `octane.php` under `flush`.

The critical insight: **anything not in the flush list persists across requests**.

Common Leakage Patterns
-----------------------

### 1. Singletons That Accumulate State

```php
// AppServiceProvider
$this->app->singleton(ReportBuilder::class, function () {
    return new ReportBuilder();
});

// ReportBuilder.php
class ReportBuilder
{
    private array $filters = [];

    public function addFilter(string $f): static
    {
        $this->filters[] = $f; // leaks across requests!
        return $this;
    }
}

```

Request 1 adds `['status' => 'active']`. Request 2 resolves the **same** instance and sees that filter already present. Fix: make the class immutable, or register it as `scoped` instead of `singleton`.

```php
$this->app->scoped(ReportBuilder::class, fn () => new ReportBuilder());

```

`scoped` bindings are flushed by Octane automatically at the end of each request — they behave like singletons within a request but are discarded afterward.

### 2. Static Properties

```php
class TenantContext
{
    public static ?Tenant $current = null;
}

```

Octane's sandbox clone does **not** reset static class properties. If middleware sets `TenantContext::$current` and a subsequent request hits the same worker before middleware runs, it reads the previous tenant. Use `app()->scoped()` or reset explicitly in an Octane `RequestHandled` listener.

```php
// OctaneServiceProvider or EventServiceProvider
Octane::tick('reset-tenant', function () {
    TenantContext::$current = null;
});

```

### 3. Closures Captured in Long-Lived Objects

```php
$this->app->singleton(EventDispatcher::class, function ($app) {
    $d = new EventDispatcher();
    $d->listen('*', function ($event) use ($app) {
        // $app is the root container — fine.
        // but if you capture $request here, it leaks.
    });
    return $d;
});

```

Capturing the current `Request` or `Auth` object inside a singleton closure is a classic leak. Always resolve them lazily from the container at call time.

Memory Management
-----------------

Octane workers will grow in memory over time even with correct code, because PHP's garbage collector does not always collect cyclic references immediately.

**Configure `max_requests` in `octane.php`:**

```php
'swoole' => [
    'options' => [
        'max_request' => 500,
    ],
],

```

After 500 requests the worker restarts cleanly. Tune this number based on your memory growth rate — profile with `memory_get_usage()` logged in a `RequestHandled` listener.

**Use `octane:status` and Horizon-style metrics** to watch worker memory in production. A worker that grows beyond ~128 MB before its `max_requests` limit is a signal of a genuine leak.

Verifying Your Code Is Octane-Safe
----------------------------------

The `laravel/octane` package ships a `--watch` flag for development, but for correctness testing:

```bash
php artisan octane:start --workers=1 --max-requests=1000

```

Then hammer a route that exercises your singletons with `wrk` or `ab` and assert response consistency. Automated: write a Pest test that dispatches the same request twice through the kernel and asserts no state bleeds.

```php
it('does not leak filters between requests', function () {
    $kernel = app(\Illuminate\Contracts\Http\Kernel::class);

    $r1 = $kernel->handle(Request::create('/report?status=active'));
    $r2 = $kernel->handle(Request::create('/report'));

    expect($r2->getContent())->not->toContain('active');
});

```

Key Takeaways
-------------

- Use `scoped` instead of `singleton` for any service that holds per-request state.
- Never store the current `Request`, `Auth`, or `Session` in a singleton property or static variable.
- Reset static class properties in an Octane `RequestHandled` listener or `tick`.
- Set `max_requests` to recycle workers and cap worst-case memory growth.
- Profile memory growth per request in staging before deploying Octane to production.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [octane](https://www.msaied.com/public/articles?search=octane)
- [performance](https://www.msaied.com/public/articles?search=performance)
- [swoole](https://www.msaied.com/public/articles?search=swoole)
- [roadrunner](https://www.msaied.com/public/articles?search=roadrunner)

 Frequently asked questions 
---------------------------

  What is the difference between `singleton` and `scoped` in an Octane context?A `singleton` is resolved once per worker process and persists for the entire lifetime of that worker. A `scoped` binding is resolved once per request and automatically flushed by Octane at the end of each request, making it safe for stateful per-request services.

   Does Octane automatically reset all Laravel services between requests?Only the services listed under the `flush` key in `config/octane.php` are reset automatically. Core stateful services like `Request`, `Auth`, and `Session` are included by default, but any custom singletons you register are your responsibility.

   How do I detect a state leak in an Octane application?Run a single worker with a high `max\_requests` value and send the same request repeatedly with different inputs. Log the response or assert consistency in a Pest test that calls the kernel twice in the same process. Diverging responses between calls indicate leaked state.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleMySQL Index Strategies for Laravel: Composite, Prefix, and Invisible Indexes](https://www.msaied.com/public/articles/mysql-index-strategies-for-laravel-composite-prefix-and-invisible-indexes-1) [Next articleFilament v3 Custom Field Plugins, Custom Columns, and Render Hooks in Practice](https://www.msaied.com/public/articles/filament-v3-custom-field-plugins-custom-columns-and-render-hooks-in-practice)  

   On this page
-------------

1. [Why Octane Changes Everything About Application State](#why-octane-changes-everything-about-application-state)
2. [The Worker Lifecycle in Detail](#the-worker-lifecycle-in-detail)
3. [Common Leakage Patterns](#common-leakage-patterns)
4. [1. Singletons That Accumulate State](#1-singletons-that-accumulate-state)
5. [2. Static Properties](#2-static-properties)
6. [3. Closures Captured in Long-Lived Objects](#3-closures-captured-in-long-lived-objects)
7. [Memory Management](#memory-management)
8. [Verifying Your Code Is Octane-Safe](#verifying-your-code-is-octane-safe)
9. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
