ReplayRail
Durable, replayable and auditable realtime events for Python WebSockets, powered by Redis Streams.
ReplayRail is a Python library for building WebSocket systems where realtime events are persisted, assigned cursors, replayable after reconnect, and traceable through audit metadata.
Installation
ReplayRail requires Python 3.14 or later.
pip install replayrail
pip install "replayrail[redis,fastapi]"
pip install "replayrail[postgres,fastapi]" # PostgreSQL instead of Redis
For local development:
pip install -e ".[redis,fastapi,postgres,dev]"
Quickstart With Redis
import redis.asyncio as redis
from replayrail import ReplayRail, ReplayRailConfig
from replayrail.stores.redis import RedisStreamStore
redis_client = redis.from_url("redis://localhost:6379", decode_responses=True)
rail = ReplayRail(
store=RedisStreamStore(redis_client),
config=ReplayRailConfig(
stream_prefix="rr",
default_replay_limit=100,
max_stream_length=10_000,
),
)
event = await rail.publish(
channel="restaurant:123:orders",
event_type="order.created",
payload={"order_id": "ord_123"},
actor={"type": "waiter", "id": "usr_123"},
metadata={"correlation_id": "req_abc123"},
)
missed_events = await rail.replay(
channel="restaurant:123:orders",
after=event.id,
)
Quickstart With FastAPI WebSockets
from fastapi import FastAPI, WebSocket
from replayrail.integrations.fastapi import ReplayRailWebSocket
app = FastAPI()
ws = ReplayRailWebSocket(rail)
@app.websocket("/ws/{channel}")
async def websocket_endpoint(websocket: WebSocket, channel: str):
await ws.subscribe(websocket, channel=channel)
Run the example app:
docker compose up -d redis
uvicorn examples.fastapi_app:app --reload
uvicorn needs a WebSocket library to serve WebSockets. The dev extra includes websockets; in your own application, install uvicorn[standard], or install websockets or wsproto. Without one, uvicorn answers the WebSocket handshake with 404 and logs "No supported WebSocket library detected".
Publish a test event:
curl -X POST http://localhost:8000/events/restaurant:123:orders \
-H "content-type: application/json" \
-d '{"type":"order.created","payload":{"order_id":"ord_123"}}'
Subscribe:
ws://localhost:8000/ws/restaurant:123:orders?last_event_id=0-0
last_event_id
Every event has a stream cursor in event.id. A client should store the latest cursor it has processed. When it reconnects, it can pass that cursor as ?last_event_id=<id>, and ReplayRail replays events after that ID.
Every event also has a logical event_id. Use event_id for tracing, deduplication, retries, external outbox integration, and client-side duplicate handling. Do not use event_id as the replay cursor.
If last_event_id is missing, ReplayRailConfig.default_start_position controls startup:
latest: send only events published after the client connects.earliest: replay from the beginning of the channel.
Replay cursors use Redis Stream ID format:
<milliseconds>-<sequence>
The live-only cursor $ is accepted for blocking reads and WebSocket startup. If a replay cursor is invalid, ReplayRail raises InvalidCursorError. If a store can determine that a valid cursor is older than retained history, ReplayRail raises ReplayWindowExpiredError. Over a WebSocket, these errors close the connection with a code instead; see WebSocket Close Codes.
For latest, and for last_event_id=$, the WebSocket integration looks up the newest event ID once with ReplayRail.latest_cursor(), before it accepts the connection, and reads after it, so no event published once the client sees the connection open is skipped. Custom stores should implement an async latest_cursor(channel) that returns the newest stream ID, or 0-0 for an empty channel. Without it, latest_cursor() returns $, which a store resolves again on every read, so events published between two reads can be missed.
Each live WebSocket read waits up to ReplayRailConfig.websocket_read_block_ms for new events (5000 by default); 0 waits until an event arrives. Custom stores should give the block_ms argument of read() the meaning Redis XREAD gives it: None returns at once, 0 waits until an event arrives, and a positive value waits at most that many milliseconds.
The repository's tests/test_store_contract.py checks the behaviors that every store shares against the memory, Redis and PostgreSQL stores. To check a custom store, add a factory for it to the suite's new_store fixture.
Retention
ReplayRailConfig.max_stream_length is passed to stores as the stream maxlen retention setting. The Redis backend forwards it to XADD; the memory backend applies the same observable trimming behavior for tests and local development.
Clients should treat last_event_id as a recovery cursor within the configured retention window, not as a permanent archive pointer. If the cursor falls outside retained history and the backend can identify that condition, replay raises ReplayWindowExpiredError.
The check is conservative: a cursor that is exactly the last trimmed event also counts as expired, even though no later event was lost, because the retained history alone cannot tell the two cases apart. While a WebSocket client catches up, the Redis backend checks retention whenever a read returns a full batch. That catches every trimmed cursor as long as max_stream_length is at least websocket_batch_size, which holds for the defaults (10 000 and 100).
WebSocket Close Codes
ReplayRailWebSocket.subscribe() accepts the connection first. When a subscription cannot continue, it closes the connection with one of these codes and a short reason:
| Code | Reason | Cause | What the client should do |
|---|---|---|---|
4400 |
invalid_channel, invalid_cursor |
The channel name or last_event_id is not valid. |
Fix the request; retrying it unchanged fails again. |
4403 |
forbidden |
The application's authorize hook denied the subscription. |
Do not retry with the same credentials. |
4410 |
replay_window_expired |
last_event_id is older than retained history, at connection time or while catching up. |
Reload the current state from your API, then reconnect without last_event_id. |
4429 |
slow_consumer |
The client fell too far behind its channel's shared read loop; see Shared Reads Per Channel. | Reconnect with the last processed event.id. |
1011 |
store_error, internal_error |
The store failed, or another server error happened. | Reconnect with the last processed event.id. |
With 4400, 4403, 4410 and 4429, subscribe() returns normally. With 1011 it also raises WebSocketDeliveryError, so the server logs the failure. The codes are available as CLOSE_INVALID_REQUEST, CLOSE_FORBIDDEN, CLOSE_REPLAY_WINDOW_EXPIRED, CLOSE_SLOW_CONSUMER and CLOSE_INTERNAL_ERROR in replayrail.integrations.fastapi.
A browser client can react to them like this:
let lastEventId = localStorage.getItem("lastEventId");
function connect() {
const query = lastEventId ? `?last_event_id=${lastEventId}` : "";
const socket = new WebSocket(`ws://localhost:8000/ws/restaurant:123:orders${query}`);
socket.onmessage = (message) => {
const event = JSON.parse(message.data);
// Handle the event, then remember its cursor.
lastEventId = event.id;
localStorage.setItem("lastEventId", lastEventId);
};
socket.onclose = (close) => {
if (close.code === 4400 || close.code === 4403) {
return; // Invalid or forbidden: fix the request or the credentials instead of retrying.
}
if (close.code === 4410) {
// Cursor too old: reload the current state from your API, then start live.
lastEventId = null;
localStorage.removeItem("lastEventId");
}
setTimeout(connect, 1000); // 1011, 4429 or a dropped connection: retry with the cursor.
};
}
connect();
subscribe() also watches the WebSocket's receive() for the client's disconnect and stops reading as soon as it arrives, so a client that leaves an idle channel does not leave a read loop behind. Messages from the client are ignored. A custom WebSocket object without receive() is only noticed when a send fails.
Shared Reads Per Channel
ReplayRailWebSocket reads each channel once, however many clients subscribe to it. The first subscriber of a channel starts a read loop at the newest event, the others join it, and the loop stops when the last one leaves. A subscriber that reconnects with a cursor first catches up on its own with replay(), then follows the loop through a queue of its own, so it still receives every event after its cursor, once and in order.
- Create the adapter once, as in the quickstart. The loops belong to the adapter: an adapter created per connection shares nothing, and each process has its own loops.
- A subscriber with more than
ReplayRailConfig.websocket_fanout_queue_sizeevents waiting in its queue is closed with 4429slow_consumer, so that it cannot hold back the others. The default is 1000, and a value belowwebsocket_batch_sizecounts aswebsocket_batch_size. The client reconnects with its cursor and catches up from the stream. ReplayRailWebSocket(rail, fanout=False)keeps one read loop per subscription. A store withoutlatest_cursor()always does.- Each catch-up batch is a
replay(), so an observer receives onereplayedper batch.
WebSocket Control Messages
A client can ask for control messages by connecting with ?control=1. The application can also force the choice with subscribe(..., control_messages=True) or False. Without them, the connection carries only events, as before.
A control message is a JSON object with a control key, which no event has:
{"control": "replay_complete", "cursor": "1719367320123-0"}arrives once. It comes after every event that was in the channel when the client connected, and before any newer event. On a live start it arrives right after the connection opens.cursoris the position reached; on a live start with a store that cannot look up the newest event, it isnull.{"control": "closing", "code": 4410, "reason": "replay_window_expired"}arrives right before ReplayRail closes the connection, with the same code and reason as the close frame.
socket.onmessage = (message) => {
const data = JSON.parse(message.data);
if (data.control === "replay_complete") {
// The client has caught up: switch the UI from "syncing" to "live".
} else if (data.control === undefined) {
// An event.
}
};
See docs/design/websocket-protocol.md for the exact rules.
Authorizing Subscriptions
Pass an authorize hook to decide, per channel, whether a client may subscribe:
from fastapi import WebSocket
from replayrail.integrations.fastapi import ReplayRailWebSocket
async def authorize(websocket: WebSocket, channel: str) -> bool:
user = await current_user(websocket)
return user is not None and user.can_read(channel)
ws = ReplayRailWebSocket(rail, authorize=authorize)
The hook receives the WebSocket, so it can read headers, cookies and query parameters. It can be a plain function or a coroutine. It runs for every subscription before the connection is accepted: after the channel is validated, and before any store lookup. If it returns false, the connection closes with 4403 forbidden; if it raises, with 1011.
Event Envelope
{
"id": "1719367320123-0",
"event_id": "b6d8c2f1-7e35-4f86-9a67-8d9c8fdd1c55",
"channel": "restaurant:123:orders",
"type": "order.created",
"payload": {"order_id": "ord_123"},
"actor": {"type": "waiter", "id": "usr_123"},
"metadata": {"correlation_id": "req_abc123"},
"created_at": "2026-06-29T12:00:00Z"
}
Reliable publishing and databases
ReplayRail is not a database transaction manager. If your app writes to a database and then publishes to ReplayRail, use an app-owned transactional outbox for critical workflows.
ReplayRail is outbox-friendly via:
event_idprepare_event()publish_event()- event serialization helpers
- optional Redis idempotency
See docs/reliable-publishing.md.
Redis idempotency
RedisStreamStore(..., idempotency=True) can deduplicate publishes by logical event_id for outbox retry flows. By default, duplicate matching events return the existing stream id. With duplicate_policy="raise", duplicates raise DuplicateEventError.
If the same event_id is reused for different content, ReplayRail raises DuplicateEventConflictError.
See docs/idempotency.md.
PostgreSQL
For applications that already run PostgreSQL, PostgresEventStore keeps each channel in PostgreSQL tables instead of a Redis stream. It needs the postgres extra, which installs asyncpg. In your startup code, for example a FastAPI lifespan handler:
import asyncpg
from replayrail import ReplayRail
from replayrail.stores.postgres import PostgresEventStore
pool = await asyncpg.create_pool("postgresql://app@db/app")
store = PostgresEventStore(pool)
await store.create_tables()
rail = ReplayRail(store)
- The pool belongs to your application:
rail.close()releases the store's own connection and leaves the pool open. While it waits for events, the store keeps one connection listening forNOTIFY, so the pool needs at least two. create_tables()createsreplayrail_events,replayrail_channelsandreplayrail_event_idsif they do not exist. To create them in your own migrations instead, apply the SQL thatstore.schema_sql()returns.table_prefixchanges the names.- Publishes to one channel run one at a time, so event IDs follow commit order without gaps. Different channels publish in parallel.
- Publishing is still a write separate from your own data, so critical workflows still need an outbox, as with Redis; see Reliable publishing and databases.
- Payloads, actors and metadata are stored as JSONB, which cannot hold the NUL character (
\u0000); publishing one raisesStoreError. - The idempotency options work as in
RedisStreamStore.
See docs/design/postgresql.md.
Observability
Pass an observer to count publishes, replays, deliveries and closes, measure delivery latency, and see store failures, with the metrics library of your choice:
from replayrail import Failed, Published, ReplayRail, ReplayRailObserver
class Metrics(ReplayRailObserver):
def published(self, published: Published) -> None:
PUBLISHED.labels(published.event.channel).inc()
def failed(self, failed: Failed) -> None:
FAILURES.labels(failed.operation).inc()
rail = ReplayRail(store, observer=Metrics())
The methods of ReplayRailObserver do nothing by default; override the ones you need. Each one receives a single immutable object:
| Method | Fields | When |
|---|---|---|
published |
event |
An event was stored, including a deduplicated one. |
replayed |
channel, after, count |
replay() returned count events. |
subscribed |
channel, live |
A WebSocket subscription passed its checks and was accepted. |
delivered |
channel, event, latency_seconds, replay |
An event was sent to a WebSocket client. |
closed |
channel, code, reason |
ReplayRail closed a connection with one of its codes, including rejections before delivery. |
unsubscribed |
channel |
A subscription reported by subscribed ended, for any reason. |
failed |
operation, channel, error |
publish(), replay() or read() raised StoreError or an unexpected exception. |
subscribed and unsubscribed always come in pairs, so their difference is the number of active subscriptions. latency_seconds runs from the event's created_at to the send, on the server's clock. replay is true for events the client missed while away, and false for events published after it subscribed. To tell them apart, a subscription that starts with a replay looks up the newest event once more when an observer is configured.
Invalid input, expired cursors and duplicate events are not reported as failures. Other errors inside the WebSocket integration appear as closed with code 1011. Observer methods run synchronously and should only record values. If one raises, ReplayRail logs the exception under the replayrail logger and the operation continues. See docs/design/observability.md.
RestaurantHUB Example
ReplayRail core stays generic. RestaurantHUB can model application-specific behavior with channels and event types:
await rail.publish(
channel=f"restaurant:{restaurant_id}:kitchen",
event_type="order.ready",
payload={
"order_id": order_id,
"table_id": table_id,
},
actor={
"type": "kitchen_staff",
"id": staff_id,
},
metadata={
"source": "restauranthub-api",
"correlation_id": request_id,
},
)
Suggested channels:
restaurant:{restaurant_id}:ordersrestaurant:{restaurant_id}:kitchenrestaurant:{restaurant_id}:tablesrestaurant:{restaurant_id}:reservationsrestaurant:{restaurant_id}:adminorder:{order_id}user:{user_id}:notifications
Suggested events:
order.createdorder.confirmedorder.preparingorder.readyorder.deliveredorder.cancelledkitchen.ticket.createdkitchen.ticket.updatedtable.occupiedtable.releasedreservation.createdreservation.cancelledpayment.failedinventory.low
Why Not Just redis.asyncio?
You can use redis.asyncio directly. ReplayRail adds reusable application semantics on top of Redis Streams:
- event envelopes;
- channel validation;
- JSON serialization boundaries;
- cursor-based replay;
- reconnect recovery through
last_event_id; - retention configuration;
- WebSocket delivery;
- pluggable stores for tests and future backends.
redis.asyncio gives you Redis commands. ReplayRail gives your WebSocket application a durable realtime event contract.
Included
- Python package named
replayrail. - Core event models and validation.
- Config object.
- Event store protocol.
- Redis Streams backend using
redis.asyncio. - PostgreSQL backend using asyncpg, as the
postgresextra. - In-memory backend for tests and local development.
ReplayRail.publish(...),ReplayRail.replay(...), andReplayRail.read(...).- FastAPI / Starlette WebSocket integration.
- Cursor-based recovery with
last_event_id. - WebSocket close codes for invalid requests (4400), expired cursors (4410) and server errors (1011).
- Opt-in WebSocket control messages:
replay_completeandclosing. - An
authorizehook per channel, with close code 4403. - One read loop per channel, shared by its WebSocket subscribers, with close code 4429 for a subscriber that falls too far behind.
- Observability hooks through
ReplayRailObserver. ReplayRail.latest_cursor()for live reads that do not skip events.- Basic stream retention through
maxlen. - JSON serialization.
- Logical
event_idfor tracing and deduplication. ReplayRail.prepare_event(...)andReplayRail.publish_event(...).- Stable event dict serialization helpers.
- Optional Redis and memory-store idempotency by
event_id. - Optional healthcheck support.
- Reliable publishing documentation for app-owned outbox patterns.
- Minimal FastAPI example.
Development Verification
The reproducible local verification path uses Docker:
docker compose run --rm test
docker compose down
The test service uses Python 3.14 by default, installs .[redis,fastapi,postgres,dev] with the versions pinned in constraints-dev.txt, builds with the backend versions pinned in constraints-build.txt, runs Redis and PostgreSQL through Compose, sets REDIS_URL=redis://redis:6379 and POSTGRES_URL=postgresql://postgres@postgres:5432/replayrail, and executes:
pytest -p no:cacheprovider
ruff check .
ruff format --check .
mypy src/replayrail
python -m build --dependency-constraints-txt constraints-build.txt
twine check dist/*
pyproject.toml only sets a minimum hatchling version in [build-system], so other builders can use newer ones.
Intentionally Not Included
- database sessions, commits, or rollbacks;
- SQLAlchemy models;
- outbox tables;
- migrations;
- background outbox workers;
- advanced client ACK protocol, delivery tracking, retries, or dead-letter streams;
- Redis consumer groups;
- distributed fanout optimization;
- long-term compliance archive;
- complex auth framework;
- admin UI;
- CLI.
Metrics exporters, dashboards, more backends (NATS JetStream, Kafka/Redpanda) and a frontend client are planned; see ROADMAP.md in the repository.
Known Limitation
ReplayRail prioritizes correctness and simplicity.
- Shared reads are local to one adapter in one process: with several workers, each one reads every channel that its clients subscribe to.
- Replay recovery is bounded by stream retention. ReplayRail can signal expired windows only when the backend can determine that a cursor is older than retained history. Over a WebSocket, an expired cursor closes the connection with 4410.
actorandmetadataare preserved and delivered as audit context, but ReplayRail does not provide a compliance archive or authorization framework.
Planned work is listed in ROADMAP.md in the repository.
Metadata
Release files for replayrail 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| replayrail-0.3.0.tar.gz | 101.0 kB | With provenance | Details for replayrail-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| replayrail-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for replayrail-0.3.0-py3-none-any.whl |
Total release size: 138.3 kB
Release files / replayrail-0.3.0.tar.gz
| Download URL | replayrail-0.3.0.tar.gz |
|---|---|
| Size | 101.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1c128b9bb77278f9a373f81e1b9a97b89041b4fb0a72d0d575619312d277a970
|
|
BLAKE2b-256 checksum How to use checksums |
cd314d12a3c64434da1220d6273583637e1c1bbd55321c0081f7d2efa53c3588
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logRelease files / replayrail-0.3.0-py3-none-any.whl
| Download URL | replayrail-0.3.0-py3-none-any.whl |
|---|---|
| Size | 37.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5c21d86ccc2ee708d2871fbb40ccd7fd6023fac4ed6815d3a6438d9b68314430
|
|
BLAKE2b-256 checksum How to use checksums |
5772d9c2cd5ba8669b3ceb2613c9032f650bf80ee89a3df109ded162b3ccdfb7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logSecurity for replayrail 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for replayrail-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.