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 responseBoth fit a one-way information flow:
Server → browserToday, 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 → serverAdd this review note
Server → browsersA new review note was committedThis 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 DOMThe WebSocket transports messages. It does not perform the document review, replace the database, or make authorization unnecessary.
Why not use SSE again?
Section titled “Why not use SSE again?”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 notesThat 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.
The persisted review note
Section titled “The persisted review note”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.
from datetime import datetime, timezone
from sqlalchemy import DateTime, ForeignKey, Stringfrom 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 runsThe WebSocket connection cannot make an uncommitted Python object durable. The service must still commit a database transaction.
The browser page
Section titled “The browser page”Our Jinja template begins with useful server-rendered content:
<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:
- The browser requests the document page.
- Middleware reconstructs the signed session.
- FastAPI authenticates and authorizes the request.
- SQLAlchemy reads the document and existing notes.
- Jinja turns Python values into HTML.
- FastAPI sends a normal HTTP response.
- 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.
The incoming and outgoing message models
Section titled “The incoming and outgoing message models”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:
from datetime import datetimefrom 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: datetimeThe names communicate direction and purpose:
AddNoteCommand→ A browser asks the application to do something
NoteCreatedEvent→ The server reports that something happenedThe word “created” matters.
The server does not broadcast the note merely because the browser requested it. It broadcasts only after SQLite successfully commits it.
Authenticating the WebSocket handshake
Section titled “Authenticating the WebSocket handshake”A WebSocket begins with an HTTP handshake.
The browser sends something conceptually resembling:
GET /documents/101/live HTTP/1.1Host: app.example.comUpgrade: websocketConnection: UpgradeOrigin: https://app.example.comCookie: 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:
from dataclasses import dataclassfrom typing import Annotated
from fastapi import Depends, WebSocket, WebSocketExceptionfrom sqlalchemy import select
from .config import settingsfrom .database import SessionLocalfrom .models.documents import Documentfrom .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: DbSessionThat 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 sessionThat is an unnecessarily long unit of work.
Instead, the dependency uses:
with SessionLocal() as db:and returns only scalar values:
user_iddocument_idfirm_idroleThe 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 that saves a note
Section titled “The service that saves a note”The service rechecks current authorization and writes the note:
from sqlalchemy import select
from ..database import SessionLocalfrom ..models.documents import Documentfrom ..models.review_notes import ReviewNotefrom ..models.users import Userfrom ..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 eventSessionLocal.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.
Why db.flush() appears
Section titled “Why db.flush() appears”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.idThe transaction has not necessarily committed yet.
The sequence is:
db.add()→ Track pending object
db.flush()→ Execute INSERT inside transaction
Exit begin block→ Commit transactionWe 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.
Tracking connected browsers
Section titled “Tracking connected browsers”We need a small connection manager:
import asynciofrom collections import defaultdict
from fastapi import WebSocketfrom 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 browserWhen 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.
The WebSocket endpoint
Section titled “The WebSocket endpoint”Here is the complete endpoint:
import asynciofrom json import JSONDecodeError
from fastapi import APIRouter, WebSocketfrom pydantic import ValidationErrorfrom starlette.websockets import WebSocketDisconnect
from ..websocket_dependencies import ReviewSocketContextDepfrom ..schemas.review_messages import AddNoteCommandfrom ..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.
Accepting the connection
Section titled “Accepting the connection”Before the function begins, FastAPI resolves:
context: ReviewSocketContextDepThe dependency validates:
- The
Originheader - 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 ProtocolsUpgrade: websocketConnection: UpgradeAfter 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.
Waiting for a browser message
Section titled “Waiting for a browser message”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."}Running synchronous database work
Section titled “Running synchronous database work”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:
- Opens a new SQLAlchemy session.
- Reloads the current user.
- Rechecks authorization.
- Creates the
ReviewNote. - Flushes the
INSERT. - Constructs the outgoing Pydantic event.
- Commits.
- Closes the session.
- Returns the event.
Only after that do we broadcast.
We will examine Python’s event loop and asyncio more deeply in the next installment.
Broadcasting the committed event
Section titled “Broadcasting the committed event”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 resultThe browser is not merely echoing its own input.
The browser JavaScript
Section titled “The browser JavaScript”Here is the complete browser-side connection:
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.
Constructing the WebSocket URL
Section titled “Constructing the WebSocket URL”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.
Browser connection events
Section titled “Browser connection events”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.readyStateThe important states are:
CONNECTINGOPENCLOSINGCLOSEDWhen 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.dataFor our text messages, this is JSON text, not a JavaScript object.
Therefore:
message = JSON.parse(event.data);performs the conversion:
JSON text→ JavaScript objectThe reverse direction uses:
JSON.stringify(...)to perform:
JavaScript object→ JSON textOnce again, Python and JavaScript objects do not travel across the network. Both sides serialize and parse data.
Submitting the form
Section titled “Submitting the form”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.OPENA 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 Createdfor 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", ...}Safely adding the note to the DOM
Section titled “Safely adding the note to the DOM”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.
Disconnects and reconnection
Section titled “Disconnects and reconnection”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 secondIf it fails again, the delay doubles:
1 → 2 → 4 → 8 → 10 secondsThe 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:
- The browser sends its current cookie again.
- The server validates the origin again.
- The user is authenticated again.
- Document authorization is checked again.
- 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.
What happens when the page closes
Section titled “What happens when the page closes”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:
WebSocketDisconnectThe 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 transactionThe in-memory manager’s production limit
Section titled “The in-memory manager’s production limit”Our manager stores connections in Python memory:
self._connectionsThat works in one application process.
Suppose production uses four Uvicorn workers:
Worker 1→ Alice’s WebSocket
Worker 2→ Max’s WebSocketAlice 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 socketsThe 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 pageIf 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.
The complete lifecycle
Section titled “The complete lifecycle”For Alice joining the live review room:
- Her browser requests the ordinary Jinja page.
- Middleware reconstructs her authenticated session.
- FastAPI authorizes access to document
101. - SQLAlchemy reads the document and existing notes.
- Jinja renders HTML.
- The browser builds the DOM.
- JavaScript constructs a
wss:URL. - The browser begins the WebSocket handshake.
- It sends the session cookie and
Originheader. - FastAPI validates the origin.
- The connection dependency authenticates Alice.
- A short SQLAlchemy session checks document access.
- That session closes.
- FastAPI accepts the WebSocket.
- The manager records Alice’s connection.
- The server sends
connection_ready.
For Alice adding a note:
- The form dispatches a
submitevent. - JavaScript prevents ordinary page navigation.
- JavaScript creates an object containing
typeandbody. JSON.stringify()converts it into JSON text.- The browser sends a WebSocket message.
- Python awaits and receives that message.
- JSON parsing produces a Python dictionary.
- Pydantic validates it as
AddNoteCommand. - The service runs in a worker thread.
- It creates a short SQLAlchemy session.
- It reloads Alice and rechecks authorization.
- It constructs a
ReviewNoteORM object. - SQLAlchemy sends an
INSERTto SQLite. - SQLite assigns the primary key.
- The transaction commits.
- The database session closes.
- The service returns a Pydantic event.
- FastAPI serializes that event into JSON-compatible data.
- The manager sends it to every local connection in room
101. - Each browser parses the JSON.
- Each browser creates safe DOM elements.
- 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 representationA 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.