Knowledgebase

Reducing Database Queries Per Request Print

  • developersgitdeployment, developers, database, troubleshooting, caching, performance, guide, howto
  • 0

The most common performance problem in web applications.

THE CLASSIC MISTAKE

A loop that queries the database on each iteration. Displaying fifty items with a query each means fifty-one queries where two would do.

Frameworks call this the N+1 problem, and every ORM provides a way to avoid it through eager loading.

FINDING IT

A profiling tool showing queries per request. Hundreds of queries on a single page is the signature.

Look for many near-identical queries differing only in an ID.

FIXING IT

Fetch the related data in one query rather than one per item Use your ORM's eager loading Cache the result if it is the same for every visitor

OTHER REDUCTIONS

Select only the columns you need Combine queries that fetch related data Cache expensive aggregate queries rather than recalculating

A REASONABLE TARGET

Most pages should be well under fifty queries. Hundreds indicates a structural problem rather than something to tune.

MEASURING THE IMPROVEMENT

Count queries before and after. It is the clearest metric available for this class of problem.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot