Skip to content

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 status

That worked, but polling created a complete HTTP request every few seconds:

GET status
→ authenticate
→ authorize
→ open Session
→ query SQLite
→ return JSON
→ close Session
→ wait
→ repeat

Today 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 connection

The review’s background execution does not change.

SSE changes only how the browser learns about progress.


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 EventSource

SSE is a one-way channel:

FastAPI → browser

The browser cannot send a “start review” command back through the SSE connection. That still requires the authenticated POST request from the previous lesson.


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


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.


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:

app/dependencies.py
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, HTTPException
from sqlalchemy import select
from .database import SessionLocal
from .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_id
firm_id
is_admin

It does not contain:

SQLAlchemy Session
database connection
ORM Document object
Request object

The 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.


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 status
FROM documents
WHERE 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 404

We 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 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: ReviewStatus

This 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"
}

Here is the complete route:

import asyncio
import time
from collections.abc import AsyncIterable
from fastapi import APIRouter, Request
from fastapi.sse import (
EventSourceResponse,
ServerSentEvent,
)
router = APIRouter(prefix="/documents")
TERMINAL_STATUSES = {
"completed",
"failed",
}
STATUS_CHECK_SECONDS = 1
HEARTBEAT_SECONDS = 15
MAX_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.


The browser will request:

GET /documents/101/events HTTP/1.1
Accept: text/event-stream
Cookie: app_session=...

Session middleware reconstructs the session from the cookie.

FastAPI then resolves:

access: DocumentStreamDep

The 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-stream

Unlike 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 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
+
yield

Each 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
→ finish

The entire sequence occurs inside one HTTP response.


The loop begins with:

if await request.is_disconnected():
return

This 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:

return

ends 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.


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 thread

We 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.


The route remembers:

previous_status = None

After each database read, it compares:

if current_status != previous_status:

On the first pass:

previous_status = None
current_status = pending

The values differ, so FastAPI sends an event.

On the next pass:

previous_status = pending
current_status = pending

Nothing changed, so it sends no status event.

Later:

previous_status = pending
current_status = processing

The 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.


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_status

The second is:

data=DocumentStatusEvent(...)

FastAPI serializes the Pydantic model as event data.

The third is:

retry=3000

This 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_status
retry: 3000
data: {"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.


A common misunderstanding is to picture each event as a new response:

Response 1: pending
Response 2: processing
Response 3: completed

That is not what happens.

There is one response:

HTTP/1.1 200 OK
Content-Type: text/event-stream

Its body arrives gradually:

event: review_status
data: {"document_id":101,"status":"pending"}
event: review_status
data: {"document_id":101,"status":"processing"}
event: review_status
data: {"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.


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-alive

An 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.

After yielding a changed status, the route checks:

if current_status in TERMINAL_STATUSES:
return

The terminal statuses are:

{
"completed",
"failed",
}

For completed, the sequence is:

Read completed from SQLite
→ yield completed event
→ return from generator
→ server finishes response

The 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.


The loop has a maximum lifetime:

MAX_STREAM_SECONDS = 60

and:

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
→ continue

The connection is long-lived, but not permanent.

This also prevents one stale authentication decision from living indefinitely.


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.


The connection begins with:

const eventSource = new EventSource(
panel.dataset.eventsUrl,
);

The browser immediately sends a GET request to:

/documents/101/events

EventSource 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


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/events

Opening 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 state

A 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.


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, failed

A review can continue normally while the SSE connection is temporarily interrupted.


The server sends:

event: review_status
data: {"document_id":101,"status":"processing"}

Because it has the event name:

review_status

the browser calls:

eventSource.addEventListener(
"review_status",
handler,
);

The handler receives an event object.

Its:

event.data

property 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.status

contains:

"processing"

The handler safely updates the page using:

statusElement.textContent =
data.status;

textContent treats the value as text rather than executable HTML.


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=3000

asks it to wait about three seconds.

The reconnection is a new HTTP request:

New GET
→ middleware
→ authentication
→ authorization dependency
→ new event-stream response

The 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 42
Audit event 43
Audit event 44

If 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 → processing

but reconnects and receives:

completed

nothing 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 ID

If 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.


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.


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 SQLite

When the user returns later, Jinja renders the latest database status into a new page.


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 second

So this first SSE implementation reduces:

Repeated HTTP requests
Repeated middleware execution
Repeated authentication dependency resolution

but 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.


A reverse proxy may buffer response data instead of forwarding every small event immediately.

That would produce confusing behavior:

FastAPI yields pending
FastAPI yields processing
FastAPI yields completed
Nginx buffers everything
Browser receives all three at once

For 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: no
Cache-Control: no-cache

This is not a Python control-flow problem. It is part of the complete production path:

FastAPI
→ Uvicorn
→ Nginx
→ network
→ browser

Every layer between FastAPI and the browser must allow incremental delivery.


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.


For one successful SSE review:

  1. Jinja renders the page with start and events URLs.
  2. The browser constructs the DOM.
  3. The user clicks Start review.
  4. JavaScript sends the CSRF-protected POST.
  5. Middleware reconstructs the authenticated session.
  6. FastAPI authenticates and authorizes the write.
  7. The service commits pending to SQLite.
  8. FastAPI schedules the background operation.
  9. FastAPI returns 202 Accepted.
  10. JavaScript constructs an EventSource.
  11. The browser sends GET /documents/101/events.
  12. Middleware authenticates the stream request.
  13. The stream dependency verifies document access.
  14. FastAPI begins a text/event-stream response.
  15. The SSE generator opens a short SQLAlchemy session.
  16. SQLite returns pending.
  17. FastAPI yields a review_status event.
  18. The browser parses its JSON data.
  19. JavaScript displays pending.
  20. The background worker commits processing.
  21. The SSE generator’s next short query sees the change.
  22. FastAPI yields another event through the same response.
  23. JavaScript displays processing.
  24. The background worker finishes and commits completed.
  25. The generator yields the terminal event.
  26. JavaScript displays completed.
  27. JavaScript calls EventSource.close().
  28. The server generator ends.
  29. 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 updates

SSE 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.