Skip to content

Tile Serving ​

The map renders large geometry layers (per-segment density, per-event markers, road sections) as Mapbox Vector Tiles (MVT) rather than fetching JSON GeoJSON for every viewport change. Tiles are produced by PostGIS functions in the tiles schema. The NestJS TilesModule at /api/tiles/* calls them as the application user and applies the viewer's company scope; a request without a session gets an empty tile. pg_tileserv is still defined in Docker Compose, but the app no longer reads from it.

Why MVT ​

The legacy path (/api/accidents/map, /api/road-sections/geometries) re-serialised the same ST_AsGeoJSON(...)::json payloads on every request, ran ST_SimplifyPreserveTopology per request for roads, and used a custom degree-aligned tile grid that no HTTP cache could key on. MVT gives:

  • 5–10× smaller wire payloads than equivalent GeoJSON.
  • Stable {z}/{x}/{y} URLs that the browser cache can key on.
  • Native Mapbox clustering on a vector source, removing the MAX_MARKERS = 500 cap the JSON path imposed.
  • Pre-sliced simplification via ST_AsMVTGeom quantisation to 4096 units — no per-zoom manual tolerances.

Components ​

Browser
  │
  │  GET /api/tiles/accidents/{z}/{x}/{y}.pbf?reason=...
  │  GET /api/tiles/accidents/points/{z}/{x}/{y}.pbf?...
  │  GET /api/tiles/breaking/{z}/{x}/{y}.pbf?...
  │  GET /api/tiles/breaking/points/{z}/{x}/{y}.pbf?...
  │  GET /api/tiles/speed/{z}/{x}/{y}.pbf?...
  ▼
nginx (frontend)
  • proxies /api/ to the API
  • returns 404 for every /tiles/ path
  ▼
NestJS API (TilesController, TilesService)
  • resolveCompanyScope(user) → road_ids
  • no session, or a company without roads → empty tile, no query
  • validates (z, x, y), DTO-whitelists filters
  • SELECT tiles.accidents_filtered($1, …) as the gis user
  ▼
PostgreSQL + PostGIS, schema "tiles"
  ├── accidents_filtered(z,x,y, …, road_ids)
  ├── accidents_points(z,x,y, …, road_ids)
  ├── breaking_filtered(z,x,y, …, road_ids)
  ├── breaking_points(z,x,y, …, road_ids)
  ├── speed_lines(z,x,y, …, road_ids)
  ├── accidents_density(z,x,y)    (no caller; EXECUTE revoked in migration 039)
  └── breaking_density(z,x,y)     (no caller; EXECUTE revoked in migration 039)

pg_tileserv (compose service "tileserv", port 7800): still defined, unused.
Its database role has no grants left.

pg_tileserv Docker service (unused) ​

Still defined in docker-compose.yml, but nothing in the app reads from it:

yaml
tileserv:
  image: pramsey/pg_tileserv:20250131
  ports: ["127.0.0.1:7800:7800"]
  environment:
    DATABASE_URL: "postgresql://tileserv:${TILESERV_DB_PASSWORD:-tileserv_secret}@postgres:5432/gis_data?sslmode=disable"
    TS_BASEPATH: "/tiles"
    TS_CORSORIGINS: "http://localhost:8000"
  depends_on:
    postgres:
      condition: service_healthy

It connects as the tileserv Postgres role, created in migration 1700000000017-CreateTileFunctions; migration 1700000000033-RotateTileservPassword sets its password from TILESERV_DB_PASSWORD. The role has no grants left:

  • 1700000000036-RevokeUnusedTileservGrants revoked SELECT on breaking and analytics.breaking_by_segment, which had let pg_tileserv publish the raw braking table.
  • 1700000000039-RevokeAllTileservGrants revoked the rest: EXECUTE on tiles.accidents_density and tiles.breaking_density (from tileserv and from PUBLIC), SELECT on analytics.subsegments and analytics.density_by_segment, and USAGE on the tiles and analytics schemas.

pg_tileserv publishes what its role can SELECT or EXECUTE, so it has no tile layer left to serve. The service, the role and TILESERV_DB_PASSWORD stay for now; removing pg_tileserv is a separate decision.

Frontend nginx routing ​

frontend/nginx.conf.template proxies /api/ to the NestJS service and returns 404 for every /tiles/ path, so it exposes nothing from pg_tileserv. The Vite dev server likewise proxies only /api; the /tiles dev proxy and the TILESERV_URL variable are gone. Tile requests go to /api/tiles/* on the app's own origin, so the browser sends the JWT cookie with them.

NestJS TilesController (api/src/tiles/) ​

The controller serves every tile the apps request, with or without filters:

  • Filter-aware tiles — clients pass query-string filters; the controller validates them via AccidentFiltersQuery / BreakingTileFilters DTOs and re-encodes them when calling the SQL function. No client value reaches the tile function unless it survived class-validator whitelisting.
  • Company scope — resolveCompanyScope(user) produces a server-side road_ids array that is passed as the function's last argument. The scope is never sourced from the URL. If a scoped user has zero roads, the controller short-circuits to an empty MVT before even hitting Postgres.
  • Session required for data — the controller class is @Public(), so the guard lets a request without a session through, but resolveCompanyScope(undefined) scopes it to an empty road set and it gets the same empty MVT (200, zero bytes) instead of a 401.
  • ParseIntPipe + assertValidTile — (z, x, y) are bounded by MAX_ZOOM = 22 and the per-zoom max tile index, rejecting nonsense coordinates with 400 instead of running the SQL.

Both density and points handlers respond with Content-Type: application/vnd.mapbox-vector-tile and Cache-Control: private, max-age=300 so browsers can cache, but shared proxies/CDNs cannot. The empty short-circuit tiles are sent with Cache-Control: no-store, and every response sets Vary: Cookie, because the URL is the same for every account and the cookie decides the scope.

TilesService calls the SQL functions as the application user (gis), not as tileserv — this is what enforces the no-EXECUTE-to-tileserv contract on the filtered/points functions.

Tile functions ​

All seven functions live in the tiles schema and are created as STABLE PARALLEL SAFE SQL functions returning bytea. The zoom → segment-size mapping mirrors shared/src/config/segments.config.ts (250 / 500 / 1000 / 2000 / 4000 m), so client-visible behaviour matches the legacy JSON path exactly.

FunctionSource migrationEXECUTENotes
tiles.accidents_density(z,x,y)1700000000017-CreateTileFunctionsrevoked from tileserv and PUBLIC in 1700000000039Unfiltered density from analytics.density_by_segment. Unused: no caller in the app.
tiles.accidents_filtered(z,x,y, reason, type, classification, start_date, end_date, road_ids[], participant_type, participant_sex, participant_injury, age_min, age_max, alcohol_involved)1700000000018 (base) + 1700000000024-AccidentsFilteredParticipants (participants)gis onlyFilter-aware density. CSV main-axis filters split inside SQL with string_to_array; participant args drive an EXISTS join against accident_participants.
tiles.accidents_points(z,x,y, …, sections, …, road_ids[], participant_type, participant_sex, participant_injury, age_min, age_max, alcohol_involved)1700000000019 (base) + 1700000000022-AccidentsPointsSeverity (classification + participants)gis onlyOne MVT point per accident at zoom ≥ 16. Emits accidentclassification + accidentreason so the frontend can paint markers by severity without a detail fetch.
tiles.breaking_density(z,x,y)1700000000020-CreateBreakingTileFunctionsrevoked from tileserv and PUBLIC in 1700000000039Unfiltered braking density. Unused: no caller in the app.
tiles.breaking_filtered(z,x,y, sections, speed_mins[], speed_maxs[], months[], dows[], hour_from, hour_to, road_ids[])1700000000020gis onlySpeed ranges arrive as paired arrays (max is NULL for 100+).
tiles.breaking_points(z,x,y, …same shape…)1700000000020gis onlyPer-event markers.
tiles.speed_lines(z,x,y, month_from, month_to, min_pct85, max_pct85, min_average, max_average, min_pct15, max_pct15)1700000000023-CreateSpeedTileFunctions (base) + 1700000000025-SpeedLinesPct15Filter (pct15)gis onlyPre-aggregates AVG(pct85), AVG(avg), AVG(pct15), MIN(min) per NIRA segment across the month window. All three bounds are post-aggregate filters. The frontend sub-layer toggle picks which emitted property (speedPct85 / speedAvg / speedPct15) drives the paint expression.

No function is granted to the tileserv role. The filtered, points and speed functions are reachable only through TilesService, which controls road_ids server-side.

Adding a tile layer ​

A new layer is a tiles.* function called through TilesModule:

  1. Create the function in a migration, with road_ids integer[] as an argument so the company scope applies.
  2. In the same migration, REVOKE ALL ON FUNCTION ... FROM PUBLIC. Grant nothing to tileserv.
  3. Add a TilesService method that calls the function and a TilesController route that passes the road_ids from resolveCompanyScope(user).

Frontend integration ​

The map composables build every vector source from an /api/tiles/... URL, with the active filters (if any) as the query string:

ts
const base = absoluteTileUrl('/api/tiles/accidents/{z}/{x}/{y}.pbf');
map.addSource('accidents-density', {
  type: 'vector',
  tiles: [qs ? `${base}?${qs}` : base],
});

Mapbox invalidates its tile cache automatically when setTiles([...]) is called with new URLs, so changing a filter immediately re-fetches.

Verification ​

  • curl -i http://localhost:8001/api/tiles/accidents/11/1106/728.pbf without a session cookie returns 200 with Content-Length: 0 and Cache-Control: no-store.
  • The same request with a logged-in session's cookie (curl -b 'access_token=<jwt>' -o tile.pbf ...) returns the tile for that account's company scope; file tile.pbf reports data.
  • DevTools Network panel during map navigation: tile requests go only to /api/tiles/...; responses are 200 OK, Content-Type: application/vnd.mapbox-vector-tile, and orders of magnitude smaller than the legacy /api/accidents/map JSON.
  • Scoped user E2E: a logged-in admin assigned to one company sees points only on their roads, even when calling /api/tiles/accidents/.../.pbf directly (decode with @mapbox/vector-tile).