Streaming callbacks with multiplexed transport - #3931
Conversation
A callback defined as a generator (or async generator) function streams: its yields are pushed to the browser as they are produced, with no keyword. Each yield has the same shape as a regular return and replaces the outputs; yielding dash.Patch gives incremental updates (e.g. LLM token streaming). Streams ride the WebSocket callback transport when active, otherwise the HTTP response streams NDJSON frames. Works on Flask, Quart and FastAPI; synchronous generators are rejected at registration since they occupy a worker for the whole stream. HTTP streams emit a keepalive line every stream_keepalive_interval ms so proxy idle timeouts don't close a working stream.
All of a page's HTTP streams share a single downlink NDJSON connection -- a server-side StreamHub and a renderer-side StreamClient -- instead of one connection per callback, so they no longer count against the browser's ~6-connections-per-host limit, and the downlink resumes from its last sequence on reconnect without dropping frames. This rides the shared-storage pub/sub, so Subscription now exposes (sequence, message) pairs (iter_with_seq / aiter_with_seq, with the plain message iterators built on them) across all backends, letting the downlink resume from a cursor.
|
| def subscribe_envelopes( | ||
| storage: BaseSharedStorage, | ||
| connection_id: str, | ||
| replay_from: Optional[int] = None, | ||
| ) -> Iterator[Any]: | ||
| """Yield a connection's downlink envelopes until the subscription ends. | ||
|
|
||
| These frames feed a ``StreamedCallbackResponse`` so the existing NDJSON | ||
| response path serializes and keep-alives them -- no bespoke endpoint. It is | ||
| long-lived: it carries frames for every callback on the connection, not one | ||
| stream, and ends when the client hangs up. ``replay_from`` resumes a | ||
| reconnecting downlink from its last cursor. Each envelope carries its ``seq`` | ||
| so the client can resume from it after a reconnect without losing frames. | ||
| """ | ||
| with storage.subscribe(stream_topic(connection_id), replay_from) as sub: | ||
| for seq, message in sub.iter_with_seq(): | ||
| yield {**message, "seq": seq} |
There was a problem hiding this comment.
The loop here ends on client disconnect, but not always on server shutdown. As a result, streams continue even after a Ctrl+C (see the repro app below).
We should respond to a shutdown event the way ws.py does.
import asyncio
from dash import Dash, Input, Output, callback, html
app = Dash(__name__, backend="fastapi")
server = app.server
app.layout = html.Div([
html.H3("If you click the button, Ctrl+C won't stop this server"),
html.Button("stream", id="btn", n_clicks=0),
html.Div(id="out"),
])
@callback(
Output("out", "children"),
Input("btn", "n_clicks"),
prevent_initial_call=True
)
async def long_stream(n):
for i in range(600):
await asyncio.sleep(0.5)
print(f"tick {i}")
yield f"tick {i}"
if __name__ == "__main__":
app.run(debug=True)| frames = subscribe_envelopes( | ||
| storage, downlink["connectionId"], downlink.get("from") |
There was a problem hiding this comment.
Here we are implicitly trusting the connectionId sent by a client.
If the ID is somehow leaked or derived, then anyone can use the ID to join someone else's stream and receive its data. Suggest generating the ID server-side and tying it to a cookie or session.
See also _serve_uplink where a connectionId could also be used to inject frames into someone else's stream.
This also applies to the fastapi & quart backends.
| // Last sequence applied; the downlink resumes from here on reconnect. Starts | ||
| // at 0 so the first connect replays anything published before it subscribed | ||
| // (the uplink POST and the downlink open race). | ||
| private cursor = 0; |
There was a problem hiding this comment.
This cursor is per-page, monotonic, and is never reset.
On reconnect, the client sends from: this.cursor (line 160 below).
This seems correct as long as the server is running, but a server restart introduces a flaw: the server's cursor must catch up to the client before the stream can resume.
See this example app (works with gunicorn as well as the dev server)
import time
from dash import Dash, Input, Output, callback, dcc, html
app = Dash(__name__, backend="flask")
server = app.server
app.layout = html.Div(
children=[
html.H3("Streamed clock stalls silently after a server restart"),
html.P("Watch it tick a few seconds, then restart the server."),
html.P("Observe that it stays frozen for as many seconds as the previous server was alive."),
html.Pre(id="clock", children="waiting for first tick…"),
dcc.Interval(id="kick", interval=1000),
],
)
@callback(
Output("clock", "children"),
Input("kick", "n_intervals"),
prevent_initial_call=True,
)
async def stream_clock(_):
yield f"serverside clock: {time.strftime('%H:%M:%S')}"
if __name__ == "__main__":
app.run(debug=True, port=8050)


Summary
This PR adds streaming callbacks and the multiplexed HTTP transport that carries them across worker processes, built on the backend-agnostic shared storage primitive from #3930.
async defgenerator; eachyieldis pushed to the browser as it is produced (same shape as a normal return;dash.Patchyields apply incrementally, e.g. LLM token streaming). No opt-in keyword — a generator streams by definition. Sync generators are rejected at registration.dash.ctx.shared_storage/app.shared_storage, from Shared storage: backend-agnostic state manager + pub/sub #3930) — a cross-process key/value store + ordered publish/subscribe, used internally here as the broker for streaming.Streaming callbacks
Shared storage (base PR #3930)
The default
LocalSharedStorageelects a single owner process per machine (AF_UNIX socket on POSIX, TCP loopback on Windows — the bind is the lease, re-elected on owner death) and serves the others. A single-process deployment is its own owner and pays no socket overhead. Subscriptions are ordered and replayable: a reconnecting consumer resumes from its last-seen sequence out of a bounded buffer, and a buffer overrun surfaces as an explicit gap rather than a silent loss. Passshared_storage=Noneto disable, or aBaseSharedStoragesubclass/instance to swap the backend (DiskcacheSharedStorage,RedisSharedStorage, ... — see #3930).Architecture — multiplexed streaming
A streaming callback no longer holds its own HTTP connection. Its POST returns a fast ack; its frames are pumped onto a shared-storage topic and relayed over the page's single downlink, routed back to the right callback by
requestId. Because the frames travel through shared storage, the worker that runs a callback and the worker that holds the downlink need not be the same process — shared storage is the broker.flowchart TB subgraph browser["Browser — one page"] cbs["streaming callbacks<br/>(async def generators)"] sc["StreamClient<br/>single downlink per page"] cbs --> sc end subgraph server["Dash server — any number of worker processes"] wa["worker A<br/>runs callback, pumps frames"] wb["worker B<br/>serves the downlink"] end store[("Shared storage owner process<br/>KV + ordered pub/sub<br/>topic per connection")] sc -->|"1 · uplink POST, fast ack<br/>streamConnection = conn + requestId"| wa wa -->|"2 · publish frames, tagged requestId + seq"| store sc -->|"3 · single downlink<br/>streamDownlink = conn, from = seq"| wb store -->|"4 · subscribe, replay from seq"| wb wb -->|"5 · NDJSON frames"| sc sc -->|"6 · route by requestId, apply"| cbsTransport selection (renderer): a streaming callback rides the WebSocket transport when websocket callbacks are enabled; otherwise the multiplexed HTTP transport when shared storage is available; otherwise falls back to today's one NDJSON connection per callback. So nothing changes for apps that don't opt into shared storage.
Scheduler: long-lived streams no longer consume the renderer's concurrent-request budget, and clientside callbacks are exempt from it — a page full of streams no longer starves other callbacks.
Testing
StreamClientrouting, multiplexing, reconnect-from-cursor, keepalive (karma).iter_with_seq/aiter_with_seqsequence-aware subscriptions the downlink resumes from, across all backends (test_stream_hub.py).Notes
dcc.Store).RedisSharedStorage(see Shared storage: backend-agnostic state manager + pub/sub #3930).Follow-up (not in this PR)
StreamClientis written host-agnostic for this; the per-page transport already solves the connection-limit problem.