Making amtrack data timely and understandable.
README.md

amtrak-otp #

An independent archive of Amtrak arrival times. It polls Amtrak's public train-status map feed, records the scheduled and actual time of every station stop, and publishes on-time statistics as a static dashboard plus a JSON/SQL API.

Amtrak map feed ──(every 3 min)──▶ collect ──▶ amtrak.db (SQLite)
                                                 ├──▶ live (every minute)   ──▶ site/  current trains
                                                 ├──▶ summary (daily)       ──▶ site/  90-day dashboard
                                                 └──▶ Datasette ──▶ /api/  browse + JSON/SQL

One Rust binary, one SQLite file, no other services. Expect roughly a few hundred MB of database per year.

Quick start #

cargo build --release
B=target/release/amtrak-otp

# 1. First thing on a real network: confirm the live feed still decrypts
$B collect --once

# 2. Run the collector (Ctrl-C to stop)
$B collect --interval 180 --raw-dir raw

# 3. Build the dashboard data and view it
$B export --out site/data
python3 -m http.server -d site 8000      # http://localhost:8000

No network handy? Generate synthetic feeds and run the whole pipeline offline:

$B simulate --out sim-feeds --days 14 --every 5   # encrypted, feed-shaped, made up
$B --db demo.db ingest sim-feeds/*
$B --db demo.db export --out site/data --note "Synthetic sample data"

For benchmarks, build a synthetic archive at the measured real volume (about 112 runs a day, 15 stops each). --out is a new file, and an existing file is refused, so it can't overwrite amtrak.db. The same seed always gives the same data:

$B synth --out scratch/synth-5y.db --years 5 --seed 42
$B --db scratch/synth-5y.db bench --out scratch/bench-out   # time and count rows for each SQL statement in a full export

bench runs against a copy, never the archive. It prints each statement with its run count, total milliseconds, and full-scan rows read, slowest first. Rows come from SQLite's full-scan counter, so index lookups are not included and the total is a floor.

Deploying on your own box #

sudo ./deploy/install.sh builds the binary, creates an amtrak system user, sets up /var/lib/amtrak-otp, installs Datasette in a venv, and enables:

Unit Does
amtrak-otp-collect.service polls the feed forever; restarts on failure; backs off up to 30 min on repeated errors
amtrak-otp-live.timer rewrites site/data/live.json (current trains) every minute, with export --live-only
amtrak-otp-export.timer rebuilds the 90-day site/data/summary.json and per-station and per-train pages once a day (atomic swap)
amtrak-otp-datasette.service Datasette on 127.0.0.1:8001 under /api/

deploy/Caddyfile serves both on one domain with automatic HTTPS. To expose a home machine without opening ports, put a Cloudflare Tunnel in front of Caddy.

Watch it: journalctl -fu amtrak-otp-collect. Every fetch, good or bad, is also logged in the snapshots table, and gaps show up on the dashboard footer and in the coverage_gaps query.

Back up the database. The history is the asset and can't be recreated. For a consistent copy while the collector runs: sqlite3 amtrak.db ".backup amtrak-$(date +%F).db", then ship it off-box (e.g. rclone copy to R2 or B2).

When the feed breaks #

Amtrak's feed is undocumented and can change without notice. Two failure modes:

  • Decryption fails (AES decrypt failed in the log). Amtrak rotated the constants. Get the new values (they ship in Amtrak's map JavaScript; the Amtraker and amtk projects usually update quickly) and set AMTRAK_PUBLIC_KEY, AMTRAK_SALT_HEX, AMTRAK_IV_HEX in the collect unit. No rebuild needed.
  • Format changes (trains parse but stops are skipped). Check the skipped column in snapshots. With --raw-dir, hourly decrypted snapshots are kept as .json.gz, so after fixing the parser you can rebuild with ingest raw/*.

The parser is deliberately lenient: one malformed train or stop is skipped, it never costs a whole snapshot.

Data model #

All times are UTC ISO-8601. Delays are minutes; negative means early.

Tables #

trains: one row per run. A run is one train's trip from its origin on one date. Primary key train_key = train number + local date it left its origin, e.g. 80-2026-10-14.

Column Meaning
train_num, route_name Train number and route, from the feed
origin_date Local date the run left its origin. The 90-day window filters on this
orig_code, dest_code First and last station codes
orig_sch_dep Scheduled departure from the origin, UTC
state Predeparture, Active, or Completed
lat, lon Latest position the feed reported
first_seen, last_seen When the collector first and last saw the run

stops: one row per (run, station). Primary key (train_key, station_code). About 15 stops per run, so this table is roughly 15 times the size of trains.

Column Meaning
seq, bus Position on the run, and whether it's a Thruway bus stop (bus = 1)
sch_arr, sch_dep Scheduled times
act_arr, act_dep Actual times, from Amtrak's posted values. Write-once: never overwritten or cleared by a later snapshot
est_arr, est_dep Latest estimate, only while the actual is still unknown. Never copied into act_*
updated_at When the row last changed
arr_delay_min, dep_delay_min Generated columns: actual minus scheduled, in minutes. Computed when read, not stored

stations: one row per station code. Holds name, city, state, time zone, and coordinates. It's loaded from static/stations.json when the database is opened.

snapshots: one row per collector fetch, keyed by fetched_at. Records whether the fetch succeeded, how many trains and stops it found, how many were skipped, the payload size, and any error. Gaps here are gaps in coverage.

Indexes #

  • trains_origin_date on trains(origin_date): the window filter starts here.
  • trains_route on trains(route_name): route queries.
  • stops_station on stops(station_code): station queries.
  • Primary keys create their own indexes: trains(train_key), stops(train_key, station_code), stations(code), and snapshots(fetched_at). Lookups from stops to trains and back use these.

Views #

Views store nothing. They run their query when read.

  • arrivals: every arrival with Amtrak's on-time rule applied: late after 10 min for Acela, 15 for everything else. Joins stops to trains, and excludes origin stops (no arrival time) and Thruway bus stops. Every other view reads from it.
  • route_otp, station_otp, daily_otp: on-time figures grouped by route, station, and origin date.

Volumes #

Measured on the real archive (5 days, 2026-10-14 to 10-18): about 112 runs a day and 15.2 stops per run, so roughly 1,700 new stop rows a day. A synthetic five-year archive (synth) has 204,400 runs, 3.3 million stop rows, and 3.05 million arrivals.

Query rule #

Queries about a time window must start from trains, filtered by origin_date through trains_origin_date, and then read that run's stops by key. Never scan stops or the arrivals view first: that reads every stop in the archive, which is what the D1 budget in AGENTS.md rules out. Check the plan with EXPLAIN QUERY PLAN before merging.

API (Datasette) #

Any table, view or query is JSON by adding .json:

/api/amtrak/route_otp.json?_shape=array
/api/amtrak/train_history.json?train_num=80&_shape=array
/api/amtrak/station_arrivals.json?station=RGH&_shape=array
/api/amtrak/worst_segments.json?_shape=array      # where trains lose time
/api/amtrak/route_by_month.json?_shape=array
/api/amtrak/coverage_gaps.json?_shape=array

Canned queries live in deploy/datasette-metadata.json. Arbitrary read-only SQL is allowed with a 3-second limit; set --setting default_allow_sql off in the unit file if you'd rather expose only the canned queries.

Caveats #

  • Coverage starts when you start. There's no backfill; ASMAD (juckins.net) is the place for older history.
  • Reporting gaps are real. Some stops never get a posted time in Amtrak's feed. Those are left empty, never guessed.
  • Unofficial. This reads an undocumented feed. Its figures won't exactly match Amtrak's published customer OTP, which weights by passengers. Don't sell access before getting permission to use the feed.

Credits #

  • Decryption scheme and test vectors: amtk by Erin Moon (MIT).
  • Station reference list: amtrack_rs by Quinn Patwardhan (MIT).