Skip to content

feat: live inbox updates over SSE - #4

Merged
anshg1214 merged 26 commits into
mainfrom
feat/inbox-live-updates
Nov 11, 2026
Merged

anshg1214 merged 26 commits into
mainfrom
feat/inbox-live-updates

Conversation

@anshg1214

@anshg1214 anshg1214 commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds live updates to the in-app inbox (#3). When a user's inbox changes, Synapse pushes a nudge over Server-Sent Events to their open tabs, and the page refetches the unread count through the existing routes. Before this, a client only saw new notifications when it polled.

A nudge carries no notification content and no counts: {"kind": "created" | "changed", "tenant": "…"}. The API stays the only source of truth, so a nudge that is dropped or merged costs nothing, because the next refetch is correct.

Architecture: what changes

Publishing is added after the existing commits. Delivery to browsers goes through Redis pub/sub and a hub in each API instance. New parts are green.

flowchart TB
    subgraph W["Writes (existing)"]
        direction TB
        ING["ingest consumer / POST /v1/events<br/>fan-out transaction"]
        MUT["/v1/me/.../notifications<br/>read, read-all, dismiss"]
    end

    PUB["NEW: live.Publisher<br/>after commit, best effort, 500 ms budget<br/>created per (user, tenant) / changed per tenant"]
    ING -- commit --> PUB
    MUT -- commit --> PUB

    R[["NEW: Redis pub/sub<br/>channel synapse:inbox:{user_id}"]]
    PUB -- PUBLISH --> R

    subgraph API["Each API instance"]
        direction TB
        HUB["NEW: live.Hub<br/>one SUBSCRIBE connection,<br/>per-user channel while the user has a stream open"]
        S1["NEW: stream (tab 1)"]
        S2["NEW: stream (tab 2)"]
        HUB --> S1
        HUB --> S2
    end
    R --> HUB

    B["Browser (fetch)"]
    B -- "NEW: GET /v1/stream/...<br/>Authorization: Bearer (MusicBrainz token)" --> S1
    S1 -- "event: inbox" --> B
    B -- "refetch count / list (existing routes)" --> MUT

    classDef added fill:#e6f4ea,stroke:#2e7d32
    class PUB,R,HUB,S1,S2 added
Loading

Routes introduced

Route Auth Purpose
GET /v1/stream/tenants/{tenant}/notifications OAuth Bearer One tenant's nudges. 404 for an unknown tenant.
GET /v1/stream/notifications OAuth Bearer Every tenant's nudges. 403 unless cross_tenant_notifications is on.
OPTIONS on both none CORS preflight: Allow-Methods: GET, Allow-Headers: Authorization, Max-Age: 600 for allowed origins

What a stream sends:

event: inbox
data: {"kind":"created","tenant":"listenbrainz"}

event: ping
data: {}
  • created: an ingest committed a notification for the user.
  • changed: the user read, read-all'd or dismissed, in any tab or on any device.
  • ping: every 25 s.

How it works

Auth. The browser already holds the user's MusicBrainz token (ListenBrainz's musicbrainzAuth), so it opens the stream with fetch and Authorization: Bearer. EventSource can't send headers, so it isn't used. The stream routes use the same NewUserAuth middleware and introspection cache as /v1/me/*. CORS runs before auth, so an allowed page can read a 401 (refresh the token) or 503 (back off).

Publishing.

  • Nudges are published only after the transaction commits, with a context detached from the request, so a client hanging up doesn't drop them.
  • An ingest sends one created per deduplicated (user, tenant), never for dry runs or duplicates, and only for event types that allow in-app.
  • A read or dismiss sends changed unless it returns 404; read-all sends one per tenant that had unread notifications.
  • Fan-outs are pipelined 1000 users at a time and stop at the first failed batch.
  • The publisher has its own Redis client with ContextTimeoutEnabled. Without that, go-redis ignores the 500 ms budget and waits its 3 s ReadTimeout.
  • A failure is logged and never fails the ingest or the request.

Hub (internal/live/hub.go). One shared Redis PubSub per instance.

  • Subscriptions: the first stream for a user sends SUBSCRIBE synapse:inbox:{user}, and the last one to close sends UNSUBSCRIBE. It uses per-user SUBSCRIBE, not PSUBSCRIBE synapse:inbox:*, so an instance only receives its own users' messages.
  • Confirmation: Register returns only after Redis confirms the subscription, so a nudge published after the stream opens is never missed. Confirmations are counted per channel, so a late reply to an earlier subscribe/unsubscribe pair can't mark a newer subscription live.
  • Fan-out never blocks: each stream has an 8-slot buffer, and when a buffer is full that stream drops the nudge. A slow client loses nudges, not its neighbours.
  • Connection loss: if Redis errors, or stays silent for 30 s and doesn't answer a PING, the hub closes every stream on the instance and starts a fresh PubSub. Reusing the old one would let go-redis resubscribe old channels on reconnect, and those replies would confuse the confirmation counts.

Stream limits (internal/api/stream.go):

Limit Value Why
Streams per user per instance 32; the 33rd gets 429 Bounds file descriptors per account
Stream opens Same per-user rate limit as /v1/me/*; 429 when exceeded A client stuck in a reconnect loop can't hammer introspection and the users table
Write deadline 10 s per frame A client that stops reading frees its goroutine and slot
Lifetime 15 min plus up to 20% random extra Reconnecting re-checks the token (matching the 15-minute introspection cache) and preferences. The randomness stops streams opened together from expiring together.

Reconnect is client-driven. On 401 the client refreshes its token and reconnects; on any other status, a network error or a closed stream it waits a random backoff and reconnects. It refetches on every open, which covers anything missed while disconnected. A Redis, hub or preferences failure before the stream starts returns 503. There's no retry: field. The full client contract and a fetch snippet are in docs/tenant-integration.md.

CORS. Exact match against the tenant's stream_origins, plus Vary: Origin. The global stream accepts any tenant's origins.

Notes for review

  • No replay or Last-Event-ID. A reconnect means a refetch.
  • Restricting which tokens may call Synapse to the synapse:notifications scope is a separate PR. The ListenBrainz frontend should ship after it.
  • MarkRead and Dismiss now return the tenant (RETURNING n.tenant_id), and MarkAllRead returns a count per tenant, so the global routes know which tenant to nudge.
  • There's no circuit breaker on publishing. While Redis is down, each ingest takes about 0.5 s longer and still succeeds.
  • Documentation is included:
    • New docs/tenant-integration.md: registering a tenant, publishing events, building the inbox, and adding live updates.
    • A Live updates section in docs/architecture.md, a Redis row in docs/failure-handling.md, and the README.

Testing

  • go build, go vet (including -tags integration), and the internal/live tests and e2e stream tests pass under -race against Postgres, Redis and RabbitMQ.

  • Stress runs:

    Scenario Result
    100k users, 20k with streams open, 20 events × 5,000 recipients All 20k notified; ingest about 150 ms per event; delivery 460 ms p50, 726 ms p99
    9,000 stream opens with reconnect churn, -race No missed nudges, no races; subscriptions and goroutines back to baseline
    Redis down during ingest Still 202, about 0.5 s added per request, recovers on its own
    Hub loses Redis with 2,000 streams open All closed in 35 ms; all 2,000 reconnected in 1.5 s (measured with tickets, before the switch to token auth)
    One client stops reading Its neighbour is unaffected
  • Known flakes: TestPipelineHTTPIngest, TestPipelineAMQPIngest and TestRelayPublishesAndClearsOutbox time out on a loaded Docker host. They fail the same way without this branch and pass on a clean run.

  • Not automated: the write-deadline path for a stalled client (filling loopback buffers with pings takes minutes), and a browser smoke test against docker-compose.

go-redis ignores context deadlines on socket I/O unless ContextTimeoutEnabled
is set, so a stalled Redis held each publish for ReadTimeout (3s) instead of
publishTimeout (500ms). The publisher now owns a client with it enabled.
Clearing the write deadline let a client that stops reading hold its
goroutine and one of its 32 stream slots until the OS dropped the
connection. Each frame now gets a 10s write deadline.
A stream outlived token revocation and preference changes because tickets
are checked only when the stream opens. Expiry forces a new ticket; 15m
matches the OAuth introspection cache, and up to 20% jitter keeps streams
opened together from expiring together.
tenants_listenbrainz_in_app_retention_days (default 30) and
tenants_listenbrainz_stream_origins (comma-separated, default
https://listenbrainz.org) can now differ per environment.
The browser already holds the user's MusicBrainz token, so a ticket
protected nothing. Stream routes now run CORS then the OAuth middleware,
so a 401 or 503 is readable by an allowed page, and answer the preflight
that the Authorization header triggers.
Streams authenticate with the OAuth token, so the ticket store, the
stream-ticket route and their tests have no caller.
The 200-then-close and retry field existed for EventSource, which stops
on any non-200. fetch clients read every status, so Redis, hub and
preference failures now return 503 and the client owns its backoff.
Ticket minting went through the Surface B limiter; token-authenticated
streams skipped it, so a client stuck in a reconnect loop could open
streams at network speed, each costing an introspection and a user
upsert. Stream routes now run the same per-user limiter after auth.
A token was cached until it expired, so a revoked token kept working on
/v1/me and the streams for its whole remaining life. The cache now holds
it for at most 15 minutes, as the docs already said.
An unknown tenant has no origins of its own, so the 404 carried no
Access-Control-Allow-Origin and the page saw a network error. It now
allows any tenant's origins, like the global stream.
Stop on 403/404 instead of retrying forever, arm the watchdog before
fetch so a hung connect is retried, return a stop function for logout
and unmount, and accept CRLF event endings.
With 2,000 open streams, go-redis v9's default RESP3 lost a large share
of messages on the hub's shared pub/sub connection while subscribes
were being written (325-930 of 2,000 streams missed their nudge in
TestStreamDeliversToManyStreams). The hub now opens its own RESP2
client; the shared client is unchanged.
@anshg1214
anshg1214 merged commit c96042f into main Nov 11, 2026
1 check passed
@anshg1214
anshg1214 deleted the feat/inbox-live-updates branch November 11, 2026 12:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant