EN TR
Journal

Making Laravel Fast: N+1 Queries, Caching and Queues in Practice

Admin 3 min read
Making Laravel Fast: N+1 Queries, Caching and Queues in Practice

When an application slows down, the first reflex is to buy a bigger server. More often the problem is not hardware but the way the application talks to its database. These steps are the improvements that make the most difference in Laravel projects, in order of priority.

Measure first

Optimizing by guesswork wastes time. In development, use a debug bar or query log to see how many queries a page runs and which is slowest. In production, enable the slow query log and an application monitoring tool. The goal is to find your three slowest pages and the real bottleneck in each.

Remove N+1 queries

If a list page loads one hundred records and then queries each record's relation inside a loop, it runs one hundred and one queries. The fix is to load relations up front, which in Eloquent means eager loading. If you enable the setting that prevents lazy loading in development, the mistake becomes visible while you code.

Do not fetch what you do not need

  • Select only the required columns and avoid large text fields on list pages.
  • Process thousands of records in chunks rather than loading them all into memory.
  • Paginate, and question whether you need a total count on every request.

Review your indexes

Without an index on frequently filtered or sorted columns, the database scans the whole table. Use EXPLAIN on a slow query to confirm the index is used. Too many indexes slow down writes, so decide based on real queries rather than indexing every column.

Cache in the right places

Data that is read often and changes rarely, such as menus, settings and category trees, is a good candidate. Always define an expiry and a way to clear the entry when the data changes, and never store user-specific data under a shared key. Make sure configuration, route and view caches are enabled in production deployments.

Queue the heavy work

Sending email, processing images, generating reports and calling external services should not make users wait. Push them to a queue handled by workers, with retries and failure logging, so page response time no longer depends on how long the job takes.

Lighten assets and responses

Once the server side is done, look at the browser: serve images in modern formats at the right size, minify CSS and JavaScript and serve them with cache headers, and consider a CDN.

Conclusion

Performance work is a measurement habit, not a one-time cleanup. Find the bottleneck, make the change with the biggest gain, and measure again. In most projects, fixing N+1 queries, adding the right indexes and caching wisely shortens page times noticeably without raising server costs.

laravel performance n+1 queries caching queues database index optimization

More articles