Part 2 drew the architecture in one line: the mobile app talks to a Laravel API, and the API talks to OpenTripPlanner. It also left a promise: the distinction between routing and application orchestration becomes important once there is more than one engine.
There is more than one engine now. This part is about the layer in between: what it decides, what it hides, and the handful of patterns that keep several engines looking like one.
1. Why the clients never call an engine directly
It would be simpler, on day one, to let the app call OpenTripPlanner's GraphQL endpoint itself. Four reasons it doesn't:
OTP has no authentication. It belongs on a private network. In production, its port isn't reachable from the internet at all.
Engines change, apps update slowly. OTP 2.10 removed the REST API that the transit engine was built on. Because only the backend knew about it, the app didn't change. A rider on a six-month-old version of the app never noticed.
A journey is more than a route. Fares, next departures, landmarks to board by, live traffic: none of that comes from the router. It needs the database and other services.
Caching and cost control live in one place. Several thousand riders asking about the same morning commute should cost one search, not several thousand.
So the API exposes one endpoint, POST /journey/calculate, with a mode (transit, bus, rail, walk, bicycle, car, motorbike), and everything else is its business.
2. Each engine for what it does best

Engine | Used for | Why it, and not the others |
|---|---|---|
OpenTripPlanner 2.10 | Transit (matatu, rail), walking, cycling | Multimodal, schedule-aware, elevation for cycling and walking |
Valhalla 3.9 | Cars, boda bodas, walk-time isochrones | Real alternative routes, toll avoidance, a motorcycle profile |
TomTom | Live and typical travel times, incidents | Traffic data, but never used to choose roads (Part 7) |
Mapbox and Google Directions | Turn-by-turn wording for walking legs | Richer pedestrian instructions than OTP's steps |
PostgreSQL / PostGIS | Fares, next departures, landmarks, POIs | Navigo's own data |
Valhalla deserves a word, because OTP can route cars. It just can't do two things we needed. It returns one car route, not alternatives, and it can't avoid the Nairobi Expressway: the toll road isn't tagged toll=yes in OpenStreetMap. Valhalla has alternates and costing options, and the toll road can be detected by name in its results. Boda bodas (motorcycle taxis) are banned from the Expressway too, and OTP has no motorcycle profile at all.
3. Dispatch by mode
The first decision is a match:
private function resolveOtpModeString(string $mode): string
{
return match (strtolower(trim($mode))) {
'walk', 'walking' => 'WALK',
'bike', 'bicycle' => 'BICYCLE',
'car', 'drive' => 'CAR',
'motorbike', 'motorcycle', 'boda' => 'MOTORBIKE',
'bus' => 'BUS,WALK',
'rail', 'train' => 'RAIL,SUBWAY,TRAM,WALK',
default => 'TRANSIT,WALK',
};
}From there, two paths:
Transit modes go to OTP as one search (with the search window from Part 3), then through diversity, enrichment and caching.
Street modes fan out into several option requests in parallel. Cars try Valhalla first and fall back to OTP if it's down. Boda bodas go to Valhalla only.
The fallback order is a product decision as much as a technical one. A car route from OTP without alternatives is better than no car route, so OTP backs up Valhalla. A boda route from OTP would use the Expressway, which is worse than nothing, so there is no fallback.
4. One itinerary contract, adapters at the edges
Every engine returns a different shape. OTP 2.10 returns GraphQL with ISO timestamps; OTP's old REST API returned milliseconds; Valhalla returns maneuvers and a precision-6 polyline.
The rest of the backend (fare resolution, landmark annotation, parsing into the app's segments) was written against OTP's REST itinerary. Rewriting all of it for each new engine would have been the expensive option. Instead, each engine gets an adapter that produces that one shape:
private function toRestLeg(array $l): array
{
$route = $l['route'] ?? null;
return [
'mode' => $l['mode'] ?? 'WALK',
'transitLeg' => (bool) ($l['transitLeg'] ?? false),
// Prefer the real-time estimate when OTP has one.
'startTime' => $this->ms($l['start']['estimated']['time'] ?? $l['start']['scheduledTime'] ?? null),
'endTime' => $this->ms($l['end']['estimated']['time'] ?? $l['end']['scheduledTime'] ?? null),
'routeId' => $route['gtfsId'] ?? null,
'routeShortName' => $route['shortName'] ?? null,
'legGeometry' => ['points' => $l['legGeometry']['points'] ?? ''],
// … from/to places, intermediate stops, steps
];
}OtpClient maps GraphQL to that shape; ValhallaService maps Valhalla's trips to the same shape (one leg, a re-encoded polyline, its own instructions as steps). Downstream, a car route from Valhalla and a walk from OTP are parsed by the same function.
The lesson generalises: the boundary with something you don't control is the cheapest place to absorb its changes. When OTP 2.10 removed REST, the change was one new class, not a rewrite of the transit engine.
5. Fan out in parallel
Asking OTP for "the safest bike route" and "the flattest bike route" are separate requests with different preferences. Sequentially, three options cost three round trips. In parallel, they cost the slowest one:
private const STREET_OPTIONS = [
'WALK' => [
'fastest' => ['label' => 'Fastest', 'params' => ['walkSafetyFactor' => 0.0]],
'safer' => ['label' => 'Safer streets', 'params' => ['walkSafetyFactor' => 1.0]],
'step_free' => ['label' => 'Step-free', 'params' => ['wheelchair' => true]],
],
'BICYCLE' => [
'fastest' => ['label' => 'Fastest', 'params' => ['bicycleOptimization' => 'SHORTEST_DURATION']],
'safest' => ['label' => 'Safest', 'params' => ['bicycleOptimization' => 'SAFE_STREETS']],
'flattest' => ['label' => 'Flattest', 'params' => ['bicycleOptimization' => 'FLAT_STREETS']],
],
];
$results = $this->otp->planMany($plans, 20); // Http::pool, one request per optionPart 3 measured these direct street requests at 10 to 200 ms each, so three in parallel cost about as much as one.
Parallel options create a presentation problem: often, the fastest route is the safest. Two identical cards labelled differently look like a bug. So options that land on the same route (within 40 m and 30 s) merge into one card with both labels: "Fastest · Safest".
The same pattern fixed the slowest part of transit planning. Each walking leg gets turn-by-turn wording from Mapbox and Google, at about 1.6 seconds per leg, and a transit plan can have 16 walking legs. Fetched one by one while parsing, that alone took longer than the search. Now every walking leg of every itinerary is collected first and fetched in one parallel pool, and parsing reads from the cache: 18 legs in 1.5 seconds.

6. Forcing diversity on a frequency-based network
OTP returns the Pareto-optimal itineraries: none is worse than another on every criterion. On Nairobi's network, that has a strange consequence. Route 118 leaves every few minutes, so the optimal set for "CBD to Westlands" is route 118 at 08:00, 08:04, 08:08… Route 119A, which takes ten seconds longer, never makes the list.
A configuration filter (removeItinerariesWithSameRoutesAndStops) stops OTP from filling every slot with time-shifted copies. It can't invent alternatives it didn't find. So the API asks again, excluding the routes it already has:
private const MAX_DIVERSITY_PASSES = 2;
private const DIVERSITY_TARGET = 3;
$limit = min($durations) * 1.5 + 600; // at most 1.5× the best, plus 10 minutes
for ($pass = 0; $pass < self::MAX_DIVERSITY_PASSES && count($keys) < self::DIVERSITY_TARGET; $pass++) {
foreach ($itineraries as $it) {
foreach ($transitLegs($it) as $l) {
$excluded[$l['routeId']] = true;
}
}
$more = $this->otp->plan([...$params, 'excludeRoutes' => array_keys($excluded), 'first' => 4], 15);
// keep only new route combinations within $limit
}The limit matters as much as the loop. Without it, the third "alternative" for a 20-minute trip can be a 70-minute detour, and showing it is worse than showing two options. Part 3 measured a pass at 81 to 446 ms, so the worst case adds under a second.
7. Cache the expensive part, compute the live part
A journey has parts that change at different speeds:
Part | Changes when | Where it's computed |
|---|---|---|
Itineraries, geometry, walking directions, landmarks | The graph changes (a publish) | Once, then cached for 5 minutes |
Fares | Fare rules change, or the time of day crosses a peak band | On every read |
Next departures at each boarding stop | Every minute | On every read |
Live traffic on matatu legs | Every few minutes | When the trip leaves now (Part 7) |
So the cache stores the itineraries before enrichment, and every read, cached or not, goes through the same final step:
$cached = Cache::get($cacheKey);
if ($cached !== null) {
return $this->enrichDynamicRealtimeAndFares($cached, $departureCarbon);
}The key is a hash of the request plus the graph epoch from Part 4, so a publish retires every cached journey at once:
$cacheKey = 'otp:journey:v7:'.Cache::get('otp:graph_epoch', 0).':'.md5(
"{$fromLat},{$fromLng},{$toLat},{$toLng},{$date},{$time},{$mode},{$walkReluctance},{$maxWalk},{$arriveBy}"
);The v7 is the response-format version. When the itinerary shape changes, bumping it is the same trick as the epoch: old entries become unreachable without a scan.
The effect on latency is large. Measured end to end through the API, an uncached transit search took 5 to 7.6 seconds (most of it walking directions and enrichment, not OTP) and a cached one 0.6 seconds.
8. "No route" is not "engine down"
The most important line in the client, from the app's point of view, is the distinction between two empty results:
/** One plan. REST-shaped itineraries, [] when none, null on failure. */
public function plan(array $p, int $timeout = 45): ?array[]means OTP answered: there's no way to make this trip at this time. The app says so, and offers to change the time.nullmeans OTP didn't answer: it's down, restarting after a publish, or timed out. The API returns a 503, and the app says "try again in a moment".
Conflating them is a classic bug. A rider told "no route" when the server is restarting stops trusting the planner; a rider told "try again" when there really is no service at midnight keeps retrying.
One empty result gets special treatment. If a transit search between 21:00 and 04:30, with no explicit time, finds nothing, the engine searches again for the first departures in the morning (05:30) and marks the result first_morning_service. The rider sees a real plan, labelled as tomorrow's, instead of an empty screen.
Timeouts form a budget
Every outbound call has its own timeout, and together they have to fit inside the client's:
Call | Timeout |
|---|---|
The app's request to the API | 15 s |
OTP router's own processing limit ( | 15 s |
One OTP transit plan, from the API | 45 s |
Parallel street options ( | 20 s |
A diversity pass | 15 s |
Valhalla route requests | 12 s |
The table shows a mismatch worth admitting: the API will wait 45 seconds for OTP, three times longer than the app waits for the API. It's a leftover from the days of 46-second searches (Part 3). With a 30-minute search window and OTP's own 15-second limit, it no longer bites, but the right fix is to derive every inner timeout from the outer budget rather than set each one independently.
What the orchestration layer is for
Looking back over this part, the routing engines do the hard algorithmic work, and the orchestration layer does everything that makes the result usable:
it hides the engines (adapters, one contract, one endpoint);
it chooses between them (dispatch, fallbacks that are product decisions);
it compensates for them (diversity passes, merged options, the morning fallback);
and it protects them (caching, parallelism, timeouts,
nullversus[]).
None of those belong in an engine, and none belong in the app.
Part 6: Beyond One City, Regional Graphs and Long-Distance Transport takes the same architecture beyond Nairobi: one graph for a whole country or one per region, SGR trains and intercity services in GTFS, and the per-mode settings that make a train or a flight behave differently from a matatu.
Technical references
OpenTripPlanner: the GTFS GraphQL API and
planConnection.Valhalla: the route API, costing options and alternates.
Laravel HTTP client concurrent requests (
Http::pool).





