Finding the real performance problem in a Laravel app · Part 4 of 6
Caching: what to cache, the stampede, and the cache that looked right
What earns a cache and what does not, the dashboard served stale while it revalidates, the cold-start stampede counted with and without a lock, why the dashboard is not invalidated, a year of immutable assets, and the per-row cache that cost more than the query.
By Abhishek Fouzdar
Part 3 ended with the database doing honest work: a dashboard that counts two hundred thousand tickets by status on every load, an inbox that counts a hundred and seventy thousand closed ones for a number in the corner of the page, and a search that ranks a common word in a fifth of a second and is asked the same word all day. None of those is a query problem any more. They are the same answer computed over and over, and this part is about computing it once. It is also about the three ways a cache goes wrong, each of them measured, and one cache that looked exactly right and made the page slower.
What to cache, and what that rules out
A cache earns its place when three things are true at once: the value is expensive, it is read far more often than it changes, and a reader can tolerate a value that is a little old. The dashboard's aggregates pass all three. Six hundred milliseconds of database time, read by every agent several times an hour, and a number that is thirty seconds stale is still a dashboard. The inbox's total passes too: a hundred milliseconds to count the closed tickets, for a figure nobody reads to the digit.
The same three questions rule out most of the rest of the app. The ticket page changes with every reply and is read by one agent at a time, so there is nothing to share. The inbox listing is different per agent and per filter, and its first page costs 40 ms, which is less than the discipline of invalidating it would cost. A page that is cheap, or personal, or must be current, is not a cache candidate however often it is requested, and the first instrument from part 2, desk:queries, is what says which it is.
The dashboard: stale while revalidating
The computation moved out of the controller into a class with one public method, and the controller became a line:
public function __invoke(DashboardStats $stats): View
{
return view('dashboard', $stats->get());
}
get() wraps part 3's grouped queries in Cache::flexible, which Laravel has had since 11.23 and which does the thing most hand-written caches get wrong:
return Cache::flexible(self::KEY, [$fresh, $stale], fn () => $this->compute());
Two numbers instead of one TTL. For thirty seconds the value is fresh and served as is. For the five minutes after that it is stale and still served, immediately, while the request that found it stale refreshes it in the background after the response has gone out (Laravel defers the callback, and takes a lock so only one request does the refreshing). Nobody waits for the recomputation except the first visitor after five idle minutes. With a plain Cache::remember and a thirty-second TTL, one request in every thirty seconds pays the full 600 ms; with flexible, none does while the page has traffic.
The cached value is an array, not models: the agents table, the tags and the oldest tickets are plain arrays of the fields the view needs. That is partly size and partly the reason in "What went wrong" below. The page now says "Numbers as of 12 seconds ago" at the top, which is the honest thing a cached dashboard does.
/ db;dur=237.8;desc="12 queries", total;dur=274.5 (cold: computed)
/ db;dur=1.3;desc="1 queries", total;dur=13.9 (warm)
/ db;dur=1.3;desc="1 queries", total;dur=12.5
The one remaining query is the session user. Thirteen milliseconds for the page that took ten seconds in part 1.
The stampede, measured
A cold cache and ten users is the case every cache tutorial describes and few measure. The first request finds nothing and starts computing; so does the second, and the tenth, because none of them can see that someone else is already on it, and the database gets ten copies of the same 600 ms of work. Cache::flexible does not help here: its lock covers the refresh of a stale value, not the absence of one.
Measured with the cache emptied and the dashboard scenario started cold, ten users for twenty seconds, counting how many times the computation ran through a counter the class increments:
| Cold start, 10 users | Computations | p50 | p99 | max | req/s |
|---|---|---|---|---|---|
Cache::flexible alone |
5 | 88 ms | 561 ms | 1.91 s | 93.7 |
| With the lock | 1 | 81 ms | 171 ms | 1.52 s | 110.6 |
Five, not ten, because PHP-FPM has five workers and only five requests can be computing at once; the other five were waiting for a worker, which is the same queue from part 1 wearing a different hat. Five copies of the same work, and a 99th percentile three times higher for the twenty seconds it took to settle. On a dashboard it is a hiccup; on a value that takes ten seconds to compute, with a hundred users, it is the outage that follows every cache flush, and every deploy that flushes the cache.
The fix is a lock around the cold path only, so the warm path stays a single GET:
return Cache::get(self::KEY) ?? Cache::lock(self::KEY.':lock', 10)->block(10, function () use ($fresh, $stale) {
return Cache::flexible(self::KEY, [$fresh, $stale], fn () => $this->compute());
});
The first request takes the lock and computes; the other nine block on the lock, and when it is released they find the value flexible just stored and return it. block(10, …) is the longest a waiter will wait before giving up with an exception, and ten seconds is more than the computation has ever taken on this machine; it is the kind of number to set from a measurement rather than a feeling. The setting DASHBOARD_LOCK=false in .env puts the stampede back, which is how the table above was made.
The counts and the search
The inbox total is the same shape with less at stake. The key is the filter set, so each combination an agent uses gets its own entry, and the value lives for a minute:
'total' => Cache::remember('inbox:count:'.md5(json_encode($filters)), config('desk.count_ttl'), fn () => $tickets->clone()->count()),
/inbox?status=closed db;dur=57.1;desc="9 queries", total;dur=86.0 (cold)
/inbox?status=closed db;dur=6.8;desc="8 queries", total;dur=35.0 (warm)
Search caches the ranked id list per term for a minute, which is the part that costs 200 ms for a common word; the page's twenty-five tickets are still read fresh from the database, so their status and last message are current even when the ranking is a minute old:
/search?q=invoice db;dur=196.6;desc="8 queries", total;dur=238.5 (cold)
/search?q=invoice db;dur=5.5;desc="6 queries", total;dur=34.1 (warm)
What a minute costs is one thing: a ticket that arrives in that minute and matches the term is not on the first page until the list expires. For a helpdesk that is the right trade at sixty seconds and the wrong one at an hour, and the number is in config/desk.php with the reasoning next to it.
Invalidation, and why the dashboard does not do it
The textbook alternative to a TTL is invalidation: forget the cached value when the data changes, so it is never stale. Laravel makes it one line in a model observer, and for the dashboard it would be the wrong line. Part 1's webhook scenario delivers ten tickets a second at five virtual users, and every one of them changes a status count. Forgetting the dashboard on each write means recomputing it, 600 ms of database time, up to ten times a second, which is a cache that never serves anything and a database doing more work than it did with no cache at all. That is arithmetic rather than a measurement, and it is enough: invalidation suits values that change rarely and must be exact, the customer's company name, a tag's colour, a setting. For values that change constantly and are read as summaries, a short TTL is not a compromise, it is the design.
The one cache the app does invalidate is the search list, implicitly: a minute is short enough that the question never arises, and an explicit forget on every message would flush it ten times a second for the same reason.
HTTP caching, the part the browser does for free
Vite names every built asset after its content hash, so app-BV8WrX4k.css will never contain anything but what it contains now. nginx can say so:
location /build/ {
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
curl -I http://localhost:8070/build/assets/app-BV8WrX4k.css
Cache-Control: public, max-age=31536000, immutable
A year, and immutable tells the browser not to revalidate even on reload. A deploy that changes the stylesheet produces a new hash and a new URL, so there is nothing to expire. The pages themselves stay no-cache, private, which Laravel sets by default and which is right for pages behind a login. The k6 scenarios never requested an asset, so this change has no row in the tables below; in a browser it is the difference between two requests per page and twenty.
The cache that looked right
Every row in the inbox shows a message count, and part 2 made it a correlated subquery in the page's one query. Caching it per ticket is the obvious next idea: a key per ticket, a lookup per row, invalidated when a message arrives. Measured, from tinker, for one page of twenty-five tickets, seven runs each, medians:
withCount subquery, 25 tickets median 1.8 ms
Cache::get per row, 25 round trips median 3.5 ms
Cache::many, one round trip median 1.5 ms
plain get, no counts median 1.2 ms
Twenty-five round trips to Redis cost twice what the database charged for the counts, and the batched version saves three tenths of a millisecond on a page that takes forty. For that, the app would own twenty-five keys per page, an invalidation on every message and the bug that comes with every invalidation. A cache lookup is not free; it is a network call to another process, about 70 microseconds here, and anything the database can answer in that time from an index it should keep answering. The cache is for the 600 ms answers, not the 2 ms ones.
What Redis holds
After the three scenarios below, Redis's own counters, reset before the first one:
keyspace_hits:26994 keyspace_misses:402
A 98.5% hit rate, which is what a cache with a handful of keys and a minute of life looks like under steady load; the misses are the first request after each expiry plus the per-filter inbox counts that nobody asked for twice. The keys are few: the dashboard, the timestamp flexible keeps beside it, the computation counter, one inbox count per filter set an agent has used, one id list per search term, each gone within a minute or five of its last use. redis-cli -n 1 --scan is the way to know what a cache holds, and INFO keyspace the way to see that it is on database 1 while thirteen thousand sessions sit on database 0.
The scenarios again
Ten users, sixty seconds, the three scenarios whose pages this part changed, against part 3:
| Scenario | p50 before | p50 after | p95 before | p95 after | req/s before | req/s after |
|---|---|---|---|---|---|---|
| dashboard | 1.8 s | 77 ms | 2.3 s | 115 ms | 5.6 | 130.8 |
| inbox | 264 ms | 208 ms | 421 ms | 300 ms | 35.3 | 49.3 |
| search | 154 ms | 71 ms | 623 ms | 107 ms | 12.4 | 45.2 |
The dashboard is twenty-three times faster and serves twenty-three times as many users, which is what caching a 600 ms aggregate does and the reason this part exists. Search doubled from caching 200 ms of ranking per term. The inbox moved by a fifth: the count it cached was 100 ms on the closed filter and 4 ms on the open one, and the open one is 80% of the scenario, so most requests had nothing to gain. The baseline from part 1 for these three, for the whole arc: dashboard 1.4 s median and 53 s at the 95th; inbox 1.07 s and 2.8 s; search 20 s and 32 s.
What went wrong
The cached search list came back as an incomplete object. The ranked ids were stored as a Collection and the second search for the same term was a 500: "The script tried to call a method on an incomplete object". Laravel 13's config/cache.php ships with 'serializable_classes' => false, and the cache stores pass that to unserialize() as allowed_classes, so no object at all comes back from the cache as what it was; it comes back as a shell that throws on first use. The config comment gives the reason, a good one: a cache that unserialises arbitrary classes is a gadget chain for anyone who gets hold of APP_KEY. A model or a collection put in the cache on this version is a bug waiting for the second request. The list is stored as a plain array now and wrapped with collect() on the way out, which is the rule to keep regardless of the allow-list: a cache holds data, and a serialised object is a dependency on a class, a version and an allow-list that the cache has no business having.
Redis already had 13,504 keys in it, and the cache keys were nowhere. Before any of this part's caching, DBSIZE reported thirteen thousand entries, and after it redis-cli --scan could not find a single dashboard key. Both were the same mistake: Laravel's Redis config puts the cache on database 1 (REDIS_CACHE_DB) and everything else, sessions included, on database 0, and redis-cli talks to 0 unless told -n 1. The thirteen thousand were sessions: the load tests sign in once per virtual user, and the run in part 1 whose cookies were reset every iteration signed in several thousand times. They expire after two hours and cost six megabytes. The cache keys were on database 1 all along, which is also why cache:clear empties the cache and leaves the sessions alone.
The slow log filled with thirteen thousand fast queries. Part 3 turned on log_queries_not_using_indexes, and under this part's load it logged the inbox's latestOfMany join 5,314 times and select * from users where role = 'agent' 2,942 times, each in a millisecond, because a table of twenty rows is read without an index whatever one does. The setting is right for finding scans on big tables and wrong without min_examined_row_limit beside it, which makes it ignore queries that examined fewer rows than a threshold; a thousand is a sensible one.
nginx sent two Cache-Control headers. expires 1y and add_header Cache-Control "public, immutable" each add one, and a browser reading max-age=31536000 and public, immutable on separate lines is within its rights to pick either. One add_header with the whole value.
Part 5 is the layer outside the app: the webhook that still sends an email before it answers, the export that ties up a worker for twenty seconds, the nightly digest that loads everything, all of them moved to the queue with Horizon watching; then PHP-FPM's five workers, which have set the shape of every table in this series, OPcache's production settings, and nginx, with the load test ramped until something breaks.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
4 / 6- OverviewFinding the real performance problem in a Laravel app
- Part 1The app, the data, a load test and a baseline
- Part 2The application layer: a profiler, flame graphs and the N+1s
- Part 3The database on a million rows
- Part 4Caching: what to cache, the stampede, and the cache that looked right
- Part 5Queues, workers and the server: the number that shaped every table
- Part 6Observability: Pulse, Telescope and OpenTelemetry, and what each one costs