← Back to Pull requests

Stop GTFS-RT alerts refreshes from stalling arrivals and trip requests #481

Closed
unknown closed this pull request without merging on Oct 12, 2026 22:40 UTC
View on GitHub
unknown unknown commented on Oct 12, 2026 17:17 UTC
Author

Problem

Every request that reads service alerts can stall for seconds once per alerts refresh. That includes arrivals-and-departures, trip details, and vehicles. The stall grows with alert count and database latency.

  • GtfsRealtimeSource.handleAlerts calls ServiceAlertsServiceImpl.createOrUpdateServiceAlerts and removeServiceAlerts. Both are synchronized, and both look up and save each alert in the database while holding the monitor.

  • Since 0f36d40da (MTA-56, Dec 2023), the reader method getServiceAlertIdsForKey is synchronized on the same monitor. Readers therefore wait for every one of those round trips.

  • The source re-saves every alert on every poll, changed or not. GtfsRealtimeAlertLibrary stamps creationTime/modifiedTime with the current time on each conversion, so the existingAlert.equals(serviceAlert) check never matches. This has been the case since 2011; it became expensive when alerts moved to the database in c76d8fac5 (2020).

  • A thread dump showed http-nio threads BLOCKED on ServiceAlertsServiceImpl while scheduledExecutorService-1 held it, waiting in a Postgres socket read.
  • King County Metro's feed has about 78 alerts. With 5 ms of database latency, each KCM refresh held the monitor for about 13 s out of every 30 s.

    Fix

    ServiceAlertsServiceImpl

  • Writers serialize on a ReentrantLock. Readers take only a short index lock to copy alert IDs and look up records. No database call happens under the index lock, and the copy still prevents the ConcurrentModificationException that 0f36d40da fixed.

  • loadServiceAlerts reads rows before swapping the index. Readers no longer see an empty cache mid-reload.

  • A reader that finds the cache stale queues the check and reload on a single background thread (service-alerts-sync) and serves the current cache meanwhile. At most one check is queued at a time, and readers queue one at most every 250 ms, so busy traffic doesn't wake the sync thread on every request.

  • The staleness check lives in getServiceAlertIdsForKey, which every indexed reader calls, so no reader can skip it (four didn't call it before). getServiceAlertForId and getAllServiceAlerts call it directly.

  • Every reader, including getServiceAlertForId and getAllServiceAlerts, reads the cache under the index lock, so none of them can see a half-rebuilt cache during a reload. Before, the reader did the reload inline; in testing that held one request for 3.7 s.

  • createOrUpdateServiceAlerts and removeServiceAlerts return immediately for empty lists.
  • GtfsRealtimeSource

  • The alerts cache stores each alert without the two timestamps (withoutTimestamps). The fields are required, hence buildPartial(). After the first poll, only alerts that changed are saved.

  • An unchanged alert is still saved again if the service no longer has it. Otherwise an alert that was pruned (it dropped out of one poll), deleted in the admin console, or lost to a failed save would stay missing when the feed sent it again unchanged, until its text changed. Before this PR the always-changing timestamps hid this, because every alert was re-saved on every poll.

  • The source remembers an alert's content only after its batch saves. A failed save leaves the old content in place, so the next poll sees a change and retries. New and updated alerts are remembered separately, so a failed update batch doesn't lose the new alerts that already saved.

  • A feed that repeats an alert id in one poll queues it once instead of saving the same id twice.

  • Both alert paths (handleAlerts, handleAlertCollection) share one saveAlerts helper.

  • Removed an unused per-alert getServiceAlertForId lookup.
  • Saving to the database before updating the service's cache, so a failed save can't leave the cache serving unsaved content, is split out into #483. It changes every save path, including the admin console.

    Behavior change

    A reader-triggered sync is now eventual. A change written by another instance (or the admin console) shows up a moment after the first read that notices it, not on that read. ServiceAlertsServiceImplTest writes through its test transaction, which other threads can't see, so it injects a same-thread executor through the new setSyncExecutor.

    Tests

  • New ServiceAlertsServiceImplConcurrencyTest (alerts-persistence). Holds a fake database call open during a bulk update, a removal, and a stale-cache reload, and requires a reader to answer within 1 s each time. All three failed before the fix.

  • New GtfsRealtimeSourceAlertsTest. Polling an unchanged feed twice saves once, a changed alert is saved again, an unchanged alert the service lost is saved again, and a changed alert whose save failed is saved on the next poll. The unchanged and failed-save cases failed before their fixes.

  • Throwaway local integration test (real GtfsRealtimeSource + ServiceAlertsServiceImpl + Hibernate/HSQLDB, a persister that fails once). After a failed save the database keeps v1 and the next poll writes v2; before the fix it stayed on v1. Unchanged polls don't write, and an alert deleted from the database is restored on the next poll.

  • alerts-persistence: 3 tests pass. transit-data-federation: 148 tests pass, 1 skipped (existing).
  • Version

    Bumps every module from 2.7.1 to 2.7.2, along with the Dockerfile OBA_VERSION, the SCM tag, CLAUDE.md, and the API-key CLI README.

    Measured

    Setup:

  • onebusaway-api-webapp:2.7.1-latest, with this branch's two jars rebuilt from v2.7.1.

  • 1 CPU, 2 GB, live Puget Sound feeds (CT, ET, IT, KT, KCM).

  • Postgres behind toxiproxy with 5 ms latency.

  • A 4-minute fixed-rate probe: 5 rps arrivals at busy KCM stops and 2 rps current-time as a control.
  • | | Stock 2.7.1 | This branch |
    |---|---|---|
    | KCM handleAlerts per cycle | ~13,000 ms | ~40 ms (first cycle ~7,200 ms) |
    | Arrivals p95, outside alerts windows | 7,500 ms | 65 ms |
    | Arrivals p95, inside alerts windows | 11,788 ms | 88–369 ms |
    | Arrivals overlapping the cold first cycle (all 78 KCM alerts written) | — | 27 requests, median 44 ms, max 177 ms |
    | current-time p95 (control) | 19–23 ms | 18–20 ms |

    On stock, even the "outside" requests stall, because CT and Intercity cycles also hold the monitor for 4–5 s. Alerts are still served after the change: alerts-for-agency/1.pb returned 41 KB.

    Re-check on the final commit

    Same setup, but with the 2.7.2 build of this branch:

  • Cold start: all 78 KCM alerts were written on the first cycle. alerts-for-agency/1.pb returns 41 KB.

  • Arrivals p95 86 ms, max 584 ms (that max overlaps the cold write). current-time p95 24 ms. No non-200 responses.

  • max(modifiedtime) held steady across polls, so unchanged alerts aren't re-saved.

  • At 1 s per DB round trip, arrivals tracked the current-time control within about 10 ms. Both sat near 1 s, because something else makes a DB round trip on every request (#482).

  • Deleting an alert directly in the database and watching the next poll restore it was not run on a deployed server. The local Hibernate/HSQLDB integration test above covers it.

  • The failed-save retry was not run on a deployed server either; the unit test and the local integration test cover it.
  • Review notes

    These are judgment calls; I left them out of this PR:

  • GtfsRealtimeAlertLibrary stamps now() into creationTime/modifiedTime on every conversion. Stamping 0 there would let the source use plain equals() and drop the stripping. I didn't make that change because it's outside this diff.

  • cleanup() still runs its orphan DELETEs on every poll, even when nothing changed. It doesn't block readers anymore, but it is avoidable database load.

  • A reader that makes several lookups, such as getServiceAlertsForStopId, takes the index lock once per key. A reload landing between those acquisitions can mix two cache generations in one response.

  • When a save fails, handleAlerts stops before pruning alerts that left the feed and before cleanup(). While the database fails intermittently, removed alerts stay until a poll succeeds.

  • Reader-triggered syncs are eventual. The first read after another instance writes a change still gets the old cache. This is intended, as described under Behavior change.
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

    Bug Fixes
    Alert lookups remain responsive while database updates, removals, or stale-cache refreshes are in progress. Stale data is refreshed in the background.
    Repeated alerts from real-time feeds are not saved again when their content is unchanged. Changes to alert content or collection-feed timestamps are saved, and alerts missing from the service are saved again.
    Failed alert saves can be retried, and duplicate alert IDs received in a single poll are processed only once.
    * Empty bulk create or removal requests complete without unnecessary work.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: aaronbrethorst Review duration: 322m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #481"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%