Solving The N+1 Problem In PHP
Solving The N+1 Problem In PHP
About the Book
The web page was taking three hours to load.
Let that sink in for a moment: three hours.
The code backing the page was a reporting script written in PHP, attempting to build 40,000 entity objects from 2 million database rows. Indeed, sometimes the page never loaded at all. At least the client could tell when it failed, because a big ugly error popped up in the browser window. Unfortunately that was also around the three hour point. The client was understandably frustrated.
It turned out the cause was not that the database was unoptimized. It was not the number of rows being returned. It was not the number of objects being built.No, the cause was the high volume of queries being issued from the reporting script.
When I say "high volume", I mean two hundred thousand and one queries. These 200,000+ queries were used to build each root entity along with each of its five associated collections and entities, all as a result of how the script was assembling the entity objects. No wonder the script was was taking three hours to finish!
After discovering this, I was able to apply the techniques presented in this book to refactor how the entity objects were assembled. Over the course of a few days of refactoring I was able to reduce the load time from 3+ hours to just under 6 minutes. That's a 30x improvement, and while still slow by typical standards, it was much more bearable for the client. (Later refactorings improved the load time even further.)
The causes leading to the terrible performance of that reporting script have a name: The N+1 Problem. The problem goes by various aliases, such as the "1+N problem", "N+1 queries", "SELECT N+1", and so on, but they all refer to the same thing.
While I mention the N+1 problem more than once in Modernizing Legacy Applications in PHP, I did not address a solution directly. This book remedies that. Herein, we will discuss the specifics of the N+1 problem:
- what the N+1 problem is,
- how to diagnose and discover the problem in your application,
- why the problem occurs, and
- how to solve the problem in your codebase using plain old PHP (no ORMs needed!).
If your application code has database performance issues, or if you want to learn how to prevent creating an N+1 problem in your codebase, buy this book today!
Table of Contents
-
1. Introduction
- The Slow Reporting Script
- Example Application
-
2. Defining The N+1 Problem
- The Problem By Example
- The Problem Defined
- Performance Implications
-
3. Diagnosing N+1 Problems
- Codebase Examination
- Log/Profile Examination
- Easier Query Examination
-
4. Why Does The N+1 Problem Occur?
- CRUD Is The Problem
- BREAD Is The Answer
-
5. Solving N+1 With A Single Query
- Handling “Many-To-One” Relationships
- Handling “One-To-One” Relationships
- Combining “Many-To-One” and “One-To-One”
- Handling “To-Many” Relationships
- Single-Query Fails With “To-Many” Relationships
-
6. Solving N+1 With Query-And-Stitch
- Tradeoffs In Query-And-Stitch
- Handling “One-To-Many” Relationships
- Handling “Many-To-Many” Relationships
- Handling “Many-To-One” Relationships
- Handling “One-To-One” Relationships
- Performance Implications
-
7. Refactoring The Codebase To Remove N+1 Problems
- Prerequisites
- The Process
- N+1 In A Single Location
- N+1 Across Separated Locations
- Test, Commit, Push, Notify QA
- Do … While
-
8. Common Questions
- Can I Combine Single-Query With Query-And-Stitch?
-
Can I Use Sub-Selects Instead Of The
IN()
Operator? - Should I Use A Transaction With Query-And-Stitch?
- Can I Just Use An ORM?
-
Appendix
- SQL Schema
- PHP Classes
- Colophon
- About the Author
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
Do Well. Do Good.
Authors have earned$11,710,555writing, publishing and selling on Leanpub, earning 80% royalties while saving up to 25 million pounds of CO2 and up to 46,000 trees.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers), EPUB (for phones and tablets) and MOBI (for Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them
Top Books
Recipes for Decoupling
Matthias NobackWrite software that survives
CQRS by Example
Carlos Buenosvinos, Christian Soronellas, and Keyvan Akbary- Leverage your Software Architecture skills by learning everything about CQRS in detail with lots of examples
- Develop faster applications by applying CQRS and fostering Read Models and Projections
- Learn how to apply CQRS into a brownfield project from a pragmatic approach
OpenIntro Statistics
David Diez, Christopher Barr, Mine Cetinkaya-Rundel, and OpenIntroA complete foundation for Statistics, also serving as a foundation for Data Science.
Leanpub revenue supports OpenIntro (US-based nonprofit) so we can provide free desk copies to teachers interested in using OpenIntro Statistics in the classroom and expand the project to support free textbooks in other subjects.
More resources: openintro.org.
Ansible for DevOps
Jeff GeerlingAnsible is a simple, but powerful, server and configuration management tool. Learn to use Ansible effectively, whether you manage one server—or thousands.
Maîtriser Apache JMeter
Philippe Mouawad, Bruno Demion (Milamber), and Antonio Gomes RodriguesToute la puissance d'Apache JMeter expliquée par ses commiteurs et utilisateurs experts. De l'intégration continue en passant par le Cloud, vous découvrirez comment intégrer JMeter à vos processus "Agile" et Devops.
If you're looking for the newer english version of this book, go to Master JMeter : From load testing to DevOps
Functional Event-Driven Architecture
Gabriel VolpeExplore the event-driven architecture (EDA) in a purely functional way. Learn to design and develop distributed systems that scale. Identify common design patterns in such systems.
Take your functional programming skills to the next level by joining me in developing a distributed system powered by Apache Pulsar and Fs2 streams, all in Scala 3!
C++20 - The Complete Guide
Nicolai M. JosuttisAll new language and library features of C++20 (for those who know previous C++ versions).
The book presents all new language and library features of C++20. Learn how this impacts day-to-day programming, to benefit in practice, to combine new features, and to avoid all new traps.
Buy early, pay less, free updates.
Other books:
On Java 8
Bruce EckelBy the author of "Thinking in Java," covering version 8 of the Java programming language (with updates to Java 17). Intended for “dedicated beginners,” it doesn’t assume you know anything about programming and takes you through the material step-by-step. However, I assume you are able to figure things out. It’s not a “dummies” or “idiot’s” guide.
Jetpack Compose internals
Jorge CastilloJetpack Compose is the future of Android UI. Master how it works internally and become a more efficient developer with it. You'll also find it valuable if you are not an Android dev. This book provides all the details to understand how the Compose compiler & runtime work, and how to create a client library using them.
The C4 model for visualising software architecture
Simon BrownA guide to visualising your software architecture with the C4 model.
Top Bundles
- #1
Software Architecture
2 Books
"Software Architecture for Developers" is a practical and pragmatic guide to modern, lightweight software architecture, specifically aimed at developers. You'll learn:The essence of software architecture.Why the software architecture role should include coding, coaching and collaboration.The things that you really need to think about before... - #2
CCIE Service Provider Ultimate Study Bundle
2 Books
Piotr Jablonski, Lukasz Bromirski, and Nick Russo have joined forces to deliver the only CCIE Service Provider training resource you'll ever need. This bundle contains a detailed and challenging collection of workbook labs, plus an extensively detailed technical reference guide. All of us have earned the CCIE Service Provider certification... - #4
Pattern-Oriented Memory Forensics and Malware Detection
2 Books
This training bundle for security engineers and researchers, malware and memory forensics analysts includes two accelerated training courses for Windows memory dump analysis using WinDbg. It is also useful for technical support and escalation engineers who analyze memory dumps from complex software environments and need to check for possible... - #7
All the Books of The Medical Futurist
6 Books
We put together the most popular books from The Medical Futurist to provide a clear picture about the major trends shaping the future of medicine and healthcare. Digital health technologies, artificial intelligence, the future of 20 medical specialties, big pharma, data privacy, digital health investments and how technology giants such as Amazon... - #8
Practical FP in Scala + Functional event-driven architecture
2 Books
Practical FP in Scala (A hands-on approach) & Functional event-driven architecture, aka FEDA, (Powered by Scala 3), together as a bundle! The content of PFP in Scala is a requirement to understand FEDA so why not take advantage of this bundle!? - #9
The Python Craftsman
3 Books
The Python Craftsman series comprises The Python Apprentice, The Python Journeyman, and The Python Master. The first book is primarily suitable for programmers with some experience of programming in another language. If you don't have any experience with programming this book may be a bit daunting. You'll be learning not just a programming...