Part 2 ended with a warning: the Nairobi GTFS feed that most projects start from lists services between January 2019 and December 2020. A graph built from it compiles fine and routes fine. It just describes a city that has moved on.
Part 3 added a second constraint: any change to the transit data, even one stop, means rebuilding the whole graph, and the street network makes that a 17-minute job.
Put together, those two facts define the problem. You need to own the data, and you need a pipeline that turns every edit into a routing graph safely. This part describes that pipeline as it runs for Navigo: a GTFS-shaped database, a validation gate, scoped exports, a rebuild that can roll itself back, and a cache that knows when the graph changed.
1. Why a database, and not a folder of GTFS files
GTFS is an exchange format. It's excellent at describing a network to a router, and poor at being edited by people.
The people who know Nairobi's matatu routes are the SACCOs (the co-operatives that own them), their members, and the staff who map them. They need to move a stage, add a midday headway, split a route into two patterns. Doing that in CSV files inside a zip invites the errors GTFS validators exist to catch: a stop time that refers to a deleted stop, two rows with the same sequence, a calendar that ends before it starts.
So the network lives in PostgreSQL with PostGIS, behind a console where each change is a validated write. GTFS is an output of that database, produced on demand, like the GTFS-Flex, NeTEx and Excel exports that sit behind the same interface.
Three things become possible that a folder of files doesn't give you:
Validation at the source. A form refuses a stop without coordinates. It doesn't wait for a build log to say so.
History. Every create, update and delete on agencies, routes, stops, trips, shapes and vehicles goes through model observers into a snapshot service. That history powers network versioning and "what if" scenarios. (The catch: a raw SQL update bypasses the observers. Writes go through the ORM, or they don't count.)
Several outputs from one truth. The router gets GTFS; open-data portals can get NeTEx; an operator gets a spreadsheet of their own routes.
2. A schema shaped like GTFS
The tables mirror the GTFS files closely: agencies, routes, trips, stops, stop_times, shapes, calendars and calendar_dates, trip_frequencies, fares, pathways and levels for stations. Keeping the shape close to GTFS is deliberate. The export is then a projection, not a translation, and anyone who knows GTFS can read the database.
Two departures from the files are worth it:
Geometry is PostGIS, not text. Stops have a
geographypoint and shapes aLineString. Spatial checks become one SQL predicate (see the validator below), and "stops within 300 m of here" is an index scan.Route patterns are explicit. A matatu route has variants (via Ngong Road or via Kilimani, a short turn at the terminus). Trips reference a
route_pattern, and the patterns are generated from the trips after an import, so the console can show and edit "the variants of route 46" directly.
3. Modelling matatus: frequencies, not timetables
The single most important modelling decision is how to represent a service that has no timetable.
A matatu leaves its terminus when it's full. What riders know, and what operators can tell you, is the rhythm: every few minutes in the morning peak, slower around midday, busy again in the evening. GTFS has a file for exactly that, frequencies.txt:
trip_id,start_time,end_time,headway_secs,exact_times
10106110,06:00:00,09:00:00,300,0
10106110,09:00:00,15:00:00,900,0
10106110,15:00:00,21:00:00,300,0One representative trip carries the stop sequence and the running times between stops. The frequency rows say how often it repeats, and exact_times=0 says the headway is approximate: "about every five minutes", not "at 06:00, 06:05, 06:10".

Navigo's published feed has 295 trips and 792 frequency rows. It is small as a file and, as Part 3 measured, dense as a search problem. That's the trade-off of honest modelling: the data says "a matatu every five minutes" because that's the truth, and the router has to cope with it.
Two consequences ripple through the rest of the system:
"Next departures" must be computed, not read. For a frequency-based trip there is no row saying "08:05". The API derives the next departures at a stop from the headway band active at that moment, and returns an explicit status when there is no departure data at all, rather than a plausible-looking list of invented times.
Rail is timetabled. The SGR's Madaraka Express and the commuter trains run at fixed times, so their trips are ordinary
stop_times. One feed mixes both kinds, and the router handles each correctly.
4. Validate before you build
A build takes 17 minutes. A broken stop time found after the build has cost you 17 minutes and an outage. So the pipeline's first step is a validation gate, and errors stop everything.
The checks run as SQL against the database, before anything is exported:
Code | Check |
|---|---|
| Service IDs exist; every trip has stop times; stop sequences are unique; arrival ≤ departure at each stop |
| Times never go backwards between consecutive stops |
| Calendars don't end before they start |
| Trips point at route patterns that exist |
| Frequency rows have a positive headway and a start before their end |
| A stop is more than 500 m from its trip's shape (warning) |
Most are one query. The monotonic-times check joins each stop time to the next one in the same trip:
SELECT a.trip_id, a.stop_sequence
FROM stop_times a
JOIN stop_times b
ON a.trip_id = b.trip_id AND b.stop_sequence = a.stop_sequence + 1
WHERE a.departure_time IS NOT NULL
AND b.arrival_time IS NOT NULL
AND a.departure_time > b.arrival_time
LIMIT 100;And the geometry check is where PostGIS pays for itself:
WHERE NOT ST_DWithin(p.location::geography, s.path::geography, 500)Errors abort the publish with a message an operator can act on ("departure_time at seq 7 exceeds arrival_time of next stop", with the trip ID). Warnings are logged and the publish continues: a stop 600 m from a hand-drawn shape is usually a shape that needs redrawing, not a reason to block every other change.
Behind this in-house gate sits the canonical MobilityData GTFS validator, run against the exported zip when the JAR is installed. The SQL checks are fast and specific to how the data is edited; the official validator catches the long tail of the specification.
5. Export scopes and feeds as modules
A single national feed is simple until one region has a problem. So exports take a scope:
final class ExportScope
{
public const MODE_ROUTE_TYPES = [
'road' => [[3, 3], [11, 11], [200, 299], [700, 799], [800, 800], [1500, 1599]],
'rail' => [[2, 2], [100, 199]],
'metro' => [[1, 1], [400, 404]],
'air' => [[1100, 1199]],
// tram, monorail, ferry, cable…
];
public function __construct(
public readonly ?string $country = null, // ISO code
public readonly array $regionIds = [], // counties, cities, districts
public readonly array $modes = [], // families above
public readonly array $agencyIds = [], // operators
public readonly string $coverage = 'routes', // or 'inside'
) {}
}A few details make this work in practice:
Modes are families of route types. GTFS has both basic route types (
3= bus) and the extended ones (700–799= bus services,200–299= coaches). A scope that asks for "road" gets all of them, so a feed using extended types isn't silently dropped.Regions are administrative boundaries (counties, cities, districts), stored as polygons. A scope can be "Nairobi and Kiambu counties".
coveragedecides what happens at the edge. A matatu route from the CBD to Kikuyu crosses from Nairobi County into Kiambu. Withroutes, every route that serves the area is exported whole. Withinside, only the part of each trip inside the area. The first is right for routing; the second is right for a county's open-data portal.
The feeds the pipeline publishes are named navigo-*.gtfs.zip. Anything else in OTP's data folder is moved aside to unmanaged/ before the build. Without that, an old hand-copied feed would load next to the new one, and OTP would route on two copies of the same routes.
6. The publish pipeline as one job
Publishing is a button in the console. Behind it is a queued job that runs the steps in order and records each one:

The decisions behind it:
Each step is a row in a log table, updated in place. The console polls it, so an operator sees "Rebuilding the graph (6 min)" instead of a spinner. When something fails, the failing step and its output are right there.
The job runs once. tries = 1 and a 40-minute timeout: a half-finished publish retried automatically is worse than a failed one reported clearly. That has a subtle requirement. Queue workers hand a job to another worker if it runs longer than retry_after. If retry_after is shorter than the job's timeout, a long build is started twice, and the second run marks the first as failed. A preflight check now refuses that configuration:
if (in_array($conn, ['redis', 'database'], true) && $retry <= $timeout) {
$add('queue', 'error', "Queue retry_after ({$retry} s) must be longer than a publish can take ({$timeout} s)…");
}Publishing has its own queue and worker. When one worker served every queue, push notifications and incident escalations waited behind a 17-minute build. The otp queue now has a dedicated worker.
Cancellation is a flag, checked between steps. The console sets a cache key; the job checks it at each boundary, and during the build the rebuild script receives a SIGTERM. Cancelling is never "kill the process and hope".
A preflight catches the boring failures early. Before the button is even enabled, the console runs checks: is the data folder mounted, is there an .osm.pbf to build from, are there 2 GB free for the new ~350 MB graph and its backup, can the queue container reach Docker, does OTP answer its health check. Each says what to fix, in a sentence.
7. Rebuilding with a way back
The rebuild itself is a shell script, rebuild.sh, that the job calls. It does five things:
Checks its inputs: at least one
.osm.pbfand one.gtfs.zip.Reads the image and host folder of the running OTP container with
docker inspect, so the build uses exactly what the server uses, on any machine.Backs up
graph.obj.Stops OTP, runs the build, starts OTP.
On any failure or interruption, puts the backup back and starts OTP.
on_signal() { # a cancel from the console arrives as SIGTERM
[ -n "$BUILD_PID" ] && kill "$BUILD_PID" 2>/dev/null || true
docker rm -f "$BUILDER" >/dev/null 2>&1 || true
restore # previous graph.obj back, OTP started
exit 130
}
trap on_signal INT TERM
# In the background + wait: bash runs traps only between commands,
# and `wait` returns as soon as a signal arrives.
docker run --rm --name "$BUILDER" -e JAVA_TOOL_OPTIONS="$JAVA_OPTS" \
--mount "type=bind,source=${HOST_DATA},target=/var/opentripplanner" \
"$IMAGE" --build --save &
BUILD_PID=$!
if ! wait "$BUILD_PID"; then restore; exit 1; fiThe detail in the middle matters more than it looks. Run in the foreground, docker run would hold the shell for 17 minutes and the cancel would only take effect when the build finished on its own.
The worst outcome of a bad publish is therefore "nothing changed", never "journey planning is down until someone logs in".
After the build, the job polls OTP until it answers (30 tries, 10 seconds apart). Part 3 measured why that's needed: loading the graph takes 38 to 79 seconds.
The honest cost: downtime during the build
Step 4 stops OTP before the build. That's a memory decision. Part 3 measured a 6 GB build heap and a 2.4 GB serving footprint; production runs a larger serving heap for concurrency. Running both at once is possible on a 32 GB server, but it competes with PostgreSQL's 4 GB of shared buffers and everything else on the box.
So today, journey planning is unavailable for the length of a build, 10 to 20 minutes per publish. Publishing is rare enough (a few times a week) and scheduled enough (not at 07:30) that this is an acceptable trade. The fix when it isn't is a blue/green swap: build into a second directory while the current server keeps running, start a second server on the new graph, switch traffic when it's healthy, stop the old one. It needs memory for two servers and one build. Part 8 comes back to it.
8. Retiring cached journeys in one line
The API caches computed journeys for five minutes (Part 5). After a publish, those cached journeys describe the old graph. Deleting them would mean scanning Redis for keys, which is slow and racy.
Instead, the cache key includes a graph epoch, a counter stored in the cache:
$cacheKey = 'otp:journey:v7:'.Cache::get('otp:graph_epoch', 0).':'.md5($request);The last step of a successful publish increments it:
private function flushJourneyCache(): int
{
$epoch = (int) Cache::get('otp:graph_epoch', 0) + 1;
Cache::forever('otp:graph_epoch', $epoch);
return $epoch;
}Every old key becomes unreachable at once, and expires on its own TTL. No scan, no race, and the step's log row says which epoch is now live.
What this buys
The router in Part 2 was correct about whatever data it was given. This pipeline makes the data's correctness someone's job, with tools: operators edit in a console, a validator refuses what would break the build, a scoped export says exactly what is published, the rebuild can't strand the service, and the cache follows the graph.
None of it is algorithmically interesting, and that's the point. A journey planner fails in production far more often because of a stale feed or a half-finished publish than because of its routing algorithm.
Part 5: Orchestration, One API in Front of Several Routing Engines is about what happens at query time: OpenTripPlanner for transit, Valhalla for cars and boda bodas, live traffic from an external API, and how one backend turns all of them into a single, consistent journey.
Technical references
GTFS Schedule reference, in particular
frequencies.txtandexact_times.PostGIS
ST_DWithinongeography.OpenTripPlanner: building and serving graphs.





