# Maptain
Rails sitemaps that rewrite only what changed. Each build asks your database what moved since the last one and
leaves every other file alone, so it runs hundreds of times faster than regenerating everything. You describe
each kind of page once, in a small class; Maptain writes one URL per language with its `hreflang` links.
```ruby
# app/sitemaps/product_sitemap.rb
class ProductSitemap < Maptain::Source
scope { Product.published }
url { |product, locale| product_url(product, locale:) }
end
```
```sh
bin/rails maptain:build
```
That writes `public/sitemap.xml` and the files it lists. Run it again an hour later: if nothing changed, it
takes a few milliseconds and writes nothing.
Website, guide and benchmarks: .
Coding agents can start from , or read this README and the
website's pages as one Markdown file: .
## Is it for you?
Maptain was written for one site: 30,000 products in 24 languages, 720,000 URLs. It will help most if yours
looks a bit like that, with records in a database, translated, and changing a little every day.
A site of a few hundred pages in one language does not need it: [sitemap_generator](https://github.com/kjvarga/sitemap_generator)
or a view that lists them will do. Maptain is also young (0.1), so read [what it does not do yet](https://github.com/levups/maptain#not-there-yet)
before you switch.
## What it does differently
- **A page is a record in several languages.** Every language of it lists all the others and itself as
`hreflang` links, which search engines require before they trust any of them. You never write those links.
- **Files that stay put.** Each file holds a fixed range of ids, so a record lands in the same file at every
build, and crawlers only fetch again the files that changed.
- **Builds that skip what did not move.** One query per source asks the database the count, the sum of the ids
and the latest change of each range. No callback in your models, so `update_all`, imports and deletions are
seen too.
- **Dates that are true.** `lastmod` is the date your content changed. `priority` and `changefreq`, which
Google ignores, are not written.
- **IndexNow instead of pings.** Bing, Yandex, Seznam and Naver are told which URLs changed. The ping endpoints
that older gems call have been closed.
Its only runtime dependency is Active Support.
## How long it takes
`bench/build.rb` builds the same sitemap with Maptain and with sitemap_generator, on the same machine. When a
few records changed, Maptain is about 400 times faster: it rewrites 2 files where sitemap_generator writes them
all again. Once a week, a full build rewrites everything to catch what the database numbers cannot see; that one
is 15 times faster.
On 30,000 records in 24 languages (SQLite in memory, Ruby 4.0.9 without YJIT, an Apple M5 Max, median of 3
runs; seconds depend on the machine, the ratios hold from one to the next):
| Build | Maptain | sitemap_generator | Faster | Files written |
|---|---|---|---|---|
| Nothing new | 0.004 s | 150 s | (nothing to write) | 0 |
| 3 records changed | 0.35 s | 150 s | 430× | 2 |
| Everything, 720,000 URLs | 9.9 s | 150 s | 15× | 55 (16.5 MiB gzipped) |
The URLs there are plain strings. With route helpers and a real database every build takes longer, and the gap
narrows a little: on a copy of a production app's database, 560,000 URLs took 35 s in full (13 times faster) and 2.8 s after
three products changed (170 times faster), where sitemap_generator took 468 s. The [benchmarks page](https://levups.github.io/maptain/benchmarks.html) explains
where the time goes.
## Getting started
1. Add the gem. It needs Ruby 3.3 and Rails 8.0, or newer.
```ruby
gem "maptain"
```
2. Name the host of the site:
```ruby
# config/initializers/maptain.rb
Maptain.configure do |config|
config.host = "https://www.example.com"
config.locales = %i[en fr de] # default: I18n.available_locales
config.x_default = :en # the language of hreflang="x-default"; none when left out
end
```
3. Write one class per kind of page in `app/sitemaps`, like `ProductSitemap` above. Its blocks have your route
helpers.
4. Look at what it would write, without writing it:
```sh
bin/rails maptain:check
```
It fails on a URL outside the site, a URL listed twice, a date in the future, and a few other
[mistakes](https://github.com/levups/maptain#checking).
5. Build, and tell crawlers where the index is, in `public/robots.txt`:
```sh
bin/rails maptain:build
```
```
Sitemap: https://www.example.com/sitemap.xml
```
6. Run it on a schedule. With Solid Queue:
```yaml
# config/recurring.yml
production:
sitemap:
command: "Maptain.build"
schedule: every hour
```
The rest of this README is the guide: languages, dates, files, storage on S3 and the like, IndexNow.
## Coming from sitemap_generator
| sitemap_generator | Maptain |
|---|---|
| `config/sitemap.rb`, one `add` per URL | one `Maptain::Source` per kind of page, in `app/sitemaps` |
| `alternates:` written by hand for each URL | `hreflang` links written from `config.locales`, or a source's `locales` |
| `default_host` | `config.host`, and `config.host_by_locale` for one host per language |
| `rake sitemap:refresh` | `bin/rails maptain:build`, which rewrites only what changed |
| `lastmod:` | `updated_at` by default, or `lastmod :column` |
| `images:`, `video:`, `news:` | an `images` block, and `video` and `news` blocks run in each language |
| `priority:`, `changefreq:` | left out: Google ignores them |
| pinging search engines | IndexNow, with `config.index_now_key` |
| `sitemaps_host`, adapters | `config.sitemaps_url`, and any Active Storage service |
sitemap_generator names its index `sitemap.xml.gz`, Maptain `sitemap.xml`: change the `Sitemap:` line of
`robots.txt`, and delete the old files once the first build has written the new ones.
## Sources
A source is a class in `app/sitemaps`. Its blocks run in an object that has your route helpers, already set to
`config.host`, or in the `url` block to the host of the language being written. That block also runs with its
language as `I18n.locale`, so a slug read from a translated attribute comes out in the language of its page; a
language that is not in `I18n.available_locales` runs in the app's.
```ruby
class ProductSitemap < Maptain::Source
# The records: an Active Record relation. Add the `includes` your other blocks need.
scope { Product.published.includes(:photos) }
# The URL of a record in a language. A path gets the host of its language; nil leaves that language out.
url { |product, locale| product_url(product, locale:) }
# The languages a record exists in. Without it, every configured language.
locales { |product| product.translated_locales }
# The column that holds the date the content changed. Default: updated_at.
lastmod :content_updated_at
# Image URLs, for Google Images.
images { |product| product.photos.map(&:url) }
end
```
The model needs an integer primary key: files are cut by ranges of ids.
### Pages that are not records
The scope can be any list. Such a source is one file, rendered at each build and published when it differs:
```ruby
class PageSitemap < Maptain::Source
scope { %i[root about contact] }
url { |page, locale| public_send(:"#{page}_url", locale:) }
end
```
### Videos and news
A page's [videos](https://developers.google.com/search/docs/crawling-indexing/sitemaps/video-sitemaps) and its
[Google News](https://developers.google.com/search/docs/crawling-indexing/sitemaps/news-sitemap) entry are written
in each of its languages: their blocks run like the `url` block, with that language as `I18n.locale`, so titles come
out translated. Return a Hash, an array of them for several videos, or nil for none.
```ruby
class VideoSitemap < Maptain::Source
scope { Video.live }
url { |video, locale| video_url(video, locale:) }
video do |video|
next unless video.thumbnail.attached?
{title: video.title, description: video.description, thumbnail_loc: url_for(video.thumbnail),
player_loc: video.player_url, duration: video.duration} # or content_loc:; publication_date:, expiration_date:
end
end
```
A video without a title, a description, a thumbnail or a `player_loc` or `content_loc` is left out with a warning,
as is one lasting more than 8 hours, one whose player is the page itself, or one with a date that lacks its day.
Titles are cut at 100 characters, descriptions at 2,048.
Google News reads articles of the last two days only, and 1,000 per file at most: a source with a `news` block gets
files that hold no more. Give the articles a source of their own, scoped to those days: an article that leaves the
scope changes the count of its file, which is rewritten without it. sitemap_generator's `publication_name:` and
`publication_language:` are `name:` and `language:` here; any other key leaves the entry out with a warning. A
video field Maptain does not write (`rating:`, `tag:`) is left out of its video, with a warning.
```ruby
class NewsSitemap < Maptain::Source
scope { Post.live.where(published_at: 2.days.ago..) }
url { |post, locale| post_url(post, locale:) }
# language: defaults to the page's
news { |post| {name: "Example Blog", title: post.title, publication_date: post.published_at} }
end
```
## Languages
Every record gets one URL per language of `config.locales`, or of its source's `locales` block. Each ``
then lists every language of its page, itself included:
```xml
https://www.example.com/fr/products/42
2026-11-03T09:12:44Z
```
A page in one language gets no `hreflang` link. A page that does not exist in the `x_default` language gets
no `x-default` link. A Rails locale such as `pt_BR` is written `hreflang="pt-BR"`, and two languages that share
a URL list it once.
A URL your block writes by hand is percent-encoded: spaces, accents and control characters cannot break a file.
### One host per language
When some languages are served from a host of their own, name those hosts:
```ruby
config.host = "https://www.example.com"
config.host_by_locale = {fr: "https://fr.example.com", de: "https://de.example.com"}
```
The other languages stay on `config.host`, and so does the index. The `robots.txt` of every host names that one
index: a sitemap may list the pages of a host only when that host's `robots.txt` points to it. Each key is one
of `config.locales`: a build refuses any other.
## The date of a page
`lastmod` is read from `updated_at`. Name another column when the content has its own: `lastmod
:content_updated_at`.
A column that moves when the content does not, such as an `updated_at` touched by a view counter, makes every
build rewrite files for nothing and tells search engines a date that is not true. Give such a model a column of
its own for content changes.
### When the date depends on more than one column
`lastmod` also takes a block. The build then needs to know what to watch in the database, as an SQL expression:
```ruby
class ProductSitemap < Maptain::Source
scope { Product.published }
url { |product, locale| product_url(product, locale:) }
lastmod { |product| [product.updated_at, product.reviewed_at].compact.max }
fingerprint "GREATEST(products.updated_at, COALESCE(products.reviewed_at, products.updated_at))"
end
```
## Files
A source named `ProductSitemap` writes `sitemap-product-00000.xml.gz`, `sitemap-product-00001.xml.gz` and so
on, one per range of ids; `slug "products"` changes the middle part, `config.filename` the first. The size of a
range comes from the number of languages, so that a file stays under 50,000 URLs and 50 MiB: 50,000 ids with one
language, 554 with 24. `shard_size 1_000` sets it yourself. A range that still outgrows a file continues in
`sitemap-product-00000-2.xml.gz`.
`sitemap.xml` is the index. It lists every file with the latest `lastmod` it holds, so a crawler fetches again
only the files that changed.
## Building
```sh
bin/rails maptain:build # rewrite the files whose records changed
bin/rails maptain:rebuild # rewrite everything
```
`Maptain.build` does the same from Ruby and returns what it did (`full`, `written`, `kept`, `deleted`,
`url_count`, `submitted`, `warnings`).
### How a build decides
For each source, one query groups the records by range of ids and returns the count, the sum of the ids and the
latest change of each. A range whose answer is the one the last build stored keeps its file. The others are
rendered again, and a file that comes out the same is not uploaded (a full build uploads every file). In the
index, a file that changed takes the latest `lastmod` it holds, or the time of the build when a record left it,
so that crawlers read it again.
Some changes leave those numbers alone: `update_columns`, a change in another table that the `url`, `locales`,
`images`, `video` or `news` blocks read, a new `url`, `video` or `news` block, a file someone removed from the
storage. Name the other table in `fingerprint`, or `touch` the record from it. For the rest, a full build comes
once a week by itself:
```ruby
config.rebuild_every = 1.day # default: a week; nil leaves it to maptain:rebuild
```
After deploying a change to a `url` block, run `maptain:rebuild` rather than wait.
A build notes the files it is about to add in `sitemap-manifest.json`, its memory of what each file held, then
writes the sitemap files, then the index, then removes the files no range fills any more, then writes the
manifest again. A build that fails midway is repaired by the next one. Changing a host, the languages, the
size of a range or the version of Maptain rewrites everything it moves once.
## Storage
Files go to `public/` by default.
### Through Active Storage
An app that already uses Active Storage can send the sitemaps through one of its services, with the credentials
it already has. Give them a service of their own in `config/storage.yml`, in the bucket you want:
```yaml
sitemaps:
service: S3
bucket: example-sitemaps
region: eu-west-3
public: true
access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
```
```ruby
Maptain.configure do |config|
config.storage = Maptain::Storage::ActiveStorage.new(:sitemaps, prefix: "sitemaps")
config.sitemaps_url = "https://cdn.example.com/sitemaps" # where those files are served from
end
```
No blob is created: the files keep their names as keys, and nothing is written to the database. Any service
works that serves a key at a stable URL: S3, Google Cloud Storage, Azure, a mirror of them. The Disk service
does not, it scatters keys in subfolders: keep the default for files on disk.
The `Sitemap:` line of `robots.txt` then names the index there: a sitemap on another host, or in a folder of the
site, may list the pages of the site only when its `robots.txt` points to it.
A storage is any object with `read(name)`, `write(name, path)` and `delete(name)`.
## IndexNow
[IndexNow](https://www.indexnow.org) tells Bing, Yandex, Seznam and Naver that a URL changed. Google does not
take part. Choose a key of 8 to 128 characters among a-z, A-Z, 0-9 and -:
```ruby
config.index_now_key = "c1f0e2b4a6d84f3e9b7a5c3d1e0f2a4b"
```
Each build then publishes the key as `.txt` at the root of the site, and sends, from the files it rewrote,
the URLs whose `lastmod` is later than the previous build, and those that appeared or went away whatever their
`lastmod`. The first build sends nothing, nor does a new configuration beyond the pages whose `lastmod` moved,
and only URLs on the hosts of the site are sent.
When the sitemaps are served from elsewhere (`config.sitemaps_url`), the key cannot follow them: IndexNow reads
it on the site. Put `.txt` in `public/` and set `config.index_now_key_location` to its path,
`"/.txt"`; a build warns until you do.
With one host per language, every host must serve the key: IndexNow reads it on the host of the URLs it is given.
A refusal or an endpoint that cannot be reached is a warning, never a failed build: the URLs it did not take are
kept in the manifest and sent again with the next build. Once the endpoint cannot be reached, a build asks it
nothing more.
## llms.txt
An [llms.txt](https://llmstxt.org) is a short Markdown summary of a site for language models: its name, a line
about it, then a few lists of links to the pages that matter most. Maptain writes it with the sitemaps, from the
same sources, when you give it a title:
```ruby
config.llms_txt = {
title: "Example Store",
summary: -> { I18n.t("llms_txt.summary") }, # a String, or a block run in the language of the file
details: "Prices include VAT. We ship to the EU.",
locale: :en # default: config.x_default, else the first language
}
```
A source joins it with a heading and, for each record, a title and optional notes. Keep it to the pages a reader
would start from: past 200 links a build warns, since the file is no longer a summary.
```ruby
class CategorySitemap < Maptain::Source
scope { Category.all }
url { |category, locale| category_url(category, locale:) }
llms_txt("Categories", scope: -> { Category.top_level }) { |category| [category.name, category.tagline] }
end
```
Its links come from the `url` block, in the language of the file, where the `scope:` and title blocks run too.
Records that do not exist in that language, or whose title is blank or a missing translation, are left out.
Records are read in id order until the file is full, a scope with its own order, limit or offset as it says, and
never more than 2,000 per source and file: past that a build warns, and `scope:` should pick the records of the file's
language. The first 200 links are listed. A subclass does not inherit its parent's `llms_txt`. The file is
`llms.txt`, next to `sitemap.xml`, rewritten only when it changes, and deleted when the setting goes away.
With one host per language (`config.host_by_locale`), each host gets a file of its own, in its language and with
links to its pages: `llms-en.txt`, `llms-de.txt`. A host with several languages gets the one of `locale:` if it has
it, else `x_default`, else its first.
Crawlers look for the file at `/llms.txt` on each host. When the sitemaps are served from the site on one host,
`public/llms.txt` is that already. Otherwise, with the sitemaps elsewhere (`config.sitemaps_url`) or one host per
language, serve it from the app, which reads from `config.storage` the file of the host it is asked on:
```ruby
# config/routes.rb
get "llms.txt", to: Maptain::LlmsTxt::App.new
```
It picks the file from the `Host` header, never from `X-Forwarded-Host`, which a cache does not key responses by:
behind a proxy, pass the original `Host` on.
## Checking
```sh
bin/rails maptain:check
```
It renders every sitemap without publishing or submitting anything, and fails on:
- a URL outside the hosts of the site, listed twice in a source, or longer than 2,048 characters, and a page whose
languages all share one URL;
- an `hreflang` that is not a language code (`en`, `pt-BR`, `zh-Hant`, `es-419`);
- a `lastmod` in the future, or one that is not a W3C date, which is then left out;
- a video or a news entry left out, or a video field Maptain does not write;
- an index with more than the 50,000 files it may hold.
When many URLs of a source are outside the hosts of the site, listed twice, too long or dated in the future, one
line names the first and counts the others. A build reports the same, for the files it rewrites, in `warnings`.
Maptain never requests a page of the site. Whether a URL answers 200 or carries a `noindex` is what Search
Console reports, from the visits crawlers make anyway.
## Instrumentation
`build.maptain` wraps a build, with `full` and `result` in its payload; `shard.maptain` wraps each file
range it renders, with `source` and `shard`. `storage_error.maptain`, with `name` and `exception_object`, reports a
storage `LlmsTxt::App` could not read: it answers with its copy, or a 503 without one.
```ruby
ActiveSupport::Notifications.subscribe("build.maptain") do |event|
built = event.payload[:result] # nil when the build raised
Rails.logger.info "Sitemap: #{built.written.size} files written in #{event.duration.round} ms" if built
end
```
## Not there yet
Models without an integer primary key, and building several ranges in parallel.
## Development
```sh
bundle exec rake test
bundle exec rubocop
bundle exec ruby bench/build.rb # also builds the same sitemap with sitemap_generator: a few minutes
bundle exec rake docs:highlight # after editing a code block in docs/
bundle exec rake docs:llms # after editing the README or docs/
```
## License
MIT. See [LICENSE](https://github.com/levups/maptain/blob/main/LICENSE).
Made by [Level UP Solutions](https://github.com/levups).
## Maptain Guide
From a first sitemap in six steps to storage on S3, IndexNow, and what a build does under the hood.
### Getting started
1. Add the gem. It needs Ruby 3.3 and Rails 8.0, or newer; its only runtime dependency is Active Support.
```ruby
# Gemfile
gem "maptain"
```
2. Name the host of the site:
```ruby
# config/initializers/maptain.rb
Maptain.configure do |config|
config.host = "https://www.example.com"
config.locales = %i[en fr de] # default: I18n.available_locales
config.x_default = :en # the language of hreflang="x-default"; none when left out
end
```
3. Write one class per kind of page in `app/sitemaps`, as in [Sources](https://levups.github.io/maptain/guide.html#sources) below:
```ruby
# app/sitemaps/product_sitemap.rb
class ProductSitemap < Maptain::Source
scope { Product.published }
url { |product, locale| product_url(product, locale:) }
end
```
4. Look at what it would write, without writing it. It fails on a URL outside the site, a URL listed twice, a date in the future, and a few other [mistakes](https://levups.github.io/maptain/guide.html#checking):
```sh
bin/rails maptain:check
```
5. Build, then tell crawlers where the index is, in `public/robots.txt`:
```sh
bin/rails maptain:build
```
```text
Sitemap: https://www.example.com/sitemap.xml
```
6. Run it on a schedule, every hour or every night. With Solid Queue:
```yaml
# config/recurring.yml
production:
sitemap:
command: "Maptain.build"
schedule: every hour
```
That is all most sites need. The sections below go further: records in some languages only, dates from several columns, files on S3, IndexNow.
### Sources
A source is a class in `app/sitemaps` that inherits from `Maptain::Source`, one per kind of page. Its blocks run in an object that has your route helpers, already set to `config.host`, or in the `url` block to the host of the language being written. That block also runs with its language as `I18n.locale`, so a slug read from a translated attribute comes out in the language of its page; a language that is not in `I18n.available_locales` runs in the app's.
```ruby
# app/sitemaps/product_sitemap.rb
class ProductSitemap < Maptain::Source
# The records: an Active Record relation. Add the includes your other blocks need.
scope { Product.published.includes(:photos) }
# The URL of a record in a language. A path gets the host of its language; nil leaves that language out.
url { |product, locale| product_url(product, locale:) }
# Image URLs, for Google Images.
images { |product| product.photos.map(&:url) }
end
```
The model needs an integer primary key: files are cut by ranges of ids.
#### Pages that are not records
The scope can be any list. Such a source is one file, rendered at each build and published when it differs from the last one.
```ruby
class PageSitemap < Maptain::Source
scope { %i[root about contact] }
url { |page, locale| public_send(:"#{page}_url", locale:) }
end
```
#### Videos and news
A page's [videos](https://developers.google.com/search/docs/crawling-indexing/sitemaps/video-sitemaps) and its [Google News](https://developers.google.com/search/docs/crawling-indexing/sitemaps/news-sitemap) entry are written in each of its languages: their blocks run like the `url` block, with that language as `I18n.locale`, so titles come out translated. Return a Hash, an array of them for several videos, or nil for none.
```ruby
class VideoSitemap < Maptain::Source
scope { Video.live }
url { |video, locale| video_url(video, locale:) }
video do |video|
next unless video.thumbnail.attached?
{title: video.title, description: video.description, thumbnail_loc: url_for(video.thumbnail),
player_loc: video.player_url, duration: video.duration} # or content_loc:; publication_date:, expiration_date:
end
end
```
A video without a title, a description, a thumbnail or a `player_loc` or `content_loc` is left out with a warning, as is one lasting more than 8 hours, one whose player is the page itself, or one with a date that lacks its day. Titles are cut at 100 characters, descriptions at 2,048.
Google News reads articles of the last two days only, and 1,000 per file at most: a source with a `news` block gets files that hold no more. Give the articles a source of their own, scoped to those days: an article that leaves the scope changes the count of its file, which is rewritten without it. sitemap_generator's `publication_name:` and `publication_language:` are `name:` and `language:` here; any other key leaves the entry out with a warning. A video field Maptain does not write (`rating:`, `tag:`) is left out of its video, with a warning.
```ruby
class NewsSitemap < Maptain::Source
scope { Post.live.where(published_at: 2.days.ago..) }
url { |post, locale| post_url(post, locale:) }
news { |post| {name: "Example Blog", title: post.title, publication_date: post.published_at} } # language: the page's
end
```
### Languages
Every record gets one URL per language of `config.locales`. When records are not all translated, `locales` names the languages each one exists in:
```ruby
class ProductSitemap < Maptain::Source
scope { Product.published }
url { |product, locale| product_url(product, locale:) }
locales { |product| product.translated_locales }
end
```
Each `` then lists every language of its page, itself included, as `hreflang` links. A page in one language gets no link. A page that does not exist in the `x_default` language gets no `x-default` link. A Rails locale such as `pt_BR` is written `hreflang="pt-BR"`, and two languages that share a URL list it once.
A URL your block writes by hand is percent-encoded: spaces, accents and control characters cannot break a file.
#### One host per language
When some languages are served from a host of their own, name those hosts:
```ruby
config.host = "https://www.example.com"
config.host_by_locale = {fr: "https://fr.example.com", de: "https://de.example.com"}
```
The other languages stay on `config.host`, and so does the index. The `robots.txt` of every host names that one index: a sitemap may list the pages of a host only when that host's `robots.txt` points to it. Each key is one of `config.locales`: a build refuses any other.
### The date of a page
`lastmod` is read from `updated_at`. Name another column when the content has its own:
```ruby
lastmod :content_updated_at
```
A column that moves when the content does not, such as an `updated_at` touched by a view counter, makes every build rewrite files for nothing and tells search engines a date that is not true. Give such a model a column for content changes.
#### When the date depends on more than one column
`lastmod` also takes a block. The build then needs to know what to watch in the database, as an SQL expression:
```ruby
class ProductSitemap < Maptain::Source
scope { Product.published }
url { |product, locale| product_url(product, locale:) }
lastmod { |product| [product.updated_at, product.reviewed_at].compact.max }
fingerprint "GREATEST(products.updated_at, COALESCE(products.reviewed_at, products.updated_at))"
end
```
### Files
A source named `ProductSitemap` writes `sitemap-product-00000.xml.gz`, `sitemap-product-00001.xml.gz` and so on, one per range of ids. `slug "products"` changes the middle part, `config.filename` the first.
The size of a range comes from the number of languages, so that a file stays under the 50,000 URLs and 50 MiB the protocol allows: 50,000 ids with one language, 554 with 24. `shard_size 1_000` sets it yourself. A range that still outgrows a file continues in `sitemap-product-00000-2.xml.gz`.
`sitemap.xml` is the index. It lists every file with the latest `lastmod` it holds, so a crawler fetches again only the files that changed.
### Building
```sh
bin/rails maptain:build # rewrite the files whose records changed
bin/rails maptain:rebuild # rewrite everything
```
`Maptain.build` does the same from Ruby and returns what it did: `full`, `written`, `kept`, `deleted`, `url_count`, `submitted` and `warnings`. Run it on a schedule, every night or every hour. With Solid Queue:
```yaml
# config/recurring.yml
production:
sitemap:
command: "Maptain.build"
schedule: every hour
```
#### How a build decides
For each source, one query groups the records by range of ids and returns the count, the sum of the ids and the latest change of each. A range whose answer is the one the last build stored keeps its file. The others are rendered again, and a file that comes out the same is not uploaded (a full build uploads every file). Nothing hooks into your models, so `update_all`, imports and deletions are seen too.
In the index, a file that changed takes the latest `lastmod` it holds, or the time of the build when a record left it, so that crawlers read it again.
Some changes leave those numbers alone: `update_columns`, a change in another table that the `url`, `locales`, `images`, `video` or `news` blocks read, a new `url`, `video` or `news` block, a file someone removed from the storage. Name the other table in `fingerprint`, or `touch` the record from it. For the rest, a full build comes once a week by itself:
```ruby
config.rebuild_every = 1.day # default: a week; nil leaves it to maptain:rebuild
```
After deploying a change to a `url` block, run `maptain:rebuild` rather than wait.
A build notes the files it is about to add in `sitemap-manifest.json`, its memory of what each file held, then writes the sitemap files, then the index, then removes the files no range fills any more, then writes the manifest again. A build that fails midway is repaired by the next one. Changing a host, the languages, the size of a range or the version of Maptain rewrites everything it moves once.
### Storage
Files go to `public/` by default.
#### Through Active Storage
An app that already uses Active Storage can send the sitemaps through one of its services, with the credentials it already has. Give them a service of their own in `config/storage.yml`, in the bucket you want:
```yaml
sitemaps:
service: S3
bucket: example-sitemaps
region: eu-west-3
public: true
access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
```
```ruby
Maptain.configure do |config|
config.storage = Maptain::Storage::ActiveStorage.new(:sitemaps, prefix: "sitemaps")
config.sitemaps_url = "https://cdn.example.com/sitemaps" # where those files are served from
end
```
No blob is created: the files keep their names as keys, and nothing is written to the database. Any service works that serves a key at a stable URL: S3, Google Cloud Storage, Azure, a mirror of them. The Disk service does not, it scatters keys in subfolders: keep the default for files on disk.
Sitemaps served from another host than the pages they list are accepted when the site's `robots.txt` names the index there.
#### Your own
A storage is any object with `read(name)`, `write(name, path)` and `delete(name)`.
### IndexNow
[IndexNow](https://www.indexnow.org) tells Bing, Yandex, Seznam and Naver that a URL changed. Google does not take part. Choose a key of 8 to 128 characters among a-z, A-Z, 0-9 and -:
```ruby
config.index_now_key = "c1f0e2b4a6d84f3e9b7a5c3d1e0f2a4b"
```
Each build then publishes the key as `.txt` at the root of the site, and sends, from the files it rewrote, the URLs whose `lastmod` is later than the previous build, and those that appeared or went away whatever their `lastmod`. The first build sends nothing, nor does a new configuration beyond the pages whose `lastmod` moved, and only URLs on the hosts of the site are sent.
When the sitemaps are served from elsewhere (`config.sitemaps_url`), the key cannot follow them: IndexNow reads it on the site. Put `.txt` in `public/` and set `config.index_now_key_location` to its path, `"/.txt"`; a build warns until you do.
With one host per language, every host must serve the key: IndexNow reads it on the host of the URLs it is given.
A refusal or an endpoint that cannot be reached is a warning, never a failed build: the URLs it did not take are kept in the manifest and sent again with the next build. Once the endpoint cannot be reached, a build asks it nothing more.
### llms.txt
An [llms.txt](https://llmstxt.org) is a short Markdown summary of a site for language models: its name, a line about it, then a few lists of links to the pages that matter most. Maptain writes it with the sitemaps, from the same sources, when you give it a title:
```ruby
config.llms_txt = {
title: "Example Store",
summary: -> { I18n.t("llms_txt.summary") }, # a String, or a block run in the language of the file
details: "Prices include VAT. We ship to the EU.",
locale: :en # default: config.x_default, else the first language
}
```
A source joins it with a heading and, for each record, a title and optional notes. Keep it to the pages a reader would start from: past 200 links a build warns, since the file is no longer a summary.
```ruby
class CategorySitemap < Maptain::Source
scope { Category.all }
url { |category, locale| category_url(category, locale:) }
llms_txt("Categories", scope: -> { Category.top_level }) { |category| [category.name, category.tagline] }
end
```
Its links come from the `url` block, in the language of the file, where the `scope:` and title blocks run too. Records that do not exist in that language, or whose title is blank or a missing translation, are left out. Records are read in id order until the file is full, a scope with its own order, limit or offset as it says, and never more than 2,000 per source and file: past that a build warns, and `scope:` should pick the records of the file's language. The first 200 links are listed. A subclass does not inherit its parent's `llms_txt`. The file is `llms.txt`, next to `sitemap.xml`, rewritten only when it changes, and deleted when the setting goes away.
With one host per language (`config.host_by_locale`), each host gets a file of its own, in its language and with links to its pages: `llms-en.txt`, `llms-de.txt`. A host with several languages gets the one of `locale:` if it has it, else `x_default`, else its first.
Crawlers look for the file at `/llms.txt` on each host. When the sitemaps are served from the site on one host, `public/llms.txt` is that already. Otherwise, with the sitemaps elsewhere (`config.sitemaps_url`) or one host per language, serve it from the app, which reads from `config.storage` the file of the host it is asked on:
```ruby
# config/routes.rb
get "llms.txt", to: Maptain::LlmsTxt::App.new
```
It picks the file from the `Host` header, never from `X-Forwarded-Host`, which a cache does not key responses by: behind a proxy, pass the original `Host` on.
### Checking
```sh
bin/rails maptain:check
```
It renders every sitemap without publishing or submitting anything, and fails on:
- a URL outside the hosts of the site, listed twice in a source, or longer than 2,048 characters, and a page whose languages all share one URL;
- an `hreflang` that is not a language code (`en`, `pt-BR`, `zh-Hant`, `es-419`);
- a `lastmod` in the future, or one that is not a W3C date, which is then left out;
- a video or a news entry left out, or a video field Maptain does not write;
- an index with more than the 50,000 files it may hold.
When many URLs of a source are outside the hosts of the site, listed twice, too long or dated in the future, one line names the first and counts the others. A build reports the same in `warnings`, for the files it rewrites.
Maptain never requests a page of the site. Whether a URL answers 200 or carries a `noindex` is what Search Console reports, from the visits crawlers make anyway.
### Instrumentation
`build.maptain` wraps a build, with `full` and `result` in its payload. `shard.maptain` wraps each range it renders, with `source` and `shard`. `storage_error.maptain`, with `name` and `exception_object`, reports a storage `LlmsTxt::App` could not read: it answers with its copy, or a 503 without one.
```ruby
ActiveSupport::Notifications.subscribe("build.maptain") do |event|
built = event.payload[:result]
Rails.logger.info "Sitemap: #{built.written.size} files written in #{event.duration.round} ms"
end
```
### Coming from sitemap_generator
| sitemap_generator | Maptain |
| --- | --- |
| `config/sitemap.rb`, one `add` per URL | One `Maptain::Source` per kind of page, in `app/sitemaps` |
| `alternates:` written by hand for each URL | `hreflang` links written from `config.locales`, or a source's `locales` |
| `default_host` | `config.host`, and `config.host_by_locale` for one host per language |
| `rake sitemap:refresh` | `bin/rails maptain:build`, which rewrites only what changed |
| `lastmod:` | `updated_at` by default, or `lastmod :column` |
| `images:`, `video:`, `news:` | an `images` block, and `video` and `news` blocks run in each language |
| `priority:`, `changefreq:` | Left out: Google ignores them |
| Pinging search engines | IndexNow, with `config.index_now_key` |
| `sitemaps_host`, adapters | `config.sitemaps_url`, and any Active Storage service |
sitemap_generator names its index `sitemap.xml.gz`, Maptain `sitemap.xml`: change the `Sitemap:` line of `robots.txt`, and delete the old files once the first build has written the new ones.
## Maptain Benchmarks
A site of 30,000 pages in 24 languages, built by Maptain and by sitemap_generator on the same machine: about 400 times faster when a few records changed, 15 times for a full build.
### Building 720,000 URLs
`bench/build.rb` creates 30,000 records, builds their sitemap in 24 languages, builds it again with nothing new, then once more after three records changed. Every URL carries the 25 `hreflang` links of its page. It then builds the same sitemap, URLs, dates and links, with sitemap_generator, which has no build that skips what did not change.
Ruby 4.0.9 without YJIT, Rails 8.1.4, sitemap_generator 7.1.1, SQLite in memory, Apple M5 Max, median of 3 runs
| Build | Maptain | sitemap_generator | Faster | Files written |
| --- | --- | --- | --- | --- |
| Nothing new | 0.004 s | 150 s | (nothing to write) | 0 |
| 3 records changed | 0.35 s | 150 s | 430× | 2 |
| Everything, 720,000 URLs | 9.9 s | 150 s | 15× | 55 (16.5 MiB gzipped) |
With YJIT, the same runs give 0.012 s, 0.32 s and 9.5 s for Maptain, and 115 s for sitemap_generator: 360 and 12 times faster instead of 430 and 15.
Seconds depend on the machine: the full build took 32 s on a Linux x86_64 server with Ruby 3.3.6, before the change to gzip, three times as long as here. Compare builds on the same machine rather than with this table: the ratios hold, the seconds do not.
The URLs here are built from a string: with route helpers and a real database, every build takes longer, and the gap narrows a little. On a copy of a production app's database, 560,000 URLs built on a laptop before the change to gzip, Maptain's full build took 35 s where sitemap_generator took 468 s, 13 times faster, and a build with three changed products 2.8 s, 170 times faster.
### Why the full build takes seconds
sitemap_generator lists every URL again at each run, so each of its builds is a full one. Maptain asks the database one question per source, and rewrites only the files whose records moved: that is the build a site runs every day, or after every deploy.
The full build runs once a week ([`rebuild_every`](https://levups.github.io/maptain/guide.html#building)), to catch what the database numbers cannot see. Its size grows with the square of the languages: each of the 720,000 URLs lists the 25 links of its page, about 18 million links and 2 GiB of XML before compression. Maptain writes that XML as strings, without a document tree, and spends most of the time in gzip, at its best level: files that search engines download again and again are worth a few more seconds once a week. The largest file is 39.8 MiB before compression, under the 50 MiB the protocol allows.
### Running it again
From a checkout of the gem, once with YJIT off and once with it on:
```sh
bundle exec ruby bench/build.rb
bundle exec ruby --yjit bench/build.rb
```
It takes a few minutes, nearly all of them in sitemap_generator.