sse-starlette is a production-ready Python library that provides a Server-Sent Events (SSE) plugin for Starlette and FastAPI frameworks. It offers a standards-compliant implementation of the W3C SSE specification, including features like automatic client disconnect detection, graceful shutdown, and thread-safe event management. The current version is 3.3.3, and the library maintains an active release cadence with regular updates and dependency management.
pip install sse-starletteVerified import paths — ran on the pinned version, not inferred.
This quickstart sets up a basic Starlette application with an `/events` endpoint that streams ten Server-Sent Events, each separated by a one-second delay. The `EventSourceResponse` handles the SSE protocol details, including event formatting and connection management.
Avoid using GZipMiddleware on routes that serve `EventSourceResponse`. Consider configuring your reverse proxy for compression if needed for other endpoints, but bypass it for SSE streams.
Configure your reverse proxy to disable buffering for SSE endpoints. For Nginx, add `proxy_buffering off;` and `X-Accel-Buffering: no` header. For other proxies, consult their documentation for equivalent settings.
Upgrade to v3.2.0 or newer. Use the `shutdown_event` exposed in generators (v3.3.0+) for cooperative shutdown, or configure `AppStatus.enable_automatic_graceful_drain_mode` to manage how streams terminate during server shutdown. Ensure your graceful shutdown period in `sse-starlette` is less than your ASGI server's graceful shutdown timeout.
Upgrade to v3.1.2 or newer to benefit from the fix preventing this task leak.
Ensure that any objects passed to SSE generators are thread-safe or are instantiated within the generator's context to prevent concurrent access issues. For database sessions, open and close them within the generator's async scope.
It is recommended to use a virtual environment for Python projects to avoid permission issues and conflicts with the system package manager. Avoid running pip as the 'root' user. Regularly update pip to its latest version (e.g., `pip install --upgrade pip`).
pip install sse-starlette
Define an `async def` function that uses `yield` to produce events, then pass this generator function to `EventSourceResponse`.
Serialize the data to a JSON string (e.g., using `json.dumps()`) before yielding it from the `async` generator.
Modify the `async` generator to catch `GeneratorExit` and break its loop gracefully, for example, by wrapping the loop in `try...except GeneratorExit: break`.