A financial dashboard is one of those projects that sounds straightforward until you realize you have to handle thousands of price updates per second, render crisp charts at 60fps, and keep the UI responsive while all this is happening.
Designing a real-time financial dashboard with WebSocket streaming, canvas-based chart rendering, downsampling for large datasets, and a grid workspace that persists across sessions.
A financial dashboard is one of those projects that sounds straightforward until you realize you have to handle thousands of price updates per second, render crisp charts at 60fps, and keep the UI responsive while all this is happening.
The dashboard follows a container-presenter pattern. The DashboardShell owns the layout state, the ChartContainer manages subscriptions for each symbol, and individual ChartInstance components render to isolated canvases.
Each chart is completely self-contained: it has its own WebSocket subscription, its own data buffer, and its own RAF render loop. This isolation is what lets us add or remove charts without affecting anything else.
interface ChartConfig {
id: string;
symbol: string;
timeframe: "1D" | "1W" | "1M" | "1Y";
indicators: IndicatorDef[];
gridPos: { x: number; y: number; w: number; h: number };
}gridPos field. The grid system uses absolute positioning within a CSS Grid container — each chart occupies w × h cells starting at (x, y). This makes drag-and-drop layout updates trivially simple: just update gridPos and re-render.The CanvasRenderer is the heart of each chart instance. It receives raw candle data, applies the current time range filter, runs any active indicator calculations, and draws everything to a 2D canvas. Indicators are rendered as transparent overlays on top of the candle chart.
Financial data has a beautiful property: it is append-only. Candles are never modified — only new ones arrive. This simplifies our state management enormously because we never deal with mutations, just insertions.
Each symbol-timeframe pair gets its own ring buffer of candles. When the buffer fills up, we drop the oldest entries. This keeps memory bounded regardless of how long the user keeps the dashboard open.
interface Candle {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
interface SeriesData {
symbol: string;
timeframe: string;
candles: Candle[];
}
interface IndicatorDef {
type: "SMA" | "RSI" | "MACD" | "Bollinger";
params: Record<string, number>;
color: string;
}A dashboard is only as good as its data pipeline. The API layer handles everything: historical data via REST, real-time ticks via WebSocket, and layout persistence via localStorage. Defining the contracts upfront means the frontend and backend teams can work in parallel.
Two REST endpoints handle symbol search and historical chart data. The search endpoint uses a 300ms debounce to avoid flooding the server while the user types. Historical data is cached aggressively — candles for AAPL in 2023 are not going to change tomorrow.
GET /api/tickers/search?q=AAPL
→ Response: { results: [{ symbol, name, exchange }] }
GET /api/chart/{symbol}?timeframe=1D&from=0&to=now
→ Response: { symbol, candles: Candle[], timeframe }
→ Headers: Cache-Control: public, max-age=60, stale-while-revalidate=300
WebSocket wss://api.example.com/ws
→ subscribe: { type: "subscribe", symbols: ["AAPL","TSLA"] }
→ unsubscribe: { type: "unsubscribe", symbols: ["AAPL"] }
→ tick: { type: "tick", symbol: "AAPL", price: 198.45, ts: 1620000000 }
→ ping/pong: { type: "ping" } / { type: "pong" } (every 30s)The WebSocket layer uses a typed message protocol. Every message has a typefield that the message router uses to dispatch to the correct handler. The protocol includes subscription management, tick delivery, and a ping/pong heartbeat to detect zombie connections.
type WSMessage =
| { type: "subscribe"; symbols: string[] }
| { type: "unsubscribe"; symbols: string[] }
| { type: "tick"; symbol: string; price: number; volume: number; ts: number }
| { type: "ping"; clientTs: number }
| { type: "pong"; serverTs: number }
| { type: "error"; code: string; message: string };
class MessageRouter {
private handlers = new Map<string, (msg: WSMessage) => void>();
on(type: string, handler: (m: WSMessage) => void) {
this.handlers.set(type, handler);
}
route(msg: WSMessage) {
const handler = this.handlers.get(msg.type);
if (handler) handler(msg);
}
}ping/pong heartbeat is not optional. Without it, a firewall or proxy can silently drop the connection, and your UI sits frozen with stale prices. Every 30 seconds, send a ping — if no pong within 5 seconds, force reconnect.This is the most critical piece of the entire system. If the WebSocket pipeline is unreliable, the dashboard is useless. Real-time financial data needs a connection manager that handles disconnects gracefully, a subscription manager that tracks which symbols each chart needs, and a message router that delivers ticks to the correct chart instance.
class ConnectionManager {
private ws: WebSocket | null = null;
private retries = 0;
private maxRetries = 10;
connect() {
this.ws = new WebSocket(WS_URL);
this.ws.onopen = () => { this.retries = 0; this.subscribe(); };
this.ws.onclose = () => this.reconnect();
this.ws.onmessage = (msg) => this.router.route(msg);
}
reconnect() {
if (this.retries >= this.maxRetries) return;
const delay = Math.min(1000 * 2 ** this.retries, 30000);
setTimeout(() => this.connect(), delay);
this.retries++;
}
}The exponential backoff pattern (min(1000 * 2^retries, 30000)) prevents thundering herd problems when the server restarts. The first retry is immediate (1 second), then 2s, 4s, 8s, up to 30 seconds max.
onopen event.{ type: "ping" } every 30 seconds. If no { type: "pong" } arrives within 5 seconds, force-close the connection and reconnect. This catches silent failures like zombie connections.For a financial chart with potentially thousands of candles, SVG is not the right tool. SVG creates a DOM node for every element it draws. With 1000 candles (each having open, high, low, close) you are looking at 4000+ DOM nodes per chart. Multiply by 16 charts and you kill the browser.
Canvas, on the other hand, is a single pixel buffer. It does not care how many candles you draw. The rendering happens in one shot per frame. The CPU cost is proportional to what you draw, but the memory cost is fixed at the canvas resolution.
A key detail: canvas rendering on Retina displays needs devicePixelRatio handling. Set the canvas buffer size to width * dpr and height * dpr, then scale the context by dpr. This keeps charts sharp on all screens.
function createRenderLoop() {
let pending = false;
const queue: (() => void)[] = [];
function schedule(fn: () => void) {
queue.push(fn);
if (!pending) {
pending = true;
requestAnimationFrame(() => {
pending = false;
const batch = queue.splice(0);
for (const f of batch) f();
});
}
}
return { schedule };
}requestAnimationFrame per-chart. Have a single global RAF loop that iterates over all chart instances. This gives you centralized control over frame timing and makes it easy to skip frames when the tab is backgrounded.A financial dashboard without workspace persistence is a toy. Users arrange their charts exactly how they want them — AAPL in the top-left, TSLA next to it, portfolio overview spanning the bottom row. If a refresh loses that layout, they will not come back.
The layout manager serializes the entire grid state to localStorage on every meaningful change (drag, resize, add, remove). On page load, it deserializes and hydrates the grid. If no saved layout exists, it falls back to a sensible default.
interface LayoutState {
version: number;
charts: ChartConfig[];
activeSymbol: string;
gridCols: number;
gridRows: number;
}
class LayoutManager {
private state: LayoutState;
private readonly STORAGE_KEY = "fd-layout";
save() {
localStorage.setItem(this.STORAGE_KEY,
JSON.stringify(this.state));
}
load(): LayoutState | null {
const raw = localStorage.getItem(this.STORAGE_KEY);
if (!raw) return null;
return JSON.parse(raw) as LayoutState;
}
}Performance is not optional for a financial dashboard. When the market moves, every millisecond counts. Here are the three techniques that make the biggest difference.
When a chart covers 1 year of 1-minute data, that is ~250,000 candles. No chart needs to render that many points. The Largest Triangle Three Buckets (LTTB) algorithm reduces thousands of points to a few hundred while preserving the visual shape of the chart. It picks points that form the largest triangles — visually important points survive, noise gets dropped.
function downsampleLTTB(data: Point[], threshold: number): Point[] {
if (data.length <= threshold) return data;
const result: Point[] = [data[0]];
const bucketSize = (data.length - 2) / (threshold - 2);
for (let i = 0; i < threshold - 2; i++) {
const start = Math.floor((i + 0) * bucketSize) + 1;
const end = Math.floor((i + 1) * bucketSize) + 1;
const avgX = (data[end].x + data[start].x) / 2;
// Pick point that forms largest triangle area
let maxArea = -1, maxIdx = start;
for (let j = start; j < end; j++) {
const area = triangleArea(result[i], data[j], { x: avgX, y: 0 });
if (area > maxArea) { maxArea = area; maxIdx = j; }
}
result.push(data[maxIdx]);
}
result.push(data[data.length - 1]);
return result;
}Instead of rendering immediately when a tick arrives, queue the render call and let RAF batch all pending renders into the next frame. This prevents redundant renders when multiple ticks arrive in the same frame and keeps the UI responsive.
For multi-chart layouts, render each chart to an offscreen canvas using OffscreenCanvas (available in Web Workers). This moves the rendering work off the main thread entirely. The main thread only blits the final pixel buffers to the visible canvases.
Financial data is sensitive. Users trust this dashboard with their trading decisions, and a security breach — whether data exposure or manipulated charts — destroys that trust instantly. Here is how we protect it.
The WebSocket connection authenticates via a JWT token in the query string. The token is stored in sessionStorage (never localStorage — that persists across tabs and survives restarts, creating a broader attack surface). On expiry, the token is cleared and the user is re-prompted for login. The backend validates the token on every WebSocket message, not just on connection.
const WS_URL = \`wss://api.example.com/ws?token=\${getJWT()}\`;
function getJWT(): string {
const token = sessionStorage.getItem("fd-token");
if (!token) throw new AuthError("No session");
const decoded = jwtDecode(token);
if (decoded.exp * 1000 < Date.now()) {
sessionStorage.removeItem("fd-token");
throw new AuthError("Session expired");
}
return token;
}
const WS_URL = \`wss://api.example.com/ws?token=\${getJWT()}\`;Price data is considered confidential while it is live. Historical data can be cached, but real-time ticks should never be written to localStorage or IndexedDB beyond the current session. I set Cache-Control: no-store on all tick responses and never include raw tick data in error logs or analytics events.
Always use wss:// (TLS), never ws://. The WebSocket connection is authenticated on every message, not just the initial handshake. Rate limit subscriptions — a client cannot subscribe to more than 20 symbols simultaneously, and subscription changes are throttled to once per second to prevent abuse.
Testing a financial dashboard is uniquely challenging. You are testing canvas pixels, WebSocket message streams, and real-time state mutations — none of which are trivial in a test environment. Here is the strategy.
Canvas tests verify that chart rendering produces correct pixel outputs. Instead of asserting on specific pixel colors (which vary by rendering engine), I test structural properties: the canvas has the correct dimensions, candle colors differ for bullish and bearish candles, and charts handle empty data without crashing.
describe("ChartInstance - canvas rendering", () => {
let canvas: HTMLCanvasElement;
beforeEach(() => {
canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 400;
});
it("renders candles with correct colors", () => {
const candles = [
{ open: 100, high: 102, low: 98, close: 101 },
{ open: 101, high: 105, low: 100, close: 98 },
];
renderChart(canvas, candles);
const ctx = canvas.getContext("2d")!;
const pixels = ctx.getImageData(0, 0, 800, 400);
expect(pixels).toBeTruthy();
});
it("handles empty data gracefully", () => {
renderChart(canvas, []);
const ctx = canvas.getContext("2d")!;
expect(ctx.getImageData(10, 10, 1, 1).data).toBeTruthy();
});
});WebSocket tests use a mock server that simulates connection drops, reconnection, and message bursts. I test that the subscription manager re-subscribes all symbols after reconnect, that message routing dispatches ticks to the correct chart instance, and that the exponential backoff stops retrying after the 10th failure.
Every PR runs a performance benchmark: render 16 chart tiles with 100 candles each and assert the frame time stays under 16ms (60fps). If the benchmark regresses by more than 20%, the PR is blocked. This catches slow rendering paths before they reach production.
Financial dashboards have a reputation for being inaccessible — all those charts and numbers with no textual alternatives. But accessibility is especially important here because many traders use screen readers and cannot rely on visual patterns alone.
<canvas> element has fallback content describing the chart in text. Screen readers get a data table of the latest prices.aria-live="polite" region announces price changes (e.g., "AAPL up 2.3 percent"). Users can toggle this on/off.Here is a working financial dashboard with four live-updating chart tiles. Each tile shows a simulated price stream with mini line charts drawn on canvas. The prices update every 3 seconds, mimicking a real data feed.
Tip: try opening the browser devtools performance tab and watch the frame rate while the prices update. The canvas rendering is lightweight enough to maintain 60fps even with 8+ chart tiles.
Building a financial dashboard taught me more about performance than any other frontend project. Here is what I wish I knew before starting:
SVG creates DOM nodes per data point. Canvas is a pixel buffer — fixed memory cost regardless of data size.
Fixed-size, O(1) append, automatic eviction. Perfect for real-time streaming data.
Prevents thundering herd. Start at 1s, max at 30s. Re-subscribe all symbols on reconnect.
Reduces thousands of candles to hundreds while preserving visual shape.
Serialize grid positions to localStorage. Do NOT store candle data — that is what the server is for.
One global RAF batches all renders. OffscreenCanvas moves work off the main thread.