cenko.tech

tram-pulse: working out how late every tram in Kraków is

A live map of Kraków's trams and buses coloured by delay, built from a feed that publishes predictions but no delay figure, plus a daily ranking of the worst lines.

Kraków’s transit authority, ZTP, publishes live data for every tram and bus in the city. Their positions and predicted arrival times update every few seconds. What the feed doesn’t publish is the number most people care about: how late each vehicle is.

tram-pulse works that number out. It’s a live map of about 850 vehicles at peak (roughly 225 trams and 625 buses), each coloured by its delay, next to a ranking of today’s most delayed lines.

The repo is private for now, so there’s nothing to install from this post. It’s about how the delay is derived, and the rules that keep the figures honest.

What it shows#

  • Every vehicle, coloured by delay: green under 3 minutes late, amber from 3 to 10, red over 10. A vehicle with no known delay is a hollow grey ring, not a guess. Trams are drawn as short pills pointing in their direction of travel, buses as discs.
  • A ranking of the day’s worst lines, on a fixed 0–30 minute scale that never rescales to fit the data, so a bad day looks bad. Each line shows its share of late readings, compared with its usual delay.
  • An hour-by-hour profile for any line you pick, with its route drawn on the map.
  • Each vehicle’s upcoming stops, with the scheduled time, ZTP’s predicted time and the difference.
  • ZTP’s service alerts next to the lines they affect.
  • Bunching (two vehicles of a line running almost together) and the stretches of the network where delay builds up.

The server is Node.js with Express and the built-in node:sqlite. The map is Leaflet with OpenStreetMap tiles, and the front end is plain JavaScript.

Delay isn’t in the feed#

ZTP publishes standard GTFS data: a static timetable as a zip file, plus GTFS-Realtime feeds for vehicle positions, trip updates and service alerts. There are three groups: trams, MPK buses and Mobilis buses. tram-pulse fetches all three every 15 seconds.

GTFS-Realtime trip updates can carry a delay field. ZTP’s mostly don’t. They give an absolute predicted arrival time for each upcoming stop instead. So the delay has to be worked out:

  1. For each vehicle, take the first upcoming stop that has a predicted time.
  2. Look up when the vehicle’s trip was scheduled to reach that stop in the static timetable.
  3. Delay = predicted − scheduled.

The timetable is about 33 MB of zipped CSV. On first start, tram-pulse indexes it into SQLite, which takes about 15 seconds, so each lookup is one indexed query.

Step 2 sounds simple. It’s where most of the work went.

Timetable times don’t start at midnight#

GTFS doesn’t measure scheduled times from midnight. It measures them from “noon minus 12 hours” of the service day, and times can run past 24:00. A night tram scheduled at 25:10:00 belongs to yesterday’s service day and runs at 01:10 today.

The “noon minus 12 hours” rule exists for the two days a year when the clocks change. On the last Sunday of October, Poland’s clocks go back an hour at 03:00, so the day is 25 hours long. Noon minus 12 hours then lands at 01:00, not midnight:

Last Sunday of October, Warsaw time (clocks go back at 03:00)

Service-day origin = noon − 12 h          = 01:00
A trip scheduled at 08:00:00               → 01:00 + 8 h = 08:00 ✓

Counting from midnight instead             = 00:00
The same trip                              → 00:00 + 8 h = 07:00 ✗ (an hour early)

Counting from midnight would put every trip after the change an hour early, which would show the whole network as an hour late for the rest of the day.

When tram-pulse matches a prediction, it doesn’t decide which service day a trip belongs to in advance. It tries both yesterday’s and today’s origin, and keeps the one that gives the smallest delay. The same trick handles loop routes that pass one stop twice: every visit to that stop is a candidate, and the closest one wins.

Filtering out feed artefacts#

Some readings are wrong in ways that are easy to spot:

  • A vehicle still at its first stop gets no delay. During a layover, a vehicle often already carries its next trip, or a stale one, so its “delay” would be its rest time.
  • Delays outside −30 to +90 minutes are dropped. Values like that come from timestamps left over from another day, not from real lateness.
  • Positions older than 3 minutes are ignored, so a vehicle that stopped reporting disappears instead of freezing on the map.

To check the calculation, I compared it against the few entries where ZTP’s feed does carry its own delay field. The two agree on all 240 of 240 Mobilis stops and on 67 of 74 MPK stops. In the 7 MPK mismatches, the feed reports a delay of exactly 0.

A ranking you can trust#

Each time a feed brings new data, every vehicle with a known delay adds one sample to its line’s totals for that hour. The check is the feed’s own timestamp, so a feed that stops updating doesn’t count the same readings twice. The totals live in SQLite, so a restart keeps the day’s numbers.

The transit day rolls over at 03:00, not midnight, so night lines count towards the evening they belong to.

A line needs at least 20 samples over 2 trips before it can rank. Without that rule, one stuck bus on a quiet route would top the chart every morning. The same idea applies elsewhere:

  • An hour with fewer than 10 readings shows no figure in a line’s profile, rather than a misleading zero.
  • Before 07:00, or while fewer than 5 lines qualify, the ranking opens on yesterday’s final result and says so. A morning visitor never lands on an empty chart.

Each ranked line is compared with its usual delay. That’s its average on the same weekday over the previous four weeks or, failing that, over the previous 28 days. The average is weighted by samples, and it only counts days with enough data, so one thin Sunday can’t set a line’s baseline. The last 60 days are kept and can be browsed.

Bunching#

On a frequent line, delay often shows up as bunching: a late tram picks up more passengers, falls further behind, and the next one catches up with it. tram-pulse pairs each vehicle with the one just ahead of it on the same line and direction. It compares their predicted arrival times at a stop they’ll both reach.

If the actual gap is under a quarter of the scheduled gap, the pair is bunched, and the map ties them together with a short bar. This is only judged where the scheduled gap is between 2 and 60 minutes, which leaves out layovers and odd timetable entries. Each line’s ranking entry shows the share of its readings that were bunched.

Where delay builds up#

A daily average says which lines are late, but not where they lose the time. To show that, tram-pulse watches each vehicle’s next stop change. When the next stop moves on from C to D, it has just passed C. The delay gained between B and C is the last delay recorded while C was next, minus the last one recorded while B was next.

These gains are only kept for consecutive stops in the timetable. If a vehicle passes two stops between polls, the chain breaks rather than spreading the gain across them, and gains over 10 minutes between two stops are thrown out.

A map layer then highlights stretches where vehicles lose 15 seconds or more per pass on average, for today or for the past 7 days. Stretches with fewer than 10 passes are left out.

Running it on shared hosting#

tram-pulse runs on Hostinger’s Node.js hosting, not on a server of its own. The Stet post covered this host’s constraints, and tram-pulse handles them in its own ways.

The host stops apps that get no visitors. While the app is asleep, nothing polls the feeds. A cron job requests the health endpoint every five minutes to keep it awake, but gaps still happen. So the app counts its own polls per hour, and an hour it polled through less than half of is reported as a gap. The ranking says something like “Recorded 17 of 19 hours so far” instead of passing missing hours off as quiet ones, and the gaps are drawn dashed in the hour profile.

The host may run several copies of the app at once. Each copy polls the feeds, but if they all recorded, every reading would count two or three times. So only one copy records, using a lease stored as a single row in SQLite:

UPDATE recorder SET owner = :me, until = :now + :ttl
WHERE id = 1 AND (owner = :me OR until < :now)

If that update changes one row, this copy holds the lease and records. Any other copy finds the row taken and only serves the map. The lease lasts three poll intervals, so if the copy holding it dies, another takes over within 45 seconds.

The timetable changes without warning. Every three hours the app asks ZTP for the timetable zip using the ETag from the last download, so an unchanged file costs one small response. When it does change, the new index is built in a temporary file and renamed into place, so a request never reads a half-built index. Data is kept outside the deploy directory, because every deploy replaces the app’s files.

The built-in node:sqlite module means there’s no native database driver to compile on the host. Node 22.13 is the oldest release where it works without a flag, so CI runs the test suite on both 22.13 and 24.

Drawing 850 vehicles#

Leaflet’s usual markers are DOM elements, and 850 of them redrawn every 15 seconds would slow the page right down. tram-pulse draws every vehicle onto a single canvas layer instead. Between readings, vehicles glide to their new positions over 1.4 seconds rather than jumping, and the glide is switched off when the visitor prefers reduced motion.

Line labels are placed so that they never overlap each other or a vehicle. Each label tries the right of its vehicle, then the left, above and below, and is left out if none of those spots is free. Vehicles of the same line close together share one label, such as 4 ×3.

The design is based on a Kraków ticket validator, the kasownik. Figures the “machine” produced, such as the refresh time and the delay numbers, are set in a violet dot-matrix font. The map tiles are muted to grey, so that the delay colours are the brightest thing on the screen. The URL keeps the pinned line, the tram or bus filter and the map view, so a shared link opens on the same view.

Tests#

The rules above are easy to get subtly wrong, so most of them have a test. The suite has 36 tests, including these cases:

  • a trip that runs past midnight, seen both before and after 24:00
  • the day the clocks go back
  • a loop trip that visits the same stop twice
  • a vehicle laying over at its first stop
  • two processes competing for the recording lease
  • hours missed by the recorder
  • skipped stops between two polls
  • lines with too little data to rank

The limits#

  • Delay is only as good as ZTP’s predictions. tram-pulse compares ZTP’s own predicted time with the timetable. If the prediction is wrong, so is the delay.
  • Some vehicles have no known delay: those at their first stop, and those without a trip update. They’re shown as unknown rather than estimated.
  • The ranking averages readings, not trips. A line that runs late for longer, or runs more vehicles, contributes more samples. That’s what “how late is this line today” means here, but it isn’t a per-passenger figure.
  • Gaps happen. If the host idles the app between cron pings, or a feed goes down, those hours are missing. They’re marked as missing rather than filled in.
  • Polling every 15 seconds limits the detail. The stretch-by-stretch figures depend on catching each stop change. They’re good for finding the problem spots, not for timing a single journey.
  • Stop and line names are kept as ZTP publishes them, in Polish.

Like latency-atlas, tram-pulse is a live map of Kraków built from public data. The difference is that latency-atlas only had to measure a number, while tram-pulse first had to define one. Most of the code is about deciding when a figure is good enough to show, and saying so when it isn’t.

cd ~/blog