The database was fine. One session_start() call made every page uncacheable

2026-12-01来源 dev.toEnglish

A production e-commerce app was taking 4.6 to 6.6 seconds to return uncached pages. The first thing everyone suspected was the database, and it was the one part of the stack that was healthy. The real cause was one session_start() call: it told every cache layer not to store the page, and it made concurrent requests from the same visitor wait in line.

This post is about how I found that by measuring each phase of a request instead of guessing, and the checks I now run first on any slow PHP app. The stack was a bilingual (EN/JA) WooCommerce store with 42 plugins, LiteSpeed with a Redis object cache, and Cloudflare in front. Cached pages came back in about 40ms, so the question was really two questions. Why is a cache miss so expensive, and why are there so many misses?

Measuring before guessing

I put a temporary request profiler on staging (deleted afterwards) and split one uncached request into phases. This was the baseline:

Metric Before
Uncached TTFB (home EN/JA, product) 4.6 to 6.6s
DB time per uncached page 0.068s (260 queries)
Plugin bootstrap (start to wp_loaded) ~1.5s
Template render (wp_head to wp_footer) ~3.1s
Admin dashboard 6.5s
HTML page weight (home) 773 KB, of which 347 KB inline CSS

0.07s of database time in a 5 second request. Redis and OPcache were configured correctly. So upgrading the server or adding database indexes would have done almost nothing. The cost was PHP execution: plugin boot, then Elementor and theme rendering. Two product carousels alone cost about 1.07s per page.

That part has normal fixes (cache the carousel HTML in Redis, move Elementor CSS to external files). The more interesting finding was on the caching side.

Every response said "do not cache me"

When I looked at the response headers of a plain anonymous page view, every single response had this:

Set-Cookie: PHPSESSID=... Cache-Control: no-store, no-cache, must-revalidate 

An anonymous visitor reading a product page should not have a PHP session at all. With PHPSESSID and no-store on every response, Cloudflare and the browser are told not to keep the HTML. So the CDN in front of the site was doing nothing for HTML, and every visitor who missed the LiteSpeed cache paid the full 5 seconds.

There were two places calling session_start():

  1. A code snippet left over from an old "random but stable" product sort. The sort had been rewritten and no longer used $_SESSION, but the session_start() block was still there, running on every request.
  2. The theme framework (Unyson). It starts a session on every frontend request (hooked on send_headers) and on every admin page (current_screen), only to support flash messages.

On top of that, two custom cookies were being set on normal page views: one for the random sort seed on every page, and a "return to list" cookie on every archive view, which was already handled in JavaScript anyway.

Why session_start() kills caching

This is not WordPress specific. Any PHP app, or really any app behind a CDN, has the same rules. A shared cache will usually refuse to store a response, or will store it per user, when any of these are true:

  • The response has Set-Cookie. Most CDNs, Cloudflare included, will not cache an HTML response that sets a cookie, because caching it would hand one visitor's cookie to everyone else.
  • Cache-Control says private, no-store or no-cache. PHP does this for you. When you call session_start(), PHP sends cache headers based on session.cache_limiter, and the default is nocache, which emits Cache-Control: no-store, no-cache, must-revalidate plus an old Expires date. You never wrote that header, but it is there.
  • Vary is on something with many values. Vary: Cookie or Vary: User-Agent splits the cache into so many variants that the hit rate drops close to zero.
  • The URL is unique per request. Tracking parameters, cache busters, random sort seeds in the query string.

So one session_start() at the top of the request is enough to turn off edge caching for the whole site, and nothing in the page looks wrong.

The second problem: session locking

There is another cost that has nothing to do with the CDN. PHP's default file session handler takes an exclusive lock on the session file when session_start() runs, and keeps it until the request ends or you call session_write_close().

That means if one visitor's browser sends three requests at the same time (the page, a cart fragments AJAX call, a filter request), and all three start the same session, they run one after another, not in parallel. wp-admin fires several AJAX and REST calls at once too, so on this site it was a big part of why the admin felt randomly slow.

The fix

The fix was small, which is usually a sign the diagnosis was right.

In the old snippet, I deleted the session_start() block and changed the sort-seed cookie so it is only set when someone actually picks the random sort (orderby=random_list).

For the theme framework, it has an official opt-out, so I did not need to touch the parent theme:

add_filter('fw_use_sessions', '__return_false'); 

That one filter removed session locking on both the frontend and admin. Two more cookies were busting the cache: a random seed cookie set on every page, and a "return to list" cookie set on every archive view. After the changes the home and Japanese pages went from two Set-Cookie headers to zero. The PHP version of the "return to list" cookie is still on my list to remove, since JavaScript already does the same job.

All of this was done on staging first, with a dated .bak next to every edited file.

Results

Check Before After
PHPSESSID / Cache-Control: no-store on pages every response gone
Set-Cookie on home and JA pages 2 cookies 0
Cloudflare/browser HTML caching impossible possible
Shop page repeat view uncacheable ~30ms (LiteSpeed hit)
WPML admin self-check 2.57s blocking HTTP call 0.003s
Home page HTML weight 773 KB ~554 KB (28% smaller)

The 2.57s to 0.003s line is a separate fix in the same pass. WPML runs a self-check on admin loads that makes a blocking loopback HTTP request to the site's own REST endpoint, cached for only 300 seconds and retried twice on failure. Because the loopback hits the same slow uncached bootstrap, it took 2.57s. I answered it internally with rest_get_server()->dispatch(), which is the same code path WPML already uses as its fallback when a WAF blocks the loopback. Same answer, no HTTP.

To be clear about the numbers: the 30ms is a LiteSpeed cache hit measured on staging, not a Cloudflare edge hit. The uncached render is a different problem. On production, a later pass (LiteSpeed's crawler and serve-stale, Elementor CSS moved to files, and the Facebook Conversions API call made async) took uncached shop pages from 4.0 to 4.4s down to 3.5 to 3.7s. Better, but still slow, because 42 plugins still have to boot on a miss. That's why making pages cacheable mattered more than anything else here.

What I check first now

Before profiling anything on a slow site behind a CDN, I run curl -sI on a page as an anonymous visitor and read the headers. If I see Set-Cookie, no-store, private, or a wide Vary, the cache is not working, and making the origin faster only helps the people who were going to miss anyway.

After that, if a session really is needed, start it only on the requests that need it (cart, checkout, account), and call session_write_close() as soon as you are done writing so parallel requests from the same user stop queuing behind each other.

原文:https://www.a8q9.cn/en/article/the-database-was-fine-one-session-start-call-made-every-page-uncacheable-cdbcda.html

相关文章