A progress bar that tracks the upload and download progress of HTTP requests in real time. Every file uploader, image compressor, and bulk data exporter on the web needs one. The hard part is not the bar — it's computing accurate speed and ETA, throttling progress events without dropping frames, and managing a queue of concurrent requests without overwhelming the browser or the server.
FrontendX EngineeringSystem Design Series #12
What Are We Building?
An API progress bar component — call it <ProgressBar> — that accepts an array of HTTP request descriptors and renders a live progress update for each one. Uploading a dozen 4K photos to a cloud album? Each file gets its own progress bar showing percentage done, transfer speed, and estimated time remaining. A bulk CSV export? The component shows aggregate progress across all the pages being fetched.
The browser gives us two ways to track request progress: XMLHttpRequest fires onprogress events for both upload and download; the fetch API can track download progress through a ReadableStream but has no built-in upload progress. I support both: XHR for upload tracking, fetch for downloads where XHR feels outdated.
Here is the API shape I settled on — a compound component where the root manages the request lifecycle and children define the visual layers:
The component handles debouncing progress events, computing speed and ETA, managing a concurrency-bounded queue, supporting cancellation via AbortController, and aggregating progress across all requests. Let's walk through each decision.
1 · Requirements (R)
Before writing a single line of code, here are the clarifying questions I asked myself and the answers that shaped the design.
Functional requirements
Track request progress: For each request, display the percentage of data transferred so far. Both upload and download phases must be visible.
Show transfer speed and ETA: Speed in KB/s or MB/s, and estimated time remaining. These are computed from the byte delta and time delta between progress events.
Multiple concurrent requests: Support a configurable concurrency limit. Requests beyond the limit are queued and started as slots free up.
Cancel in-flight requests: Each progress item exposes a cancel action that aborts the underlying HTTP request via AbortController.
Aggregate progress: When tracking multiple requests, show a summary bar with total progress, combined speed, and overall ETA.
Custom rendering: Consumers supply their own layout for each progress entry. Some need compact rows; others need rich cards with file names, icons, and action buttons.
Non-functional requirements
60fps animations: Progress bars must animate smoothly. Rapid progress events from XHR (up to 200 events/sec on fast connections) must be throttled to avoid layout thrashing.
Accessibility: Progress bars must use the ARIA progressbar role with aria-valuenow, aria-valuemin, and aria-valuemax. Screen readers must announce percentage and status changes.
Race-condition safety: When a request is cancelled and retried, old progress events from the cancelled request must not update the new one.
Bundle size: Zero external dependencies for core logic. Speed calculation, queue management, and XHR adapter must be written from scratch.
Tip
I explicitly scoped out WebSocket progress tracking. The GFE source notes that "WebSocket progress is a different problem — the server controls the data rate." This component is designed for HTTP request progress only. If the consumer needs to track WebSocket throughput, they can implement a separate adapter that emits the same progress events.
2 · Architecture (A)
The architecture has four layers. At the top is the compound component root, which owns the request registry and exposes the rendering API. Below it sits the engine layer — pure functions that compute speed, ETA, and throttle progress events. At the bottom is the adapter layer, which wraps browser APIs (XHR and fetch) into a uniform stream of progress events.
Figure 1 — The compound component API for ProgressBar. The root manages a request registry and delegates rendering to sub-components. The engine layer computes speed, ETA, and throttles updates. Adapters normalise XHR and fetch events into a uniform interface.
Option A: Single XHR request (rejected for multi-request)
A single XMLHttpRequest with inline onprogress. Simple for one request, but the callback structure is imperative and does not compose. To track multiple concurrent requests, we would need to create separate XHR instances anyway, so the adapter abstraction is necessary from the start.
Option B: Fetch + ReadableStream (rejected for uploads)
The fetch API can track download progress via response body's ReadableStream, but it provides no upload progress mechanism. Fetch is also harder to abort mid-stream for uploads. XHR is the only browser API that natively supports both upload and download progress events.
Option C: Dual adapter — XHR + fetch (chosen)
I expose a unified adapter interface. The XHR adapter handles requests with a body (POST, PUT, PATCH) and provides both upload and download tracking. A fetch adapter handles GET requests where only download progress matters. The engine layer does not care which adapter produced the events — it only sees (loaded, total) tuples.
Single XHR
Simple but does not compose for multiple concurrent requests. Rejected.
Fetch + ReadableStream
Download only — no upload progress. Harder to abort. Rejected.
Dual adapter (XHR + fetch)
XHR for upload progress, fetch for simple downloads. Engine is agnostic. Chosen.
Key Insight
The dual-adapter pattern keeps the engine pure. The speed calculator, ETA estimator, and rAF throttle work the same way regardless of whether the bytes come from XHR or fetch. This makes the engine testable in isolation — mock an adapter that emits (loaded, total) tuples and verify the outputs.
3 · Data Model (D)
The state is a map of request IDs to progress entries, plus a queue and an aggregate summary. The map structure makes lookups O(1) and avoids iterating an array to find a specific entry.
example.typescript
interface ProgressBarState {
/** Map of request ID → progress entry */
entries: Map<string, ProgressEntry>;
/** Queue of requests waiting to start */
queue: ProgressRequest[];
/** Number of active (in-flight) requests */
activeCount: number;
/** Derived aggregate across all entries */
aggregate: AggregateProgress;
}
interface AggregateProgress {
totalBytes: number;
loadedBytes: number;
overallSpeed: number;
overallEta: number;
percent: number;
completed: number;
totalCount: number;
}
const initialState: ProgressBarState = {
entries: new Map(),
queue: [],
activeCount: 0,
aggregate: {
totalBytes: 0,
loadedBytes: 0,
overallSpeed: 0,
overallEta: 0,
percent: 0,
completed: 0,
totalCount: 0,
},
};
Why a Map and not an array?
Fast lookups: When a progress event arrives for request "abc-123", we need to update that entry. Finding it in a map by key is O(1). Finding it in an array requires O(n) iteration or building a separate index.
No duplicates: A map enforces unique keys. An array could accidentally contain two entries with the same request ID, leading to duplicate progress bars.
Ordered iteration: Modern JavaScript engines preserve Map insertion order, so the progress bars render in the same order the requests were submitted.
The seven statuses
Each entry moves through these states: idle (queued, not started), pending (request sent, waiting for headers), uploading (sending body),downloading (receiving response), complete (all bytes transferred), error (network failure or HTTP error), and cancelled (aborted by user or program). The speed and eta fields are derived — they are computed from the history of loaded and timestamp samples, not stored directly.
Figure 2 — State machine for a single progress entry. Every request starts as idle, transitions through pending/uploading/downloading, and terminates in complete, error, or cancelled. Uploading only fires for requests with a body.
Note
The state intentionally keeps the queue and entries separate. The queue is an array of not-yet-started requests; the entries map holds all started requests. When a request finishes, it is removed from the active count but remains in the entries map so the consumer sees its final status. The consumer decides when to clear completed entries.
4 · Interface API (I)
The API is the contract between the component and its consumer. The types must cover every state a progress entry can be in.
example.typescript
type RequestStatus =
| "idle"
| "pending"
| "uploading"
| "downloading"
| "complete"
| "error"
| "cancelled";
interface ProgressEntry {
id: string;
status: RequestStatus;
loaded: number; // bytes transferred
total: number; // Content-Length (0 if unknown)
speed: number; // bytes/sec (moving average)
eta: number; // seconds remaining
error: string | null;
label: string; // human-readable request name
startTime: number; // Date.now() when request started
}
interface ProgressRequest {
id: string;
label: string;
method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
url: string;
body?: BodyInit | null;
headers?: Record<string, string>;
}
interface ProgressBarProps {
/** Requests to track */
requests: ProgressRequest[];
/** Max concurrent requests (default: 3) */
maxConcurrent?: number;
/** Called when any request updates progress */
onProgress?: (entry: ProgressEntry) => void;
/** Called when all requests complete */
onComplete?: (entries: ProgressEntry[]) => void;
/** Custom render for each progress item */
renderItem?: (entry: ProgressEntry) => React.ReactNode;
/** Custom render for aggregate */
renderAggregate?: (aggregate: AggregateProgress) => React.ReactNode;
/** Show aggregate progress bar */
showAggregate?: boolean;
/** Poll interval when Content-Length is unknown (ms) */
pollInterval?: number;
className?: string;
}
Prop decisions
requests: An array of ProgressRequest objects. Each request has an id, label, HTTP method, URL, optional body, and optional headers. The component does not execute requests until it is mounted, so the array can be updated dynamically.
maxConcurrent: Caps the number of in-flight requests. Defaults to 3, which is a safe limit for most applications. Browser HTTP/1.1 connections max out at 6 per origin anyway, and overwhelming the server with concurrent uploads degrades throughput.
renderItem / renderAggregate: Render props for custom UI. The component provides the data; the consumer provides the layout. This is the inversion-of-control pattern that makes the component reusable across different design systems.
pollInterval: When Content-Length is unknown (not sent by the server), the component cannot calculate percentage or ETA. In this case, it falls back to an indeterminate progress bar, but if pollInterval is set, it polls the response size via periodic checks on the response body length.
Server API contract
For the progress bar to work correctly, the server should:
Send a Content-Length header. Without it, the component cannot compute percentage or ETA and falls back to an indeterminate spinner.
Use chunked transfer encoding only when the total size is unknown at the start of the response. Streaming responses (such as server-sent events) are better served by a different component.
Return appropriate error codes (4xx, 5xx) so the component can transition to the error state rather than timing out.
5 · Component Deep Dive
The interesting engineering is in the engine layer: how we calculate speed and ETA accurately, how we throttle progress events, and how we manage the request queue.
Speed and ETA — the moving average
Instantaneous speed is just Δbytes / Δtime between two progress events. But on fast connections, a single event can spike the speed reading wildly. A moving average smooths this: keep the last N (loaded, timestamp) samples and calculate speed across the entire window.
example.typescript
interface SpeedSample {
loaded: number;
timestamp: number;
}
function createProgressCalculator(windowSize = 20) {
const samples: SpeedSample[] = [];
return function calculate(loaded: number, total: number) {
const now = Date.now();
samples.push({ loaded, timestamp: now });
// Keep only the last N samples
while (samples.length > windowSize) samples.shift();
const first = samples[0];
const last = samples[samples.length - 1];
const elapsed = (last.timestamp - first.timestamp) / 1000;
const bytesDelta = last.loaded - first.loaded;
const speed = elapsed > 0 ? bytesDelta / elapsed : 0;
const remaining = total - loaded;
const eta = speed > 0 ? remaining / speed : Infinity;
const percent = total > 0 ? (loaded / total) * 100 : 0;
return { speed, eta, percent, elapsed };
};
}
// Usage inside the engine
const calculate = createProgressCalculator(20);
function onProgressEvent(loaded: number, total: number) {
const { speed, eta, percent } = calculate(loaded, total);
updateEntry({ loaded, total, speed, eta, percent });
}
The window size matters. Too small (3-5 samples) and the speed bounces around. Too large (50+ samples) and the speed reacts slowly to real changes — a throttled connection takes seconds to reflect lower speed. I settled on a window of 20 samples, which balances responsiveness and smoothness. At 60 fps throttled events, that is roughly 300ms of history.
Figure 3 — Progress calculation pipeline. Raw bytes from the adapter pass through a requestAnimationFrame throttle, then the speed engine computes instantaneous speed, a moving average, and remaining ETA. All derived metrics update at most once per frame.
Throttling progress events with rAF
XHR fires onprogress at the rate the data arrives. On a fast Gigabit connection, that can be 100-200 events per second. Calling setState 200 times per second forces React to reconcile the virtual DOM 200 times per second, which causes visible jank even with batching.
example.typescript
function useThrottledProgress() {
const callbackRef = useRef<((loaded: number, total: number) => void) | null>(null);
const pendingRef = useRef<{ loaded: number; total: number } | null>(null);
const rafRef = useRef<number | null>(null);
const flush = useCallback(() => {
if (pendingRef.current) {
callbackRef.current?.(
pendingRef.current.loaded,
pendingRef.current.total,
);
pendingRef.current = null;
}
rafRef.current = null;
}, []);
const update = useCallback(
(loaded: number, total: number, cb: (l: number, t: number) => void) => {
callbackRef.current = cb;
pendingRef.current = { loaded, total };
if (rafRef.current === null) {
rafRef.current = requestAnimationFrame(flush);
}
},
[flush],
);
useEffect(() => {
return () => {
if (rafRef.current !== null) {
cancelAnimationFrame(rafRef.current);
}
};
}, []);
return update;
}
// XHR fires onprogress 60-200 times per second on fast connections.
// Without rAF throttling, that means 60-200 setState calls per second.
// With rAF throttling, React updates at most once per frame (60fps).
The requestAnimationFrame throttle stores the latest (loaded, total) values and schedules a single update per frame. If 8 progress events arrive between two frames, only the last one triggers a render. The bar still updates smoothly because we never skip more than 16ms — the browser paints at 60fps anyway, so there is no benefit to rendering intermediate states that the user never sees.
Warning
Do not use setTimeout(fn, 0) to throttle. It fires after the frame budget, which can cause the progress bar to lag behind the actual data arrival. requestAnimationFrame fires just before the browser paints, so the progress bar always shows the most recent data in the next frame. This is the standard pattern used by Chrome's download manager and React Concurrent Mode's scheduler.
XHR adapter — bridging the imperative gap
The XHR adapter wraps the callback-based XMLHttpRequest API into a Promise-based interface that emits progress events through a callback. It listens to both xhr.upload.onprogress (for request body upload tracking) and xhr.onprogress (for response download tracking).
The adapter checks e.lengthComputable before emitting progress. Some servers respond without Content-Length, making e.total = 0. In that case, the adapter emits total: 0 and the engine falls back to indeterminate mode — the bar pulses instead of filling.
Queue concurrency management
When the consumer passes 20 requests with maxConcurrent: 3, the component starts the first 3 immediately and queues the remaining 17. As each request finishes (or errors out), the controller dequeues the next waiting request and starts it.
Each request gets its own AbortController stored in a Map keyed by request ID. When the consumer calls onCancel, the manager looks up the controller and calls controller.abort(). The adapter's event listener for abort triggers XHR's onabort, which rejects the promise with an AbortError.
Figure 4 — Multi-request concurrency model. A request queue feeds into a concurrency-limited pool (max 3). When a request completes, the controller dequeues the next waiting request and updates the aggregate progress metrics. Aborted or failed requests also trigger the dequeue cycle.
6 · Data Flow & Communication
Let's trace the lifecycle of a single request through the component.
Request registered
Consumer passes requests array. Component creates entries in idle status. First N requests (up to maxConcurrent) transition to pending.
Adapter sends request
XHR adapter opens the connection and sends the body. Entry status → pending. AbortController is stored in the abort map.
Upload progress (if body exists)
xhr.upload.onprogress fires. Each event passes through rAF throttle. Speed and ETA update once per frame. Status → uploading.
Download progress
Server response arrives. xhr.onprogress fires with response bytes. Speed, ETA, and percentage update from the moving average calculator.
Request completes
xhr.onloadend fires. Entry status → complete. Active count decrements. Controller checks queue for next request.
Next request starts
If queue is non-empty, the next waiting request transitions to pending. The cycle repeats until all requests finish or are cancelled.
The aggregate progress updates whenever any entry changes. The aggregate sums loaded and total across all entries, computes an overall percentage, and calculates a combined speed by summing individual speeds. This gives the consumer a single "overall progress" bar when tracking multiple requests.
7 · Performance (O)
Performance is the primary concern for a progress bar component. The whole point is to show progress smoothly — if the bar stutters, the user loses confidence in the operation.
rAF throttling (critical)
As discussed above, rAF throttling reduces setState calls from 200/sec to at most 60/sec. This is the single most important optimization. Without it, the component drops frames on any page with complex layout. With it, the progress bar updates at the display refresh rate regardless of network speed.
CSS transitions on the bar element
Even at 60fps updates, jumping from 23% to 47% instantly looks janky. Use a CSS transition: width 0.3s ease on the bar fill element. This smooths the visual transition between updates. The transition should be faster than the update interval (300ms vs 16ms) so the bar never appears to lag.
Memoizing derived data
The aggregate progress is derived from the entries map. Compute it in a useMemo keyed on the entries map reference. The speed calculator's moving average window is a closure stored in a useRef — it does not trigger re-renders.
Virtualizing the request list
For use cases with hundreds of requests (bulk file upload, batch data processing), rendering a DOM node for each request causes scroll jank. Virtualize the list: only render the visible items and use placeholder elements for the rest. This keeps the DOM count constant regardless of the number of requests.
Tradeoff table
Strategy
Pros
Cons
XHR only
Native upload + download progress, works everywhere
Node.js / edge workers do not have XHR
Fetch + ReadableStream
Modern API, works in workers, streaming
No upload progress, harder to abort
Dual adapter (chosen)
Best of both — XHR for uploads, fetch for downloads
Two code paths to maintain
rAF throttle
60fps max, no frame drops, syncs with paint cycle
Slightly more code than setTimeout
Moving avg speed
Smooth, accurate speed readings
Delayed reaction to real speed changes
8 · Security Considerations
A progress bar seems harmless, but it touches the network layer and exposes metadata about the transfer.
Content-Length leakage: The progress bar displays the total response size. If the server sends a Content-Length header, the user sees exactly how big the response is. For sensitive endpoints, this may leak information about the dataset size. The component should not display Content-Length directly, only the derived percentage.
AbortController reuse: Never reuse an AbortController across requests. Once aborted, the controller stays aborted, and fetch() or XHR will immediately fail for the next request. The component creates a fresh controller for each request.
Credential exposure in error messages: When a request fails, the XHR adapter catches the error and stores the message. Network errors can contain sensitive information in the URL or response text. The component should sanitize error messages before displaying them.
CSRF via progress endpoint: If the consumer builds a progress-checking endpoint that reflects the request URL, an attacker could exploit it for CSRF. Ensure that progress-related endpoints use standard anti-CSRF measures (tokens, SameSite cookies).
Warning
If the component is used in a browser extension or Electron context, the XHR adapter may bypass CORS restrictions. Document clearly that the component is designed for standard web applications, and that consumers must ensure their server sends appropriate CORS headers for cross-origin requests.
9 · Testing Strategy
Testing a progress bar is harder than testing a dropdown because we need to simulate async data arrival. The key is to mock the adapter layer and control the timing of progress events.
Renders progress entries: Pass a request array and verify that each request label appears in the DOM. This tests the basic mapping from data to UI.
Respects maxConcurrent: Mock XHR and verify that only N requests start simultaneously. The rest wait in the queue. Use Jest spies on XMLHttpRequest.prototype.open.
Cancels via AbortController: Click a cancel button and verify that the entry transitions to cancelled status and the underlying XHR is aborted.
Aggregate progress: With two requests of sizes 100 and 200, verify the aggregate shows 0/300 before any bytes arrive.
Error state: Mock XHR to dispatch an error event and verify the UI shows the error state.
Completion decrements active count: With 3 requests and maxConcurrent of 3, verify all 3 complete and the active count returns to 0.
Indeterminate when Content-Length is missing: Mock a response without Content-Length and verify the bar renders in indeterminate (pulsing) mode.
Note
For testing speed and ETA calculation, unit-test the purecreateProgressCalculator function in isolation. Pass it known (loaded, total) pairs at specific time intervals and assert on the returned speed and ETA. This is faster and more reliable than testing through the rendered component.
10 · Accessibility
Progress bars have a dedicated ARIA role with well-defined browser support. Getting it right means screen reader users get announcements for progress changes.
The ARIA progressbar pattern
ARIA defines two modes for progress bars:
Determinate: The total size is known. Use role="progressbar" with aria-valuenow (current loaded amount), aria-valuemin="0", and aria-valuemax (total amount). The browser maps these to a percentage internally, so screen readers announce "45%."
Indeterminate: The total size is unknown. Use role="progressbar" and omit aria-valuenow. The screen reader announces "progress bar" without a percentage, and the visual bar animates (pulsing or cycling).
Live region for status changes
In addition to the progressbar role, use a aria-live="polite" region for status transitions (e.g., "Upload complete" or "Download failed"). The progressbar role handles percentage changes; the live region handles state changes that the percentage alone does not capture.
Cancel button focus management
When a request is cancelled, the cancel button disappears from the DOM. If focus was on that button, it is lost. Move focus to the retry button (if available) or to the next request's cancel button. If no other entries exist, move focus to the aggregate bar. This follows the WAI-ARIA focus management pattern for removed elements.
Screen reader announcements for speed and ETA
Speed and ETA are secondary information. Do not include them in the aria-valuetext attribute — that would make the screen reader announce the full text on every progress update, which is overwhelming. Instead, render speed and ETA as plain text alongside the bar and let the user navigate to them if they want. The aria-hidden attribute on the visual bar fill element prevents double announcement.
The aria-busy attribute tells screen readers that the element is still loading. When set to true, screen readers like VoiceOver announce "loading" or "busy" periodically. Set it to true while the request is in-flight and false when it completes or errors. This gives the user continuous awareness of background activity.
11 · Live Demo
Try the full implementation in a WebContainer playground. You can edit the code and see changes instantly — experiment with different concurrency limits, custom renderers, and cancellation behavior.
Editable example loads when this section enters view.
Try these interactions: start multiple requests and watch the queue drain, cancel an in-flight request and see it transition, trigger an error by requesting a non-existent URL, and observe how the aggregate bar reflects overall progress.
12 · Key Takeaways
rAF throttle is non-negotiable. Without it, progress events overwhelm React's rendering pipeline. requestAnimationFrame guarantees the bar updates at the display refresh rate and never drops frames.
Moving average for stable speed readings. A window of 20 samples balances responsiveness and smoothness. Instantaneous speed bounces too much to be useful.
Dual adapter covers all scenarios. XHR for upload progress, fetch for simple downloads. The engine layer is agnostic to the source of bytes, making it testable and extensible.
Queue with concurrency limit prevents server overload. Starting 20 requests simultaneously overwhelms both the browser and the server. A queue with a sane default (3) ensures fair scheduling.
Content-Length is critical for determinate progress. Without it, the bar falls back to indeterminate mode. Document this requirement clearly for backend teams.
Accessibility goes beyond role="progressbar". Use aria-busy for loading states,aria-live for status transitions, and manage focus when cancel buttons are removed.
The API progress bar looks like a simple animated rectangle. It isn't. Behind that 16-pixel fill are throttled event pipelines, moving-average speed calculators, concurrency queues, abortable HTTP adapters, and ARIA compliance. That depth behind a deceptively simple visual is the hallmark of a well-engineered component.