Laravel Octane State Leakage: Fix Worker Memory Bugs | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    Octane State Leakage: Detecting and Fixing Shared-Memory Bugs in Laravel Workers        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)

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

  #laravel   #octane   #performance   #testing   #architecture  

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

     26 Sep 2026      4 min read    ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said  

       Table of contents

  11 sections  

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

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Foctane-state-leakage-detecting-and-fixing-shared-memory-bugs-in-laravel-workers&text=Octane+State+Leakage%3A+Detecting+and+Fixing+Shared-Memory+Bugs+in+Laravel+Workers) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Foctane-state-leakage-detecting-and-fixing-shared-memory-bugs-in-laravel-workers) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  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. 

      Q02  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. 

      Q03  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. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Production AI Agents in Laravel: Streaming, Token Budgets, and Structured Output Contracts](https://cdn.msaied.com/704/165bcb76b898fe9911130d2c93b9b805.png) laravel ai llm 

### Production AI Agents in Laravel: Streaming, Token Budgets, and Structured Output Contracts

Building reliable AI agents in Laravel means more than wiring up an API call. Learn how to stream responses sa...

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

 26 Sep 2026     3 min read  

  Read    

 ](https://msaied.com/articles/production-ai-agents-in-laravel-streaming-token-budgets-and-structured-output-contracts-4) [ ![Decide with Jev: Build a Laravel AI Content Preflight Checker That Returns a Probability](https://cdn.msaied.com/701/916a0dd2b427c6335395d6d2684524ab.png) Laravel AI Jev TypeSafe 

### Decide with Jev: Build a Laravel AI Content Preflight Checker That Returns a Probability

Jev is a TypeSafe AI model that returns a probability score instead of text. Learn how Harris Raftopoulos uses...

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

 25 Sep 2026     4 min read  

  Read    

 ](https://msaied.com/articles/decide-with-jev-build-a-laravel-ai-content-preflight-checker-that-returns-a-probability) [ ![Filament v4 Migrating from v3: Breaking Changes and Refactor Patterns](https://cdn.msaied.com/700/85cddaf32751d756924869323a845563.png) filament laravel upgrade 

### Filament v4 Migrating from v3: Breaking Changes and Refactor Patterns

A practical, opinionated guide to the most impactful breaking changes when upgrading Filament v3 to v4, with c...

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

 25 Sep 2026     4 min read  

  Read    

 ](https://msaied.com/articles/filament-v4-migrating-from-v3-breaking-changes-and-refactor-patterns-1) 

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

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
