ix
ix

informatix

PL version Book a discovery call
Home / Blog / Laravel Performance Optimization — Practical Guide [2026]
• Updated: • 14 min read •

Laravel Performance Optimization — Practical Guide [2026]

Slow apps lose users and revenue. A complete Laravel performance guide — from measurement and N+1 queries, through caching, queues and indexes, to OPcache, PHP-FPM and Laravel Octane. With a deployment checklist and costs.

Laravel Performance Optimization — Practical Guide [2026]
Web development, DevOps & maintenance

Slow applications lose users and revenue — research shows 53% of visitors abandon a page that takes longer than 3 seconds to load, and every additional second of latency cuts conversions while raising infrastructure costs. Laravel performance optimization is not a luxury; it is part of a production standard that affects SEO, server bills and retention. A full performance audit with fixes typically costs 2,000–15,000 PLN net + VAT, depending on how deep the problems go.

This guide walks through every layer of Laravel application performance — from database queries, through caching and queues, to PHP configuration, the web server and Laravel Octane. The order of the sections matches the order in which I would diagnose a real project: measurement first, then the optimizations with the best return on effort, and finally the advanced topics.

Key takeaway: The short version — in most projects, four things deliver the biggest wins: eliminating N+1 queries (with()), caching repeated queries in Redis, moving external operations to queues, and adding the missing database indexes. Only then reach for OPcache preloading, Octane or a CDN. Always start with measurement — without a profile you do not know what is actually slowing the application down.

Measure first — profile before you optimize

The most common optimization mistake is guessing. A team spends two days micro-optimizing a loop while a single unindexed query or an N+1 in the busiest view eats 80% of the response time. Start by answering two questions: what is slow and by how much.

Tool What it shows Where to use it
Laravel Debugbar query count and time per request, duplicates, timeline locally, development
Laravel Telescope requests, queries, exceptions, mail, jobs staging; careful in production (data exposure)
Laravel Pulse slow queries, slow endpoints, cache usage, queues production
pg_stat_statements / slow query log the most expensive queries in the database (SUM of time) production
Blackfire / Xdebug CPU profile — which function consumes the time dev, staging
k6 / ab throughput, p50/p95/p99 under load staging, before releases
  • A practical start: enable Debugbar locally and walk through your three to five most important screens. If any of them fires hundreds of queries, or a single query takes hundreds of milliseconds — those are your first candidates.

Tip: Optimize after measuring, and measure the result. Without it you cannot tell a real gain from a placebo — and when the next change comes, you will not know what to roll back. Minimum: profile before, profile after, one metric (p95 response time) as the yardstick.

The N+1 query problem — the most common Laravel performance bug

Picture a loop that runs a separate query for each of 100 orders to fetch the customer name. That is 101 queries instead of 2. The N+1 problem is the most common cause of a "suddenly slow" Laravel application — it creeps in whenever a relation is accessed in a loop or a Blade view.

// BAD: 101 queries for 100 orders
$orders = Order::all();
foreach ($orders as $order) {
    echo $order->customer->name;
}

// GOOD: 2 queries
$orders = Order::with('customer')->get();

The fix is eager loading (with()), and when you do not know upfront which relations will be needed — lazy eager loading (load()). Use withCount() when you only need the number of related records instead of loading the entire relation.

For detection, enable Model::preventLazyLoading() in your development environment — Laravel will throw an exception on every lazily loaded relation. The laravel-query-detector package logs suspicious repeated patterns, and Debugbar shows the query count per request. Add a query budget assertion to your test suite and N+1 can never sneak back in unnoticed.

Eloquent performance — chunk, cursor and column selection

Eloquent is convenient, but by default it does more than you need. Here are three habits worth adopting in every project.

  • Select columns — Order::select('id', 'total', 'status')->get() instead of loading entire models with text and JSON columns.
  • Stream large result sets — chunk() (batches of 1,000), chunkById() (safe when records change mid-iteration) or cursor() (one record at a time, minimal memory).
  • Aggregate in the database — withCount(), withSum(), avg() instead of fetching collections and counting in PHP.
// Import 100,000 rows without exhausting memory
Order::query()
    ->where('status', 'pending')
    ->chunkById(1000, function ($orders) {
        foreach ($orders as $order) {
            ProcessOrder::dispatch($order->id);
        }
    });
  • The rule of thumb: replace "a query per record" with "a query per collection". Gather IDs, fetch related records with a single whereIn(), then map them in memory. with() does exactly that for relations.

Caching — Redis, cache tags and response caching

Laravel ships a unified caching system with Redis, Memcached, DynamoDB and file backends. Cache what does not change on every request: category lists, configuration, aggregates, heavy view fragments.

$categories = Cache::remember('categories:tree', now()->addHour(), fn () =>
    Category::with('children')->whereNull('parent_id')->get()
);

Three layers worth distinguishing

  • Object cache (Cache::remember) — query results and computations. Use Redis in production: fast, reliable, with tags and atomic locks.
  • View cache — the @cache Blade directive stores a rendered fragment for a given time; great for heavy sections with many relations.
  • HTTP response cache — spatie/laravel-responsecache or Cache-Control headers for full responses that are identical for all visitors.

Remember the other side of the coin: cache is debt. Every entry needs invalidation — and badly invalidated cache is worse than no cache at all. Invalidate through tags (Redis) or key versioning, never with Cache::flush() in production.

Warning: Cache tags (Cache::tags()) work exclusively on Redis and Memcached — the file and database drivers throw an exception. If you plan selective invalidation of key groups, choose Redis before you design the cache.

Queues — heavy work out of the request cycle

Sending mail, generating PDFs, calling external APIs, processing uploads — none of it belongs inside an HTTP request. The user should not wait for SMTP, and you gain retries, backoff and job monitoring for free.

SendOrderConfirmation::dispatch($order->id);
  • In production: the Redis driver, workers under Supervisor (or systemd), Laravel Horizon for monitoring and auto-scaling, and every job designed to be idempotent. For integrations with third-party APIs add rate limiting (RateLimited on jobs) — otherwise a cascade of 429 responses from a partner will stall the queue.

Database — indexes and EXPLAIN ANALYZE

A missing index on a status column in a table with a million rows guarantees slow queries — a sequential scan of the whole table on every filter. An index is the cheapest optimization in the entire stack: one migration, a gain measured in orders of magnitude.

Before adding an index, diagnose the query

EXPLAIN ANALYZE
SELECT * FROM orders WHERE status = 'pending' ORDER BY created_at DESC;

A Seq Scan on a large table means a missing index or an index that does not match the query. Index Scan instead means the problem is solved. In PostgreSQL you can also create partial indexes (WHERE status = 'active') — smaller, faster and cheaper to maintain when queries always filter on a constant value.

Mind the cost: indexes speed up reads but slow down writes and take disk space. Create them on columns actually used in WHERE, JOIN and ORDER BY. For database engine selection criteria, see PostgreSQL vs MySQL for Laravel.

php artisan optimize — config, route and view caching

Every deployment should end with a series of commands that turn hundreds of configuration files and definitions into compiled artifacts:

composer install --optimize-autoloader --no-dev
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
  • config:cache — merges all config/*.php files into one cached file; the application stops parsing them on every request.
  • route:cache — compiles routing (with hundreds of routes this is tens of milliseconds per request).
  • view:cache — precompiles all Blade templates.
  • --optimize-autoloader — Composer generates an optimized class map instead of scanning the filesystem.

Warning: After config:cache, the env() helper works only inside config/*.php files. If you call env() in a controller or service, you will get null after deployment. Always go through config('services.x.key').

OPcache and PHP-FPM configuration

PHP compiles source files to opcodes on every request; OPcache remembers the result — one of the cheapest optimizations in the stack. Production settings:

opcache.enable=1
opcache.memory_consumption=192
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
opcache.revalidate_freq=0
realpath_cache_size=4096K
  • memory_consumption — 128–256 MB for a typical Laravel app (the framework alone is thousands of files).

  • max_accelerated_files — must fit the project plus vendor; 20,000 is safe.

  • validate_timestamps=0 — OPcache stops checking file modification times on every request; requires clearing the cache on deploy (opcache_reset() or an FPM restart). Never enable this where files change outside a deploy.

  • Next, PHP-FPM: pm.max_children is the parameter that matters most. Size it from memory, not gut feeling: max_children = available_RAM / average_process (typically 40–80 MB per Laravel process). Too few processes and requests queue; too many and the box starts swapping.

pm = dynamic
pm.max_children = 25
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 500

pm.max_requests = 500 is a fuse against memory leaks in extensions: a worker serves 500 requests and is replaced with a fresh one.

Tip: JIT (since PHP 8.0) mostly accelerates CPU-bound code (math, image processing). A typical Laravel app spends its time in I/O — database and network — so the gain from opcache.jit=tracing is often in the single digits. Measure before you treat it as an optimization.

Laravel Octane — when PHP-FPM is not enough

Classic PHP-FPM boots the framework on every request. Laravel Octane boots the application once and serves requests through long-lived workers (FrankenPHP, Swoole, RoadRunner). The result: 2–4× higher throughput and lower latency — without changing application code.

  • Octane makes sense when: traffic is steady and high, infrastructure is vertically constrained, and the application is "clean" (no state in singletons and statics). It does not make sense for small applications with low traffic — the operational cost outweighs the gain.

Warning: Octane changes the execution model: state is not reset between requests. A singleton holding user data or a static cache means data leaking between users. Audit your state before deploying — long-lived workers execute whatever is in memory, not what you assume is there.

Frontend performance — Vite, minification and images

Assets can weigh more than the entire HTML document. The Laravel standard is Vite (it replaced Laravel Mix), which builds, minifies and versions files out of the box (npm run build). Minifying CSS and JavaScript is table stakes, but the biggest visual win usually comes from image compression:

  • Images are typically ~60% of page weight — compress before uploading (WebP/AVIF instead of JPEG/PNG).
  • loading="lazy" for images below the fold — the browser loads them on scroll.
  • font-display: swap for fonts — text is visible before the font loads.

For Inertia.js applications, watch what each page actually sends in its props: oversized props are a common cause of slow navigation. See Inertia.js with Laravel and React for the architecture details.

CDN and HTTP caching

For static assets, configure a CDN and Cache-Control headers. Files built by Vite carry a hash in the name (app-8f3c2a.js), so they can be cached aggressively:

Cache-Control: public, max-age=31536000, immutable

For full HTML responses, consider Varnish or Nginx FastCGI Cache (caching for anonymous users, offloading PHP) or spatie/laravel-responsecache (application-layer caching with invalidation on model save). This is particularly effective for public pages: blogs, landing pages, catalogues.

Production monitoring — know before users do

Performance is a process, not a one-off deployment. The minimum production toolkit is short.

  • Laravel Pulse — slow queries, slow endpoints, cache usage, queues; safe for production.
  • Laravel Telescope — a developer tool: full insight into individual requests; in production only with restricted access.
  • queue:monitor — alerts when a queue grows past a threshold (php artisan queue:monitor redis:default --max=100).
  • Laravel Nightwatch (SaaS from the Laravel team) or APM tools like Blackfire/Scout APM — when you need history and alerts.

The optimization checklist

The deployment order in a typical project — from the biggest win to the smallest return on effort

Optimization Typical gain Effort Priority
Eliminate N+1 (with, withCount) 50–90% of view response time 1–2 days critical
Missing indexes (EXPLAIN) 10–100× on a single query hours–1 day critical
Redis cache for repeated data 5–20× on reads 1–3 days high
Queues for external operations −1–3 s off the HTTP request 2–5 days high
artisan optimize + OPcache 10–40% of bootstrap time hours high
PHP-FPM sized to RAM stability under load 0.5 day high
  • | Frontend: minification, images, CDN | LCP and Core Web Vitals | 1–3 days | medium | | Laravel Octane | 2–4× throughput | 3–10 days | medium | | Profiling and monitoring (Pulse, k6) | keeps the gains over time | 1–2 days | continuous |

What performance optimization costs

Indicative costs, net + VAT (rate 90–160 PLN/h)

  • Performance audit with a report (profile, queries, indexes, cache) — 2,000–5,000 PLN.
  • Implementing the critical fixes (N+1, indexes, cache, optimize) — 3,000–10,000 PLN, usually 3–7 days.
  • Production PHP/OPcache/FPM configuration + monitoring (Pulse, alerts) — 2,000–5,000 PLN.
  • Laravel Octane rollout with an application state audit — 5,000–15,000 PLN.

If your application slows down as traffic grows, or the infrastructure budget grows faster than revenue — describe your project via the contact form; the estimate is free. Looking for a team to take over an application? See Laravel development services and code maintenance.

Frequently asked questions

Where should I start optimizing a Laravel application?

With measurement. Enable Laravel Debugbar locally (query count and time) and use Pulse or the database slow query log in production. In most projects the list of problems turns out to be short: N+1 queries, missing indexes, repeated heavy queries without cache, and external operations inside the request cycle. Only after fixing those do infrastructure-level optimizations make sense.

How do I find N+1 queries?

Enable Model::preventLazyLoading() in your development environment — Laravel will report every lazily loaded relation. Use Laravel Debugbar (the queries tab — hundreds of queries per page is an N+1 signature) or the laravel-query-detector package, which logs suspicious patterns automatically.

How much faster can a Laravel app get?

It depends on the starting point. Removing N+1 queries and adding caching and queues commonly cuts response times by 50–80%. Applications with structural issues (missing indexes, no caching at all) often improve even more. The honest answer is always: measure first, then compare before and after.

Which cache backend is best for Laravel?

Redis — for production applications. It is fast, reliable, supports tags and atomic locks, and can also handle queues and sessions at the same time. The file driver is fine for development only, and database for very small applications without Redis.

Is Redis required for good performance?

Not required, but highly recommended in production. Redis serves as cache, queue driver and session store — offloading the database and enabling Horizon monitoring. For small applications, the database cache and queue drivers can be enough.

Should I use Laravel Octane instead of PHP-FPM?

Only when traffic is steady and high, and your application holds no state in singletons or statics. Octane typically delivers 2–4× higher throughput, but it requires a different deployment process (worker restarts) and a state audit. For low-traffic applications, the gain will not cover the operational cost.

Does php artisan optimize make a difference?

Yes — it runs config:cache, route:cache, view:cache and event:cache, compiling configuration, routing, views and events into single cache files. The effect is 10–40% less bootstrap time per request. It is a mandatory step of every production deployment.

How much does performance optimization cost?

A performance audit with a report: 2,000–5,000 PLN. Implementing the critical fixes (N+1, indexes, cache, optimize): 3,000–10,000 PLN. Production PHP/FPM configuration with monitoring: 2,000–5,000 PLN. Octane: 5,000–15,000 PLN. In new projects, a solid performance baseline is included in the hourly rate.


👉 Need your Laravel app to run faster? Describe your project via the contact form or email us at kontakt@informatix.com.pl — a performance audit starts with measurement, not with rewriting code.

📖 Read more: Laravel application security — OWASP Top 10, CI/CD and DevOps for Laravel, PostgreSQL vs MySQL for Laravel and Filament & Livewire admin panels.

📖 See the case study: OneCRMApp — Laravel 12, React and Inertia.js in production.

📖 Looking for a developer — see hire a Laravel developer and Laravel developer salary in Poland.

KS

Krzysztof Słonina

Full stack developer and owner of Inoventis Solutions (informatix). Since 2009 he has built Laravel/PHP web applications, e-commerce integrations and process automations — including OneCRMApp and FamilyTimelineApp, both running on Laravel, React and Inertia.js.

About the author
Free PDF

Web app requirements checklist

12 control questions to answer before talking to a vendor — faster estimates, fewer hidden costs.

Related posts