15 · Server-Sent Events and One-Way Live Status Updates
In the previous lesson, we completed both sides of the review workflow:
Background task→ changes SQLite status
Browser polling→ repeatedly asks for SQLite statusThat worked, but polling created a complete HTTP request every few seconds:
GET status→ authenticate→ authorize→ open Session→ query SQLite→ return JSON→ close Session→ wait→ repeatToday we replace that polling loop with Server-Sent Events, usually shortened to SSE.
The browser will open one longer-lived HTTP connection. FastAPI will keep that response open and send status events through it:
Browser opens SSE connection ↓Server sends pending ↓Server sends processing ↓Server sends completed ↓Browser closes connectionThe review’s background execution does not change.
SSE changes only how the browser learns about progress.
Where today’s code sits
Section titled “Where today’s code sits”The complete lifecycle becomes:
Browser clicks Start review→ POST /documents/101/review→ authentication, authorization, and CSRF validation→ service commits pending→ 202 Accepted returns→ in-process background work begins
Browser opens EventSource→ GET /documents/101/events→ authentication and authorization→ FastAPI keeps response open
Background worker commits processing→ SSE endpoint observes processing→ server writes an event into the open response→ browser receives event→ JavaScript updates DOM
Background worker commits completed→ SSE endpoint sends completed event→ JavaScript updates DOM→ browser closes EventSourceSSE is a one-way channel:
FastAPI → browserThe browser cannot send a “start review” command back through the SSE connection. That still requires the authenticated POST request from the previous lesson.
The modern FastAPI SSE interface
Section titled “The modern FastAPI SSE interface”Modern FastAPI includes:
from fastapi.sse import ( EventSourceResponse, ServerSentEvent,)This interface was added in FastAPI 0.135.0. Older examples often use the third-party sse-starlette package, so this is one area where older tutorials can look different.
FastAPI’s current pattern is:
@router.get( "/events", response_class=EventSourceResponse,)async def events(): yield ServerSentEvent( event="update", data={"message": "Something changed"}, )Each yield writes one event into the same ongoing HTTP response. FastAPI
The browser page
Section titled “The browser page”Our Jinja page now provides an events URL:
<section id="review-panel" data-start-url="{{ url_for( 'start_document_review', document_id=review_document.id ) }}" data-events-url="{{ url_for( 'document_review_events', document_id=review_document.id ) }}"> <p> Review status: <strong id="review-status"> {{ review_document.status }} </strong> </p>
<button id="start-review" type="button" > Start review </button>
<button id="reconnect-events" type="button" hidden > Reconnect </button>
<p id="status-message" role="status" aria-live="polite" ></p></section>For document 101, Jinja produces:
data-start-url="/documents/101/review"data-events-url="/documents/101/events"The HTML response gives JavaScript the document-specific URLs without hard-coding IDs into the shared JavaScript file.
Keep the CSRF <meta> element from lesson 14 as well. The events URL belongs to a read request, but the Start review button still sends the protected write request.
A short-lived authorization dependency
Section titled “A short-lived authorization dependency”An SSE response may remain open for a while.
We do not want to load a SQLAlchemy ORM object through the normal request-scoped session and then carry that object throughout the stream.
Instead, the authorization dependency returns a small immutable description of the permitted access:
from dataclasses import dataclassfrom typing import Annotated
from fastapi import Depends, HTTPExceptionfrom sqlalchemy import select
from .database import SessionLocalfrom .models.documents import Document
@dataclass(frozen=True)class DocumentStreamAccess: document_id: int firm_id: int | None is_admin: bool
def get_document_stream_access( document_id: int, current_user: CurrentUserDep,) -> DocumentStreamAccess: access = DocumentStreamAccess( document_id=document_id, firm_id=current_user["firm_id"], is_admin=current_user["role"] == "admin", )
if read_document_status(access) is None: raise HTTPException( status_code=404, detail="Document not found", )
return access
DocumentStreamDep = Annotated[ DocumentStreamAccess, Depends(get_document_stream_access),]This code belongs alongside the existing CurrentUserDep definition in app/dependencies.py. Define read_document_status() below in that same module before serving requests.
The dataclass contains ordinary Python values:
document_idfirm_idis_adminIt does not contain:
SQLAlchemy Sessiondatabase connectionORM Document objectRequest objectThe option:
@dataclass(frozen=True)makes instances immutable through normal attribute assignment.
Once constructed, the dependency result serves as a small access description for this connection.
Reading the status with a fresh session
Section titled “Reading the status with a fresh session”The dependency calls this helper:
def read_document_status( access: DocumentStreamAccess,) -> str | None: with SessionLocal() as db: statement = select(Document.status).where( Document.id == access.document_id, )
if not access.is_admin: if access.firm_id is None: return None
statement = statement.where( Document.firm_id == access.firm_id, )
return db.scalar(statement)Every call creates a short-lived SQLAlchemy session:
with SessionLocal() as db:It constructs a query for the document’s status:
select(Document.status)For an ordinary user, the query is restricted by both document and firm:
SELECT statusFROM documentsWHERE id = 101 AND firm_id = 10;If no authorized row matches:
db.scalar(statement)returns None.
This preserves the authorization behavior used earlier:
Nonexistent document→ 404
Document belonging to another firm→ also 404We do not reveal whether another firm’s document exists.
Most importantly, the session closes immediately after one query. We do not leave a session or database transaction open for the full streaming connection.
The event data model
Section titled “The event data model”The browser needs only two values:
from typing import Literal
from pydantic import BaseModel
ReviewStatus = Literal[ "not_started", "pending", "processing", "completed", "failed",]
class DocumentStatusEvent(BaseModel): document_id: int status: ReviewStatusThis is a Pydantic model, but it is not the model for one complete HTTP JSON response.
It describes the data carried inside each SSE event.
An event may contain:
{ "document_id": 101, "status": "processing"}The SSE route
Section titled “The SSE route”Here is the complete route:
import asyncioimport timefrom collections.abc import AsyncIterable
from fastapi import APIRouter, Requestfrom fastapi.sse import ( EventSourceResponse, ServerSentEvent,)
router = APIRouter(prefix="/documents")
TERMINAL_STATUSES = { "completed", "failed",}
STATUS_CHECK_SECONDS = 1HEARTBEAT_SECONDS = 15MAX_STREAM_SECONDS = 60
@router.get( "/{document_id}/events", response_class=EventSourceResponse,)async def document_review_events( request: Request, access: DocumentStreamDep,) -> AsyncIterable[ServerSentEvent]: previous_status = None
started_at = time.monotonic() last_event_at = started_at
while ( time.monotonic() - started_at < MAX_STREAM_SECONDS ): if await request.is_disconnected(): return
current_status = await asyncio.to_thread( read_document_status, access, )
if current_status is None: yield ServerSentEvent( event="review_unavailable", data={ "message": "The document is no longer available." }, ) return
if current_status != previous_status: yield ServerSentEvent( event="review_status", data=DocumentStatusEvent( document_id=access.document_id, status=current_status, ), retry=3000, )
previous_status = current_status last_event_at = time.monotonic()
if current_status in TERMINAL_STATUSES: return
if ( time.monotonic() - last_event_at >= HEARTBEAT_SECONDS ): yield ServerSentEvent( comment="keep-alive", )
last_event_at = time.monotonic()
await asyncio.sleep( STATUS_CHECK_SECONDS )This is one route, one response, and potentially several events.
Let’s walk through it carefully.
Opening the EventSource connection
Section titled “Opening the EventSource connection”The browser will request:
GET /documents/101/events HTTP/1.1Accept: text/event-streamCookie: app_session=...Session middleware reconstructs the session from the cookie.
FastAPI then resolves:
access: DocumentStreamDepThe dependency authenticates the user through CurrentUserDep, constructs the access description, and confirms that the user may read this document.
If authorization fails, FastAPI returns a normal 404 response before establishing the event stream.
If it succeeds, the route begins producing an SSE response with the content type:
Content-Type: text/event-streamUnlike polling, authentication and the top-level authorization dependency run once when the connection is established. They do not run again for every event sent through that connection.
This is one reason long-lived streams should have a bounded lifetime. Our example ends each connection after at most 60 seconds. If the review is still running, the browser reconnects and the entire authentication and authorization process runs again.
This is a soft lifetime bound: a database call already in progress can extend it. The access description holds the user’s role and firm as they were at connection time. Those user attributes are refreshed on the next connection; immediate permission revocation would require checking the current user during the stream as well.
The async generator
Section titled “The async generator”The route is declared with:
async def document_review_events(...)but it does not return one final object.
It uses:
yield ServerSentEvent(...)A function containing yield is a generator.
In this case, it is an asynchronous generator because it combines:
async def+yieldEach yield temporarily gives FastAPI one event to send. Later, execution resumes after that yield.
The route can therefore behave like this:
Query current status→ yield pending→ wait
Query again→ no change→ wait
Query again→ yield processing→ wait
Query again→ yield completed→ finishThe entire sequence occurs inside one HTTP response.
Detecting a disconnected browser
Section titled “Detecting a disconnected browser”The loop begins with:
if await request.is_disconnected(): returnThis asks whether the browser connection has gone away.
That may happen because the user:
- Closed the tab
- Navigated elsewhere
- Lost network connectivity
- Explicitly closed the
EventSource - Put the device to sleep
If the connection is gone:
returnends the generator.
This stops the SSE route from continuing to query SQLite for a browser that can no longer receive events.
It does not stop the document review.
The background worker still owns that operation.
Calling synchronous SQLAlchemy safely
Section titled “Calling synchronous SQLAlchemy safely”Our SQLAlchemy configuration is synchronous.
The database helper contains blocking operations:
with SessionLocal() as db: return db.scalar(statement)The SSE route is asynchronous, so it calls the helper using:
current_status = await asyncio.to_thread( read_document_status, access,)asyncio.to_thread() runs the synchronous helper in a worker thread and allows this asynchronous function to wait without directly blocking the server’s event loop.
The important division is:
Event-stream coordination→ async function
Synchronous SQLAlchemy query→ worker thread
SQLAlchemy Session→ created and closed inside that threadWe will examine Python’s event loop and the difference between “blocking” and “waiting” in a later dedicated lesson. For now, the architectural rule is enough:
Do not execute slow synchronous database work directly inside the async event loop, and do not share one Session between concurrent threads or tasks.
Sending only changed statuses
Section titled “Sending only changed statuses”The route remembers:
previous_status = NoneAfter each database read, it compares:
if current_status != previous_status:On the first pass:
previous_status = Nonecurrent_status = pendingThe values differ, so FastAPI sends an event.
On the next pass:
previous_status = pendingcurrent_status = pendingNothing changed, so it sends no status event.
Later:
previous_status = pendingcurrent_status = processingThe route sends another event.
This means the server may check SQLite once per second without sending identical pending messages once per second.
The open HTTP connection carries events only when visible application state changes.
Building an SSE event
Section titled “Building an SSE event”The route yields:
yield ServerSentEvent( event="review_status", data=DocumentStatusEvent( document_id=access.document_id, status=current_status, ), retry=3000,)There are three important fields.
The first is:
event="review_status"This names the event.
Browser JavaScript can register a handler specifically for:
review_statusThe second is:
data=DocumentStatusEvent(...)FastAPI serializes the Pydantic model as event data.
The third is:
retry=3000This tells the browser to wait approximately 3,000 milliseconds before reconnecting if the connection is lost.
On the network, the event conceptually looks like:
event: review_statusretry: 3000data: {"document_id":101,"status":"processing"}The blank line ends the event.
SSE is a text protocol. The browser receives text in the data: field and will parse the JSON into a JavaScript object.
This is not several HTTP responses
Section titled “This is not several HTTP responses”A common misunderstanding is to picture each event as a new response:
Response 1: pendingResponse 2: processingResponse 3: completedThat is not what happens.
There is one response:
HTTP/1.1 200 OKContent-Type: text/event-streamIts body arrives gradually:
event: review_statusdata: {"document_id":101,"status":"pending"}
event: review_statusdata: {"document_id":101,"status":"processing"}
event: review_statusdata: {"document_id":101,"status":"completed"}With polling, the browser repeatedly opens complete request-response exchanges.
With SSE, the response body remains open and grows as the server yields events.
Heartbeats
Section titled “Heartbeats”Suppose the review stays processing for 45 seconds.
Our route will not send repeated status events, because the status has not changed. But an entirely silent connection may be closed by a proxy, load balancer, or other intermediary.
After 15 seconds without a real event, the route sends:
yield ServerSentEvent( comment="keep-alive",)On the wire, this resembles:
: keep-aliveAn SSE line beginning with a colon is a comment. The browser ignores it as application data, but the bytes keep the connection active.
SSE comments are commonly used as keep-alives for otherwise quiet connections. MDN
The heartbeat does not mean:
The review made progress.It means:
The event stream is still alive.Terminal statuses
Section titled “Terminal statuses”After yielding a changed status, the route checks:
if current_status in TERMINAL_STATUSES: returnThe terminal statuses are:
{ "completed", "failed",}For completed, the sequence is:
Read completed from SQLite→ yield completed event→ return from generator→ server finishes responseThe browser receives the final event before the response closes.
Its JavaScript handler will then explicitly close the EventSource so the browser does not reconnect unnecessarily.
Why the stream ends after 60 seconds
Section titled “Why the stream ends after 60 seconds”The loop has a maximum lifetime:
MAX_STREAM_SECONDS = 60and:
while ( time.monotonic() - started_at < MAX_STREAM_SECONDS):time.monotonic() is appropriate for measuring elapsed durations because it is not affected by ordinary wall-clock corrections.
If the review is still running after 60 seconds, the generator ends and the response closes.
By default, EventSource reconnects when its connection closes. MDN
That creates a useful cycle:
Open stream→ authorize→ stream for at most 60 seconds→ close→ browser reconnects→ authenticate and authorize again→ continueThe connection is long-lived, but not permanent.
This also prevents one stale authentication decision from living indefinitely.
The browser JavaScript
Section titled “The browser JavaScript”Here is the event-stream client. It replaces the polling portion of lesson 13; we do not keep both observers running. Keep shared declarations such as panel, statusElement, and messageElement only once when combining this with the start-request code.
const ACTIVE_STATUSES = new Set([ "pending", "processing",]);
const TERMINAL_STATUSES = new Set([ "completed", "failed",]);
const panel = document.querySelector("#review-panel");
const statusElement = document.querySelector("#review-status");
const messageElement = document.querySelector("#status-message");
const reconnectButton = document.querySelector("#reconnect-events");
let reviewEvents = null;
reconnectButton.addEventListener( "click", connectReviewEvents,);
window.addEventListener( "pagehide", closeReviewEvents,);
window.addEventListener("pageshow", (event) => { if ( event.persisted && ACTIVE_STATUSES.has(statusElement.textContent.trim()) ) { connectReviewEvents(); }});
const initialStatus = statusElement.textContent.trim();
if (ACTIVE_STATUSES.has(initialStatus)) { connectReviewEvents();}
function connectReviewEvents() { closeReviewEvents();
reconnectButton.hidden = true; messageElement.textContent = "Connecting to review updates…";
const eventSource = new EventSource( panel.dataset.eventsUrl, );
reviewEvents = eventSource;
eventSource.addEventListener( "open", () => { if (reviewEvents !== eventSource) { return; }
messageElement.textContent = "Listening for review updates…"; }, );
eventSource.addEventListener( "review_status", (event) => { if (reviewEvents !== eventSource) { return; }
const data = JSON.parse(event.data);
statusElement.textContent = data.status;
if ( TERMINAL_STATUSES.has(data.status) ) { finishReviewStream(data.status); return; }
messageElement.textContent = `Review is ${data.status}.`; }, );
eventSource.addEventListener( "review_unavailable", (event) => { if (reviewEvents !== eventSource) { return; }
const data = JSON.parse(event.data);
closeReviewEvents();
messageElement.textContent = data.message; }, );
eventSource.addEventListener( "error", () => { if (reviewEvents !== eventSource) { return; }
if (eventSource.readyState === EventSource.CLOSED) { closeReviewEvents(); reconnectButton.hidden = false; messageElement.textContent = "Connection closed. Check your access, then reconnect."; } else { messageElement.textContent = "Connection interrupted. Reconnecting…"; } }, );}
function finishReviewStream(status) { closeReviewEvents();
messageElement.textContent = status === "completed" ? "Review completed." : "Review failed.";}
function closeReviewEvents() { reviewEvents?.close(); reviewEvents = null;}There are also two small changes to startReview() from lesson 14.
First, the start URL now lives on the panel rather than on the button. The request therefore begins with:
const response = await fetch( panel.dataset.startUrl, { method: "POST", headers: { Accept: "application/json", "X-CSRF-Token": csrfToken, }, },);Second, after the existing response checks and JSON parsing, replace the call to startPolling() with:
statusElement.textContent = data.status;connectReviewEvents();Keep the click listener, CSRF-token lookup, and error handling from lesson 14. Remove the old polling listeners and timers. We are changing the observer, while preserving the authenticated command that starts the work.
This focused version leaves the start button disabled after acceptance; reload the page before deliberately starting another review. Lesson 18 will connect terminal events, saved results, and the controls into one page lifecycle.
Now let’s follow what the browser does.
Constructing EventSource
Section titled “Constructing EventSource”The connection begins with:
const eventSource = new EventSource( panel.dataset.eventsUrl,);The browser immediately sends a GET request to:
/documents/101/eventsEventSource is a browser-provided object designed specifically for receiving text/event-stream responses.
The connection remains open until:
- The server closes it
- The network fails
- JavaScript calls
.close() - The page disappears
Unlike a normal fetch() call, we do not await one final response body. Events arrive over time and invoke registered handlers.
SSE is unidirectional: messages travel from the server to the browser, not in both directions. MDN
Cookies, headers, and CSRF
Section titled “Cookies, headers, and CSRF”For a same-origin EventSource URL, the browser includes applicable cookies. Session middleware can therefore authenticate the connection.
But the native EventSource constructor does not let us freely add headers such as:
X-CSRF-Token: ...That is acceptable because this endpoint is a read:
GET /documents/101/eventsOpening the stream does not start a review or change database state. Therefore, it does not require the write-request CSRF token used by the POST route.
The architectural split remains:
POST /documents/101/review→ changes state→ requires CSRF protection
GET /documents/101/events→ observes state→ must authenticate and authorize→ does not change stateA GET endpoint should not secretly perform mutations merely because EventSource makes GET convenient.
Also, authentication tokens should not casually be placed in the events URL. Query strings can appear in logs, browser history, monitoring tools, and proxy records.
Cookie authentication is a cleaner fit for this same-origin server-rendered application.
The open event
Section titled “The open event”Once the browser establishes the connection, it dispatches:
"open"Our handler displays:
Listening for review updates…This tells the user that the live connection exists.
It does not mean the review is completed—or even processing. It describes the communication connection, not the business operation.
Again, there are two different states:
Connection state→ connecting, open, interrupted
Review state→ pending, processing, completed, failedA review can continue normally while the SSE connection is temporarily interrupted.
Receiving a named status event
Section titled “Receiving a named status event”The server sends:
event: review_statusdata: {"document_id":101,"status":"processing"}Because it has the event name:
review_statusthe browser calls:
eventSource.addEventListener( "review_status", handler,);The handler receives an event object.
Its:
event.dataproperty contains JSON text:
'{"document_id":101,"status":"processing"}'It is still a string.
JavaScript converts that string into an object:
const data = JSON.parse(event.data);Now:
data.statuscontains:
"processing"The handler safely updates the page using:
statusElement.textContent = data.status;textContent treats the value as text rather than executable HTML.
Reconnection
Section titled “Reconnection”If Wi-Fi briefly disappears, the browser dispatches an error event:
eventSource.addEventListener( "error", ...);Our code displays:
Connection interrupted. Reconnecting…It does not immediately call:
eventSource.close();That is intentional.
Native EventSource automatically attempts to reconnect. The server’s:
retry=3000asks it to wait about three seconds.
The reconnection is a new HTTP request:
New GET→ middleware→ authentication→ authorization dependency→ new event-stream responseThe new server generator immediately reads SQLite’s current value.
If the browser disconnected during processing and reconnects after completion, the first new event may be:
{ "document_id": 101, "status": "completed"}The browser does not need to receive every intermediate status. It needs the current authoritative state.
Current-state streams versus event history
Section titled “Current-state streams versus event history”SSE supports event IDs and a Last-Event-ID reconnection header.
Those are valuable when every event matters:
Audit event 42Audit event 43Audit event 44If the browser received event 42 before disconnecting, it could reconnect and ask to resume after 42.
Our review-status stream has different semantics:
What is the document’s current status now?If the browser misses:
pending → processingbut reconnects and receives:
completednothing important is lost.
Therefore, this example does not maintain an event-history table or event IDs. It simply rereads current state after reconnection.
This is an important design choice:
State stream→ reconnect by reading current state
Event log→ reconnect by resuming after a durable event IDIf we later streamed document findings that must each be delivered exactly once, we would need persistent event records rather than only the latest document status.
Closing at the terminal state
Section titled “Closing at the terminal state”When JavaScript receives:
data.status === "completed"it calls:
finishReviewStream(data.status);That function begins with:
closeReviewEvents();which calls:
reviewEvents?.close();The optional chaining operator means:
If an EventSource exists, call its
close()method.
Then:
reviewEvents = null;clears our reference.
Explicitly closing is important. Otherwise, when the server finishes the response after sending completed, the browser may interpret the closed connection as something to reconnect.
The review is terminal, so another connection would provide no value.
Leaving the page
Section titled “Leaving the page”The browser also registers:
window.addEventListener( "pagehide", closeReviewEvents,);If the user navigates away, JavaScript closes the EventSource.
FastAPI’s request-disconnection check then ends the server generator.
This tears down the communication channel, but the background review remains independent:
Close page→ close EventSource→ stop streaming updates
Background worker→ continues processing→ commits result to SQLiteWhen the user returns later, Jinja renders the latest database status into a new page.
SSE still has costs
Section titled “SSE still has costs”SSE removes repeated HTTP setup, but it does not make updates free.
Every connected browser occupies:
- An open HTTP stream
- Application connection state
- Server resources
- Proxy and load-balancer capacity
Our particular implementation also queries SQLite once per second for each active stream:
One browser stream→ one status query per secondSo this first SSE implementation reduces:
Repeated HTTP requestsRepeated middleware executionRepeated authentication dependency resolutionbut it does not eliminate database polling.
At larger scale, the background worker could publish updates to:
- An in-process channel
- Redis pub/sub
- A message broker
- PostgreSQL notifications
- Another durable event mechanism
The SSE endpoint would then wait for published changes instead of querying SQLite every second.
An in-memory channel works only within one process. If the background worker and SSE connection live in different FastAPI workers or servers, they need shared infrastructure.
For our small SQLite application, short status queries are a reasonable teaching and MVP pattern.
Nginx and buffering
Section titled “Nginx and buffering”A reverse proxy may buffer response data instead of forwarding every small event immediately.
That would produce confusing behavior:
FastAPI yields pendingFastAPI yields processingFastAPI yields completedNginx buffers everythingBrowser receives all three at onceFor an SSE route, buffering should be disabled.
A typical Nginx location includes settings such as:
proxy_buffering off;proxy_cache off;proxy_read_timeout 90s;The application or proxy may also use:
X-Accel-Buffering: noCache-Control: no-cacheThis is not a Python control-flow problem. It is part of the complete production path:
FastAPI→ Uvicorn→ Nginx→ network→ browserEvery layer between FastAPI and the browser must allow incremental delivery.
Polling versus SSE
Section titled “Polling versus SSE”The difference is now concrete:
| Polling | Server-Sent Events |
|---|---|
| Browser repeatedly asks | Browser opens one stream |
| Many request-response cycles | One longer-lived response |
| Auth runs for every poll | Auth runs when stream connects |
| Easy to inspect and scale modestly | Faster updates with fewer HTTP exchanges |
| Natural retry under application control | Browser reconnects automatically |
| No persistent connection | Server holds an open connection |
| Works almost everywhere | Proxy buffering and connection limits matter |
For a review taking 10–30 seconds, polling every three seconds may be entirely sufficient.
SSE becomes attractive when:
- Updates should arrive promptly.
- Several progress changes may occur.
- Repeated request overhead is undesirable.
- Communication is naturally server-to-browser.
- The infrastructure supports streaming correctly.
WebSockets are not automatically “better.” We still do not need bidirectional messages over one connection.
The browser sends commands through ordinary HTTP writes. The server sends progress through SSE.
That is a clean division.
The complete execution trace
Section titled “The complete execution trace”For one successful SSE review:
- Jinja renders the page with start and events URLs.
- The browser constructs the DOM.
- The user clicks Start review.
- JavaScript sends the CSRF-protected
POST. - Middleware reconstructs the authenticated session.
- FastAPI authenticates and authorizes the write.
- The service commits
pendingto SQLite. - FastAPI schedules the background operation.
- FastAPI returns
202 Accepted. - JavaScript constructs an
EventSource. - The browser sends
GET /documents/101/events. - Middleware authenticates the stream request.
- The stream dependency verifies document access.
- FastAPI begins a
text/event-streamresponse. - The SSE generator opens a short SQLAlchemy session.
- SQLite returns
pending. - FastAPI yields a
review_statusevent. - The browser parses its JSON data.
- JavaScript displays
pending. - The background worker commits
processing. - The SSE generator’s next short query sees the change.
- FastAPI yields another event through the same response.
- JavaScript displays
processing. - The background worker finishes and commits
completed. - The generator yields the terminal event.
- JavaScript displays
completed. - JavaScript calls
EventSource.close(). - The server generator ends.
- All database sessions used during the stream have already been individually closed.
The central idea is:
Background processing→ performs the review
SQLite→ stores authoritative state
SSE→ carries state changes toward the browser
JavaScript→ turns received events into visible DOM updatesSSE does not perform the review, replace authorization, or keep one database session alive. It is simply a browser-friendly way for the server to send one-way updates over an HTTP response that remains open.
The next installment will introduce WebSockets and show what genuinely changes when the browser and server can both send messages through the same persistent connection—and why most document-review workflows still do not need that additional power.