Laravel Octane State Leakage: Fix Worker Memory Bugs | 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 State Leakage: Detecting and Fixing Shared-Memory Bugs in Laravel Workers

 Octane State Leakage: Detecting and Fixing Shared-Memory Bugs in Laravel Workers
=================================================================================

 Laravel Octane keeps workers alive across requests, making shared state a silent killer. Learn how to detect, reproduce, and permanently fix state leakage with practical code patterns.

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

ShareCopy linkCopied

 ![Octane State Leakage: Detecting and Fixing Shared-Memory Bugs in Laravel Workers](https://cdn.msaied.com/705/8e7dc5a87f9f9a30b8523ca5280e8f97.png) 

  On this page +1. [The Problem With Persistent Workers](#the-problem-with-persistent-workers)
2. [What Actually Leaks](#what-actually-leaks)
3. [Detecting Leakage Before Production](#detecting-leakage-before-production)
4. [Write a Leakage Smoke Test](#write-a-leakage-smoke-test)
5. [Use Octane's RequestHandled Hook](#use-octanes-coderequesthandledcode-hook)
6. [Safe Patterns for Stateful Services](#safe-patterns-for-stateful-services)
7. [Bind as Scoped, Not Singleton](#bind-as-scoped-not-singleton)
8. [Immutable Value Objects Are Always Safe](#immutable-value-objects-are-always-safe)
9. [Avoid Static Caches; Use the Cache Store Instead](#avoid-static-caches-use-the-cache-store-instead)
10. [Audit Checklist](#audit-checklist)
11. [Takeaways](#takeaways)

 The Problem With Persistent Workers
-----------------------------------

Laravel Octane boots your application once and reuses that process across thousands of requests. The performance gains are real, but so is the footgun: any mutable state stored in a singleton, a static property, or a service-provider binding leaks from one request into the next.

This is not a theoretical concern. A user sees another user's cart. A tenant's database connection bleeds into a different tenant's request. A cached config value from request one silently poisons request two.

### What Actually Leaks

The three most common sources of leakage:

1. **Singletons that accumulate state** — a service registered as a singleton that appends to an internal array on every call.
2. **Static class properties** — PHP statics survive the entire worker lifetime.
3. **Request-scoped data stored in long-lived objects** — injecting `Request` into a constructor that is resolved once at boot.

```php
// DANGEROUS: static accumulator
class AuditLogger
{
    private static array $entries = [];

    public static function record(string $message): void
    {
        self::$entries[] = $message; // grows forever across requests
    }
}

```

```php
// DANGEROUS: request injected into a singleton
class CurrentUser
{
    public function __construct(private Request $request) {}

    public function id(): int
    {
        return $this->request->user()->id; // stale after first request
    }
}

```

Detecting Leakage Before Production
-----------------------------------

### Write a Leakage Smoke Test

Octane ships with `Octane::fake()` for feature tests, but the fastest feedback loop is a dedicated Pest test that boots the app twice and asserts isolation:

```php
it('does not leak audit entries between requests', function () {
    AuditLogger::record('request-one-event');

    // Simulate what Octane does between requests
    app()->forgetInstance(AuditLogger::class);
    AuditLogger::flush(); // you must implement this

    AuditLogger::record('request-two-event');

    expect(AuditLogger::entries())->toHaveCount(1);
});

```

If `flush()` does not exist yet, the test forces you to add it.

### Use Octane's `RequestHandled` Hook

Octane fires `RequestHandled` after every request. Register a flush callback in your `AppServiceProvider`:

```php
use Laravel\Octane\Facades\Octane;

public function boot(): void
{
    Octane::tick('flush-audit-logger', function () {
        AuditLogger::flush();
    })->everySeconds(0); // runs after every request cycle
}

```

Actually, the correct hook is the `RequestHandled` event listener:

```php
use Laravel\Octane\Events\RequestHandled;

public function boot(): void
{
    $this->app['events']->listen(RequestHandled::class, function () {
        AuditLogger::flush();
        app()->forgetInstance(SomeStatefulService::class);
    });
}

```

Safe Patterns for Stateful Services
-----------------------------------

### Bind as Scoped, Not Singleton

Octane respects `scoped()` bindings — they are re-resolved per request, not per worker boot:

```php
$this->app->scoped(CurrentUser::class, function ($app) {
    return new CurrentUser($app->make(Request::class));
});

```

This is the single most impactful change you can make. Audit every `singleton()` call and ask: does this service touch request data?

### Immutable Value Objects Are Always Safe

```php
final class Money
{
    public function __construct(
        public readonly int $amount,
        public readonly string $currency,
    ) {}

    public function add(self $other): self
    {
        return new self($this->amount + $other->amount, $this->currency);
    }
}

```

No setters, no internal arrays, no static state — safe to share across the worker lifetime.

### Avoid Static Caches; Use the Cache Store Instead

```php
// RISKY across requests
private static array $resolvedPermissions = [];

// SAFE: scoped to request via the cache store with a short TTL
public function permissions(int $userId): array
{
    return cache()->remember("perms:{$userId}", 5, fn () => $this->query($userId));
}

```

The cache store is external; it does not live in worker memory.

Audit Checklist
---------------

- \[ \] Run `grep -rn 'static \$' app/` — review every hit.
- \[ \] Run `grep -rn '->singleton(' app/` — confirm none touch request state.
- \[ \] Add `RequestHandled` listeners for every service that must reset.
- \[ \] Replace request-injected constructors with `scoped()` bindings or lazy resolution via `app()`.
- \[ \] Write at least one Pest test per stateful service that asserts isolation across two simulated requests.

Takeaways
---------

- Octane's performance comes from worker reuse; correctness requires explicit state isolation.
- `scoped()` is the right binding for anything that touches per-request data.
- Static PHP properties are the hardest leaks to spot — grep for them proactively.
- `RequestHandled` is your flush hook; use it for anything that cannot be `scoped()`.
- Immutable value objects and external cache stores are naturally safe across worker lifetimes.

- [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)
- [testing](https://www.msaied.com/public/articles?search=testing)
- [architecture](https://www.msaied.com/public/articles?search=architecture)

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

  What is the difference between `singleton()` and `scoped()` in Laravel Octane?A `singleton()` is resolved once per worker boot and reused for the entire worker lifetime across all requests. A `scoped()` binding is resolved once per request and discarded at the end of that request, making it safe for services that depend on per-request data like the authenticated user or the current tenant.

   How do I flush static state between Octane requests?Listen to the `Laravel\\Octane\\Events\\RequestHandled` event in your service provider's `boot()` method and call your static `flush()` or `reset()` methods there. Alternatively, refactor the class to eliminate static state entirely and bind it as `scoped()` instead.

   Does Octane automatically handle Eloquent model state between requests?Eloquent model instances themselves are not singletons, so they are garbage-collected normally. However, if you store a model instance inside a singleton service, that instance persists. The fix is to move such services to `scoped()` bindings or re-fetch the model from the database on each request.

   ![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 articleProduction AI Agents in Laravel: Streaming, Token Budgets, and Structured Output Contracts](https://www.msaied.com/public/articles/production-ai-agents-in-laravel-streaming-token-budgets-and-structured-output-contracts-4) [Next articleTyped PHP 8.3 Enums as Eloquent Casts, Route Parameters, and Validation Rules](https://www.msaied.com/public/articles/typed-php-83-enums-as-eloquent-casts-route-parameters-and-validation-rules-1)  

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

1. [The Problem With Persistent Workers](#the-problem-with-persistent-workers)
2. [What Actually Leaks](#what-actually-leaks)
3. [Detecting Leakage Before Production](#detecting-leakage-before-production)
4. [Write a Leakage Smoke Test](#write-a-leakage-smoke-test)
5. [Use Octane's RequestHandled Hook](#use-octanes-coderequesthandledcode-hook)
6. [Safe Patterns for Stateful Services](#safe-patterns-for-stateful-services)
7. [Bind as Scoped, Not Singleton](#bind-as-scoped-not-singleton)
8. [Immutable Value Objects Are Always Safe](#immutable-value-objects-are-always-safe)
9. [Avoid Static Caches; Use the Cache Store Instead](#avoid-static-caches-use-the-cache-store-instead)
10. [Audit Checklist](#audit-checklist)
11. [Takeaways](#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)
