Skip to main content
Search Train

Live trains for Arenaways: how I made the RFI API usable

Jun 29, 2026·4 min read
tRPCVercelNext.jsTypescriptTanstack QueryMongooseRFI API IntegrationReal-Time Data StreamingCircuit Breaker Pattern

Arenaways is the first private railway company in Italy. On the website and in the app, travellers look up a train by number or by route and see its times, delays and platforms. That data comes from RFI, the Italian rail network operator, through an API that was not designed for a public website: it responds slowly, sometimes with HTML error pages, and the account has a session limit shared with production systems.

In this article I go through the choices that made that integration usable. None of them is complicated, but each one comes from a problem seen in production.

The backend sits in between

The website and the app never talk to RFI directly. They go through the project's Express API, which holds the credentials, validates the parameters and decides how many calls to make. Credentials stay on the server, and what one user asks for can also serve the next one.

Every call to RFI has a timeout: without one, a hanging request would keep that train or board busy until the process restarts. Errors go into the logs summarised, because RFI answers with full HTML pages and the first few lines are enough to understand what happened.

A cache that also shares the wait

With a session limit the problem is not only speed: ten people looking at the same train cannot turn into ten calls. So I wrote an in-memory cache with expiry that does three things:

  • it returns the data if it is still fresh;
  • if the data is loading, it makes callers wait for that same call instead of opening a new one;
  • it never stores errors, so a temporary RFI failure does not stay on the page for the whole cache lifetime.
ttl-cache.ts
export function createTtlCache<T>(ttlMs: number) {
  const store = new Map<string, { at: number; value: T }>();
  const pending = new Map<string, Promise<T>>();

  return async function get(key: string, load: () => Promise<T>) {
    const hit = store.get(key);
    if (hit && Date.now() - hit.at < ttlMs) return hit.value;

    // Whoever arrives during a load waits for the same call.
    const inFlight = pending.get(key);
    if (inFlight) return inFlight;

    // Only successes are cached: an error is retried on the next visit.
    const loading = load()
      .then((value) => {
        store.set(key, { at: Date.now(), value });
        return value;
      })
      .finally(() => pending.delete(key));

    pending.set(key, loading);
    return loading;
  };
}

The lifetime depends on the data. The list of stations is almost static and refreshes once a day. Boards and train details change minute by minute, so there the cache lasts one minute: enough to absorb peaks, short enough not to show an old platform.

A board that doesn't cover the day

RFI does not expose a daily board: each request returns the trains of a window of a few hours. To show every train on a route until the evening, the backend asks for several overlapping windows and merges them, with a cap on the number of calls per search. The cost of a search is known in advance.

At first the clients received only the list of numbers and then asked for details train by train: a route with ten trains meant eleven calls for every user. Now the backend returns the route already complete with path, delays and notices, and thanks to the cache that work is done once for everyone.

Same number, different operators

The subtlest bug had nothing to do with timing. The same train number can belong to several operators, and when searching by number RFI returns a single run, not always the right one: someone looking for an Arenaways train could see another company's regional train.

Runs can be told apart by their identifier, which also depends on the day. The backend tries the possible identifiers for today and tomorrow, one at a time because the session limit does not allow trying them all at once, and keeps only Arenaways runs. When the board already provides the identifier, it uses that directly.

A related detail: stop names come from RFI and not from a list in the project, because an international train also passes through stations Arenaways does not serve.

Fresh pages without fetching in the browser

Train pages are rendered on the server with Next.js. For live tracking there is a small client component that asks the server to render the page again every minute, but only when the tab is visible: a background tab has no reason to call the API.

auto-refresh.tsx
"use client";

import { useRouter } from "next/navigation";
import { useEffect } from "react";

export function AutoRefresh({ everyMs = 60_000 }: { everyMs?: number }) {
  const router = useRouter();

  useEffect(() => {
    const id = setInterval(() => {
      if (document.visibilityState === "visible") router.refresh();
    }, everyMs);
    return () => clearInterval(id);
  }, [router, everyMs]);

  return null;
}

When something goes wrong the page tells the cases apart: train not found, train of another operator, RFI unreachable, timeout. A precise message stops travellers from thinking their train does not exist.

What I take from this project

  • A slow external API belongs behind a backend that decides how many calls to make, not exposed to clients.
  • A useful cache also shares the wait and never stores errors.
  • A provider's limits, such as sessions, are project requirements.
  • The most expensive bug is often in the data, not in the speed: the same number for different trains.

The full project, with website, app and back office, is in the Arenaways case study.

Related articles

Ask the AI