title: "Le problème N+1 en GraphQL — pourquoi votre API Laravel ralentit (et comment le régler avec Lighthouse)"
GraphQL integrates well with Laravel APIs, offering clean queries and developer satisfaction. However, a common performance issue, the N+1 problem, can arise when lists grow in size, drastically increasing response times. This problem occurs when a query for a list of items also triggers a separate database query for each item's related data, such as an author's name.This results in one initial query plus an additional query for every item in the list, hence "N+1." In REST APIs, this is often more apparent in the code, but GraphQL's inherent relationship resolution can mask it until significant data loads occur. The core principle to fix N+1 is to avoid queries within loops; instead, collect necessary keys and perform a single, batched query.For standard Eloquent relationships in Laravel with Lighthouse, this is handled automatically by directives like @belongsTo. These directives batch related data into a single SQL query using WHERE IN clauses, regardless of list size. For computed fields that aren't direct Eloquent relationships, developers must manually implement batching using tools like BatchLoader.This involves creating a loader class that gathers all required IDs and executes a single, grouped query. To detect N+1 problems, developers can use Laravel Debugbar to monitor SQL query counts, DB::listen() in integration tests, or Laravel Telescope for detailed request analysis. The crucial guideline is that GraphQL query performance should not degrade with increased list sizes.While N+1 is a common initial hurdle, other performance considerations for GraphQL APIs include caching strategies, query complexity limiting, and rate limiting. These topics, along with a comprehensive guide to building and consuming GraphQL APIs with Laravel and Angular, are covered in a dedicated training course.
WHERE INclauses, regardless of list size. For computed fields that aren't direct Eloquent relationships, developers must manually implement batching using tools like BatchLoader.This involves creating a loader class that gathers all required IDs and executes a single, grouped query. To detect N+1 problems, developers can use Laravel Debugbar to monitor SQL query counts, DB::listen() in integration tests, or Laravel Telescope for detailed request analysis. The crucial guideline is that GraphQL query performance should not degrade with increased list sizes.While N+1 is a common initial hurdle, other performance considerations for GraphQL APIs include caching strategies, query complexity limiting, and rate limiting. These topics, along with a comprehensive guide to building and consuming GraphQL APIs with Laravel and Angular, are covered in a dedicated training course.