Laravel
Sitemapamic 4 is a ground-up rewrite of my XML sitemap addon for Statamic. At 1,000 entries it peaks at 16.6MB of memory instead of 151MB, and at 5,000 it builds in three seconds where v3 couldn't finish at all. Here's how I got there with generators and streams, what I chose to break along the way, and how AI fit into the process.
Sitemapamic 4 is out now on the Statamic Marketplace, with full docs ready to go.
On paper, a sitemap is one of the simplest things a website can produce. It's a list of URLs in some XML.
Simple, right?
Well... yes, but also it depends... and maintaining an addon that does it for Statamic (and does it well) needs to factor in a number of considerations.
The big one, pardon the pun, is scale.
A 50-page brochure site is easy. A site with a content library in the hundreds of thousands is a very different beast, and that's where v3 started to struggle. OK, failed.
Sitemapamic was one of the first addons I wrote for Statamic (back in 2021)... and was very simple. But more features were needed - for multi-site, for multiple sitemaps - and the caching mechanism just never evolved with the evolving complexity. It really did need a rethink.
How v3 worked (and why it hurt)
v3 did its job well for most sites, but it had one fundamental problem: it built everything before it output anything.
Here's the heart of the v3 controller in single mode:
$generator = function () use ($loaders) {
$entries = $loaders
->map(fn($loader) => $loader())
->flatten(1)
->filter();
return view('mitydigital/sitemapamic::sitemap', [
'entries' => $entries
])->render();
};
Each loader returned a Collection of every URL for its source. These got flattened into one big Collection, passed to a single Blade view, rendered into one big string, and that string was stored in Laravel's cache.
To be fair to past me, there was a ->lazy(100) in the entry loader. But laziness only helps if it survives all the way to the output. The loader finished with ->toArray(), then everything was flattened and handed to a view that needed the whole collection, so it all ended up in memory anyway.
So memory grew with your URL count.
At 100 entries, nobody notices. At 5,000, v3 couldn't finish inside a 512MB memory limit.
Generators, all the way down
I'd already been through this with Feedamic v3, which had similar scale problems. The fix there, and for Sitemapamic v4, was to make sure memory depends on the size of a chunk, not the size of your site. Entries are read a chunk at a time, and each URL is rendered and written out on its own as it passes through. The tool that makes that possible in PHP is the generator.
If you haven't used generators much, here's the short version. A function that uses yield doesn't run when you call it. It returns a Generator, and the function body only runs as you iterate, pausing at each yield until the next value is asked for:
function numbers(): Generator
{
foreach (range(1, 3) as $number) {
echo "Making {$number}\n";
yield $number;
}
}
foreach (numbers() as $number) {
echo "Using {$number}\n";
}
That outputs "Making 1, Using 1, Making 2, Using 2…" and so on. Values are produced only when they're consumed, and they aren't stored along the way.
The important part, and the reason generators are necessary here rather than just nice to have, is that every step in the pipeline has to be lazy. One step that collects its results into an array, and you're back to memory that scales with URL count.
So in v4 the whole pipeline is a chain of generators:
UrlIteratoryieldsSitemapamicUrlobjects for a source, whether that's a collection, a taxonomy, collection term pages, or your own dynamic routes.Buildertakes each URL and yields a rendered XML fragment.Writerconsumes those fragments and writes them out.
The Builder step is tiny, and that's the point:
/** @return Generator<int, string> */
private function fragments(Source $source, ArrayObject $termDates): Generator
{
foreach ($this->urlIterator->forSource($source, $termDates) as $url) {
yield $this->renderer->url($url);
}
}
This is also why the Blade views had to change.
v3 had an all-in-one template that looped over a collection. v4 splits that into urlset/start, urlset/url and urlset/end partials, so each URL is rendered on its own as it passes through.
If you never published the views, you won't notice. If you did, that's the reason they changed.
Is lazy() actually doing what you think?
Laravel developers will know lazy() well. Under the hood it's a generator, and with Eloquent the database does the heavy lifting. Methods like lazyById() simply ask for the next chunk after the last ID, and an index makes that cheap no matter how far through the table you are.
Statamic has lazy() too, and it's also a generator. But it pages with an offset and a limit, and that behaves very differently depending on where your content lives.
On flat files, there's no database to lean on. Every page asks the Stache to filter and sort the whole collection again, just to take the next slice. On Eloquent, an offset means the database has to count its way past every row it has already returned. Either way, the further you get through a big collection, the more each chunk costs.
So v4 doesn't use lazy() for entries. It reads them a chunk at a time, in the way each driver handles best.
On the Stache: sort once, then load by ID
With flat files, the expensive part is the filtering and sorting. So v4 does that once, keeps just the list of IDs, and then loads each chunk directly by ID:
private function entryIdChunks(CollectionContract $collection, StatamicSite $site): Generator
{
$ids = $collection->queryEntries()->where('site', $site->handle())->orderBy('id')->pluck('id')->all();
foreach (array_chunk($ids, self::ENTRY_CHUNK_SIZE) as $chunkIds) {
// whereIn doesn't keep the order it was given, so put the entries back in id order
$entries = $collection->queryEntries()->whereIn('id', $chunkIds)->get()->keyBy(fn (EntryContract $entry): string => $entry->id());
$chunk = new ArrayObject(array_values(array_filter(array_map(fn (string $id): ?EntryContract => $entries->get($id), $chunkIds))));
unset($entries);
yield $chunk;
}
}
Holding a list of IDs is cheap. Holding thousands of hydrated entries isn't.
On Eloquent: start after the last ID
With a database, there's no need to hold every ID in PHP. v4 does what lazyById() does: each chunk starts after the last ID of the one before, so the database can go straight there using its index, and it never re-reads rows it has already returned.
private function entryPages(CollectionContract $collection, StatamicSite $site): Generator
{
$lastId = null;
do {
$query = $this->entryQuery($collection)->where('site', $site->handle())->orderBy('id')->limit(self::ENTRY_CHUNK_SIZE);
if ($lastId !== null) {
$query->where('id', '>', $lastId);
}
$entries = array_values($query->get()->all());
if ($entries === []) {
return;
}
$lastId = end($entries)->id();
$isLastPage = count($entries) < self::ENTRY_CHUNK_SIZE;
$chunk = new ArrayObject($entries);
unset($entries);
yield $chunk;
} while (! $isLastPage);
}
The rest of the pipeline doesn't know or care which one it's getting. Both yield the same thing: a chunk of entries, in ID order.
Why an ArrayObject?
You'll notice both methods wrap each chunk in an ArrayObject rather than yielding a plain array. That's deliberate.
A generator holds on to whatever it last yielded until it's asked for the next value. With a plain array, the previous chunk would still be sitting in memory while the next one loads, so you'd always have two chunks in memory at once.
Because the caller and the generator share the same object, the caller can take the entries out and leave the object empty:
foreach ($this->entryChunks($collection, $site) as $chunk) {
$entries = $chunk->exchangeArray([]);
// ... build and yield a URL for each entry ...
// free this chunk before the next one is loaded
unset($entries, $entry, $localisations);
}
The caller takes the entries out, uses them, and unsets them before asking for the next chunk. Once that happens, nothing is holding on to them, so each chunk is freed before the next one arrives.
The cost you don't see
Generators keep Sitemapamic lean, but Statamic does some remembering of its own during a request. Blink holds onto entries and translations, and Statamic keeps every URL it tidies until the request ends. Neither is a problem on a normal page load, but in a build that touches every entry, they grow with your content. So between chunks, v4 clears both, keeping only the collections themselves, which would otherwise be queried again for every chunk.
The bigger surprise was on Eloquent, and it only showed up when I ran the benchmarks on a real Forge server: locally, it was invisible. The driver stores an entry's content as JSON, and as it builds each entry, it reads that column several times. Laravel's JSON cast decodes it fresh every time. With a few KB of content per entry, that's a lot of work repeated for nothing.
v4 swaps in a cast that decodes each entry's JSON once and reuses the result. The decoded copies live in a WeakMap, so each one is freed with its model and memory stays flat. If the JSON changes, it's decoded again, and a model with its own cast for that column is left alone. Together with loading each chunk's original entries in one query instead of one per translation, that took 10,000 Eloquent entries from 21 seconds down to under 14.
Streams, not strings
Generators keep the input lean, but the output also needs somewhere to go that isn't a giant string.
The Writer writes each sitemap file into a temporary stream that stays in memory up to 5MB and then spills to disk:
$this->stream = fopen('php://temp/maxmemory:5242880', 'w+b');
As each fragment arrives, the Writer checks whether it would push the current file past the sitemap protocol limits of 50,000 URLs or 50MB. If it would, the current file is finished and a new numbered file is started. That's how files split automatically without ever needing to know the total number of URLs upfront. The decision is made one fragment at a time.
While it writes, it keeps a running byte count and builds a content hash incrementally:
private function append(string $contents): void
{
fwrite($this->stream, $contents);
hash_update($this->hash, $contents);
$this->bytes += strlen($contents);
}
That hash comes in handy later as the file's ETag, so a crawler that already has the current version of a file gets a 304 instead of the whole thing again.
Finished files are handed off to a filesystem disk with writeStream, and they're served back with readStream. At no point does a whole sitemap file need to exist as a PHP string.
The numbers
I ran v3 (3.5.1) and v4 side by side on otherwise identical Statamic 6 sites on a Laravel Forge VPS: same server, same content, with 100 to 10,000 articles plus 10 topics. v3 ran in single mode, and v4 in automatic mode - both of these are their defaults.
Entries | Flat file | Eloquent | ||
|---|---|---|---|---|
Sitemapamic v3 | Sitemapamic v4 | Sitemapamic v3 | Sitemapamic v4 | |
100 | 17.3 MB / 0.12 s | 14.5 MB / 0.08 s | 16.3 MB / 0.20 s | 16.3 MB / 0.14 s |
500 | 76.8 MB / 0.66 s | 15.5 MB / 0.27 s | 30.7 MB / 0.68 s | 16.4 MB / 0.50 s |
1,000 | 151.2 MB / 1.30 s | 16.6 MB / 0.52 s | 31.2 MB / 1.39 s | 16.5 MB / 0.98 s |
5,000 | Out of memory† | 27.0 MB / 2.98 s | 35.9 MB / 19.38 s | 17.2 MB / 5.60 s |
10,000 | Out of memory† | 39.7 MB / 6.28 s | Timed out‡ | 18.1 MB / 13.61 s |
Peak memory / build time on a Laravel Forge VPS (PHP 8.5, OPcache on), with 10 topics. Average of 6 runs, with a warm stache.
† Ran out of PHP's 512 MB memory limit.
‡ The web server gave up waiting after 30 s (504).
So this is telling me two things.
On flat files, it's about memory. v4 is more than twice as fast as v3 from 500 entries up, but the bigger number is peak memory: 16.6MB instead of 151MB at 1,000 entries. At 5,000 entries, v3 won't even build within a 512MB memory limit, and v4 does it in 27MB.
v4's memory still creeps up on flat files, though, and that's not Sitemapamic. Statamic's Stache holds its indexes for every entry in memory, so on flat files that cost grows with your content no matter how lean the sitemap build is.
If you're heading towards tens of thousands of entries, that's your sign to move to Eloquent anyway.
And with Eloquent, it's about time. v4 is faster at every size, and the gap widens as your site grows: about 30% less time at 1,000 entries, three and a half times faster at 5,000 (5.6s vs 19.4s), and at 10,000, v3 times out while v4 finishes in under 14 seconds. Memory is the quieter win: v3 doubles as entries grow, while v4 barely moves, from 16.3MB to 18.1MB between 100 and 10,000 entries.
In all cases, once a sitemap is built, serving it is fast for both versions at every size. The difference is all in the build. But also... v3 uses a cache driver, so depending on your sitemap size and cache driver, that could vary on your production server.
Beyond the raw numbers, a few other things fall out of this design:
No half-built sitemaps. Builds are written to a new version and then published via a manifest, so a crawler never sees a sitemap mid-build.
Stale while rebuilding. If a request arrives while a rebuild is underway, it gets the previous version rather than waiting (or worse, kicking off a second build).
ETags. Crawlers that already hold the current file don't need to download it again.
Dynamic routes as generators
The same rules apply to your own URLs. Return an array of 50,000 events and you've undone all of the gains above, but this time inside your own closure.
In v3, your dynamic routes closure returned an array of URLs. In v4, the closure receives the Site being built and can return any iterable, including a generator. For anything beyond a handful of URLs, a generator is the way to go:
use App\Models\Event;
use Generator;
use MityDigital\Sitemapamic\Facades\Sitemapamic;
use MityDigital\Sitemapamic\Models\SitemapamicUrl;
use Statamic\Sites\Site;
public function boot(): void
{
Sitemapamic::addDynamicRoutes(function (Site $site): Generator {
foreach (Event::query()->where('published', true)->lazy() as $event) {
yield new SitemapamicUrl(
loc: route('events.show', $event),
lastmod: $event->updated_at->toAtomString(),
);
}
});
}
The closure only runs when a sitemap is actually being built, not when it's registered. So using route(), models and queries inside it in your boot method is perfectly safe.
A few other things worth knowing:
You can pass a site handle (or an array of them) as the second argument to limit the routes to certain sites.
Each URL is validated as it's yielded. It must be an absolute
httporhttpsURL, and an invalid change frequency or priority is simply left out.Sitemapamic rebuilds when your Statamic content changes, but it can't know when your data changes. Call
Sitemapamic::markStale()from a model observer or after an import, and the next request will rebuild.
The dynamic routes docs have the full details.
Deciding what to break
Once I'd committed to generating, yielding and streaming, some breaking changes were unavoidable.
So I asked myself: with this being a major version anyway, what else is worth tidying up while I'm here?
Every breaking change costs someone time on an upgrade, so I tried to make each one earn its place, not only for a valid reason, but also for on-going maintenance of the addon:
Statamic 6 only. v4 drops Statamic 5. Supporting both would have meant carrying compatibility code through a brand new architecture.
A new default mode. v3 had
singleandmultiple, and defaulted tosingle. v4 hasautomaticandsingle, and defaults toautomatic, which is a sitemap index with one file per source. It scales better, so it's the sensible default.Auto-discovery config. The config is now built around
'*', which includes every routable collection and taxonomy. You can exclude things withfalseor select them explicitly. There's less to configure on most sites, and you still get fine control when you need it.A properly typed
SitemapamicUrl. In v3,lastmodwas a required string andprioritywas a string too. In v4,lastmodis nullable,priorityis a?float, andchangefreqaccepts aChangeFrequencyenum or a string.
The upgrade guide walks through what needs changing too.
Building v4 with AI
I'll be upfront here: I didn't write most of the code in v4. Claude did a lot of the heavy lifting. But I was there for the steering, and the review.
I don't want that to read as "I typed a prompt and went to lunch", because, well, I've still got to keep a hand on the code I work with, and I wanted to ensure this was something that matched my tastes, style, preferences and ability to understand and maintain it without an agent. I steered it very tightly: the architecture, the constraints, what "done" looked like, and what was and wasn't in scope.
That steering mattered, because the hardest part of a sitemap for Statamic isn't writing XML. Statamic doesn't expose a "here are all of the routes in your site" list. The routes have to be discovered from the rules of how a Statamic site is built:
Does the collection have a route for this site?
Is the entry published? If the collection is dated, what's the future and past date behaviour?
Does the entry actually have a template that exists?
Is it a taxonomy term page, or a term page in the context of a collection? And does that term have any published entries on this site?
Which localisations for a multi-site exist, and how do they link together as alternates?
And is the content in the Stache or in Eloquent, since each behaves slightly differently?
Knowing those rules, and knowing where the edge cases hide, is where the experience comes in. AI can write a generator. It doesn't know that a term page with no published entries shouldn't be in your sitemap unless someone tells it.
What I found really interesting was the difference between tools. I had been using Codex for quite some time, and was really happy with it as a coding companion. But over the past few weeks, it started to fall over. In Codex, with Sol 6.1 and even Astra, everything was constantly over-engineered. Both went off the rails with layers of complexity I never asked for, solving problems that didn't exist, and re-creating features and functions that are core to both Statamic and Laravel.
Claude was far more direct: it solved the problem in front of it without inventing new ones.
I even got Codex to review what Claude had done, and it agreed that it was a much better job and admitted it made an overly complicated chunk of code. It is a really interesting experiment to play them off against each other... but that can be a story for another post.
The other piece that made this work was the test suite. v4 ships with thousands of lines of Pest tests, run against both the Stache and the Eloquent driver. Those tests were the guard rails. They meant every change could be checked against the behaviour I'd defined, rather than just against how confident the output sounded.
The benchmarks did the same job for performance. Finding that Eloquent slowdown meant measuring and asking the right questions, not trusting that the code looked right, or that "faster than v3" was enough.
Sitemapamic is a free addon - and I use it on all of my sites - but it takes time to maintain addons. The majority of the ones I have published are free too. And they all take time to maintain. Even though AI helped with the code generation, I'm still the captain and am closely monitoring and managing the scope, scale and quality of the output delivered.
Get stuck in
Sitemapamic 4 is free, open source and ready for Statamic 6, and has been officially tagged:
I'd love to hear your thoughts on this new version, and how its performance helps on your site.