A Laravel endpoint can return the right payload and still become more expensive with every item on the page. On a small test database, that often goes unnoticed until a list loads slowly under traffic. A performance budget gives the team a limit and a way to check it before release. For an order list, that might mean two SQL statements to build the response, a bounded page size, and a separate latency target measured in staging. Each limit answers a different question about how the endpoint behaves.
Set the budget for a user journey
Pick a route, the actor that calls it, and a realistic range of inputs. Document the page size, dataset size, and whether related rows typically exist. Record which dependencies are part of the budget. A logged-in order list might include authentication, an orders query, and related line items. A public product page might also include CDN behaviour and the rendering work done by the browser. Agree on one measurement boundary for each metric so a change to the test does not silently redefine the goal.
Start with a production baseline if you have one. For latency, use a percentile and a time window, such as the 95th percentile during a working day, rather than a single request on a developer machine. Compare equivalent traffic slices. A route that is usually called with an empty filter can look healthy in aggregate while its busiest account consistently gets a slow response. Break out expensive operations that have different constraints, like an export which needs predictable throughput but can run in a queue.
| Budget | Where to enforce it | Example for an order list |
|---|---|---|
| SQL statements | Deterministic integration test against a fixture | At most two statements for the list and its items at the largest allowed page size, measured around the list query and rendering. |
| Payload size | Response test with a representative populated page | A fixed byte ceiling for the uncompressed JSON with the maximum page size and representative text fields. |
| Request latency | Staging load test and production monitoring | A p95 ceiling for an authenticated request over a specified load profile and test duration. |
| Background work | Queue monitoring and a representative end-to-end test | An agreed maximum queue wait for a job that the order list can enqueue. |
Set numbers from the behaviour that users need. For example, if checkout has a latency target measured from a customer browser, keep separate limits for server processing and external I/O so the team can see what consumes the available time. Keep the test fixture distinct from the load-test fixture. Small, deterministic data makes statement-count failures reproducible. Data representative of production cardinality and access patterns is needed to observe execution plans and latency.
Make the SQL budget executable
The following executable example uses Laravel 8.83's database and Eloquent components on PHP 8.2 with in-memory SQLite. It creates four orders, each with two items, and runs the same rendering operation twice. The eager-loaded version uses two statements and the lazy-loaded version uses five. The query log is enabled only after seeding. Save the example in a project root with Laravel installed and run it with the PHP CLI. The fixture is isolated from the application's configured database.
<?php
require __DIR__ . '/vendor/autoload.php';
use Illuminate\Database\Capsule\Manager;
use Illuminate\Database\Eloquent\Model;
final class BudgetOrder extends Model
{
protected $table = 'orders';
public function items()
{
return $this->hasMany(BudgetItem::class, 'order_id');
}
}
final class BudgetItem extends Model
{
protected $table = 'order_items';
}
$db = new Manager();
$db->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
$db->bootEloquent();
$connection = $db->getConnection();
$connection->statement('CREATE TABLE orders (id INTEGER PRIMARY KEY)');
$connection->statement('CREATE TABLE order_items (id INTEGER PRIMARY KEY, order_id INTEGER)');
foreach (range(1, 4) as $id) {
$connection->table('orders')->insert(['id' => $id]);
$connection->table('order_items')->insert([
['order_id' => $id],
['order_id' => $id],
]);
}
function countOrderListQueries($connection, bool $eager): int
{
$connection->flushQueryLog();
$connection->enableQueryLog();
try {
$query = BudgetOrder::query()->orderBy('id')->limit(4);
if ($eager) {
$query->with('items');
}
$itemCounts = $query->get()->map(function (BudgetOrder $order) {
return $order->items->count();
})->all();
if ($itemCounts !== [2, 2, 2, 2]) {
throw new RuntimeException('Unexpected list payload');
}
return count($connection->getQueryLog());
} finally {
$connection->disableQueryLog();
$connection->flushQueryLog();
}
}
$eager = countOrderListQueries($connection, true);
$lazy = countOrderListQueries($connection, false);
printf("Eager: %d, lazy: %d\n", $eager, $lazy);
if ($eager > 2 || $lazy <= 2) {
throw new RuntimeException('Expected the budget to pass only with eager loading');
}
Query execution happens after the initial builder is created, including when a serializer reads a relation. In a Laravel feature test, create the fixtures and set up the actor first. Then enable the query log before the HTTP call and inspect it after the response has been serialized. Define whether that check covers all statements on the request's connections or just the portion of the endpoint owned by your team. The example uses a single connection. A test for a read replica or a second connection must collect queries there too. Scope logging to the test to avoid recording sensitive bound values or generating an ever-growing log on a long-lived worker.
Eager loading can reduce queries while increasing rows read and bytes returned. If the route only displays the item count, consider loading the aggregate with Eloquent's relationship count instead of loading every item. Also account for pagination. The example uses a limit. Length-aware pagination typically adds a count query. Include the statements that the chosen endpoint actually needs and assert the response still contains the expected items. Laravel Eloquent Relationships
Measure latency separately from statement count
Two SQL statements can still be slow because of a missing index, row locks, or a large fetch. Compare execution plans for representative bind values and inspect the number of rows examined. If the database client reports cumulative query time, reconcile that with end-to-end latency. Request time also includes application work like authorization, serialization, external network calls, and waiting for a worker. Document whether your latency runs use a cold or warm cache and where requests originate. The Laravel query benchmark protocol describes how to record comparable measurements and plans. Laravel Database Monitoring
Collect p95 from a meaningful batch of requests. Compare runs with the same concurrency, traffic mix, dataset, cache preparation, and environment. Include failed requests in error reporting and state how timeouts enter the latency statistics. A faster p95 can otherwise hide a regression where slow requests simply fail earlier. When the load script uses repeated credentials, consider whether it produces an unrealistically high cache hit ratio. A mix of large and small accounts gives a better picture of how the route behaves under production traffic.
Use a budget failure in code review
Ask what changed before relaxing a threshold. An extra, deliberate authorization query may be an acceptable fixed cost. One query for every row will scale with page size and usually calls for a change to the query or payload. If the budget needs to change, record the new limit and what pays for it, such as a smaller page size, a changed response contract, or an explicit increase to the request target. Keep the smallest reproducible fixture that demonstrates the difference, then rerun the load test if the change affects a primary path.
Give each budget an owner and a clear next action when it fails. Keep deterministic limits alongside tests and check latency at the release boundary where the environment is comparable. Once the first route is under control, repeat the pattern for the next route with measured customer impact. If you need help choosing routes and turning production measurements into enforceable limits, the Laravel performance audit covers query plans, request traces, and CI checks.
Frequently asked questions
How many SQL queries should a Laravel route allow?
Choose a ceiling for the actual route and its measurement boundary. A fixed authentication or pagination query can be valid. Compare the smallest and largest supported page sizes to catch growth.
Can a query budget replace a load test?
A statement-count check catches changes such as N+1 queries. Load tests measure latency, error rates, and resource use with realistic data, traffic, and concurrency.