Redis Streams over SSE¶
The SDK serves any Redis Stream as a Server-Sent Events (SSE) response. Each
event carries its entry ID, so a client that loses its connection resumes
after the last entry it saw, with no repeat. Anything that runs XADD is a
producer: a worker in another language, a job runner, or the application
itself.
This example is a notification feed. A worker in another process writes the entries, and each user reads their own stream:
from fastapi import Depends, FastAPI, Request
from redis_fastapi import FastAPIRedis, StreamsDep, session_expiry
app = FastAPI()
FastAPIRedis(app).lifespan().streams()
@app.get("/users/{user_id}/notifications", dependencies=[Depends(require_self)])
async def notifications(user_id: str, request: Request, streams: StreamsDep):
return await streams.sse(
streams.key("notify", user_id), request=request,
start="last", if_missing="wait",
deadline=session_expiry(request),
)
require_self is your own access check; the SDK has none (see
Access). An EventSource on the route is all a client needs: it
reconnects by itself and sends the last entry ID.
To stream an agent's output with states, a cancel and a pause for input, see Agent tasks, which builds on this feature.
The entry ID is the cursor: it goes out as the SSE id:, and the client
sends it back in Last-Event-ID when it reconnects. The response sends the
entries after the cursor and then waits for new ones, in one XREAD loop.
Readers only read. The SDK assumes no field layout, never trims a stream, and
knows no end of a stream unless you name one.
Setup¶
.streams() creates the application's one RedisStreams, which StreamsDep
returns, and registers the handler that turns stream errors into status
codes. It refuses settings that cannot work (see Settings).
The feature works on every server the SDK supports: Redis 7.4 or later, standalone, Cluster or Sentinel. The reader accepts RESP2 and RESP3 replies, decoded or binary.
Reading¶
sse() does every check that decides the status code before the first byte,
then streams.
| Parameter | Default | Meaning |
|---|---|---|
key |
- | The Redis Stream to follow. Authorize it first: the key is not a credential. |
request |
- | The request, for its cursor. |
start |
"first" |
Where to begin when the client sends no cursor. "first" sends the whole stream. "last" sends only entries added after the request. |
if_missing |
"404" |
"404" refuses a key that does not exist. "wait" follows it as an empty stream, for a feed whose key appears with the first XADD. |
format |
None |
Turns an entry into an event, or returns None to skip it. See Entries to events. |
until |
None |
Returns true for the entry that is the stream's last for this reader. The response sends it and ends. Without it, a stream never ends. |
deadline |
None |
The response ends at this time, with no event. See Ending a connection with the credential. |
A job's progress stream that ends with a done entry:
return await streams.sse(
streams.key("job", job_id), request=request,
until=lambda entry: entry.fields.get("event") == "done",
)
The response sends a : ping comment every stream_heartbeat_interval while
the stream is quiet, and sets Cache-Control: no-store and
X-Accel-Buffering: no. Its first frame is a retry: hint of one to three
seconds, chosen at random per connection, so clients that a deploy closed at
the same moment do not all return at once. Never put the route behind
cache(), and exclude it from compression middleware that buffers the body.
The cursor¶
sse() reads the cursor from the request, in this order:
- The
Last-Event-IDheader. - An
?after=query parameter, for a page that reloads and restores its last ID. - None: the response begins at
start.
The header wins because EventSource keeps the URL it was built with but
sends a newer Last-Event-ID on every reconnect. sse() takes no cursor
argument, so a handler cannot pass a stale one.
A cursor must be a full entry ID such as 1700000000000-0. 0-0 means the
whole stream. The special IDs $, + and -, a bare timestamp, and a
repeated header or query parameter are refused with 422.
With start="last" the SDK resolves "last" to the stream's last entry ID
before the first byte and sends it to the client (see
Id-only frames). A reconnect then resumes from that ID and
misses nothing.
Checks before the first byte¶
sse() runs these checks in order. The first that fails decides the status:
| Check | Status | Exception | code |
|---|---|---|---|
| The cursor is malformed or repeated | 422 |
StreamInvalidCursor |
invalid_cursor |
deadline has already passed |
401 |
StreamCredentialExpired |
credential_expired |
The process has stream_max_readers live readers |
503 |
StreamCapacityExceeded |
stream_capacity_exceeded |
| The key does not exist | 404 |
StreamNotFound |
stream_not_found |
| The key holds something other than a stream | 500 |
StreamWrongType |
stream_wrong_type |
| The cursor is past the stream's last entry | 409 |
StreamCursorAhead |
cursor_ahead |
The cursor's own entry matches until |
204 |
- | - |
The reader cap is checked before any Redis call, so a client that reconnects in a loop costs Redis nothing. The checks on the key run in one transaction with the first page, so the status and the first entries are one snapshot.
With if_missing="wait", a missing key passes: the reader follows it from the
client's cursor, and no cursor is ahead of a key that does not exist.
How the response ends¶
| When | What the client gets | What the client does |
|---|---|---|
An entry matches until |
That event | Closes, or reconnects, gets 204 and stops |
deadline |
Nothing | Reconnects through your access check |
stream_max_connection_duration |
Nothing | Reconnects and resumes |
Redis is down for longer than stream_read_retry_window |
Nothing | Reconnects and resumes |
| The application shuts down | Nothing | Reconnects to another process |
The client reads too slowly (stream_send_timeout) |
Nothing | Reconnects, if it is alive |
A Redis failure shorter than the retry window never reaches the client: the reader retries the read.
The SDK cannot close open responses at shutdown: an ASGI server runs the
lifespan shutdown only after open connections have ended. Under uvicorn a stop
waits for each reader, up to stream_max_connection_duration, unless you pass
--timeout-graceful-shutdown N.
Entries to events¶
format returns the data and the event of a frame. The SDK always sets
id: to the entry ID, because resume depends on it.
The default format reads two fields, data and event:
- An entry with a
datafield sends that field, under the name in itseventfield if it has one. - Any other entry sends all its fields as one JSON object, with no event name.
So XADD key * event delta data '{"text":"hi"}' becomes:
Pass your own format for another layout, or to skip entries:
from redis_fastapi import SSEEvent, StreamEntry
def public_only(entry: StreamEntry) -> SSEEvent | None:
if entry.fields.get("visibility") != "public":
return None # skipped; the client's cursor still moves past it
return SSEEvent(entry.fields["body"], event=entry.fields.get("kind"))
return await streams.sse(key, request=request, format=public_only)
Field values are decoded as UTF-8. A reader cannot refuse an entry it did not write, so the SDK makes every frame safe:
- Data with line breaks goes out as several
data:lines, which the client joins back. - An event name with a CR, LF or NUL, or longer than 128 characters, is not sent. The SDK logs a warning and skips the entry.
Id-only frames¶
The cursor is the last entry the reader read, not the last one it sent. In two
cases the client's Last-Event-ID would fall behind the reader:
formatskips entries. Without care, every reconnect would read them again.start="last"resolves a cursor that no event carries. A client that drops before its first event would resolve "last" again, and miss the entries added in between.
So the SDK sends an id-only frame: an id: line and a blank line, with no
data:. One follows the retry: hint when start="last" chose the cursor,
and one follows skipped entries. EventSource stores the ID and dispatches no
event. Some fetch-based SSE clients deliver the frame as a message with
empty data, so a fetch client must skip messages whose data is empty.
Trimmed history¶
The SDK does not detect entries that were trimmed or deleted, and sends no
signal for them. A stream loses entries only when the application asks for
it, with MAXLEN on its XADD, XTRIM or XDEL. A client whose cursor is older than the oldest entry continues from
the oldest entry. A client that falls behind while connected skips what was
trimmed in the meantime.
An application whose clients must not skip an entry does not trim.
Reading without HTTP¶
read() is the same read for code that is not an SSE response. It runs every
check when you await it, so a WebSocket handler can refuse a bad request
before it accepts the connection. It returns a StreamSubscription, an async
iterator of StreamEntry:
from fastapi import WebSocket
from redis_fastapi import StreamsDep
@app.websocket("/jobs/{job_id}/ws")
async def job_ws(websocket: WebSocket, job_id: str, streams: StreamsDep,
after: str | None = None):
entries = await streams.read(streams.key("job", job_id), after=after)
await websocket.accept()
async with entries:
async for entry in entries:
await websocket.send_json({"id": entry.id, **entry.fields})
read() takes start, if_missing, until and deadline as sse() does,
and three parameters of its own:
| Parameter | Meaning |
|---|---|
after |
The cursor to resume from. None begins at start. |
skip |
Entries for which it returns true are not yielded. The cursor still moves past them. |
ticks |
Also yield a StreamTick after every blocking read that returned nothing, about once per stream_heartbeat_interval. |
A StreamTick has quiet_for: the seconds of successful empty reads since
the last entry. A failed read yields no tick and sets quiet_for back to
zero, so a Redis outage never counts as quiet.
The subscription has two attributes. cursor is the ID of the last entry
read, skipped ones included. ended_by is None while the subscription is
live, then "until", "deadline" or "closed". It is already "until" when
read() returns if the cursor's own entry matches until; sse() answers
204 in that case.
A subscription holds a reader slot until it ends or is closed, so it counts
toward stream_max_readers. Close one you leave early, with async with or
aclose().
Your own events¶
sse() is read() plus respond(). When you need an end condition or an
event that sse() does not have, iterate the subscription yourself and pass
the result to respond(). This response ends a job's progress stream after
ten quiet minutes:
import json
from collections.abc import AsyncIterator
from redis_fastapi import SSEEvent, StreamSubscription, StreamTick
async def frames(
entries: StreamSubscription,
) -> AsyncIterator[SSEEvent | StreamTick]:
async with entries:
async for item in entries:
if isinstance(item, StreamTick):
if item.quiet_for >= 600:
yield SSEEvent('{"reason": "idle"}', event="idle")
return
yield item # sent as ": ping"
else:
yield SSEEvent(json.dumps(item.fields), id=item.id)
@app.get("/jobs/{job_id}/progress")
async def progress(job_id: str, request: Request, streams: StreamsDep):
entries = await streams.read(
streams.key("job", job_id),
after=streams.cursor(request),
deadline=streams.connection_deadline(),
ticks=True,
)
return streams.respond(frames(entries))
streams.cursor(request) returns the request's cursor by the rules above.
respond(items) frames SSEEvent and StreamTick items as
text/event-stream. It owns the retry: hint and the send timeout, and it
closes items however the response ends.
respond() checks the longest connection time and shutdown between items,
so it cannot end a read that is waiting. connection_deadline() gives the
read the same limit: the read then ends on time by itself. Pass it your
credential's expiry, connection_deadline(session_expiry(request)), to get
the earlier of the two.
Each item you yield is one send. A long replay is cheaper in pages: iterate
entries.pages(), which gives each read's entries as one list, and yield one
list of events per page. respond() sends a list as one chunk. sse() does
this for you.
async for page in entries.pages():
yield [
item if isinstance(item, StreamTick)
else SSEEvent(json.dumps(item.fields), id=item.id)
for item in page
]
Set id on every event that stands for an entry, or the client cannot
resume. An SSEEvent whose data is None is an id-only frame. An event
with no id, such as idle above, leaves the client's cursor where it was.
When your iterator ends, the response ends, and the client reconnects unless
it closes on your last event.
Writing¶
The SDK does not write to a stream. A producer is anything that runs XADD:
a worker in another process or language, or this application with its Redis
client:
from redis_fastapi import AsyncRedisDep
@app.post("/users/{user_id}/mentions")
async def mention(user_id: str, redis: AsyncRedisDep, streams: StreamsDep):
await redis.xadd(
streams.key("notify", user_id),
{"event": "mention", "data": json.dumps({"from": "ana"})},
)
The fields are yours to choose. The default format sends a data field
under the name in the event field (see
Entries to events).
Two things to know when you write:
- Trimming and expiry are yours too.
XADDwithMAXLEN,XTRIMandEXPIREall work. A reader behind a trim skips what was removed (see Trimmed history), and an expiry of zero or less deletes the stream. - On Redis Cluster a write can be stored twice. After a timeout, Redis
may or may not hold the entry. redis-py's Cluster client sends the command
again by itself, so one
XADDcan store two entries. SetREDIS_CLUSTER_ERROR_RETRY_ATTEMPTS=0in the process that writes. The setting covers every feature in that process; the agent tasks guide shows how to deploy the writers as a service of their own.
Keys¶
sse() and read() take any key. key() is an optional helper
that builds one under the SDK's prefix (REDIS_PREFIX, default
rf) and the segment x, which keeps your streams apart from the SDK's
other keys:
Each part may use 1 to 200 of A-Z a-z 0-9 _ . -. Any other part raises
StreamInvalidName, answered with 422, so a key built from a path
parameter is safe. A part cannot hold :, so different parts never join into
the same key, and it cannot hold braces, so it cannot set a Cluster hash tag.
Access¶
The SDK does not decide who may read a stream. Your FastAPI dependency checks access first, as for any other route. The key is not a credential: build it from the object your dependency authorized.
Ending a connection with the credential¶
Your access check runs once, when the connection opens. To end an open response when the credential does, pass its deadline:
from redis_fastapi import session_expiry
return await streams.sse(key, request=request, deadline=session_expiry(request))
session_expiry() returns the absolute deadline of the SDK
session, or None when there is none. With other credentials,
pass your own, for example a JWT's exp. A datetime without a time zone is
read as UTC. At the deadline the response closes with no event. Every
connection also closes after stream_max_connection_duration. The client then
reconnects through your dependency, which answers 401 or accepts a fresh
credential, so a revoked session keeps reading for at most that long.
Redis permissions¶
A reader runs no write command. The smallest ACL for a process that only serves readers is:
A process that also writes needs the commands it writes with, such as
+xadd. On Redis Cluster the client asks the server for its layout and its
command table, so add +cluster|slots +command. Readers of
agent tasks need a few more.
Errors and status codes¶
Before the first byte, a problem is an ordinary status code: see the table in
Checks before the first byte. Your own
dependency answers 401 or 403 before the SDK runs. Two more errors can
reach the client: StreamInvalidName from key() (422,
invalid_stream_name), and StreamStoreError when Redis fails (503,
stream_unavailable).
StreamError is the base of every stream exception.
StreamConfigurationError reports a setting that cannot work, or a route that
uses StreamsDep without .streams(). The body of an error is
{"detail": ..., "code": ...}, and a 503 carries Retry-After. Branch on
code, not on detail, whose wording may change. A handler you register for
StreamError, or for one of its subclasses, takes precedence.
After the first byte the status is sent, so the response closes with no event (see How the response ends) and the client reconnects.
The client side¶
const events = new EventSource(`/users/${userId}/notifications`);
events.addEventListener("mention", (e) => show(JSON.parse(e.data)));
events.onmessage = (e) => show(JSON.parse(e.data)); // entries with no event name
EventSourcereconnects by itself after a close and sendsLast-Event-ID. It stops for good on any status other than200, a204and a503included, and it never seesRetry-After. To recover from a503, open a newEventSourceafter a pause.EventSourcehides the status of a refused connection, and it cannot tell why a response closed atdeadline. Afetch-based SSE client sees the401.EventSourcecannot send anAuthorizationheader. Cookie sessions work as they are; with bearer tokens, use afetch-based client. Never put a token in the URL.- A
fetch-based client must sendLast-Event-IDitself when it reconnects, and must skip messages with empty data (see Id-only frames). - To survive a page reload, save the last event ID with the state it produced,
and pass it as
?after=when you build the nextEventSource. - Receiving an event is not storing it, so your handlers must tolerate a replay.
Limits¶
- Live readers. At most
stream_max_readersper process, SSE responses andread()subscriptions together. Over the limit a new reader gets503withRetry-After, even for a key that would otherwise be404. Every way a reader ends frees its slot. - No limit per client. The reader cap counts the process, not the user:
the SDK does not know who a reader is. One client that opens
stream_max_readersconnections, by a script or by a bug that never closes anEventSource, takes every slot. Every other reader in that process then gets503, and anEventSourcedoes not retry a503. Limit each client yourself. A proxy can cap open connections per client; nginx does it withlimit_conn. The SDK's rate limiter on the SSE route, keyed by user, caps how fast one user opens connections. That is a rate, not a count: a connection lasts up tostream_max_connection_duration, so ten per minute at the default of 300 seconds still allows about 50 open at once. - Connections. Each live reader holds a pool connection for each blocking
read, and a pool that runs out fails every Redis call in the process. By
default the two fit: 64 readers, and the 100 connections redis-py allows
when
REDIS_MAX_CONNECTIONSis unset. When you raisestream_max_readersto the pool's limit or past it, the SDK builds a larger pool at startup, in which the readers hold 64% of the connections, and logs a warning. With 256 readers that is 400 connections: 256 for readers and 144 for everything else. To choose the size yourself, setREDIS_MAX_CONNECTIONSabovestream_max_readers. On Cluster the pool size is per node. To give readers a pool of their own, see Deploying as separate services. - Connecting. Each connect reads
XINFO STREAM, which returns the stream's first and last entries in full. With large entries, that is the main cost when many clients reconnect at once. - Slow clients. A send that waits longer than
stream_send_timeoutcloses the response, so a frozen tab does not hold a slot. A dead client on a quiet stream is not caught this way; the connection cap bounds that case. - Redis failover. Replication is asynchronous, so a failover can lose
entries the old primary had acknowledged. A reader whose cursor is past the
loss gets
409until the stream grows past it. On a409, drop the cursor and load the state again. - Memory. The SDK sets no length and no expiry on your streams. Bound them
with
maxlenandttl, or in your own producer. - One stream per reader. A reader follows one key. There are no consumer groups: each client holds its own cursor.
Settings¶
Every setting is an environment variable prefixed REDIS_, so
stream_max_readers is REDIS_STREAM_MAX_READERS. Durations are whole
seconds, as everywhere else in the SDK. See
Configuration for how these are loaded.
| Setting | Default | Notes |
|---|---|---|
stream_heartbeat_interval |
15 |
SSE ping interval; also the longest wait of one blocking read |
stream_replay_page |
100 |
Entries per read |
stream_max_readers |
64 |
Live readers per process; at the pool's limit it raises the pool |
stream_max_connection_duration |
300 |
Longest SSE connection before the client reconnects |
stream_read_retry_window |
30 |
How long a reader retries a failing Redis read before it closes |
stream_send_timeout |
10 |
Longest wait for one send to a client |
.streams() raises StreamConfigurationError at setup when:
- the key prefix contains
{or}; socket_timeoutis not longer thanstream_heartbeat_interval, which bounds each blocking read.
The pool size is not checked. A pool too small for the reader cap is built larger; see Limits.
Telemetry¶
With telemetry enabled, the feature emits
redis_fastapi.streams.operations (by operation and result),
redis_fastapi.streams.latency and the redis_fastapi.streams.readers gauge.
The operations are read and slow_consumer;
agent tasks add send, cancel and lost. No key, cursor or
entry data becomes a label.