If you host your own map, at some point you end up with a tile archive: one .pmtiles or .mbtiles file that holds every tile of a region. It may come from a vector tile generator, from an export of a raster layer, or from someone else's pipeline. The file is convenient to copy around. But a map library in the browser does not read archives from your disk. It asks for /{z}/{x}/{y} URLs and expects the right answer for each.
So something has to stand between the file and the map. That something has to get a list of small details right. Vector tiles are usually stored gzip-compressed, and the browser needs Content-Encoding: gzip to decode them. MBTiles numbers its rows from the bottom, while XYZ URLs count from the top. A missing tile in the ocean is not an error. And tiles should be cached, or every pan of the map hits your server again.
tileserver is a small tile server written in Rust with axum that handles those details for PMTiles and MBTiles archives. You put files in a directory, and the server exposes each one as XYZ tiles plus TileJSON, with correct content headers, ETags and a MapLibre preview page.
What it does
One directory, one source per file. Every *.pmtiles and *.mbtiles file directly inside --dir becomes a source named after the file: roads.pmtiles becomes roads. Unreadable files and duplicate ids are logged and skipped. They do not stop the server.
A short list of endpoints.
-
GET /is the preview page: the source list, auto-styled vector layers or raster, and a click shows a feature's properties. Adding?debugshows tile boundaries. -
GET /sourcesis a JSON list of sources with kind, format, zooms, bounds and TileJSON URL. -
GET /{id}.jsonis TileJSON 3.0.0, withvector_layersfor vector sources. -
GET /{id}/{z}/{x}/{y}[.ext]is the tile. The extension is optional, but if present it must match (pbf/mvt,png,jpg,webp,avif). -
GET /healthanswersok.
Headers done properly. These are the details that decide whether the map shows up:
-
Content-Typecomes from the archive's tile type:application/vnd.mapbox-vector-tile,image/png, and so on. -
Content-Encoding: gzip(orbr/zstd) is set when the archive stores compressed tiles. Tiles are served as stored, with no recompression. If a client does not accept gzip, the tile is inflated on the fly.Vary: Accept-Encodingis always set. -
ETagis a strong validator, an FNV-1a hash of the stored bytes. A request with a matchingIf-None-Matchgets304 Not Modified. -
Cache-Control: public, max-age=Nwith a default of 3600, andAccess-Control-Allow-Origin: *.
Status codes that map libraries expect. 204 No Content for a tile inside the zoom range that the archive does not contain, which MapLibre treats as empty. 404 for unknown sources or zooms outside the range. 400 for invalid coordinates or a wrong extension.
TileJSON URLs that work behind a proxy. They use --base-url when you set it, or else the Host header and X-Forwarded-Proto.
How to use it
Install it from GitHub with Cargo, generate the demo archives and serve them:
cargo install --git https://github.com/AbdeldjalilChougui/tileserver --locked
tileserver fixtures tiles && tileserver serve --dir tiles
Or from a clone of the repository:
cargo run --release -- fixtures tiles # generate 4 small demo archives
cargo run --release -- serve --dir tiles # http://127.0.0.1:3000/
cargo test
The whole command line fits in two lines:
tileserver serve [--dir DIR] [--addr 127.0.0.1:3000] [--base-url URL] [--max-age SECONDS]
tileserver fixtures DIR
The fixtures command is useful on its own. It needs no external data: a tiny PNG encoder draws a debug grid for zooms 0 to 3, with each tile's z/x/y shown as bar counts, and a hand-written MVT encoder produces point tiles for zooms 0 to 6 with six Algerian cities. Both are written as PMTiles and as MBTiles. That gives you a raster source and a vector source in each format to try the server with, before you bring your own files.
How it works inside
PMTiles v3 is read by a module written from the spec. The reader parses the 127-byte header, then the gzip-compressed root directory and the JSON metadata. A tile id is the count of tiles in lower zooms plus the tile's position on a Hilbert curve. The reader binary-searches the directory for the last entry less than or equal to the id. Entries with run_length > 0 point into tile data, and run_length == 0 points to a leaf directory. Leaves are cached. File reads use pread, so one open file serves concurrent requests without locking.
The same module has a writer. It deduplicates identical tiles, run-length encodes consecutive repeats, and splits into leaf directories when the root gets big. The tests and the fixtures command use it.
MBTiles files are SQLite databases, opened read-only through rusqlite with bundled SQLite. The XYZ y is flipped to the TMS row 2^z − 1 − y. The metadata table (format, bounds, center, minzoom/maxzoom, and json for vector_layers) feeds TileJSON. Gzip is detected from the first tile's magic bytes instead of being assumed.
HTTP is axum 0.8. Tile reads run in spawn_blocking, since both backends do blocking I/O.
Things to know
- Sources are discovered at startup. Restart the server to pick up new files.
- Local files only. There is no HTTP range or remote PMTiles support.
- No brotli or zstd for PMTiles internal (directory) compression. Tile-level compression of any kind is passed through.
- The leaf-directory cache is a simple bounded map, not an LRU.
- The preview page uses external resources. It loads MapLibre from unpkg, OSM raster tiles as a backdrop, and glyphs from demotiles.maplibre.org for labels.
What is tested. cargo test runs 13 integration tests on freshly generated fixtures in a temporary directory. On the PMTiles side: tile ids against the spec's values, id to z/x/y round trips over zooms 0 to 6 plus deep zooms, directory encoding and decoding, entry lookup inside runs and gaps, and writer-to-reader runs with deduplicated "ocean" tiles, both root-only and with forced leaf directories. On the HTTP side: raster headers and body, ETag and 304, gzip pass-through versus inflation depending on Accept-Encoding, the 204/404/400 cases, TileJSON including X-Forwarded-Proto and --base-url, and MBTiles row flipping checked tile by tile against the generated PNGs.
Why I built it
Serving tiles from an archive is a narrow job, and it deserves a narrow tool: one binary, one directory, no configuration file. The difficulty is not the amount of code. It is that each small mistake produces a map that is blank with no error message: a missing Content-Encoding, a flipped row, a 404 where a 204 was expected. I wanted a server where each of those cases is written down and covered by a test.
Writing the PMTiles reader and writer from the spec was the other reason. It makes the format concrete: the header, the directories, the Hilbert curve ids, the run-length trick for repeated tiles. And having a writer means the tests need no downloaded data.
Get the code
The source and tests are on GitHub: https://github.com/AbdeldjalilChougui/tileserver. It is MIT licensed. The generated fixtures contain no third-party data (city positions are approximate and typed by hand), and the preview backdrop is © OpenStreetMap contributors (ODbL).
Originally published at abdeldjalilchougui.biz.
Top comments (0)