Using Server-Sent Events for Live Train Positions
A live rail map feels simple to use: a passenger opens a page, sees a train moving along its route, and watches the position update without refreshing. Behind that smooth experience is a continuous data pipeline connecting railway feeds, a web server and the passenger’s browser. Server-Sent Events (SSE) provide a practical way to deliver those updates from the server to many connected users.
For an Australian transport website being prepared on a new domain, SSE can be a useful middle ground between repeated polling and a full two-way WebSocket system. It works well for public status information, supports ordinary browser connections and can be added to a site hosted through a standard web stack, provided the streaming endpoint and reverse-proxy settings are configured correctly.
Why SSE Fits Rail Tracking
Server-Sent Events maintain a long-lived HTTP connection. The browser opens an endpoint such as /api/train-stream, and the server sends small text messages whenever a train changes position, delay status or operating state. The connection remains open, allowing the client to update markers on a map as new data arrives.
This model matches the information flow of a train tracker. The passenger usually needs updates from the transport operator, rather than sending commands back to the tracking service. SSE also includes automatic browser reconnection, which is helpful when someone moves through a tunnel, changes from Wi-Fi to mobile data or briefly loses coverage on a Sydney commuter journey.
An event can contain a train identifier, route, latitude, longitude, timestamp, bearing and service status. The frontend can then update one marker instead of downloading the entire network repeatedly. For a busy Melbourne Metro dashboard, this reduces unnecessary requests while preserving a near-real-time view of the network.
Preparing Position Data
The stream should not connect directly to a raw operator feed for every browser. A backend service should first collect data from sources such as GTFS-Realtime vehicle positions, an operator API or an internal telemetry feed. It can validate timestamps, remove duplicate records, associate vehicles with routes and retain the latest known position in memory or a fast data store.
A useful event format is compact JSON:
event: train-position
data: {"id":"T1234","route":"T4","lat":-33.8688,"lon":151.2093,"delay":120,"ts":1710000000}
The id field lets the browser match the update to an existing marker. The timestamp helps the interface show whether a position is current or stale, which matters when a train enters a coverage gap. A delay value in seconds can be translated into plain language, while the route identifier can connect the vehicle to station, timetable and accessibility information.
The server should send a heartbeat comment every 15 to 30 seconds when no train movement has generated an event. This keeps idle connections visible to load balancers and proxies. It should also support Last-Event-ID, allowing a reconnecting browser to request missed events or receive a fresh snapshot before incremental updates resume.
Choosing A Delivery Method
The right transport depends on the direction of communication, browser support, infrastructure and scale. SSE is especially attractive when a service broadcasts updates from one backend to many browsers, while WebSockets become more useful when clients must send frequent messages through the same persistent connection.
| Delivery method | Best use for rail data | Main advantage | Main limitation |
|---|---|---|---|
| Short polling | Basic service alerts or low-frequency schedules | Simple to deploy and debug | Repeated requests create delay and extra traffic |
| Long polling | Systems needing broad HTTP compatibility | More responsive than ordinary polling | More connection management and server overhead |
| Server-Sent Events | Live positions, delays and platform notices | Lightweight one-way streaming with browser reconnection | Server-to-browser direction only |
| WebSockets | Interactive control rooms or two-way operations tools | Fast bidirectional communication | More complex scaling, monitoring and fallback handling |
| Managed pub/sub | Large public networks and multiple applications | Distribution across many consumers | Additional cost and vendor dependency |
A website still being launched on a hosting account can begin with a modest SSE service behind HTTPS. The public page might be a static JavaScript application, while a small Node.js, Python or PHP-compatible service provides the event stream. If the domain currently displays a hosting placeholder, the deployment should replace that page with the frontend and route /api/train-stream to the streaming process.
Caching must be disabled for the event endpoint. The response should use Content-Type: text/event-stream, Cache-Control: no-cache and connection settings that allow the response to remain open. Nginx, Apache, Cloudflare and hosting control panels can buffer output unless explicitly configured not to do so, making updates appear in batches rather than live.
Handling Australian Conditions
Rail data in Australia varies between networks. Sydney Trains and NSW TrainLink services may provide different levels of vehicle detail, while Melbourne’s metropolitan network has its own identifiers and operational terminology. Perth’s Transperth system, Adelaide Metro and Queensland services can also differ in feed frequency, coordinate conventions and treatment of cancelled or replacement services.
The interface should display local time correctly, including daylight-saving differences between states. A passenger in Brisbane should not be shown a Melbourne timestamp without clear conversion, and a visitor comparing services across states needs an unambiguous date and time. Australian spelling, station names and route labels should follow the relevant operator’s public conventions rather than relying on imported American transport terms.
Mobile conditions deserve practical attention. A user checking a train at Central, Flinders Street or Perth Station may have a crowded cellular connection, while a regional passenger could experience long intervals without reliable data. Send only meaningful changes, reduce map animation when the device is constrained and show “last updated” information instead of implying that every marker is exact.
Visual clarity is equally important on a public-facing dashboard. Consistent line colours, accessible contrast and recognisable service icons help passengers interpret delays quickly; a source of transport visual references can support early design exploration without replacing accessibility testing or operator branding rules.
Making The Stream Reliable
A production service needs limits. Set a maximum number of simultaneous connections per account or instance, authenticate privileged feeds separately from public viewers and place rate limits on snapshot and metadata endpoints. Public train positions generally do not require personal data, so avoid collecting passenger identities, precise device locations or unnecessary analytics in the streaming layer.
When a train disappears from the source feed, do not leave its marker moving indefinitely. Mark it as stale after a defined interval, such as two or three reporting periods, and remove it after a longer threshold. A service interruption should be represented as a state change rather than inferred solely from a missing coordinate. Logs should record connection counts, event rates, processing lag, reconnects and upstream feed failures.
The browser should handle open, message and error events, using exponential backoff for repeated failures. On reconnection, it can request a current snapshot and then reopen the SSE stream. The map should continue showing the last known state with a clear timestamp, rather than freezing silently.
A sensible first release can cover one route and a small set of fields. Replace the placeholder page with a secure HTTPS frontend, create a backend endpoint that emits validated train-position events, configure the proxy to disable buffering, and test it with a handful of simulated trains before connecting an operator feed. That concrete sequence establishes a dependable foundation for live train positions without adding the complexity of two-way messaging too early.