pg-tileserver: a PostGIS vector tile server in Go, built to learn how tiles are made
You have a PostGIS table with a few hundred thousand geometries and you want it on a web map. Sending the whole table to the browser as GeoJSON does not scale: the file is huge, and the browser has to parse and draw everything even when the user is looking at one street.
Vector tiles solve this. The map asks only for the small squares it is showing, at the zoom level it is showing, and each square carries only the features inside it. There are good servers that do this from PostGIS, pg_tileserv and Martin among them. I wanted to understand what they do, so I wrote a small one.
pg-tileserver is a vector tile server in Go that turns PostGIS tables into Mapbox Vector Tiles with ST_AsMVT and ST_TileEnvelope. It discovers layers on its own, serves TileJSON, keeps an in-memory LRU cache and ships a MapLibre preview page. It is a learning project in the spirit of those two servers, not a replacement for them.
What it does
Layer discovery. At startup the server reads PostGIS's geometry_columns view. For each geometry column it keeps the attribute columns of MVT-friendly types (text, integers, floats, numeric, bool), picks an integer id, gid, fid or ogc_fid as the feature id, and computes WGS84 bounds with ST_Extent. Tables outside public are named schema.table. Tables with several geometry columns get table.column. Rows with SRID 0 are skipped.
Tiles and TileJSON. The endpoints are few:
GET /layers: discovered layers with columns, SRID, bounds and TileJSON URLGET /tiles/{layer}.json: TileJSON 3.0.0GET /tiles/{layer}/{z}/{x}/{y}.pbf: the MVT tile (.mvtis also accepted)GET /stats: cache countersGET /health: liveness
A cache. Tiles go through an LRU cache bounded by bytes and keyed layer/z/x/y. Responses say X-Cache: HIT or MISS.
A preview page. Open the root URL and you get a MapLibre page that shows every discovered layer over an OSM basemap. Click a feature to see its attributes. The page is embedded in the binary.
How to use it
Install the binary with Go:
go install github.com/AbdeldjalilChougui/pg-tileserver/cmd/pg-tileserver@latest
To try it with the seed data, clone the repository and use the Docker Compose file, which starts PostGIS 16 with sample layers:
git clone https://github.com/AbdeldjalilChougui/pg-tileserver.git
cd pg-tileserver
docker compose up -d --wait db # PostGIS 16 + seed data on 127.0.0.1:55433
go run ./cmd/pg-tileserver # http://localhost:7800/
docker compose down -v # when done
Then open http://localhost:7800/ for the preview.
Configuration is by flags or environment variables: -db (DATABASE_URL), -addr (ADDR, default :7800), -base-url (BASE_URL), -minzoom, -maxzoom (16), -cache-mb (64, and 0 disables the cache), -max-age (1h), -max-features (50000) and -v.
What I built from scratch
The code is split into small packages:
cmd/pg-tileserverflags, pool, wiring, graceful shutdowninternal/tileXYZ math (parse, bounds, lon/lat -> tile)internal/catalogdiscovery, tile SQL builder, TileJSONinternal/cachethread-safe LRU bounded by entries and bytesinternal/serverHTTP handlers + PostGIS sourceweb/embedded MapLibre previewdb/initseed SQL run by the postgis containerintegration/end-to-end tests against docker-compose (build tag)
The heart of it is one SQL statement, generated once per layer in internal/catalog/layer.go:
SELECT ST_AsMVT ( mvt . * , 'cities' , 4096 , '__geom' , 'id' ) FROM ( SELECT ST_AsMVTGeom ( ST_Transform ( t . "geom" , 3857 ) , ST_TileEnvelope ( $1 , $2 , $3 ) , 4096 , 64 , true ) AS __geom , t . "id" , t . "name" , . . . FROM "public" . "cities" AS t WHERE t . "geom" && ST_Transform ( ST_TileEnvelope ( $1 , $2 , $3 , margin => 0.015625 ) , 4326 ) LIMIT 50000 ) AS mvt WHERE mvt . __geom IS NOT NULL
PostGIS does the hard work. ST_TileEnvelope gives the square for a z/x/y, ST_AsMVTGeom clips and scales each geometry into tile coordinates, and ST_AsMVT encodes the rows into the protobuf the map expects. The server's job is to build this query correctly and get out of the way.
What I learned
Transform the envelope, not the table. This is the detail I am most glad to have understood. The bbox filter transforms the (buffered) tile envelope into the table's SRID, not the other way round. That way the GiST index on the native geometry column is used. Transforming every row to 3857 first and filtering afterwards would give the same tiles and ignore the index. Tables already in 3857 skip both transforms.
Quote identifiers, bind values. Table and column names come from the database catalog, so they are quoted in the generated SQL. The z, x and y values come from the URL, so they are bind parameters. Mixing the two up is how an innocent tile server becomes an SQL injection.
An empty tile is a valid answer. The server validates z/x/y and checks the layer's zoom range. Then it looks up the cache and queries with a timeout. Empty tiles return 204 No Content, which MapLibre treats as empty. Responses carry Content-Type: application/vnd.mapbox-vector-tile, Cache-Control and CORS *.
TileJSON has to know its own address. The tile URLs inside TileJSON come from -base-url or from the request host, and X-Forwarded-Proto is honoured. Without that, a server behind a proxy hands out URLs that do not work.
Split what needs a database from what does not. The unit tests run with no database:
go test ./... # unit tests, no database
docker compose up -d --wait db
go test -count=1 -tags integration ./integration/ # discovery, real tiles, cache, TileJSON
docker compose down -v
The unit tests cover tile math, the LRU, the SQL builder (quoting, 3857-vs-4326 paths, limits, id column), TileJSON, and every HTTP path against a fake source: caching, 204s, 400/404/500/504 and base URLs. The integration test checks that the three seed layers (points in 4326, lines in 4326, a hexagon grid in 3857) are discovered with the right columns and bounds, and that real tiles contain the layer names and attributes.
Things to know
- Layers are discovered once at startup. Restart the server to pick up new tables.
- There is no per-layer config (zoom ranges, column filters, simplification) and no function sources or query parameters.
- Bounds use
ST_Extentover the whole table, which can be slow on very large tables. - Tiles are not gzip-compressed by the server. Put a reverse proxy in front for that.
- The cache is in-process and lost on restart. Concurrent misses for the same tile are not de-duplicated.
- The preview page loads MapLibre from unpkg and OSM raster tiles from
tile.openstreetmap.org. - The seed data in
db/init/01-seed.sqlis hand-typed approximate city coordinates, made-up straight "corridors" and a generated hexagon grid. It is not an extract of any dataset.
Why I built it
Serving vector tiles from PostGIS is a solved problem, which is exactly why it makes a good exercise: the reference tools exist, and the building blocks (ST_AsMVT, ST_TileEnvelope) are part of PostGIS. What I did not know was how little glue sits between a table and a tile, and which details in that glue matter: the index-friendly filter, the quoting, the 204, the cache key. Writing a small server end to end was the shortest way to find out. For real workloads, use pg_tileserv or Martin.
Get the code
The source, the Docker Compose setup, the seed data and the tests are on GitHub: https://github.com/AbdeldjalilChougui/pg-tileserver. The code is MIT licensed. The basemap in the preview is © OpenStreetMap contributors (ODbL). Issues and pull requests are welcome.
Originally published at abdeldjalilchougui.biz.
Comments
No comments yet. Start the discussion.