Registry / web-framework / sse-starlette

sse-starlette

JSON →
library3.4.8pypypi✓ verified 30d ago

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-starlette
INSTALL
IMPORT
SIG · SSE-STARLETTE
S
sse-starlette
web-frameworkpythonv3.4.8
Install
2.2s avg
Import
348ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v3.4.8 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.376s · 20.7MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 2.2s · import 0.320s · 21MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

EventSourceResponse
✓ from sse_starlette import EventSourceResponse
ServerSentEvent
✓ from sse_starlette import ServerSentEvent
JSONServerSentEvent
✓ from sse_starlette import JSONServerSentEvent

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.

import asyncio from starlette.applications import Starlette from starlette.routing import Route from sse_starlette import EventSourceResponse async def generate_events(): for i in range(10): yield {"data": f"Event {i}"} await asyncio.sleep(1) async def sse_endpoint(request): return EventSourceResponse(generate_events()) app = Starlette(routes=[Route("/events", sse_endpoint)]) # To run this example, you would typically use an ASGI server like uvicorn: # uvicorn your_module_name:app --reload
Debug
Known issues
gotchaSSE streaming does not work in combination with Starlette's GZipMiddleware. Applying GZipMiddleware to an SSE endpoint will buffer the response, preventing real-time delivery.
fix
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.
affects: <3.3.3
gotchaReverse proxies (e.g., Nginx, Apache, Cloudflare, Akamai, HAProxy) often buffer responses by default, which can break the real-time nature of SSE. This can cause events to be delayed or batched.
fix
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.
affects: All versions
breakingPrior to v3.2.0, handling graceful shutdown of SSE streams could be problematic, often leading to 'Waiting for background tasks to complete' warnings or immediate force-cancellation of generators upon server termination. This prevented proper cleanup or sending final events.
fix
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.
affects: <3.2.0
gotchaVersions prior to v3.1.2 had a 'watcher task leak' due to incorrect `threading.local` usage, potentially leading to resource exhaustion or unexpected behavior in long-running applications.
fix
Upgrade to v3.1.2 or newer to benefit from the fix preventing this task leak.
affects: <3.1.2
gotchaWhen using database sessions (e.g., SQLAlchemy's `AsyncSession`) or other non-thread-safe objects within SSE generators, care must be taken to avoid passing them directly. The streaming internally uses `anyio.TaskGroups`, which can lead to thread-safety issues.
fix
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.
affects: All versions
gotchaThe test environment generated warnings related to pip usage, specifically concerning running pip as the 'root' user and suggesting a pip version upgrade. These are not direct failures of the tested library but indicate sub-optimal or potentially problematic environment setup for package management.
fix
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`).
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'sse_starlette'
The `sse-starlette` library has not been installed in the active Python environment.
fix
pip install sse-starlette
TypeError: 'list' object is not async iterable
`EventSourceResponse` requires an asynchronous generator (an `async def` function that uses `yield`), but a synchronous iterable like a list was provided.
fix
Define an `async def` function that uses `yield` to produce events, then pass this generator function to `EventSourceResponse`.
TypeError: expected string or bytes-like object, got dict
The `async` generator is yielding Python objects (like dictionaries) directly, but `EventSourceResponse` expects event data to be a string or bytes.
fix
Serialize the data to a JSON string (e.g., using `json.dumps()`) before yielding it from the `async` generator.
RuntimeError: generator didn't stop itself
The `async` generator function, typically within a `while True` loop, does not properly handle `GeneratorExit` when the client disconnects, leading to the ASGI server reporting an unstopped generator.
fix
Modify the `async` generator to catch `GeneratorExit` and break its loop gracefully, for example, by wrapping the loop in `try...except GeneratorExit: break`.
Upgrade
Version history
3.4.8latest on PyPI · released Aug 5, 2026
Audit
Dependencies
starletterequiredCore web framework dependency for SSE integration.
anyiorequiredAsynchronous I/O library used for concurrency management.
pythonrequiredRequired Python version.
Agent activity
39 hits · last 30 days
node
32
OpenAI (training)
1
Resources
sse-starlette — pip install sse-starlette · libregistry