How to Implement Server‑Sent Events (SSE) in FastAPI for Real‑Time Apps
Server‑Sent Events (SSE) provide a simple, one‑way server push mechanism over HTTP, ideal for real‑time updates such as dashboards, notifications, and data streams; this guide explains SSE fundamentals, compares alternatives, and walks through integrating SSE into FastAPI using the sse‑starlette library with full code examples.
Server‑Sent Events (SSE) is a server‑push technology that allows a server to push real‑time updates to web clients over a single HTTP connection, making it useful for dashboards, notifications, or live data analysis.
SSE is a standard that lets the server actively send data to the browser after the initial client connection.
Unlike WebSockets, which support bidirectional communication, SSE is unidirectional—data flows from server to client.
This makes SSE a simpler alternative for scenarios where only server‑to‑client updates are needed.
Why use SSE?
SSE has advantages in the following scenarios:
Real‑time updates : Applications that need to push live updates to clients, such as live sports scores, stock market feeds, or chat apps.
Server monitoring and dashboards : Real‑time monitoring dashboards can update metrics and status via SSE without constant client polling.
Notifications : Server‑side notifications can be efficiently managed with SSE, reducing the need for client polling.
Data streams : SSE simplifies streaming large data sets or logs in real time.
Implementing SSE in FastAPI
FastAPI is known for its speed and ease of use; integrating the sse-starlette library makes SSE implementation straightforward.
Step 1: Install required libraries
<code>pip install fastapi sse-starlette</code>Step 2: Create FastAPI application
<code>from fastapi import FastAPI
from sse_starlette.sse import EventSourceResponse
import asyncio
app = FastAPI()
async def event_generator():
while True:
await asyncio.sleep(1)
yield {"data": "This is a server‑sent event!"}
@app.get("/events")
async def sse_endpoint():
return EventSourceResponse(event_generator())
</code>In this example, event_generator is an asynchronous generator that produces a new event every second. The sse_endpoint uses EventSourceResponse to handle the SSE connection.
FastAPI SSE use cases
Real‑time dashboard updates
Real‑time notifications
Streaming logs
SSE advantages
Simplicity : Compared with WebSockets, SSE is easier to implement and manage.
Automatic reconnection : Browsers automatically handle reconnection, making SSE more robust for live updates.
HTTP compatibility : SSE works over standard HTTP/2 connections, simplifying integration with existing infrastructure.
Alternatives to SSE
WebSockets Bidirectional communication: better for applications that require two‑way interaction. Low latency: WebSockets have lower latency, suitable for highly interactive apps like online games.
Long polling Compatibility: works with older browsers that do not support WebSockets or SSE. Overhead: repeated requests introduce more overhead compared to SSE or WebSockets.
Real‑world SSE applications
Server‑Sent Events are widely adopted in real‑time scenarios. Notable examples include live sports scores, stock market and financial data feeds, and social media platforms.
SSE implementation
Server‑side
The following JSON file contains match summaries that the server streams via SSE.
<code>[
{
"time": "00:01",
"scores": "1:0",
"event": "Goal! Team A scores!"
},
{
"time": "00:05",
"scores": "1:1",
"event": "Goal! Team B scores!"
},
{
"time": "00:10",
"scores": "2:1",
"event": "Goal! Team A scores again!"
}
]
</code>The server maintains real‑time match data and pushes updates through SSE to connected clients whenever an event occurs.
<code># main.py
from fastapi import FastAPI
from sse_starlette.sse import EventSourceResponse
import asyncio
import json
app = FastAPI()
async def event_generator():
with open("scores.json", "r") as file:
scores = json.load(file)
for score in scores:
await asyncio.sleep(5)
yield f"Match Summary: {json.dumps(score)}\n\n"
@app.get("/live-scores")
async def live_scores_endpoint():
return EventSourceResponse(event_generator())
# Add CORS middleware
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
</code>Client‑side
The client (a web application) establishes an SSE connection to the server and listens for updates.
<code><!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Real‑time Sports Scores</title>
</head>
<body>
<h1>Live Football Scores</h1>
<div id="score-updates"></div>
<script>
const eventSource = new EventSource("http://127.0.0.1:8000/live-scores");
eventSource.onmessage = function(event) {
const newElement = document.createElement("div");
newElement.innerHTML = event.data;
document.getElementById("score-updates").appendChild(newElement);
};
eventSource.onerror = function(event) {
console.error("EventSource failed:", event);
eventSource.close();
};
</script>
</body>
</html>
</code>References
https://fastapi.tiangolo.com/
https://pypi.org/project/sse-starlette/
Conclusion
With sse-starlette , integrating SSE into a FastAPI application becomes simple and efficient. Whether you are building real‑time dashboards, notification systems, or streaming data apps, SSE offers a robust and straightforward solution.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.