Skip to content

16 · WebSockets and a Live Review Room

In the previous installments, our browser learned about document-review progress in two ways:

Polling
→ Browser repeatedly asks for the current status
Server-Sent Events
→ Server sends updates over one ongoing HTTP response

Both fit a one-way information flow:

Server → browser

Today, two document reviewers will share a live document-review room. Either reviewer can submit a note, and every connected reviewer sees the committed note immediately.

This room is an optional extension. The ordinary document-review workflow in lesson 18 uses HTTP and SSE and can be followed without it.

That requires communication in both directions:

Browser → server
Add this review note
Server → browsers
A new review note was committed

This is where a WebSocket becomes reasonable.

The full lifecycle is:

Jinja renders the review room
↓
Browser opens a WebSocket
↓
FastAPI authenticates and authorizes the connection
↓
Server accepts the WebSocket
↓
Browser sends a JSON message
↓
Pydantic validates it
↓
Service opens a short SQLAlchemy session
↓
SQLite commits the note
↓
Server broadcasts a JSON event
↓
Each browser safely updates its DOM

The WebSocket transports messages. It does not perform the document review, replace the database, or make authorization unnecessary.


Suppose Alice and Max are both viewing document 101.

While they are reviewing it:

  • Alice adds: “Check the introduction for clarity.”
  • Max adds: “The opening paragraph needs a source.”
  • Both notes should appear promptly in both browsers.

We could implement this with:

POST a note using fetch()
+
SSE stream for incoming notes

That would be perfectly valid and often preferable.

A WebSocket becomes attractive when a page has frequent messages traveling in both directions and treating them as one live session simplifies the interaction.

Situation Boring first choice
Occasional browser write fetch() with POST
Periodic status changes Polling
Continuous server-to-browser updates SSE
Frequent two-way live interaction WebSocket

WebSockets are not “better HTTP.” They are a different transport with different lifecycle and operational costs.


Assume an earlier reviewed Alembic migration added a review_notes table:

These excerpts assume an existing ORM User mapping with id, firm_id, role, and display_name, plus the already introduced document table. The user table must be registered in SQLAlchemy metadata before resolving its foreign keys. SQLite also needs foreign-key enforcement enabled on each connection. The optional room’s user lookup does not change the dictionary-backed HTTP dependency used in the core lessons.

app/models/review_notes.py
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column
from ..database import Base
class ReviewNote(Base):
__tablename__ = "review_notes"
id: Mapped[int] = mapped_column(
primary_key=True,
)
document_id: Mapped[int] = mapped_column(
ForeignKey("documents.id"),
index=True,
)
author_user_id: Mapped[int] = mapped_column(
ForeignKey("users.id"),
)
body: Mapped[str] = mapped_column(
String(500),
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
)

Alembic added the table during deployment.

It does nothing while today’s WebSocket is running:

Alembic
→ establishes the database structure before deployment
SQLAlchemy
→ reads and writes rows while the application runs

The WebSocket connection cannot make an uncommitted Python object durable. The service must still commit a database transaction.


Our Jinja template begins with useful server-rendered content:

app/templates/documents/review_room.html
<section
id="review-room"
data-socket-url="{{ url_for(
'document_review_socket',
document_id=review_document.id
) }}"
>
<h1>{{ review_document.title }}</h1>
<p>
Connection:
<strong id="connection-status">
Connecting…
</strong>
</p>
<ul id="note-list">
{% for note in review_notes %}
<li data-note-id="{{ note.id }}">
<strong>{{ note.author_name }}</strong>:
{{ note.body }}
</li>
{% endfor %}
</ul>
<form id="note-form">
<label for="note-body">
Add review note
</label>
<input
id="note-body"
name="body"
type="text"
maxlength="500"
required
>
<button id="send-note" type="submit" disabled>
Add note
</button>
</form>
<p id="room-message" role="status" aria-live="polite"></p>
</section>
<script
src="{{ url_for('static', path='/review-room.js') }}"
defer
></script>

Jinja renders the title and existing notes on the server.

For this template, the page route supplies authorized note rows containing id, author_name, and body, for example from a join to the users table. The page-route query is omitted. We are not assuming an undeclared note.author ORM relationship.

That initial page follows the familiar lifecycle:

  1. The browser requests the document page.
  2. Middleware reconstructs the signed session.
  3. FastAPI authenticates and authorizes the request.
  4. SQLAlchemy reads the document and existing notes.
  5. Jinja turns Python values into HTML.
  6. FastAPI sends a normal HTTP response.
  7. The browser parses the HTML and builds its DOM.

Only after that does JavaScript open the WebSocket.

The existing notes do not need to be replayed through the socket. They were already rendered into the page.


A WebSocket carries messages, but it does not decide what those messages mean.

Our application defines a tiny message protocol.

The browser may send:

{
"type": "add_note",
"body": "Check the introduction for clarity."
}

The server validates it with Pydantic:

app/schemas/review_messages.py
from datetime import datetime
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class AddNoteCommand(BaseModel):
model_config = ConfigDict(
extra="forbid",
str_strip_whitespace=True,
)
type: Literal["add_note"]
body: str = Field(
min_length=1,
max_length=500,
)
class NoteCreatedEvent(BaseModel):
type: Literal["note_created"] = "note_created"
note_id: int
author_name: str
body: str
created_at: datetime

The names communicate direction and purpose:

AddNoteCommand
→ A browser asks the application to do something
NoteCreatedEvent
→ The server reports that something happened

The word “created” matters.

The server does not broadcast the note merely because the browser requested it. It broadcasts only after SQLite successfully commits it.


A WebSocket begins with an HTTP handshake.

The browser sends something conceptually resembling:

GET /documents/101/live HTTP/1.1
Host: app.example.com
Upgrade: websocket
Connection: Upgrade
Origin: https://app.example.com
Cookie: app_session=...

The browser includes applicable cookies during the handshake.

That lets our existing session authentication participate, but it introduces an important security concern: a malicious website could attempt to open a WebSocket to our application while the user’s authentication cookie is present.

We therefore validate both:

Session cookie
→ Who is this user?
Origin header
→ Which website initiated this connection?

OWASP recommends secure wss:// connections in production, explicit Origin allowlisting, message-level authorization, and validation of every incoming message. OWASP Cheat Sheet Series

Here is a dependency that prepares a small, detached connection context:

app/websocket_dependencies.py
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, WebSocket, WebSocketException
from sqlalchemy import select
from .config import settings
from .database import SessionLocal
from .models.documents import Document
from .models.users import User
@dataclass(frozen=True)
class ReviewSocketContext:
user_id: int
document_id: int
firm_id: int | None
role: str
def get_review_socket_context(
websocket: WebSocket,
document_id: int,
) -> ReviewSocketContext:
origin = websocket.headers.get("origin")
if origin != settings.public_origin:
raise WebSocketException(code=1008)
user_id = websocket.session.get("user_id")
if user_id is None:
raise WebSocketException(code=1008)
with SessionLocal() as db:
user = db.get(User, user_id)
document = db.get(Document, document_id)
if user is None or document is None:
raise WebSocketException(code=1008)
if (
user.role != "admin"
and document.firm_id != user.firm_id
):
raise WebSocketException(code=1008)
return ReviewSocketContext(
user_id=user.id,
document_id=document.id,
firm_id=user.firm_id,
role=user.role,
)
ReviewSocketContextDep = Annotated[
ReviewSocketContext,
Depends(get_review_socket_context),
]

FastAPI supports dependencies in WebSocket endpoints, including dependencies that inspect cookies, headers, paths, and queries. It also provides WebSocketException for rejecting WebSocket connections or policies. FastAPI


Why this dependency does not yield a database session

Section titled “Why this dependency does not yield a database session”

Our ordinary HTTP routes use:

db: DbSession

That dependency creates a SQLAlchemy session and closes it after the HTTP request finishes.

A WebSocket may stay open for minutes or hours.

If we yielded a session for the entire WebSocket endpoint, that session could remain alive for the connection’s complete lifetime:

Open socket
→ Open SQLAlchemy session
→ Wait 45 minutes
→ Close socket
→ Finally close session

That is an unnecessarily long unit of work.

Instead, the dependency uses:

with SessionLocal() as db:

and returns only scalar values:

user_id
document_id
firm_id
role

The SQLAlchemy session and ORM objects are gone before the live connection begins.

This gives us two different lifetimes:

Resource Lifetime
WebSocket Potentially long
SQLAlchemy session One short database operation
SQLite transaction One explicit unit of work
Browser DOM Until navigation or page closure

Long-lived network connections do not require long-lived database sessions.


The service rechecks current authorization and writes the note:

app/services/review_notes.py
from sqlalchemy import select
from ..database import SessionLocal
from ..models.documents import Document
from ..models.review_notes import ReviewNote
from ..models.users import User
from ..schemas.review_messages import NoteCreatedEvent
class ReviewNoteAccessDenied(Exception):
pass
def user_can_read_review_room(
*,
user_id: int,
document_id: int,
) -> bool:
with SessionLocal() as db:
user = db.get(User, user_id)
if user is None:
return False
statement = select(Document.id).where(
Document.id == document_id,
)
if user.role != "admin":
statement = statement.where(
Document.firm_id == user.firm_id,
)
return db.scalar(statement) is not None
def create_review_note(
*,
user_id: int,
document_id: int,
body: str,
) -> NoteCreatedEvent:
with SessionLocal.begin() as db:
user = db.get(User, user_id)
if user is None:
raise ReviewNoteAccessDenied
statement = select(Document).where(
Document.id == document_id,
)
if user.role != "admin":
statement = statement.where(
Document.firm_id == user.firm_id,
)
document = db.scalar(statement)
if document is None:
raise ReviewNoteAccessDenied
if user.role not in {"reviewer", "admin"}:
raise ReviewNoteAccessDenied
note = ReviewNote(
document_id=document.id,
author_user_id=user.id,
body=body,
)
db.add(note)
db.flush()
event = NoteCreatedEvent(
note_id=note.id,
author_name=user.display_name,
body=note.body,
created_at=note.created_at,
)
return event

SessionLocal.begin() creates a session and transaction.

If the block finishes normally, SQLAlchemy commits. If an exception escapes, it rolls back. The session then closes.

The service checks authorization again because the connection might be old.

Perhaps the user:

  • Changed firms
  • Lost the reviewer role
  • Was deleted
  • Lost access to the document

Authorization at connection time answers:

May this user enter the room now?

Authorization for the message answers:

May this user perform this particular action now?

A successfully authenticated connection is not permanent permission for every future message.


After:

db.add(note)

the Python object is pending.

Calling:

db.flush()

sends the INSERT to SQLite inside the current transaction. SQLite assigns the note’s primary key, allowing us to read:

note.id

The transaction has not necessarily committed yet.

The sequence is:

db.add()
→ Track pending object
db.flush()
→ Execute INSERT inside transaction
Exit begin block
→ Commit transaction

We construct the Pydantic event while the session and ORM object are still available.

After the block exits, we return a plain Pydantic object rather than carrying the SQLAlchemy session into later network operations.


We need a small connection manager:

app/websockets/review_rooms.py
import asyncio
from collections import defaultdict
from fastapi import WebSocket
from starlette.websockets import WebSocketDisconnect
from ..services.review_notes import user_can_read_review_room
class ReviewRoomManager:
def __init__(self):
self._connections: dict[
int,
set[WebSocket],
] = defaultdict(set)
self._users: dict[WebSocket, int] = {}
async def connect(
self,
document_id: int,
websocket: WebSocket,
user_id: int,
) -> None:
await websocket.accept()
self._connections[document_id].add(websocket)
self._users[websocket] = user_id
def disconnect(
self,
document_id: int,
websocket: WebSocket,
) -> None:
connections = self._connections.get(document_id, set())
connections.discard(websocket)
self._users.pop(websocket, None)
if not connections:
self._connections.pop(document_id, None)
async def broadcast(
self,
document_id: int,
message: dict,
) -> None:
disconnected = []
for websocket in list(
self._connections.get(document_id, set())
):
try:
user_id = self._users.get(websocket)
if user_id is None or not await asyncio.to_thread(
user_can_read_review_room,
user_id=user_id,
document_id=document_id,
):
await websocket.close(code=1008)
disconnected.append(websocket)
continue
await websocket.send_json(message)
except (RuntimeError, WebSocketDisconnect):
disconnected.append(websocket)
for websocket in disconnected:
self.disconnect(document_id, websocket)
review_room_manager = ReviewRoomManager()

The dictionary groups connections by document:

Document 101
├── Alice’s browser
└── Max’s browser
Document 202
└── Priya’s browser

When a note is committed for document 101, we broadcast only to the browsers in room 101.

Room membership alone is not permanent read permission. Before sending each event, the manager rechecks the recipient’s current access in a short database operation. A user who changed organizations or lost access cannot keep receiving new notes merely by leaving the old socket open. The sender’s write permission is checked separately by the note-creation service.

Calling:

await websocket.accept()

completes the WebSocket handshake.

Before acceptance, the server is deciding whether to permit the connection. After acceptance, both sides can exchange WebSocket messages.


Here is the complete endpoint:

app/routers/documents.py
import asyncio
from json import JSONDecodeError
from fastapi import APIRouter, WebSocket
from pydantic import ValidationError
from starlette.websockets import WebSocketDisconnect
from ..websocket_dependencies import ReviewSocketContextDep
from ..schemas.review_messages import AddNoteCommand
from ..services.review_notes import (
ReviewNoteAccessDenied,
create_review_note,
)
from ..websockets.review_rooms import review_room_manager
router = APIRouter(prefix="/documents")
@router.websocket(
"/{document_id}/live",
name="document_review_socket",
)
async def document_review_socket(
websocket: WebSocket,
context: ReviewSocketContextDep,
):
await review_room_manager.connect(
context.document_id,
websocket,
context.user_id,
)
try:
await websocket.send_json({
"type": "connection_ready",
"document_id": context.document_id,
})
while True:
try:
raw_message = await websocket.receive_json()
command = AddNoteCommand.model_validate(
raw_message
)
except (JSONDecodeError, ValidationError, KeyError, TypeError):
await websocket.send_json({
"type": "error",
"message": "That message was not valid.",
})
continue
try:
event = await asyncio.to_thread(
create_review_note,
user_id=context.user_id,
document_id=context.document_id,
body=command.body,
)
except ReviewNoteAccessDenied:
await websocket.close(
code=1008,
reason="Access is no longer permitted.",
)
return
await review_room_manager.broadcast(
context.document_id,
event.model_dump(mode="json"),
)
except WebSocketDisconnect:
pass
finally:
review_room_manager.disconnect(
context.document_id,
websocket,
)

FastAPI’s normal WebSocket pattern is to accept a connection, await incoming data, send outgoing data, and catch WebSocketDisconnect when the client leaves. FastAPI

Now we can follow the endpoint carefully.


Before the function begins, FastAPI resolves:

context: ReviewSocketContextDep

The dependency validates:

  • The Origin header
  • The signed session
  • The current user
  • Access to the requested document

Only then does the endpoint call:

await review_room_manager.connect(...)

The server returns an HTTP upgrade response conceptually resembling:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade

After this, the connection is no longer a series of ordinary HTTP requests and responses.

It is one ongoing WebSocket carrying individual messages.

The server sends the first message:

{
"type": "connection_ready",
"document_id": 101
}

That tells the browser that authentication, authorization, and acceptance all succeeded.


The endpoint enters:

while True:

and waits at:

raw_message = await websocket.receive_json()

The Python coroutine is suspended while no message is available.

The connection stays open, but this particular coroutine is not continuously consuming CPU.

When the browser sends:

{
"type": "add_note",
"body": "Check the introduction for clarity."
}

FastAPI/Starlette parses the JSON into a Python dictionary:

{
"type": "add_note",
"body": "Check the introduction for clarity.",
}

Then Pydantic performs explicit validation:

command = AddNoteCommand.model_validate(
raw_message
)

This differs from an ordinary HTTP route:

def create_document(payload: DocumentCreate):

With an HTTP body parameter, FastAPI automatically invokes Pydantic before calling the route.

Inside a WebSocket loop, each message is part of our application-level protocol. We must validate it ourselves.

There is also no automatic HTTP 422 Unprocessable Entity response. The handshake already completed.

For an invalid message, we send another WebSocket message:

{
"type": "error",
"message": "That message was not valid."
}

Our WebSocket endpoint is asynchronous:

async def document_review_socket(...)

But our SQLAlchemy setup is synchronous.

Calling the service directly would make synchronous SQLite work run on the event-loop thread:

event = create_review_note(...)

Instead, we use:

event = await asyncio.to_thread(
create_review_note,
...
)

Python runs the synchronous service in a worker thread. The WebSocket coroutine waits without blocking the event loop that manages other connections.

The service:

  1. Opens a new SQLAlchemy session.
  2. Reloads the current user.
  3. Rechecks authorization.
  4. Creates the ReviewNote.
  5. Flushes the INSERT.
  6. Constructs the outgoing Pydantic event.
  7. Commits.
  8. Closes the session.
  9. Returns the event.

Only after that do we broadcast.

We will examine Python’s event loop and asyncio more deeply in the next installment.


The outgoing event looks like:

{
"type": "note_created",
"note_id": 84,
"author_name": "Alice Morgan",
"body": "Check the introduction for clarity.",
"created_at": "2026-09-30T10:18:42Z"
}

The endpoint calls:

event.model_dump(mode="json")

The mode="json" argument converts values such as Python datetime objects into JSON-compatible representations.

The manager then sends that dictionary to every browser currently connected to document 101.

The sender receives the event too.

That is useful because the event confirms:

The server validated the message
→ authorization succeeded
→ SQLite committed the row
→ this is the canonical saved result

The browser is not merely echoing its own input.


Here is the complete browser-side connection:

app/static/review-room.js
const panel = document.querySelector("#review-room");
const form = document.querySelector("#note-form");
const input = document.querySelector("#note-body");
const sendButton = document.querySelector("#send-note");
const noteList = document.querySelector("#note-list");
const connectionStatus =
document.querySelector("#connection-status");
const roomMessage =
document.querySelector("#room-message");
let socket = null;
let shouldReconnect = true;
let reconnectDelay = 1000;
let reconnectTimerId = null;
let hasConnected = false;
connect();
form.addEventListener("submit", sendNote);
window.addEventListener("pagehide", () => {
shouldReconnect = false;
window.clearTimeout(reconnectTimerId);
socket?.close(1000, "Page closed");
});
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
window.location.reload();
}
});
function connect() {
connectionStatus.textContent = "Connecting…";
sendButton.disabled = true;
const socketUrl = new URL(
panel.dataset.socketUrl,
window.location.href,
);
socketUrl.protocol =
window.location.protocol === "https:"
? "wss:"
: "ws:";
const currentSocket = new WebSocket(socketUrl);
socket = currentSocket;
currentSocket.addEventListener("open", () => {
if (socket !== currentSocket) {
return;
}
if (hasConnected) {
shouldReconnect = false;
currentSocket.close(1000, "Reloading saved notes");
window.location.reload();
return;
}
hasConnected = true;
reconnectDelay = 1000;
connectionStatus.textContent = "Connected";
sendButton.disabled = false;
});
currentSocket.addEventListener("message", (event) => {
if (socket !== currentSocket) {
return;
}
let message;
try {
message = JSON.parse(event.data);
} catch {
roomMessage.textContent =
"The server sent an invalid message.";
currentSocket.close(
1007,
"Invalid message format",
);
return;
}
handleMessage(message);
});
currentSocket.addEventListener("close", (event) => {
if (socket !== currentSocket) {
return;
}
socket = null;
sendButton.disabled = true;
connectionStatus.textContent = "Disconnected";
if (event.code === 1008) {
shouldReconnect = false;
roomMessage.textContent =
"Access is no longer permitted. Reload after signing in.";
}
if (shouldReconnect) {
scheduleReconnect();
}
});
currentSocket.addEventListener("error", () => {
roomMessage.textContent =
"The live connection encountered a problem.";
});
}
function sendNote(event) {
event.preventDefault();
const body = input.value.trim();
if (body === "") {
return;
}
if (
socket === null
|| socket.readyState !== WebSocket.OPEN
) {
roomMessage.textContent =
"The live connection is not ready.";
return;
}
socket.send(JSON.stringify({
type: "add_note",
body: body,
}));
input.value = "";
roomMessage.textContent = "Sending note…";
}
function handleMessage(message) {
if (message.type === "connection_ready") {
roomMessage.textContent =
"Live review room connected.";
return;
}
if (message.type === "note_created") {
appendNote(message);
roomMessage.textContent =
"Review note saved.";
return;
}
if (message.type === "error") {
roomMessage.textContent = message.message;
}
}
function appendNote(message) {
if (noteList.querySelector(`[data-note-id="${message.note_id}"]`)) {
return;
}
const item = document.createElement("li");
const author = document.createElement("strong");
item.dataset.noteId = String(message.note_id);
author.textContent = message.author_name;
item.append(
author,
document.createTextNode(`: ${message.body}`),
);
noteList.append(item);
}
function scheduleReconnect() {
window.clearTimeout(reconnectTimerId);
roomMessage.textContent =
`Reconnecting in ${reconnectDelay / 1000} seconds…`;
reconnectTimerId = window.setTimeout(() => {
connect();
}, reconnectDelay);
reconnectDelay = Math.min(
reconnectDelay * 2,
10000,
);
}

The browser’s WebSocket object creates and manages the connection, exposes send() and close(), and dispatches open, message, error, and close events. MDN

The browser reloads the server-rendered note list after a previously working connection is restored. This recovers notes saved during the disconnection, and note IDs prevent an already displayed event from being appended twice. A policy denial (1008) stops automatic reconnection instead of retrying a forbidden connection forever.

This small example still has a snapshot-to-connection gap: a note committed between rendering the page and opening its first socket can be missed until a reload. A room that must deliver every note needs a synchronization request or durable event cursor. Calling socket.send() also does not acknowledge that a note was saved; preserving an unacknowledged draft and correlating replies would be additional application behavior.


The template gives JavaScript the route generated by FastAPI:

data-socket-url="ws://app.example.com/documents/101/live"

JavaScript constructs a URL object:

const socketUrl = new URL(
panel.dataset.socketUrl,
window.location.href,
);

Then it chooses the protocol:

socketUrl.protocol =
window.location.protocol === "https:"
? "wss:"
: "ws:";

The mapping is:

Page protocol WebSocket protocol
http: ws:
https: wss:

Production applications should use HTTPS and therefore wss: so authentication cookies and message contents are encrypted in transit.


Calling:

new WebSocket(socketUrl)

begins the handshake immediately.

It does not mean the connection is already ready.

The object moves through states represented by:

socket.readyState

The important states are:

CONNECTING
OPEN
CLOSING
CLOSED

When the handshake succeeds, the browser dispatches:

"open"

Our handler enables the form:

sendButton.disabled = false;

When the server sends a message, the browser dispatches:

"message"

The payload arrives as:

event.data

For our text messages, this is JSON text, not a JavaScript object.

Therefore:

message = JSON.parse(event.data);

performs the conversion:

JSON text
→ JavaScript object

The reverse direction uses:

JSON.stringify(...)

to perform:

JavaScript object
→ JSON text

Once again, Python and JavaScript objects do not travel across the network. Both sides serialize and parse data.


The browser normally treats a form submission as navigation.

Our listener intercepts it:

form.addEventListener("submit", sendNote);

Inside the handler:

event.preventDefault();

prevents the browser’s ordinary form-navigation behavior.

We then read:

const body = input.value.trim();

and verify that the socket is open:

socket.readyState !== WebSocket.OPEN

A socket object may exist while still connecting or after it has begun closing. Existence alone is not sufficient.

When the connection is open:

socket.send(JSON.stringify({
type: "add_note",
body: body,
}));

queues the JSON text for transmission.

The browser does not receive an HTTP status such as:

201 Created

for this individual message.

HTTP status codes belong to the initial handshake. After the upgrade, success and failure must be represented by our message protocol:

{"type":"note_created", ...}

or:

{"type":"error", ...}

When a committed note arrives, JavaScript calls:

appendNote(message);

That function creates DOM objects:

const item = document.createElement("li");
const author = document.createElement("strong");

It inserts server-provided text using:

author.textContent = message.author_name;

and:

document.createTextNode(
`: ${message.body}`
)

It does not use:

item.innerHTML = message.body;

A review note is untrusted user input. Treating it as HTML could allow markup or scripts to become part of the page.

The safe data path is:

Untrusted browser input
→ Pydantic string validation
→ parameterized SQLAlchemy INSERT
→ JSON serialization
→ JSON.parse()
→ textContent/createTextNode()

Validation, SQL parameterization, and safe DOM insertion defend different boundaries.


A WebSocket may close because:

  • The user navigated away
  • Wi-Fi changed
  • A proxy timed out the connection
  • The application restarted
  • Authentication expired
  • The server deliberately rejected an action

The browser dispatches:

"close"

Our handler disables writing and schedules a reconnect.

The first reconnect waits one second:

1 second

If it fails again, the delay doubles:

1 → 2 → 4 → 8 → 10 seconds

The cap prevents it from growing indefinitely.

This is a small exponential-backoff strategy.

Unlike EventSource, the browser WebSocket API does not automatically reconnect with application-aware behavior. The application owns the reconnect policy.

A reconnection is a new handshake:

  1. The browser sends its current cookie again.
  2. The server validates the origin again.
  3. The user is authenticated again.
  4. Document authorization is checked again.
  5. A new WebSocket is accepted.

A reconnect does not revive the old Python object or SQLAlchemy session.

Here, a restored connection triggers a page reload to read durable notes before starting a fresh live session. The database remains the recovery source. Session-cookie expiration is checked on a new handshake; a production policy requiring immediate session revocation also needs an explicit socket-expiration or revocation mechanism.


The script listens for:

window.addEventListener("pagehide", ...)

It records:

shouldReconnect = false;

and closes the socket using close code 1000, which represents a normal closure:

socket?.close(1000, "Page closed");

On the server:

await websocket.receive_json()

detects the closed connection and raises:

WebSocketDisconnect

The endpoint reaches:

finally:

and removes the browser from the connection manager.

Closing the socket does not remove notes that already committed.

Again:

Close browser connection
≠
Roll back completed database transaction

The in-memory manager’s production limit

Section titled “The in-memory manager’s production limit”

Our manager stores connections in Python memory:

self._connections

That works in one application process.

Suppose production uses four Uvicorn workers:

Worker 1
→ Alice’s WebSocket
Worker 2
→ Max’s WebSocket

Alice submits a note to worker 1.

Worker 1’s in-memory manager does not know that Max is connected to worker 2. It can broadcast only to its own connections.

A multi-process deployment normally adds a shared message broker such as Redis:

Worker 1 commits note
↓
Publishes event to Redis
↓
All workers receive event
↓
Each worker sends it to its local sockets

The database remains the durable source of truth. The broker distributes timely notifications among live application processes.

A background worker that changes document status would also publish an event. Merely changing a SQLite row does not automatically notify every connected WebSocket.


Reverse proxies must understand the upgrade

Section titled “Reverse proxies must understand the upgrade”

A reverse proxy such as Nginx must preserve the WebSocket upgrade and allow long-lived connections.

The important ideas are:

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 75s;

Exact configuration depends on the deployment, but the proxy must not treat the WebSocket as a short ordinary response.

Production systems also need:

  • Connection limits
  • Message-size limits
  • Per-user rate limits
  • Idle timeouts or heartbeat policies
  • Session-expiration handling
  • Logging of meaningful application events
  • Graceful shutdown behavior

A persistent connection consumes application and proxy resources even while no messages are moving.


WebSockets do not provide background execution

Section titled “WebSockets do not provide background execution”

A WebSocket is a communication channel.

It does not cause a review job to survive an application restart, and it does not make FastAPI’s in-process background tasks durable.

The architectural pieces remain separate:

Durable job worker
→ Performs the document review
SQLite
→ Stores review state and results
WebSocket or message broker
→ Announces new state
Browser JavaScript
→ Updates the visible page

If every browser disconnects, a durable review job should continue.

If the application process dies, current WebSockets close. Persisted notes remain in SQLite because their transactions already committed.

When browsers reconnect, the initial Jinja page or a synchronization request should reload durable state. A WebSocket event stream should not be treated as the only copy of important business data.


For Alice joining the live review room:

  1. Her browser requests the ordinary Jinja page.
  2. Middleware reconstructs her authenticated session.
  3. FastAPI authorizes access to document 101.
  4. SQLAlchemy reads the document and existing notes.
  5. Jinja renders HTML.
  6. The browser builds the DOM.
  7. JavaScript constructs a wss: URL.
  8. The browser begins the WebSocket handshake.
  9. It sends the session cookie and Origin header.
  10. FastAPI validates the origin.
  11. The connection dependency authenticates Alice.
  12. A short SQLAlchemy session checks document access.
  13. That session closes.
  14. FastAPI accepts the WebSocket.
  15. The manager records Alice’s connection.
  16. The server sends connection_ready.

For Alice adding a note:

  1. The form dispatches a submit event.
  2. JavaScript prevents ordinary page navigation.
  3. JavaScript creates an object containing type and body.
  4. JSON.stringify() converts it into JSON text.
  5. The browser sends a WebSocket message.
  6. Python awaits and receives that message.
  7. JSON parsing produces a Python dictionary.
  8. Pydantic validates it as AddNoteCommand.
  9. The service runs in a worker thread.
  10. It creates a short SQLAlchemy session.
  11. It reloads Alice and rechecks authorization.
  12. It constructs a ReviewNote ORM object.
  13. SQLAlchemy sends an INSERT to SQLite.
  14. SQLite assigns the primary key.
  15. The transaction commits.
  16. The database session closes.
  17. The service returns a Pydantic event.
  18. FastAPI serializes that event into JSON-compatible data.
  19. The manager sends it to every local connection in room 101.
  20. Each browser parses the JSON.
  21. Each browser creates safe DOM elements.
  22. The new note becomes visible without a reload.

The essential architectural boundary is:

WebSocket connection
→ long-lived message transport
Pydantic
→ message contract
Service
→ business operation and authorization
SQLAlchemy session
→ short database unit of work
SQLite
→ durable truth
JavaScript DOM update
→ visible representation

A WebSocket keeps a conversation open. It does not remove the need for careful message validation, current authorization, short database transactions, durable storage, safe rendering, or reconnection logic.

The next installment will look underneath this connection and compare the browser’s JavaScript event loop with Python’s asyncio event loop—especially why await helps while waiting, why ordinary CPU work can still block everything, and why synchronous SQLAlchemy was moved into a worker thread.