Introducing a new way to review your PRs.

Read the announcement

maplibre / martin

Blazing fast and lightweight PostGIS, MBtiles and PMtiles tile server, tile generation, and mbtiles tooling.

View on GitHub

22 documents · Updated Nov 23, 2026

docs / mbtiles-storage

MBTiles storage

The MBTiles library provides a shared storage and access model for tile archives backed by SQLite. It lets serving, generation, inspection, validation, and archive-transfer flows use tile coordinates, tile bytes, and tileset metadata without depending on one physical table layout.

Storage model

An MBTiles file is a SQLite database that maps a tile coordinate to binary tile data. The library keeps the file reference separate from an open connection and detects the file layout before operations that need layout-specific behavior.

This diagram shows how a tile request or archive task reaches the common tile view and then the layout-specific storage.

flowchart LR
    A[Tile request or archive task] --> B[MBTiles access model]
    B --> C{Detected layout}
    C --> D[Coordinate and tile row]
    C --> E[Shared tile data]
    C --> F[Cache entry]
    B --> G[Metadata key-value rows]
    D --> H[Tile bytes or tile stream]
    E --> H
    F --> H

Callers use XYZ coordinates. The file stores the Y value in the TMS direction. The access model performs this conversion at the boundary so serving and archive flows use the same coordinate contract.

Coordinate boundary

The coordinate boundary also checks that a stored index is valid for its zoom level. Invalid rows are rejected instead of being converted into an unusable tile coordinate.

References: crates/…/mbtiles.rs• L337-412 crates/…/mbtiles.rs• L414-480 crates/…/mbtiles.rs• L778-786 crates/…/streams.rs• L44-138

Schema families

The library supports storage layouts for direct lookup, per-tile identity, shared tile data, and persistent web caching. Schema detection checks the shape of the database and then lets the common tiles view serve as the read contract where possible.

Flat layouts

The flat layout stores one row per coordinate with the tile bytes in the same table. The flat-with-hash layout adds a tile hash so validation and change checks can inspect each tile without changing the basic coordinate lookup model.

The flat layout fits tilesets with few repeated blobs. The hashed form adds content checks at the cost of storing an identity value for each row.

References: crates/…/validation.rs• L219-236 crates/…/init-flat.sql• L1-7 crates/…/init-flat-with-hash.sql• L1-16

Normalized layouts

Normalized layouts store each distinct tile blob once and link coordinate rows to that shared content. The current dedup-id form uses an integer link. The older hash form uses map and images with the tile content hash as the link.

Both forms preserve a common coordinate-and-bytes view. The hash form can also expose a hash view for readers that need tile identity. The dedup-id form separates the storage link from the content hash and does not promise a per-tile hash in the read result.

References: crates/…/validation.rs• L142-217 crates/…/validation.rs• L237-256 crates/…/init-normalized.sql• L1-21 crates/…/init-normalized-dedup-id.sql• L1-21

Cache layout

The cache layout is a non-standard MBTiles form for persistent web-tile caching. It stores fetched time, expiry time, and an upstream tag with each tile while exposing tile bytes through a standard-shaped view.

Cache state belongs to the cache use case. A normal tileset reader can still read its tile data, but archive patch flows cannot treat cache expiry and upstream tags as ordinary tileset content.

Cache reads return expired entries with their stored expiry. The caller decides whether to serve stale data, revalidate it, or fetch it again. An empty blob records a cached negative response, while no row means that the coordinate is not cached.

References: crates/…/cache.rs• L1-25 crates/…/cache.rs• L71-87 crates/…/cache.rs• L137-164 crates/…/validation.rs• L247-256 crates/…/init-cache.sql• L1-18

Metadata and content identity

The metadata table describes the tileset independently of its tile layout. The library turns its key-value rows into TileJSON data for consumers and keeps content identity separate so a change to tile bytes can be checked even when the layout changes.

Tileset metadata

Metadata can describe the name, bounds, center, zoom range, attribution, format, compression, layer type, vector layers, and custom application data. Reads reconcile declared zoom ranges with the zooms present in the tile view, so consumers receive a range grounded in stored content.

Metadata edits support both setting and deleting keys. The command-line update flow applies computed zoom and compression values with explicit edits in one transaction, which keeps a rejected edit from leaving a partial update.

References: crates/…/metadata.rs• L43-63 crates/…/metadata.rs• L144-275 crates/…/metadata.rs• L278-358 crates/…/mbtiles.rs• L105-119 crates/…/mbtiles.rs• L347-360

Hash identity

agg_tiles_hash is a content signal for the tile set as a whole. Its meaning depends on the recorded hash_algorithm; when that key is absent, the library uses the historical MD5 default. Supported algorithms include MD5, FNV-1a, FNV-1a decimal, xxHash64, and XXH3.

Per-tile hashes exist only in layouts that store them or expose them through a hash view. The aggregate hash is computed in coordinate order, which gives copy, diff, patch, and validation flows a stable way to compare tile content. A diff records the expected hash before application and the expected hash after application so a patch can check both sides of the change.

Identity levelPurpose
Per-tile hashDetect a changed or corrupted tile when the layout stores tile identity
Aggregate hashRepresent the ordered content of the whole tile set
Normalized integer linkPoint to shared data without being the content hash

References: crates/…/validation.rs• L23-60 crates/…/validation.rs• L342-381 crates/…/validation.rs• L763-855 crates/…/validation.rs• L1008-1068 crates/…/diff_validation.rs• L49-76

Metadata extent updates

The update model derives minzoom and maxzoom from stored tiles and detects compression from tile content. It can reset the declared range, grow it only when content extends beyond it, or report the difference without writing.

References: crates/…/update.rs• L9-20 crates/…/update.rs• L100-159 crates/…/queries.rs• L135-157

Connection model

The library offers direct connections for controlled work and a read-only pool for concurrent serving. Both paths use the same file identity, schema detection, coordinate conversion, metadata, and tile-access rules.

Direct connections

Mbtiles is a reference to a file and does not open it when created. A caller chooses an existing read-write connection, a connection that creates a new SQLite file, or a read-only connection. A new file must receive a selected schema before it can store tiles.

The same file reference can also be attached to another SQLite connection. This supports archive comparison and transfer flows that read source and destination databases together.

References: crates/…/mbtiles.rs• L74-92 crates/…/mbtiles.rs• L161-335 crates/…/queries.rs• L83-108

Read pools

MbtilesPool is the serving interface for concurrent reads. It opens read-only SQLite connections, acquires one for each operation, and returns it when the operation ends. Callers can share one pool across request tasks without managing connection lifetime for each tile lookup.

References: crates/…/pool.rs• L75-125 crates/…/pool.rs• L127-197 crates/…/pool.rs• L243-320

Tile data access

The data-access layer covers point reads, existence checks, scans, and writes. It selects the layout-specific source behind the shared tile contract, so higher-level systems can work with coordinates and bytes instead of table names.

Tile reads and scans

Point reads return tile bytes or no result for an absent coordinate. Existence checks avoid reading the blob when a caller only needs presence. Streams support archive-scale scans of coordinates or tiles, while a combined tile-and-hash read avoids a second lookup when identity is needed.

Streams keep the connection borrowed until the stream is dropped and do not promise row order. A stored row can have no tile blob, so a tile stream can return a coordinate with no data. Invalid stored indices produce an error rather than an invalid coordinate.

References: crates/…/mbtiles.rs• L337-412 crates/…/mbtiles.rs• L414-580 crates/…/streams.rs• L44-138

Tile writes

Batch writes use a transaction and a caller-selected duplicate rule. For normalized layouts, the write path creates or reuses shared content and then links each coordinate to it. Bulk writing supports archive generation by keeping transaction work aligned with the writer's batch boundaries.

Cache bulk writes create entries with unknown fetch time, no expiry, and no upstream tag. Cache-specific writes can replace a tile with cache metadata or update only that metadata during revalidation.

References: crates/…/mbtiles.rs• L582-760 crates/…/cache.rs• L166-228 crates/…/copier.rs• L545-650 crates/…/CHANGELOG.md• L37-55

Schema validation

Validation checks SQLite integrity, tile coordinate and data types, layout links, stored per-tile hashes, and the aggregate content hash when requested. Schema detection also requires a unique coordinate constraint so one coordinate has one defined tile value when a caller writes or replaces tiles.

Validation can use a quick or full SQLite integrity check. It rejects unknown hash algorithms, invalid tile values, missing normalized content, incorrect stored hashes, and aggregate hash mismatches. The same checks protect diff and patch flows when validation is requested.

References: crates/…/validation.rs• L303-340 crates/…/validation.rs• L549-710 crates/…/validation.rs• L712-833 crates/…/validation.rs• L904-1006 crates/…/errors.rs• L55-110 crates/…/diff_validation.rs• L187-219

Archive summaries

The summary view turns stored tile data into a compact archive profile. It reports the detected schema, SQLite size data, tile counts, tile-size ranges, zoom coverage, and geographic bounds for the whole archive and each zoom level.

References: crates/…/summary.rs• L19-44 crates/…/summary.rs• L112-200

Archive operation boundary

The library's storage model is the base for copy, filter, merge, diff, patch, pack, unpack, cache purge, and metadata commands. These operations preserve the shared coordinate and metadata contracts while choosing which content and identity values to carry forward.

Copy and patch flows

Copy can move tiles, metadata, or both between supported layouts. It can filter by zoom or bounds, select the destination layout and hash algorithm, and define how duplicate coordinates behave. A copy into the cache layout keeps cache fields from a cache source and leaves them unknown for other sources.

Diff and patch flows use aggregate hashes to identify the expected before and after content. Diff creation computes missing hashes without changing its inputs. Patch creation and application check the expected base before writing, then check the expected result after the change. In-place application keeps the tile and metadata change in one transaction, so a failed result check rolls the file back unless force mode is used.

Cache files cannot be patch destinations because patch data cannot preserve cache metadata. Binary tile patches are limited to flat-family destinations supported by the patch format. Normalized destinations use their content identity rules when whole-tile patches add or remove shared blobs.

References: crates/…/copier.rs• L139-232 crates/…/copier.rs• L235-336 crates/…/copier.rs• L339-448 crates/…/patcher.rs• L14-169 crates/…/errors.rs• L118-211 crates/…/diff_validation.rs• L78-184

Transcoding

Transcoding moves tile content through a caller-supplied transform while preserving the source coordinate mapping in a new archive. It transforms each unique stored blob once when the source is normalized, or uses a bounded content cache for repeated small blobs in flat layouts.

The destination can use a supported standard schema and receives the source metadata by default. Cache files are not transcoding inputs or outputs, and some normalized schema changes are refused when the source identity model cannot be preserved safely.

References: crates/…/transcoder.rs• L81-123 crates/…/transcoder.rs• L167-238 crates/…/transcoder.rs• L241-329 crates/…/errors.rs• L234-240

For archive maintenance flows, see MBTiles archive operations. For file and remote source boundaries, see file and remote tile sources. For tile generation input and output movement, see tilegen inputs and output sinks.

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep every layout's shared tile-view contract aligned with layout detection, point reads, streams, writes, copy queries, and validation.
  • Keep XYZ-to-TMS conversion aligned across point reads, streams, filters, cache access, and writes.
  • Keep hash_algorithm, per-tile hashes, aggregate hashes, copy rehashing, diff checks, and patch checks on the same algorithm contract.
  • Keep diff before/after hash metadata aligned with base-file checks, result checks, force behavior, and transaction rollback.
  • Keep normalized coordinate links aligned with deduplication rules and with the layout selected by copy, patch, and transcode operations.
  • Keep metadata reads, writes, deletes, zoom reconciliation, compression updates, and copied metadata consistent with TileJSON consumers.
  • Keep read-pool methods read-only and connection-scoped when changing direct access methods.
  • Keep cache-only expiry, upstream fields, negative entries, and purge policy out of ordinary tileset and patch semantics.
  • Keep transformed normalized content IDs aligned with the destination map when a transform changes tile bytes.

Important failure modes

TriggerConsequenceGuard
The database matches no supported layout or lacks a unique coordinate constraintType detection or safe tile access failsDetect and validate the layout before using it for writes or transfers
A stored coordinate is outside its zoom rangeY conversion can produce an invalid tile or an errorValidate tile indices before conversion and serving
hash_algorithm is unknown or differs between source and destinationPer-tile or aggregate comparisons can report false corruption or fail a copyReject unknown algorithms and rehash when the destination algorithm differs
Metadata declares a zoom range that does not match stored tilesConsumers can request levels that do not existReconcile metadata on read or run the metadata update flow
A normalized link points to no content rowA coordinate exists but its tile bytes cannot be readRun layout validation before serving or transferring the archive
A diff has no valid content hash or its base hash does not matchThe wrong source can be changed or a diff cannot be trustedRequire diff hash metadata and check the base before writing unless force mode is explicit
The expected post-patch hash does not match the resultA patch can produce content different from its declared targetCheck the result hash and roll back in-place changes unless force mode is explicit
An expired cache entry is treated as freshA caller can serve stale content without revalidationCheck the returned expiry and apply the caller's stale or refetch policy
Cache purge reaches the schema's fixed overheadThe cache cannot shrink to an arbitrarily small byte targetTreat the size limit as a live-data budget and account for schema overhead
A binary patch targets a cache or normalized destinationPatch data cannot preserve the required cache fields or patch representationUse a supported flat-family patch destination
A transform changes normalized tile bytes but the destination keeps source IDsCoordinate links point to the wrong content or become invalidRecompute destination content identity and rebuild the map links

Key files

FileWhy to read it
crates/…/mbtiles.rsMain file reference, coordinate boundary, tile reads, streams, and tile writes
crates/…/validation.rsLayout types, hash identity, schema checks, and archive integrity rules
crates/…/cache.rsPersistent cache data, freshness metadata, negative entries, and purge behavior
crates/…/metadata.rsTileJSON mapping, custom metadata, and aggregate identity exposure
crates/…/update.rsMetadata extent and compression update behavior
crates/…/pool.rsRead-only pooling for concurrent tile serving
crates/…/queries.rsSchema creation and shared tile extent queries
crates/…/summary.rsArchive size, zoom, tile-count, and geographic summary data
crates/…/copier.rsCross-layout copy, filtering, hash mapping, diff, and patch boundaries
crates/…/patcher.rsIn-place patch application, base checks, transaction safety, and aggregate-hash checks
crates/…/errors.rsFailure contracts for invalid schemas, hashes, copies, and patches
crates/…/transcoder.rsTransform-based data movement between standard storage layouts
crates/…/mbtiles.rsUser-facing archive, metadata, validation, cache, pack, and unpack commands
crates/…/diff_validation.rsGuarantees for missing hashes, stale bases, post-patch checks, rollback, and hash algorithms
crates/…/init-normalized-dedup-id.sqlCurrent shared-content layout for new normalized files
crates/…/init-cache.sqlPersistent cache layout and its tile compatibility view