Skip to main content

SSE plugin for Starlette

Project description

Server Sent Events for Starlette and FastAPI

PyPI Version Build Status Code Coverage

Implements the Server-Sent Events specification.



pip install sse-starlette


import asyncio
import uvicorn
from starlette.applications import Starlette
from starlette.routing import Route
from sse_starlette.sse import EventSourceResponse

async def numbers(minimum, maximum):
    for i in range(minimum, maximum + 1):
        await asyncio.sleep(0.9)
        yield dict(data=i)

async def sse(request):
    generator = numbers(1, 5)
    return EventSourceResponse(generator)

routes = [
    Route("/", endpoint=sse)

app = Starlette(debug=True, routes=routes)

if __name__ == "__main__":, host="", port=8000, log_level='info')

Output: output

Caveat: SSE streaming does not work in combination with GZipMiddleware.

Be aware that for proper server shutdown your application must stop all running tasks (generators). Otherwise you might experience the following warnings at shutdown: Waiting for background tasks to complete. (CTRL+C to force quit).

Client disconnects need to be handled in your Request handler (see

async def endless(req: Request):
    async def event_publisher():
        i = 0
          while True:
              i += 1
              yield dict(data=i)
              await asyncio.sleep(0.2)
        except asyncio.CancelledError as e:
"Disconnected from client (via refresh/close) {req.client}")
          # Do any other cleanup, if any
          raise e
    return EventSourceResponse(event_publisher())

Special use cases

Customize Ping

By default, the server sends a ping every 15 seconds. You can customize this by:

  1. setting the ping parameter
  2. by changing the ping event to a comment event so that it is not visible to the client
async def handle():
    generator = numbers(1, 100)
    return EventSourceResponse(
        headers={"Server": "nini"},
        ping_message_factory=lambda: ServerSentEvent(**{"comment": "You can't see\r\nthis ping"}),

Fan out Proxies

Fan out proxies usually rely on response being cacheable. To support that, you can set the value of Cache-Control. For example:

return EventSourceResponse(
        generator(), headers={"Cache-Control": "public, max-age=29"}

Error Handling

See example: examples/

Sending Responses without Async Generators

Async generators can expose tricky error and cleanup behavior especially when they are interrupted.

Background: Cleanup in async generators.

Example shows an alternative implementation that does not rely on async generators but instead uses memory channels (examples/

Development, Contributing

  1. install pipenv: pip install pipenv
  2. install dependencies using pipenv: pipenv install --dev -e .
  3. To run tests, either:
    • pipenv run pytest


  • make sure your virtualenv is active: pipenv shell
  • check Makefile for available commands and development support, e.g. run the unit tests:
make test

For integration testing you can use the provided examples in tests and examples.

If you are using Postman, please see:

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sse_starlette-1.8.2.tar.gz (17.2 kB view hashes)

Uploaded source

Built Distribution

sse_starlette-1.8.2-py3-none-any.whl (8.9 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page