Self-hosting a world map: one PMTiles archive on R2 behind a Worker
by Chanan Braunstein, Owner
TripEagle has a live map: where everyone in the group is right now, for the few minutes they've chosen to share it. It has the same streets under it as any map app, and no tile provider. The browser fetches every tile from TripEagle's own domain.
That wasn't for cost. At TripEagle's scale, every commercial provider's free tier would cover it. The reason is what a tile request says. Whoever serves a tile sees the reader's IP address, their browser and the z/x/y of the tile, which is the rectangle of the world they're looking at. On most screens that rectangle is a restaurant. On this one it's where eight people are standing right now, and the request itself says when someone looked. And you can't hide the reader behind your own server: Mapbox's terms forbid distributing map content "by proxying", Google's forbid reaching tiles through any channel but its API, and MapTiler allows a proxy only with its approval and for extra fees.
So the map is self-hosted. The whole planet is one PMTiles archive in an R2 bucket, served by a Worker that answers range requests from its own cache. Phones get regional extracts cut on the server, so the day's map works in airplane mode. And when the archive is built, Greek and Cyrillic street names are given Latin ones, so a traveller can match the map to the street sign.
This is the fifth post in Techniques from TripEagle, after fast database tests. The code is simplified from the TripEagle monorepo so it stands on its own.
PMTiles: one file, read by range
A web map is drawn from tiles: the world cut into squares at each zoom level, each square a small vector tile of roads, buildings and labels. The usual way to serve them is a tile server answering /{z}/{x}/{y}.pbf. PMTiles puts every tile of a map in one file, with directories inside it that say where each tile's bytes are. A client reads the file with HTTP range requests, so anything that can answer Range: bytes=… can serve it. No tile server needed.
The layout is what makes that cheap:
- The first 16 KiB hold a 127-byte header and the root directory. A client asks for them in one request and keeps them.
- Tiles are numbered along a Hilbert curve, so tiles close together on the map are close together in the file, and the directories are sorted by that number.
- Leaf directories cover the parts of the world the root can't fit. A client fetches the leaf it needs and keeps that too.
- Identical tiles are stored once. The open ocean is the same tile millions of times, and every one of those entries points at the same bytes.
So the first tile in a new part of the world costs two or three range requests, and every tile after it costs one. Protomaps publishes a daily build of the whole planet from OpenStreetMap: about 140 GB at zooms 0 to 15. That's every street on Earth, in one file.
In the browser, MapLibre GL JS reads it through the pmtiles package's protocol:
import maplibregl from 'maplibre-gl'
import { Protocol } from 'pmtiles'
import { layers, namedFlavor } from '@protomaps/basemaps'
maplibregl.addProtocol('pmtiles', new Protocol().tile)
const map = new maplibregl.Map({
container: 'map',
style: {
version: 8,
glyphs: 'https://basemap.example.com/assets/0f3c9a1b2d4e/fonts/{fontstack}/{range}.pbf',
sprite: 'https://basemap.example.com/assets/0f3c9a1b2d4e/sprites/v4/light',
sources: {
protomaps: {
type: 'vector',
url: 'pmtiles://https://basemap.example.com/planet/20261007.latin-2.pmtiles',
attribution: '© <a href="https://openstreetmap.org/copyright">OpenStreetMap</a>',
},
},
layers: layers('protomaps', namedFlavor('light'), { lang: 'en' }),
},
})
MapLibre is BSD-licensed, needs no key and reports to no one. The glyphs and sprites come from the same bucket, under a prefix that names the commit of Protomaps' assets they were taken from, so the reader's browser talks only to TripEagle. The attribution is required by OpenStreetMap's licence, and it stays on the map.
First, a region at a time
The first design didn't host the planet. It cut one small archive per region of a trip, the bounding box of that region's places padded a little, with pmtiles extract, on demand, the first time someone opened the map. A Santorini extract was 2 MB.
It broke on its first real use. One member shared their position from home, the map opened on their pin, as it should, and the pin sat on a blank map. The extract was fine. There were just no tiles where the pin was. That wasn't an edge case: anyone looking before the trip, from home or on a day trip past the padding is outside the region, and the screen exists to show where people are.
Meanwhile, the thing that made cutting worth it turned out to be small. R2 charges $0.015 per GB a month and nothing for egress, so the whole planet costs about $2 a month to keep. The per-region design had a job queue, retries, a "streets on their way" state and a choice of which daily build to cut from. Hosting the planet replaced all of it with one file.
The Worker: ranges, cached at the edge
R2 can answer range requests itself, but every read goes to the bucket, and Protomaps' Cloudflare guide warns that R2 alone has latency of 500 ms or more. Every reader's map asks for the same header and the same directories, so a cache pays off fast. The Worker in front of the bucket does three things: answers a range, caches each range as its own entry, and tells everyone the bytes will never change.
// worker.ts: serves PMTiles archives from R2, caching each range at the edge
interface Env {
BASEMAPS: R2Bucket
}
interface Range {
start: number
end?: number // inclusive; open-ended when missing
}
const immutable = `public, max-age=${365 * 24 * 60 * 60}, immutable`
const largestCachedWhole = 16 * 1024 * 1024 // a glyph or a sprite, never a whole archive
// A map on another origin has to be able to read these headers off a response
const cors = {
'access-control-allow-origin': '*',
'access-control-expose-headers': 'etag, content-range, content-length, accept-ranges',
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if (request.method === 'OPTIONS') return preflight()
if (request.method !== 'GET') return new Response('Method not allowed', { status: 405 })
const url = new URL(request.url)
const key = keyOf(url.pathname)
if (!key) return refusal(404, 'Not found')
const range = rangeOf(request.headers.get('range'))
// One entry per archive and range, whatever query string a client appends
const cacheUrl = new URL(url.pathname, url.origin)
if (range) cacheUrl.searchParams.set('bytes', `${range.start}-${range.end ?? ''}`)
const cacheKey = new Request(cacheUrl)
const cached = await caches.default.match(cacheKey)
if (cached) return forTheReader(cached)
const stored = await read(env.BASEMAPS, key, range)
if (stored.status !== 200) return stored // a 404 or a 416 is never cached
if (Number(stored.headers.get('content-length')) > largestCachedWhole) {
return forTheReader(stored)
}
ctx.waitUntil(caches.default.put(cacheKey, stored.clone()))
return forTheReader(stored)
},
}
function keyOf(pathname: string): string | undefined {
try {
const key = decodeURIComponent(pathname.slice(1))
return key === '' || key.startsWith('.') ? undefined : key
} catch {
return undefined // malformed percent-encoding
}
}
// PMTiles clients ask for `bytes=start-end`. Anything else (several ranges, a suffix
// range, none) is served whole; the real Worker also resolves `bytes=-n` suffixes.
function rangeOf(header: string | null): Range | undefined {
const match = header && /^bytes=(\d+)-(\d*)$/.exec(header.trim())
if (!match) return undefined
const [start, end] = [Number(match[1]), match[2] === '' ? undefined : Number(match[2])]
return end !== undefined && end < start ? undefined : { start, end } // backwards: ignored
}
The read is where the one real gotcha lives. The Cache API refuses to store a 206. So the Worker stores every range as a plain 200 holding only that range's bytes, and keeps the range in a header of its own. It doesn't put it in content-range, because a cached 200 that claims a Content-Range is one the edge's own range handling could misread. On the way out, it turns the entry back into the 206 it was:
async function read(bucket: R2Bucket, key: string, range?: Range): Promise<Response> {
// Ask for the size first. R2 refuses a range that starts past the end, so resolving it
// here means the 416 the client is owed is ours to write.
const head = await bucket.head(key)
if (!head) return refusal(404, 'Not found')
const headers = new Headers()
head.writeHttpMetadata(headers) // content-type and the like, as stored
headers.set('etag', head.httpEtag)
headers.set('accept-ranges', 'bytes')
headers.set('cache-control', immutable)
if (!range) {
const object = await bucket.get(key)
if (!object) return refusal(404, 'Not found') // deleted since the head
headers.set('content-length', String(head.size))
return new Response(object.body, { headers })
}
const end = Math.min(range.end ?? head.size - 1, head.size - 1)
if (range.start >= head.size) {
return refusal(416, 'Range not satisfiable', { 'content-range': `bytes */${head.size}` })
}
const length = end - range.start + 1
const object = await bucket.get(key, { range: { offset: range.start, length } })
if (!object) return refusal(404, 'Not found')
headers.set('content-length', String(length))
headers.set('x-held-range', `bytes ${range.start}-${end}/${head.size}`)
return new Response(object.body, { headers }) // a 200, so the cache will take it
}
function forTheReader(stored: Response): Response {
const headers = new Headers(stored.headers)
const range = headers.get('x-held-range')
headers.delete('x-held-range')
if (range) headers.set('content-range', range)
for (const [name, value] of Object.entries(cors)) headers.set(name, value)
return new Response(stored.body, { status: range ? 206 : 200, headers })
}
function refusal(status: number, text: string, extra: Record<string, string> = {}): Response {
return new Response(`${text}\n`, {
status,
headers: { ...cors, 'cache-control': 'no-store', ...extra },
})
}
function preflight(): Response {
return new Response(null, {
status: 204,
headers: {
...cors,
'access-control-allow-methods': 'GET, OPTIONS',
'access-control-allow-headers': 'range, if-match, if-none-match',
'access-control-max-age': String(24 * 60 * 60),
},
})
}
A few choices in there are worth spelling out:
- The cache key is the range as asked for, not as resolved. Resolving
bytes=1000-needs the object's size, and asking R2 for it would be the read the cache is there to save. Since an archive never changes, the same range always means the same bytes. - Misses cost two reads, a
headand a rangedget. A range is a miss once per data centre, so I take that over teaching the code R2's own refusals. - Nothing is ever cached as missing. A 404 is usually an archive that's about to be copied in.
- A whole archive is streamed, not cached. Caching tees the stream, and the half bound for the cache is buffered for as long as the reader lags behind. That's fine for a 40 KB glyph and not for 139 GB.
immutable, for a year, to the browser and the edge. This is only safe because a new archive always gets a new path. The path names the Protomaps build and the version of the transliteration (below), so a refresh isplanet/20261123.latin-2.pmtiles, never new bytes under the old name.
Two deployment details matter too. The Worker has to be on your own zone, not workers.dev: the Cache API does nothing on workers.dev, so every request would go to R2. And it's a Worker of its own. TripEagle already had a Worker for trip photos, whose rule is that a signed URL is the whole authority. A basemap is public and nobody's secret, and adding a second kind of request to that Worker would make its one rule impossible to check.
The Worker's real version also answers HEAD from R2's metadata without reading or caching any bytes, and sets an x-basemap-cache: hit | miss | bypass header on every answer. The Cache API leaves no cf-cache-status of its own, so that header is the only way to show from outside that a deploy really caches.
Offline: a regional extract, cut on the server
The phone app has to draw the day's map in airplane mode, where a range request goes nowhere. The usual way to take a MapLibre map offline is an offline pack, and those don't support PMTiles sources on iOS or Android yet (the request, maplibre-native #2352, is still open). MapLibre's ambient cache now keeps PMTiles range reads, but it can evict them, so it promises nothing. What MapLibre Native does read on both platforms is a local archive, pmtiles://file://….
So an offline basemap is a small archive cut out of the planet. pmtiles extract can do that against a remote archive: it reads the directories by range, works out which tiles fall inside the box, and fetches only those, with no download of the planet. A dry run fetches only the directories and says how big the cut would be:
pmtiles extract https://basemap.example.com/planet/20261007.latin-2.pmtiles naxos.pmtiles \
--bbox=25.28,36.88,25.70,37.25 --maxzoom=15 --dry-run
# …
# Extract transferred 2.9 MB (overfetch 0.05) for an archive size of 2.8 MB
The server cuts them, as a background job:
- The box is the bounding box of everything in a region of the trip, padded by about 10 km, since a phone with no signal can't fetch the street someone wandered onto. Its edges snap to a grid, so two trips over the same ground ask for the same extract.
- The depth is z15, the planet's deepest zoom, where street names are drawn, unless the dry run says the cut would be over 150 MB. Then it's cut at z14.
- The key names the planet it was cut from and the box,
offline/20261007.latin-2/25.28_36.88_25.70_37.25.pmtiles, and no trip. Any trip over the same ground shares the file, and a new planet means new keys. - On demand. The app asks for each region of its trip. If the extract isn't cut yet, the server queues the job and answers "not yet", and the app asks again on its next pass over Wi-Fi.
Here's the job, with the queue left out:
// offline-basemap.ts: cut one region's offline basemap and put it in the bucket
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { run } from './run' // spawns a command, resolves with its stdout, rejects on a non-zero exit
interface CutRequest {
planetUrl: string // the planet, as the Worker serves it
extent: { west: number; south: number; east: number; north: number }
path: string // offline/<planet>/<west>_<south>_<east>_<north>.pmtiles, edges .toFixed(2)
bucket: { has(path: string): Promise<boolean>; put(path: string, file: string): Promise<void> }
}
const maxZoom = 15
const cappedMaxZoom = 14
const largestDownload = 150_000_000 // bytes: what a phone fetches on Wi-Fi without anyone noticing
export async function cutOfflineBasemap({ planetUrl, extent, path, bucket }: CutRequest) {
if (await bucket.has(path)) return // the path names the planet and the box: it's the same cut
const bbox = `--bbox=${extent.west},${extent.south},${extent.east},${extent.north}`
const extract = (into: string, zoom: number, ...flags: string[]) =>
run('pmtiles', ['extract', planetUrl, into, bbox, `--maxzoom=${zoom}`, ...flags])
const scratch = await mkdtemp(join(tmpdir(), 'offline-'))
try {
// A dry run writes nothing, but still wants a file it would have written
const said = await extract(join(scratch, 'dry-run.pmtiles'), maxZoom, '--dry-run')
const zoom = sizeOf(said) > largestDownload ? cappedMaxZoom : maxZoom
const file = join(scratch, 'extract.pmtiles')
await extract(file, zoom)
await bucket.put(path, file)
} finally {
await rm(scratch, { recursive: true, force: true })
}
}
// "… for an archive size of 2.8 MB" → 2_800_000
function sizeOf(said: string): number {
const match = /archive size of (\d+(?:\.\d+)?) ([kMGT]?B)\b/.exec(said)
if (!match) throw new Error(`pmtiles extract --dry-run said no size: ${said.slice(-200)}`)
const units: Record<string, number> = { B: 1, kB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12 }
return Number(match[1]) * units[match[2]]
}
The phone downloads the extract on Wi-Fi only, with the sprite and the glyph ranges for the scripts of the trip's countries, and draws from a style that points at local files. It deletes them when the trip ends.
The sizes are smaller than I expected. Measured on one build: Naxos 3 MB, the whole Cyclades 20 MB, Crete 37 MB, Greater Athens 54 MB. An island trip downloads in seconds.
Note that this brings back the "cut on demand" I'd just retired for the live map. The difference is what waits on it. The online map always reads the planet, so a slow or failed cut only means the phone keeps asking. And the extract is fetched ahead of time on Wi-Fi, so it doesn't say where anyone is standing.
Greek streets, Latin letters
Protomaps' style shows labels in a language you choose. With lang: 'en', a label is a feature's name:en, with its local name underneath, or just the local name when there's no name:en. In Greece there usually isn't one. In the tile for Plaka, the old town under the Acropolis, 7 of 266 named streets carry name:en. The Parthenon has one. About four in five points of interest don't. The first trip on TripEagle was to Greece, and a traveller who can't read Greek can't match Κριεζή on the map to Kriezi on the street sign.
Protomaps has no transliteration, and whatever adds a Latin name has to sit somewhere every map reads from. The web maps and the phone all read the one planet archive, and every offline extract is cut from it. So the fix went into the planet itself. TripEagle serves a derived copy of the Protomaps build: on every feature whose name is Greek or Cyrillic and that has no name:en, it sets name:en to the name in Latin letters. The rest of the archive is unchanged.
Putting it in name:en instead of a field of my own means nothing downstream changes. Protomaps' own label code shows "Kriezi" with "Κριεζή" under it, as it would for a real English name, and the style, the fonts and the offline asset list stay exactly as they were. The cost is that a transliteration can't be told apart from a real English name in the tiles. TripEagle's style is the only thing that reads them, so I accepted that.
The tables
Greek is romanized by ELOT 743, the system Greek road signs print in Latin, so the map matches the sign. Most of it is one letter for one, and a few rules read the letters around one. Here they are, for a word already lower-cased and stripped of accents:
// greek.ts: the rules of ELOT 743 that need a letter's neighbours
const voiced = new Set(['β', 'γ', 'δ', 'ζ', 'λ', 'μ', 'ν', 'ρ'])
const vowels = new Set(['α', 'ε', 'η', 'ι', 'ο', 'υ', 'ω'])
const greek: Record<string, string> = { α: 'a', β: 'v', γ: 'g', θ: 'th', η: 'i', χ: 'ch' /* … */ }
const isLetter = (char?: string) => char !== undefined && /\p{L}/u.test(char)
function greekAt(word: string[], i: number): string {
const [before, letter, next] = [word[i - 1], word[i], word[i + 1]]
const atAnEnd = (j: number) => !isLetter(word[j - 1]) || !isLetter(word[j + 2])
if (letter === 'υ' && before === 'ο') return 'u' // ου → ou
if (letter === 'υ' && ['α', 'ε', 'η'].includes(before)) {
return vowels.has(next) || voiced.has(next) ? 'v' : 'f' // αυ → av or af
}
if (letter === 'μ' && next === 'π') return atAnEnd(i) ? 'b' : 'm' // μπ → b at an end, mb inside
if (letter === 'π' && before === 'μ') return atAnEnd(i - 1) ? '' : 'b'
if (letter === 'γ' && ['γ', 'ξ', 'χ'].includes(next)) return 'n' // γγ → ng
return greek[letter] ?? letter // one letter for one; spaces and digits pass through
}
So Ευαγγελίστρια comes out Evangelistria and Μπουμπουλίνας Boumboulinas. The real version also handles case (Θ is "Th" in a word and "TH" in one written in capitals), accents and the diaeresis, which split a pair of vowels that would otherwise join (Προϋπολογισμός).
Cyrillic uses one BGN/PCGN-style table for every language that writes it. A tile doesn't say which country a name is in, and one readable table beats national exactness: Bulgarian Щ comes out "Shch", not "Sht". There's one exception. A name containing a letter only Ukrainian and Belarusian write (і, ї, є, ґ, or an apostrophe inside a word, where Russian writes ъ) takes Ukraine's own values for и, г, й, ю, я and the rest, because Russian's и would make Київ "Kiyiv". That name says its own language, so this isn't a guess about the country.
Rewriting a tile without decoding it
Each tile is a Mapbox Vector Tile, a protobuf message of layers, and each layer keeps its keys and string values in tables that features point into by index. The rewrite doesn't decode the tile and build it again. A layer with no Greek or Cyrillic name is copied as the bytes it was. In a layer that has some, name:en and the new strings go at the end of its key and value tables, so every index the other features hold still points where it did, and only the features that gain a name have their tags written again.
Most of the world's tiles have no Greek or Cyrillic in them at all, so the first check doesn't parse anything. It looks for UTF-8 lead bytes:
// Could these bytes hold a Greek (U+0370–U+03FF, U+1F00–U+1FFF) or
// Cyrillic (U+0400–U+052F) letter? A yes only means the tile gets read.
function mayHoldGreekOrCyrillic(tile: Uint8Array): boolean {
for (let i = 0; i < tile.length - 1; i++) {
const [lead, next] = [tile[i], tile[i + 1]]
const continuation = next >= 0x80 && next <= 0xbf
if (lead >= 0xcd && lead <= 0xd4 && continuation) return true
if (lead === 0xe1 && next >= 0xbc && next <= 0xbf) return true
}
return false
}
And a tile that comes back unchanged keeps its compressed bytes, so it isn't gzipped again:
const tile = gunzip(stored)
const latin = latinTile(tile) // the very same array when nothing was added
const out = latin === tile ? stored : gzip(latin)
140 GB, with no disk
The derived planet has to be written somewhere, and 140 GB doesn't fit comfortably on a laptop or through a home connection. So a throwaway machine (on Fly.io, next to both ends) reads the Protomaps build by range, rewrites it, and writes it to R2 as one multipart upload, in one pass, without either archive ever landing on a disk. The machine removes itself when the job exits.
That works because of how the Protomaps build is laid out. It's clustered: the header and root first, then the tile data in tile-id order, then the metadata and leaf directories. So the job walks the directories in order and reads the tile data front to back in 64 MB ranges, three ahead, retrying any range the server drops. A tile that changes size moves every tile after it, and directory entries that point at a tile read earlier (the shared ocean tiles) are looked up in a sorted list of only the tiles that changed size.
The hard part is the head. The header and root directory are the first bytes of the archive, and they say where everything else ended up, which isn't known until the end. A multipart upload doesn't care about order, though. So the sink holds part 1 back, sends every later part as soon as it's full, and sends part 1 last:
// The archive's first headLength bytes are only known at the end
interface Sink {
append(bytes: Uint8Array): Promise<void> // everything after the head, in order
finish(head: Uint8Array): Promise<void> // the head, sent last as part 1
}
The head's length is fixed in advance: the header and root are padded to exactly 16 KiB, the room the spec gives them, so the job knows where part 2 starts before it knows what part 1 says. R2 asks for every part but the last to be the same size, so part 1 can't just be the 16 KiB head. It's the head followed by exactly enough of the first appended bytes to fill a 64 MB part. Everything after that goes out in 64 MB parts as it's written.
The run for the October build took a few hours, gave Latin names to 7.7 million tiles, and wrote a 139.0 GB archive. A script then checks what the Worker serves: a range comes back as a 206, the header parses, its tile counts, zooms and bounds match the original build's, and the archive is as long as its header says. The Plaka tile read back from it has Adrianou, Kydathinaion, Kriezi, Mnisikleous and Tripodon.
What it costs
At TripEagle's scale, the hosted options are free, and that's worth saying plainly:
| Option | Free each month | After that |
|---|---|---|
| Mapbox GL JS | 50,000 map loads | $5 per 1,000 loads |
| Google Maps JavaScript API | 10,000 dynamic map loads | $7 per 1,000 loads |
| MapTiler Cloud | 5,000 sessions, 100,000 requests | from $30 a month |
| One planet on R2 + Worker | 10 GB of storage, 10 M Class B reads | about $2 a month in storage |
Prices as published in September 2026.
The self-hosted line is mostly storage: 139 GB at $0.015 per GB a month. R2 charges nothing for egress, the Worker's cache absorbs most reads before they reach the bucket, and the extracts are megabytes. The bill doesn't grow with readers the way a per-load price does, but at a few hundred map loads a month, that isn't why you'd do this either.
The real costs are elsewhere:
- One more deployable. A Worker with tests, a bucket and an uptime check.
- Keeping the planet current is a chore. Nothing refreshes it on its own. Protomaps keeps each daily build for about a week, so a refresh is running the script against a recent one and changing one constant to move the path. A map a year old still finds you a café, so it's rarely urgent.
- One copy for everything. If the archive is missing, every map is missing its streets at once. The screen was built to stand on its pins and names without a basemap, so that's a degraded map, not a broken page.
- Attribution is yours to keep. "© OpenStreetMap contributors", visible and linked. It can collapse, but it can't disappear.
In exchange, the sentence "no page makes a request to a map provider" is literally true. A tile request names no trip and no region: every reader of every trip reads the same archive. And the labels are mine to fix in the data itself, which a hosted tile API doesn't offer.
What to take from this
- A tile request is location data. If your map shows where people are, whoever serves the tiles learns it too, and the big providers' terms don't let you proxy them.
- PMTiles makes a world map a file. Anything that answers range requests can serve it, and the planet is about 140 GB.
- Host the planet, not regions. A region-sized extract fails the first time someone looks from outside it, and the planet costs about $2 a month on R2.
- Cache each range as its own entry, stored as a 200 with the range in a header of your own, since the Cache API won't take a 206. Run the Worker on your own zone so the cache works at all.
- Make archives immutable and put the version in the path. Then a year of
immutablecaching is safe. - For offline, cut an extract on the server with
pmtiles extract, sized by a dry run first, and key it by planet and box so trips share it. - Fix labels in the data, not the renderer. Writing transliterations into the field the style already reads means the web, the phone and every offline extract get them for free.
- Stream big rewrites. A clustered archive can be rewritten in one pass, and a multipart upload lets you send the first bytes last.
