Start free trial
Start free trial Log in

14-day free trial. No credit card.

Laravel memory usage per request

How to measure peak memory, find the routes that spike, and fix the patterns that burn your PHP memory_limit.

  • Guide
  • 3 min read

How do I measure memory usage per Laravel request?

Use memory_get_peak_usage(true) in a terminate middleware to capture the full request's peak in bytes. Record alongside route pattern, controller action, and response time, then aggregate by route to find hot spots. Routes that regularly peak near your memory_limit need attention. Laravel's nightwatch package records peak memory per request automatically.

Updated

Memory is the resource that doesn't degrade gracefully. A slow request is annoying; a request that crosses memory_limit is a hard 500 with Allowed memory size exhausted, and it tends to hit your biggest, most valuable customers, the ones with enough data to blow past the limit. The frustrating part is that it's invisible until it isn't: the route works in dev, works for most users, and falls over for the one account with 50,000 rows. Measuring peak memory per request is how you find those routes before a customer does.

Measuring peak memory per request

PHP exposes two functions:

  • memory_get_usage(true): memory currently reserved from the operating system, in bytes
  • memory_get_peak_usage(true): high-water mark since script start (or the last memory_reset_peak_usage()), in bytes

Capture the peak in a terminate middleware, which runs after the response is sent:

app/Http/Middleware/RecordMemoryUsage.php

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RecordMemoryUsage
{
    public function handle(Request $request, Closure $next)
    {
        return $next($request);
    }

    public function terminate(Request $request, $response): void
    {
        $peakMb = round(memory_get_peak_usage(true) / 1024 / 1024, 2);

        if ($peakMb > 80) {
            Log::warning('High-memory request', [
                'route' => $request->route()?->uri(),
                'method' => $request->method(),
                'peak_mb' => $peakMb,
                'user_id' => auth()->id(),
            ]);
        }
    }
}

Common memory-heavy patterns

Unbounded eager loading

php
// Bad: materializes users × posts × comments × authors in memory
$users = User::with('posts.comments.author')->get();

// Better: paginate and process in chunks
User::with('posts.comments.author')->chunkById(100, function ($users) {
    foreach ($users as $user) {
        // ...
    }
});

// Best for one loop over everything: lazyById() fetches in chunks
// behind a single foreach, and keeps eager loading (cursor() can't)
foreach (User::with('posts.comments.author')->lazyById(100) as $user) {
    // ...
}

Reading large files into memory

php
// Bad: whole file in memory
$content = file_get_contents(storage_path('big-export.csv'));

// Better: stream line by line
$handle = fopen(storage_path('big-export.csv'), 'r');
while (($line = fgets($handle)) !== false) {
    // ...
}
fclose($handle);

// Laravel wrapper: stream a response
return response()->stream(function () {
    foreach (User::lazyById(1000) as $user) {
        echo $user->id . "\n";
    }
}, 200, ['Content-Type' => 'text/plain']);

Blade rendering huge collections

@foreach (\$rows as \$row) in a Blade view with 50,000 rows renders every row to an in-memory string before sending the response. Paginate on the server side, not in Blade.

Memory is input-shaped

Unlike CPU time, memory usage tracks the size of the data a request touches, not the work it does. The same GET /export endpoint might use 12 MB for a small account and 400 MB for your biggest one, because the query returns far more rows. That's why average memory for a route tells you almost nothing. It's dominated by the common small case and hides the rare large one that actually OOMs. Look at p95 and max peak memory per route, and watch the gap between them: a route at 20 MB p95 and 480 MB max has one input shape that's about to become a 500.

Finding your memory hot spots

Aggregate peak memory per route pattern and sort by p95. The routes at the top are where to focus. Typical targets to investigate:

  • Any route with p95 peak > 64 MB
  • Routes whose p95 peak has grown 2x+ over the last 30 days (data growth outpacing pagination)
  • Routes that hit memory_limit occasionally (shows up as 500 errors with Allowed memory size of X bytes exhausted)

Octane is different

If you're on Octane (Swoole, RoadRunner, FrankenPHP) the worker process persists across requests. Memory-per-request is less meaningful than memory growth over the worker's lifetime. See the Octane monitoring guide for the specifics.

See the peak memory of every request

NightOwl records each request's peak memory and shows it in the request's Info panel, on the same page as its duration and query timeline. Open a slow request and the figure is already there, without a middleware to write.

No credit card needed.

Terminal
composer require nightowl/agent
php artisan nightowl:install
php artisan nightowl:agent

Frequently asked questions

Anything else, write to support@usenightowl.com

How do I measure memory usage per Laravel request?

PHP's memory_get_peak_usage(true) returns the high-water mark of allocated memory for the current process, in bytes. Record it in a middleware that runs after the response is produced to capture the full request's peak. The 'true' flag reports the memory PHP's allocator has reserved from the operating system (it grows in 2 MB chunks), which is the figure memory_limit is checked against. Without it you get the bytes currently in use inside those chunks, which reads lower.

Why is Laravel memory usage high on some routes?

The top three culprits: (1) unbounded Eloquent eager loading: loading User::with('posts.comments.author') across 1,000 users materializes hundreds of thousands of objects, (2) reading large files or request bodies fully into memory with file_get_contents() or $request->getContent() (stream them instead), (3) Blade template rendering with large collections (pagination or lazy loading fixes it). Profile with a per-request memory recorder before guessing.

What's a normal memory footprint for a Laravel request?

There's no universal number: it depends on your packages, your PHP version and how much data a route touches, so measure your own baseline per route. PHP's default memory_limit is 128M, and a request that regularly peaks close to it needs optimization even if it completes. Octane changes the picture (memory accumulates across requests in a worker).

How do I find which Laravel route causes the most memory pressure?

Record peak memory per request with the route pattern. Aggregate by route and sort by p95 peak memory. The top of that list is where to focus. If you don't have an APM doing this, a middleware that writes route + memory_get_peak_usage to a dedicated table gets you there in an afternoon.

How do I fix Laravel memory leaks in long-running processes?

Under PHP-FPM, PHP frees everything a request allocated when it ends, so 'leaks' aren't usually a problem. In Octane workers and queue workers the process keeps running, so memory accumulates. Fix: (1) avoid static caches that grow unbounded, (2) chunk large Eloquent queries with chunkById() instead of get()->each(), (3) unset() large collections as soon as you're done with them in long jobs, (4) restart workers before they grow too large: queue:work --memory, --max-jobs and --max-time, or the matching Horizon supervisor options.

Does Laravel Octane change memory monitoring?

Yes. Octane keeps workers alive across requests, so memory-per-request is less meaningful: you care about memory growth over a worker's lifetime. Monitor memory_get_usage() at request start and end; a persistently growing delta indicates a leak. Octane's max_requests setting recycles workers periodically as a safety net.

What's memory_get_peak_usage vs memory_get_usage?

memory_get_usage() returns current memory allocated; memory_get_peak_usage() returns the high-water mark since the script started. For per-request monitoring you want peak. In a long-running worker the peak doesn't reset between requests unless something calls memory_reset_peak_usage() (PHP 8.2+); the Nightwatch package does this itself so each recorded request gets its own peak. Current usage is what you watch for leaks across a worker's lifetime.

Should I alert on Laravel memory spikes?

Yes, but at the right granularity. Don't alert on every 100MB request. Alert when p95 peak memory for a specific route pattern exceeds a baseline by 2x, sustained over 5+ minutes. Memory spikes are usually correlated with specific inputs (large exports, user-submitted files) and warrant investigation even when requests complete. NightOwl records each request's peak memory but doesn't alert on it, so a p95 memory alert has to come from a scheduled query or your metrics stack.

Related

Flat pricing, whatever your traffic does

Every plan starts with a 14-day free trial. No credit card needed.

Hobby
$5 a month

One app for a side project. Issues and alerts, with a 14-day dashboard window.

Start my 14-day trial
TeamRecommended
$15 a month

Up to 3 apps and 5 people per team. Full history, the MCP server, data clearing and agent health.

Start my 14-day trial
Agency
$69 a month

Unlimited client apps and people, one overview of every app, and apps you can hand over.

Start my 14-day trial