The problem with building on request
WordPress core builds its sitemaps when they are asked for. On a small site that is fine. On a site with tens of thousands of posts, each sitemap page is a database query that takes real time, and a crawler asking for forty of them in a row is forty of those queries.
The obvious answer is to cache the result. The less obvious part is what happens while the cache is being refreshed.
Three ways a cached sitemap goes wrong
- A half-written file. If the new sitemap is written straight over the old one, a request that arrives mid-write reads whatever has been written so far.
- Two rebuilds at once. A publish, a scheduled job and a crawler can all decide the sitemap is stale in the same second. Without a lock they all rebuild, and the last to finish wins, whichever one that is.
- A failed write that erases a good copy. A full disk or a permissions change turns a working sitemap into an empty one.
Generations
Ace Crawl Enhancer treats each build of the sitemaps as a generation: a complete set, built to one side, in a private folder that the web server refuses to list or serve directly.
A change to content marks the affected sitemaps as out of date. Nothing is rewritten at that moment. Requests carry on being answered from the current generation.
One builder at a time
From 1.0.103 a rebuild takes a lease before it starts. The lease is atomic and checked against its owner, so a second process that wants to rebuild sees the lease and stands down, and a process cannot release a lease it does not hold. It works with or without a persistent object cache.
Swap, do not overwrite
From 1.0.104 a finished file is published atomically: written under a temporary name, then renamed into place. A rename is a single step for the filesystem, so a reader sees the old file or the new one and never a mixture.
If a write, a lock or the replacement fails, the last valid generation stays where it is and the failure is recorded with a short reason. From 1.0.106, on PHP 8.6, that reason can say what the stream error was. A failed write is also told apart from a successful write of nothing, which matters because an empty sitemap is sometimes correct.
Multisite
From 1.0.105 the state of a build, its deferred work and its request caches are kept separate when the code switches between sites in a network. One site's rebuild cannot publish into another's.
How to tell whether yours is safe
- Find where your sitemap cache lives. If it is a single transient or a single file written in place, it can be read half-written.
- Publish ten posts quickly and watch for more than one rebuild.
- Make the cache location read-only on a staging copy and request the sitemap. You should get the last good copy, not an empty document.
With Ace Crawl Enhancer you can force a rebuild and watch it from the command line:
wp ace-crawl sitemaps mark-dirty --scope=all
wp ace-crawl sitemaps run