13 · Polling for Document-Review Status
In the previous lesson, the user clicked Refresh status and JavaScript sent one request:
Click→ GET /documents/101/status→ FastAPI reads SQLite→ Browser updates the pageToday, JavaScript will repeat that request automatically while a document review is running.
The status may move through:
pending→ processing→ completedor:
pending→ processing→ failedThe browser will check every three seconds until it reaches a final status.
This technique is called polling.
Each check remains an ordinary HTTP request:
GET /documents/101/statusThere is no permanent connection. Every poll receives its own response, and the connection can then be released or reused by the browser.
The lifecycle becomes:
Jinja renders initial page ↓JavaScript reads initial status ↓fetch() requests current status ↓FastAPI authenticates and authorizes ↓SQLAlchemy reads SQLite ↓FastAPI returns JSON ↓JavaScript updates the DOM ↓Wait three seconds ↓Repeat while status remains activePolling only observes the review. It does not perform the review itself.
A separate server-side process must change the database status. We’ll introduce that processing side in the next lesson.
The status response model
Section titled “The status response model”Let’s make the possible status values explicit:
from typing import Literal
from pydantic import BaseModel, ConfigDict
ReviewStatus = Literal[ "not_started", "pending", "processing", "completed", "failed",]
class DocumentStatusRead(BaseModel): model_config = ConfigDict( from_attributes=True, )
id: int status: ReviewStatusThe Literal declaration means the outgoing value must be one of five strings.
These pass validation:
"not_started""pending""processing""completed""failed"This does not:
"finished-ish"Our SQLAlchemy column may still be a normal string column:
status: Mapped[str] = mapped_column( String(30), default="not_started",)Pydantic validates the HTTP response. A database constraint could also enforce the allowed values at the persistence layer.
These protections operate at different boundaries.
The unchanged status endpoint
Section titled “The unchanged status endpoint”The FastAPI route remains small:
@router.get( "/{document_id}/status", response_model=DocumentStatusRead,)def document_status( response: Response, document: AuthorizedDocument,): response.headers["Cache-Control"] = "no-store"
return documentBefore this function runs, FastAPI resolves:
document: AuthorizedDocumentThat dependency:
- Authenticates the requester.
- Receives
document_idfrom the URL. - Creates a request-scoped SQLAlchemy session.
- Queries the document within the requester’s firm.
- Returns
404if it is missing or unauthorized. - Returns the authorized ORM object if successful.
The endpoint returns only:
{ "id": 101, "status": "processing"}The browser does not need the title, internal file path, creator ID, or complete review result during every status check.
Small polling responses matter because the same endpoint may be requested many times.
The Jinja template
Section titled “The Jinja template”Our document page contains:
<section id="review-panel" data-status-url="{{ url_for( 'document_status', document_id=review_document.id ) }}"> <p> Review status: <strong id="review-status"> {{ review_document.status }} </strong> </p>
<button id="check-status" type="button" > Check now </button>
<p id="status-message" role="status" aria-live="polite" ></p></section>Jinja renders the current database status into:
<strong id="review-status"> processing</strong>It also generates the authorized status URL:
data-status-url="/documents/101/status"When the browser first opens the page, it already has useful content. JavaScript enhances that page with automatic updates.
If JavaScript fails to load, the user still sees the status captured when Jinja rendered the page. They can also reload the page to get a fresh server-rendered version.
This is a useful property of server-rendered applications: JavaScript adds convenience without necessarily owning the entire page.
The polling JavaScript
Section titled “The polling JavaScript”Here is the complete browser code:
const ACTIVE_STATUSES = new Set([ "pending", "processing",]);
const TERMINAL_STATUSES = new Set([ "completed", "failed",]);
const POLL_DELAY_MS = 3000;const RETRY_DELAY_MS = 6000;const REQUEST_TIMEOUT_MS = 5000;
const panel = document.querySelector("#review-panel");const statusElement = document.querySelector("#review-status");const messageElement = document.querySelector("#status-message");const checkButton = document.querySelector("#check-status");
let pollingEnabled = false;let pollTimerId = null;let activeController = null;
checkButton.addEventListener("click", checkNow);
document.addEventListener( "visibilitychange", handleVisibilityChange,);
window.addEventListener( "pagehide", stopPolling,);
window.addEventListener("pageshow", (event) => { if (event.persisted) { handleVisibilityChange(); }});
const initialStatus = statusElement.textContent.trim();
if (ACTIVE_STATUSES.has(initialStatus)) { startPolling();} else { showTerminalMessage(initialStatus);}
function startPolling() { if (pollingEnabled || document.hidden) { return; }
pollingEnabled = true; checkButton.disabled = false; messageElement.textContent = "Waiting for the review to finish…";
void pollOnce();}
function stopPolling() { pollingEnabled = false;
clearScheduledPoll();
activeController?.abort(); activeController = null;
checkButton.disabled = true;}
function pausePolling() { pollingEnabled = false;
clearScheduledPoll();
activeController?.abort(); activeController = null;}
function checkNow() { if (!pollingEnabled) { return; }
clearScheduledPoll(); void pollOnce();}
async function pollOnce() { if ( !pollingEnabled || document.hidden || activeController !== null ) { return; }
const controller = new AbortController(); let timedOut = false;
const timeoutId = window.setTimeout(() => { timedOut = true; controller.abort(); }, REQUEST_TIMEOUT_MS);
activeController = controller; checkButton.disabled = true; messageElement.textContent = "Checking status…";
try { const response = await fetch( panel.dataset.statusUrl, { headers: { Accept: "application/json", }, cache: "no-store", signal: controller.signal, }, );
if (activeController !== controller) { return; }
if (response.status === 401) { stopPolling(); messageElement.textContent = "Your session expired. Please sign in again."; return; }
if (response.status === 404) { stopPolling(); messageElement.textContent = "This document is no longer available."; return; }
if (!response.ok) { throw new Error( "The status request failed." ); }
const data = await response.json();
if (activeController !== controller) { return; }
statusElement.textContent = data.status;
if (TERMINAL_STATUSES.has(data.status)) { finishPolling(data.status); return; }
messageElement.textContent = `Review is ${data.status}. Checking again soon.`;
scheduleNextPoll(POLL_DELAY_MS); } catch (error) { if (activeController !== controller) { return; }
if (error.name === "AbortError" && !timedOut) { return; }
messageElement.textContent = timedOut ? "The status request took too long. Retrying soon." : error.message;
if (pollingEnabled) { scheduleNextPoll(RETRY_DELAY_MS); } } finally { window.clearTimeout(timeoutId);
if (activeController === controller) { activeController = null;
if (pollingEnabled) { checkButton.disabled = false; } } }}
function scheduleNextPoll(delay) { clearScheduledPoll();
if (!pollingEnabled || document.hidden) { return; }
pollTimerId = window.setTimeout(() => { pollTimerId = null; void pollOnce(); }, delay);}
function clearScheduledPoll() { if (pollTimerId !== null) { window.clearTimeout(pollTimerId); pollTimerId = null; }}
function finishPolling(status) { pollingEnabled = false; clearScheduledPoll(); checkButton.disabled = true;
messageElement.textContent = status === "completed" ? "Review completed." : "Review failed.";}
function showTerminalMessage(status) { checkButton.disabled = true;
if (status === "completed") { messageElement.textContent = "Review already completed."; } else if (status === "failed") { messageElement.textContent = "Review failed."; } else if (status === "not_started") { messageElement.textContent = "No review has been requested yet."; }}
function handleVisibilityChange() { if (document.hidden) { pausePolling(); return; }
const currentStatus = statusElement.textContent.trim();
if (ACTIVE_STATUSES.has(currentStatus)) { startPolling(); }}Let’s walk through it in browser execution order.
We retain the five-second request timeout from lesson 12. A stalled read is aborted and retried, so it cannot occupy the polling slot forever. The controller identity checks also stop a request from an earlier visible-page cycle from changing the message after a newer request has begun. Pausing the page still stops observation, not the server’s review.
Active and terminal statuses
Section titled “Active and terminal statuses”The script begins by creating two JavaScript Set objects:
const ACTIVE_STATUSES = new Set([ "pending", "processing",]);and:
const TERMINAL_STATUSES = new Set([ "completed", "failed",]);A Set is a collection of unique values.
We can ask:
ACTIVE_STATUSES.has("processing")and receive:
trueBut:
ACTIVE_STATUSES.has("completed")returns:
falseThe two groups describe control flow.
An active status means:
The review might change again, so continue checking.
A terminal status means:
The operation has reached its final outcome, so stop checking.
This avoids scattering conditions such as:
status === "pending" || status === "processing"throughout the file.
It also mirrors a common service-layer idea: an operation moves through a finite set of states.
Polling and retry delays
Section titled “Polling and retry delays”Next:
const POLL_DELAY_MS = 3000;const RETRY_DELAY_MS = 6000;The normal polling delay is three seconds.
If a request fails, we wait six seconds before trying again.
This gives us two different meanings:
Successful request, review still active→ check again in 3 seconds
Temporary request failure→ wait 6 seconds before retryingA failed network request does not necessarily mean the document review failed.
These are separate states:
Review status→ stored in SQLite→ pending, processing, completed, failed
Polling request→ browser’s attempt to read that status→ succeeded, timed out, disconnected, server errorThe browser could temporarily lose its connection while the server-side review continues normally.
That is why a request error does not change the displayed review status to failed.
Reading the initial Jinja status
Section titled “Reading the initial Jinja status”The browser gets the starting status from the HTML:
const initialStatus = statusElement.textContent.trim();Suppose Jinja rendered:
<strong id="review-status"> processing</strong>The element’s text contains whitespace from the formatted template. Calling:
.trim()removes leading and trailing whitespace.
The result is:
"processing"The script checks:
if (ACTIVE_STATUSES.has(initialStatus)) { startPolling();} else { showTerminalMessage(initialStatus);}For processing, polling starts immediately.
For completed, the script does not make another network request. Jinja has already told the browser that the review is finished.
This is one small benefit of using server-rendered initial state: JavaScript can make a reasonable decision before its first fetch.
The server remains authoritative. The first poll will still ask SQLite for current state if the initial status is active.
Starting polling
Section titled “Starting polling”The function begins:
function startPolling() { if (pollingEnabled || document.hidden) { return; }There are two reasons to refuse to start.
First:
pollingEnabledmay already be true. Calling startPolling() twice should not create two independent polling loops.
Second:
document.hiddenis true when the page is not currently visible, such as when the user switches to another browser tab.
If neither condition applies:
pollingEnabled = true;records that automatic polling is active.
Then:
checkButton.disabled = false;allows the user to request an immediate check between scheduled checks.
The message becomes:
Waiting for the review to finish…Finally:
void pollOnce();performs the first check immediately.
Why void pollOnce() appears
Section titled “Why void pollOnce() appears”The function:
pollOnce()is asynchronous, so it returns a Promise.
We are intentionally starting it without awaiting that Promise in startPolling().
Writing:
void pollOnce();communicates:
Start this asynchronous function and deliberately ignore its returned Promise here.
The expected request errors are handled inside pollOnce().
The void operator is not what makes the function run in the background. Calling pollOnce() starts it. void makes the ignored return value explicit.
This is sometimes called a “fire and forget” call, although the phrase can be misleading. Our JavaScript function still tracks and handles its own work. We are only declining to wait for it in the calling function.
Preventing overlapping polls
Section titled “Preventing overlapping polls”The first check inside pollOnce() is:
if ( !pollingEnabled || document.hidden || activeController !== null) { return;}The third condition prevents overlap:
activeController !== nullWhile a request is in progress, activeController refers to that request’s AbortController.
A second call to pollOnce() returns instead of starting another fetch.
This creates an important rule:
At most one status request may be active at a time.Without that rule, slow responses could accumulate:
0 seconds → Request A begins3 seconds → Request B begins6 seconds → Request C beginsIf Request A takes ten seconds, all three requests may be active simultaneously.
They might also finish out of order, producing stale page updates.
Why we use recursive setTimeout()
Section titled “Why we use recursive setTimeout()”A tempting polling implementation is:
window.setInterval( pollOnce, 3000,);setInterval() tries to invoke the function on a repeating schedule.
But the interval does not care whether the preceding fetch has finished.
Our implementation schedules the next timer only after the current request succeeds or fails:
scheduleNextPoll(POLL_DELAY_MS);Inside that function:
pollTimerId = window.setTimeout(() => { pollTimerId = null; void pollOnce();}, delay);The sequence becomes:
Request A begins→ Request A finishes→ Wait 3 seconds→ Request B begins→ Request B finishes→ Wait 3 seconds→ Request C beginsThis means the actual time between request starts is:
request duration + polling delayIf a request takes 200 milliseconds:
approximately 3.2 seconds between startsIf it takes two seconds:
approximately 5 seconds between startsThat behavior reduces overlap and naturally slows down when the server or network is slower.
setTimeout() schedules one future callback and returns immediately; its callback can be canceled using the returned timer ID. MDN’s setTimeout() documentation
The first polling request
Section titled “The first polling request”The browser creates:
const controller = new AbortController();and records it:
activeController = controller;The Check now button is disabled while the request is active:
checkButton.disabled = true;Then JavaScript sends:
const response = await fetch( panel.dataset.statusUrl, { headers: { Accept: "application/json", }, cache: "no-store", signal: controller.signal, },);The request resembles:
GET /documents/101/status HTTP/1.1Accept: application/jsonCookie: app_session=...The cache option asks the browser’s HTTP cache to obtain a current response rather than satisfying the request with a previously cached result. The server also sends:
Cache-Control: no-storeFor changing, authenticated status data, both sides clearly express that stale cached data is inappropriate. MDN’s request-cache documentation
Every poll is a complete FastAPI request
Section titled “Every poll is a complete FastAPI request”FastAPI does not know that this request belongs to a JavaScript polling loop.
To FastAPI, each poll is simply another request for:
GET /documents/101/statusFor every poll:
- Session middleware reads and verifies the cookie.
- FastAPI matches the route.
get_current_user()retrieves the current user.get_db()creates a new SQLAlchemy session.get_authorized_document()queries SQLite.- The authorization condition limits the query to the user’s firm.
- FastAPI validates the outgoing status.
- The response is sent.
- The SQLAlchemy session closes.
The database session from the previous poll is not reused as a long-lived global session.
The application-level engine remains available, and its connection pool may reuse database connections where appropriate. But each request gets its own SQLAlchemy session and transaction boundary.
Authentication and authorization also occur again.
The browser having received an authorized result three seconds ago does not grant permanent access to the resource.
First response: pending
Section titled “First response: pending”Suppose SQLite currently contains:
id: 101status: pendingFastAPI returns:
{ "id": 101, "status": "pending"}JavaScript parses it:
const data = await response.json();and updates the DOM:
statusElement.textContent = data.status;The page continues to show:
Review status: pendingThe status is active, so this check is false:
TERMINAL_STATUSES.has("pending")JavaScript sets the message:
Review is pending. Checking again soon.Then:
scheduleNextPoll(POLL_DELAY_MS);schedules another check.
Second response: processing
Section titled “Second response: processing”Some separate server-side operation changes SQLite:
pending → processingThree seconds later, the browser sends a new request.
This request creates a new:
- HTTP exchange
- FastAPI dependency graph
- SQLAlchemy session
- SQLite query
- JSON response
The server returns:
{ "id": 101, "status": "processing"}JavaScript updates:
statusElement.textContent = "processing";Because processing remains active, another check is scheduled.
Notice what did not happen:
- SQLite did not send a message to the browser.
- FastAPI did not push an event.
- The background operation did not directly modify the DOM.
The browser learned about the change because it asked again.
That is polling.
Final response: completed
Section titled “Final response: completed”Eventually, the server-side process saves:
status: completedThe next poll receives:
{ "id": 101, "status": "completed"}This time:
TERMINAL_STATUSES.has(data.status)returns true.
JavaScript calls:
finishPolling(data.status);That function performs:
pollingEnabled = false;clearScheduledPoll();checkButton.disabled = true;and displays:
Review completed.No further timer is created.
The final browser state is:
Review status: completedReview completed.The page arrived there without a full reload.
What happens when a poll fails
Section titled “What happens when a poll fails”Suppose a temporary network failure causes fetch() to reject.
Execution enters:
catch (error) {If the request was deliberately canceled while the page was being paused, its controller is no longer current and it leaves quietly. For an ordinary current cancellation:
if (error.name === "AbortError") { return;}No retry is scheduled by that branch. Pausing or stopping the loop controls what happens next.
Our timeout takes a different path: it sets timedOut, shows the timeout message, and schedules the normal retry while polling remains enabled.
For another failure:
messageElement.textContent = error.message;shows the error.
Then:
if (pollingEnabled) { scheduleNextPoll(RETRY_DELAY_MS);}schedules a retry after six seconds.
The review status remains unchanged on screen.
This distinguishes:
“We could not retrieve the current status”from:
“The review itself failed”Only a valid server response containing:
{"status": "failed"}moves the displayed review status to failed.
Pausing when the tab is hidden
Section titled “Pausing when the tab is hidden”The script listens for:
document.addEventListener( "visibilitychange", handleVisibilityChange,);The browser dispatches visibilitychange when the document becomes hidden or visible. MDN’s Page Visibility documentation
If the user switches to another tab:
document.hidden === trueThe handler calls:
pausePolling();That function:
pollingEnabled = false;clearScheduledPoll();activeController?.abort();activeController = null;It removes any scheduled check and cancels the browser’s current fetch if one exists.
There is little value in querying SQLite every three seconds for a page the user is not looking at.
When the user returns, document.hidden becomes false.
JavaScript reads the last displayed status:
const currentStatus = statusElement.textContent.trim();If it is still active:
startPolling();immediately requests fresh state.
Perhaps the review completed while the page was hidden. The first resumed poll will discover that.
Leaving the page
Section titled “Leaving the page”The script also registers:
window.addEventListener( "pagehide", stopPolling,);pagehide occurs when the current page is being hidden as part of browser navigation or history behavior. MDN’s pagehide documentation
The handler:
stopPolling()clears the timer and aborts the browser’s pending fetch.
Again, this does not cancel the underlying document review.
It stops this page from continuing to ask about it.
The review belongs to the server and database. The polling loop belongs to one browser page.
The Check now button
Section titled “The Check now button”During the three-second delay between polls, the user may click:
Check nowThe handler runs:
function checkNow() { if (!pollingEnabled) { return; }
clearScheduledPoll(); void pollOnce();}It removes the scheduled future timer and performs the next check immediately.
While an HTTP request is already active, the button is disabled:
checkButton.disabled = true;This prevents a manual click from overlapping the current automatic request.
When the request finishes:
finally {sets:
activeController = null;checkButton.disabled = false;provided polling remains active.
Polling does not perform background work
Section titled “Polling does not perform background work”This is the most important architectural distinction in today’s lesson.
Polling answers:
How does the browser learn whether server-side work has finished?
It does not answer:
What performs the server-side work after the original request ends?
Those are separate mechanisms:
Background processing→ Changes status and stores results in SQLite
Polling→ Periodically reads that stored statusIf no server-side process changes the database, polling will return:
{"status":"pending"}forever.
Likewise, a background task could finish successfully even if the user closes the browser. The task does not depend on the polling page remaining open.
The database connects the two sides:
Review process writes status ↓SQLite stores status ↓Status endpoint reads status ↓Browser polling displays statusThe browser and background process do not need to run at the same moment.
When polling is a good choice
Section titled “When polling is a good choice”Polling is often the best initial implementation when:
- Updates occur every few seconds or minutes.
- A slight delay is acceptable.
- The response is small.
- The number of simultaneous users is modest.
- Plain HTTP simplicity is valuable.
- Reconnection should be straightforward.
For a small document-review application, checking every three to five seconds while one document is processing can be completely reasonable.
Polling has costs:
Every check→ HTTP request→ authentication→ authorization→ database session→ database query→ JSON responseIf 100 open browser tabs poll every three seconds, that becomes roughly:
2,000 requests per minuteeven when most statuses have not changed.
Pausing hidden tabs, stopping at terminal states, returning small responses, and avoiding overlapping requests reduce that waste.
For larger scale or faster updates, Server-Sent Events can allow the server to stream one-way updates over an ongoing connection. WebSockets add bidirectional messaging when both sides genuinely need it.
But those mechanisms introduce more connection management and infrastructure concerns.
Polling remains boring, visible, and easy to debug:
Browser asks.Server answers.Browser waits.Browser asks again.The complete lifecycle
Section titled “The complete lifecycle”For one successful polling cycle:
- JavaScript confirms polling is enabled.
- It confirms the tab is visible.
- It confirms no other status request is active.
- It creates an
AbortController. - It sends
GET /documents/101/status. - Session middleware reconstructs the authenticated session.
- FastAPI matches the status route.
- Dependencies retrieve the user and create a SQLAlchemy session.
- The authorization query limits document access by firm.
- SQLite returns the current document row.
- Pydantic validates the outgoing
idandstatus. - FastAPI serializes the response as JSON.
- The request-scoped SQLAlchemy session closes.
- JavaScript parses the JSON.
- The DOM displays the new status.
- JavaScript checks whether the status is active or terminal.
- For an active status, it waits three seconds and repeats.
- For a terminal status, it stops permanently.
The server handles several independent requests. JavaScript turns their separate results into one continuous-looking browser experience.
In the next installment, we’ll build the missing other half: a request that starts a review, returns before the review finishes, and performs work after the initial response. That will let us compare FastAPI’s built-in background tasks with a durable job queue and see why the SQLAlchemy session from the original request must not be carried into later work.