Designing a high-performance analytical dashboard with panel grid, real-time data streaming, templated variables, data source plugins, and canvas-based chart rendering — inspired by Grafana, Datadog, and Kibana.
DashboardObservabilityCanvasReal-Time
0. What Are We Building?
A Grafana-like analytical dashboard. Users land on a page filled with panels — time-series charts, gauges, tables, heatmaps — each connected to a different data source. They can rearrange panels on a grid, change the global time range, filter by template variables, and watch data refresh in real time. A single dashboard might monitor production infrastructure across 40+ simultaneous queries.
Key Insight
The challenge is not rendering one chart. It is coordinating dozens of panels, each with its own live data query, time range, variable bindings, and refresh cycle — inside a single page that users can freely resize, rearrange, and share via URL. The moment you add real-time streaming and cross-panel filters that cascade updates, the complexity compounds fast.
Real-life examples: Grafana (10M+ active instances), Datadog, Kibana, New Relic, and Splunk all solve this same problem. Each made different architectural tradeoffs that we can learn from. We will focus on the core frontend design — component structure, state management across many panels, data modelling, API contracts, and performance — without diving into backend metric ingestion or alerting engines.
1. Requirements & Scoping
Functional
Display a grid-based dashboard with multiple panels (charts, gauges, tables, heatmaps)
Each panel has its own data query, visualization type, and refresh interval
Global time range picker that cascades to all panels simultaneously
Dashboard persistence — save and load layouts as JSON
Live refresh — panels poll or stream fresh data at configured intervals
Panel drill-down — click a chart to open detail view or link to another dashboard
Non-Functional
Sub-100ms panel render, 16ms frame budget for animations
Canvas-based rendering — no DOM node per data point
Data source proxy — backend holds API keys, not the browser
Memory capped — panels off-screen get unmounted, data cached outside React
Accessible: keyboard-navigable grid, ARIA live regions, high-contrast charts
Tip
Every panel should be independently renderable. If one panel is slow to fetch or render, it should not block the others. This means isolated canvases, separate data subscriptions, and independent query lifecycle per panel.
2. Architecture — Scene Graph Outside React
An analytical dashboard is not a content page. SSR does not help here — dashboards are never crawled, they require authentication, and their data changes faster than any cached HTML. Grafana ships as a CSR SPA, and this is the right call. The initial shell is a thin HTML page; the heavy lifting happens in JavaScript after auth and data are ready.
The Scene Graph Pattern
The most important architectural decision is where panel state lives. Grafana learned this lesson the hard way. Their old architecture stored all panel state inside React components — every panel had its ownuseState for data, loading, and error. The problem? React destroys component state on unmount. A panel that scrolls out of view, enters edit mode, or gets caught in a layout recalculation loses its data and must re-fetch when it comes back. Users saw this as "flicker" — panels going blank and showing spinners even though data had just loaded.
The fix is a pattern Grafana calls the scene graph — a tree of state objects that livescompletely outside the React component tree. Each panel is represented by a PanelObject that owns its query data, loading state, and configuration. These objects never unmount. React components are thin renderers that subscribe to scene objects via RxJS BehaviorSubject. When a panel scrolls off-screen, React unmounts the renderer, but thePanelObject keeps running — its refresh timer, its query data, everything. When the panel scrolls back, a new renderer mounts, subscribes, and receives the current state immediately. No network request. No flicker.
Scene graph lives outside React — PanelObject nodes never unmount. React only subscribes.
Notice useState(() => panelObject.state.data) — the lazy initializer form. If data was already loaded before this component mounted, the panel renders immediately with that data. The subscription then keeps it up to date. This is the "immediately emit on subscribe" property that eliminates flicker.
Write time range and variable changes to the URL with history.replaceState (not pushState) during drags to avoid filling the back stack. Use pushState only on deliberate actions like changing a variable dropdown.
If Building From Scratch: TanStack Query
Grafana built @grafana/scenes because they had years of accumulated technical debt. If starting fresh, TanStack Query solves the same core problem — query results outliving React component lifetimes — with a fraction of the code. Its gcTime and staleTime settings provide the exact same "immediately emit on subscribe" behavior through its cache, and the enabled option pauses queries when panels are off-screen.
TanStack Query does not handle WebSocket streaming, canvas rendering coordination, or drag-and-drop grid layout. Those remain custom work. But for the core problem — "my 20 panels are all fetching data, I need results cached and not lost on unmount" — it eliminates the need to build custom infrastructure.
3. Data Model — Dashboard as JSON
Both Grafana and Datadog use a JSON document to represent the complete state of a dashboard. This is the right pattern: dashboards can be exported, version-controlled in Git, and diffed between environments.
$env inside queryExpression is a template variable reference. Before executing the query, the frontend interpolates the variable's current value. When the user changes env from production to staging, every panel whose query references $env automatically re-fetches.
We store panels in a normalized shape for fast lookups during variable propagation:
executedAt is stamped on the frontend when the query response arrives. We use it in the refresh scheduler to decide whether a panel's data is stale. If now - executedAt > refreshIntervalMs, we queue that panel for refetch.
Variable Dependency Graph
Template variables can depend on each other. A variable region might provide the options list forhost. When region changes, we must re-fetch options for host before interpolating into panel queries. We model this as a directed graph — each VariableModel holds an array of dependsOn. When any variable changes, we topologically sort the graph and resolve variables in order.
4. Interface Definition (API)
Data Query Endpoint
The query endpoint accepts batched panel queries — this reduces HTTP overhead when 20 panels fire simultaneously. The maxDataPoints field is critical: we send the panel's rendered width in pixels. The backend downsamples the result to at most that many points.
For sub-5-second refresh needs, polling via REST introduces noticeable latency. We use WebSocket streaming: the client sends a subscribe message when a panel becomes visible, and unsubscribe when it scrolls out of view.
Panel components never fetch data. They receive everything through props and emit events upward. The parent PanelContainer handles the subscription to panelModel.data$ and passes the result down.
Data flow through the dashboard: user action → URL sync → scene graph → query scheduler → data source → panel render
5. Panel Grid — Drag, Resize, Virtualize
The panel grid is the primary interaction surface. Users drag panels to rearrange them, resize from corners, and expect the layout to hold across page reloads. We use a CSS Grid with absolute positioning in grid cells — each panel occupies w × h cells starting at (x, y).
Drag-and-Drop with react-grid-layout
react-grid-layout (used by Grafana) provides the drag, resize, and collision behavior out of the box. On every drag end, we serialize the updated layout positions into the dashboard JSON and save.
Virtualization — Only Mount Visible Panels
A dashboard with 40 panels should not mount 40 canvas elements and 40 active query subscriptions. Each canvas holds a GPU texture. Forty of them is wasted VRAM. The fix: viewport-based rendering usingIntersectionObserver. We only mount panels within or close to the visible area. Off-screen panels render as lightweight placeholder <div> elements with the correct height (to keep the scrollbar accurate).
A canvas at display: none still occupies GPU texture memory. Only unmounting the element fully releases the texture. This is why we unmount rather than hide — on a dashboard with 40 panels, hiding consumes 40 GPU textures even though 30 are not visible.
Key Insight
With virtualization, a dashboard with 40 panels behaves like 5-8 panels. Panels in the viewport (plus a 200px pre-load margin) are fully mounted. The rest are lightweight skeletons — zero GPU memory, zero network requests, zero timers. Scrolling feels the same as a 5-panel dashboard.
6. Chart Rendering — Canvas-Driven
Canvas vs SVG
Aspect
Option A
Option B
Verdict
DOM nodes
1 canvas per chart
N DOM nodes per data point
Canvas wins
Memory (10K points)
~80 KB pixel buffer
~10K+ DOM nodes
Canvas wins
Per-element interactivity
Requires hit-test math
Native event per element
SVG for low-volume
Accessibility
Requires fallback table
Native text in DOM
Draw (use fallback)
For time-series panels with up to 800 data points, SVG would create 800+ DOM nodes per chart. With 20 panels, that is 16,000 DOM nodes the browser must manage — layout recalculations, style resolution, event propagation. Canvas renders to a single pixel buffer. The CPU cost is proportional to what you draw, but the memory cost is fixed at canvas resolution. Grafana uses Canvas-based rendering through uPlot for precisely this reason.
HiDPI Support
Canvas rendering on Retina displays needs devicePixelRatio handling. Set the canvas buffer size to width * dpr and scale the context. Without this, charts look blurry on 2x and 3x screens.
Thresholds and Color Bands
Field config includes thresholds that the canvas rendering code draws as colored bands or lines behind the data. A threshold at value: 1000, color: "yellow" paints a yellow background fill from y=1000 upward. This is handled entirely in the canvas draw loop — no DOM, no CSS.
7. Data Source Abstraction — Plugin Pattern
Analytical dashboards connect to many backend types: Prometheus, InfluxDB, Graphite, Elasticsearch, SQL databases. Each has its own query language and API shape. The panel should not care which data source it is talking to. We solve this with a plugin pattern.
Data source plugins implement a common interface — panels never talk to databases directly.
example.ts
'interface DatasourcePlugin {',
' type: string;',
' uid: string;',
' name: string;',
'',
' // Query execution — returns a normalised DataFrame',
' runQuery(query: QueryDef): Promise<DataFrame[]>;',
'',
' // Query builder UI — each data source renders its own editor',
' QueryEditor: React.ComponentType<QueryEditorProps>;',
'',
' // Variable support — fetch options for template variables',
' fetchVariableOptions(query: string): Promise<SelectOption[]>;',
'',
' // Health check',
' testConnection(): Promise<boolean>;',
'}',
'',
'// Registry — panels look up plugins by datasourceUid',
'const pluginRegistry = new Map<string, DatasourcePlugin>();',
'pluginRegistry.set("prometheus-prod", new PrometheusPlugin({ url: "..." }));',
'pluginRegistry.set("influxdb-prod", new InfluxDBPlugin({ url: "..." }));'
Key Insight
The query builder is the hardest part of each plugin. A Prometheus query builder shows label selector autocomplete and metric name browsing. An SQL query builder shows schema introspection and WHERE clause construction. This is why Grafana has 100+ community data source plugins — each is a substantial project on its own.
Tip
Normalise all query results into a common DataFrame format — columns with types and rows of values. Panels only understand DataFrames, never raw Prometheus or InfluxDB responses. This is what makes plugins interchangeable.
8. Variables & Templating
Template variables let users switch between environments, regions, or hosts with a single dropdown change. When a variable changes, every panel whose query references it must re-fetch with the new value.
Variables can depend on each other. For example, region provides options for host — changing the region should reload the host list. We model this with a dependsOn field in each variable definition. When any variable changes, we topologically sort the dependency DAG and resolve in order before triggering panel queries.
URL Synchronization
Variables are encoded as URL query parameters (var-env=production). On page load, we parse these into the variable model tree before the first render. When the user changes a variable, we write back to the URL with history.replaceState. This makes dashboards shareable — a colleague gets the exact same view.
9. Performance Optimization
Performance is the defining quality of a production dashboard. Here are the techniques that make the biggest difference.
Technique 1: Query-Time Downsampling (LTTB)
The single most effective optimization is sending the panel's pixel width as maxDataPoints in every query. A panel 400 pixels wide never needs more than 400 data points — yet a Prometheus query over 24 hours with a 15-second scrape interval produces 5,760 points per metric. The backend applies LTTB (Largest Triangle Three Buckets) to downsample to exactly the requested number. This is a 93% reduction in payload size — from 461 KB to 32 KB per panel.
Never perform downsampling in the frontend after receiving raw data. You still pay the network cost of transferring the full dataset. On a 10-panel dashboard with 30-second refresh, that is 4.6 MB every 30 seconds vs 320 KB with server-side downsampling. Downsampling belongs at query time on the backend, before data crosses the wire.
Technique 2: Query & Render Scheduling
Datadog's engineering blog describes how they rebuilt their scheduler into two discrete modules: a query scheduler and a render scheduler. We adopt the same separation. Query scheduling: drain a pending queue at most 5 concurrent requests, skipping off-screen panels. Render scheduling: batch canvas redraws using requestAnimationFrame, coalescing multiple panel updates into a single frame pass.
Each visualization type — timeseries, gauge, table, heatmap — is a separate JavaScript chunk loaded only when a dashboard uses it. The initial bundle ships with the dashboard shell, grid engine, query scheduler, and variable system. Panel renderers are loaded on demand.
Every panel subscribes to the shared time range and variable state. Naively, a time range change triggers re-render of every component reading from context. We prevent this with React.memo on panel wrappers — a panel re-renders only if its own PanelData, grid position, or field config changed.
Technique 5: Time Range Sub-range Optimization
When the time range changes, we do not re-run a panel's query if its data already covers the new range. If the current data spans 6 hours and the user zooms into a 2-hour sub-range, we re-render existing data with a different viewport — no new query. This is the same optimization that makes Datadog feel fast when zooming.
10. Security Considerations
Analytical dashboards are internal tools accessed by trusted users, but that does not mean security is optional. Here are the critical protections.
Data Source Proxy
The browser never talks to Prometheus or InfluxDB directly. All data queries go through a proxy API that the backend serves. The backend holds the data source API keys and connection strings. The frontend only knows datasourceUid — it sends the query expression, and the backend authenticates and executes it. This prevents credential exposure and allows centralized access control.
XSS in Panel Titles
Dashboard titles, panel titles, annotation descriptions — any user-editable text field is a vector for stored XSS. We sanitize all text content with DOMPurify before rendering, and we never usedangerouslySetInnerHTML. Grafana had a CVE for this exact issue in 2021.
The connect-src directive restricts which WebSocket endpoints the dashboard can connect to — important for multi-data-source setups where each data source might have a different WebSocket URL.
API Key Authentication
REST endpoints authenticate via bearer JWT. The WebSocket connection authenticates via a token in the query string. Tokens are stored in sessionStorage (not localStorage) and validated on every message, not just on connection.
11. Testing Strategy
Testing an analytical dashboard is uniquely challenging: canvas pixels, WebSocket message streams, and real-time state mutations are all hard to test. Here is the strategy.
State Layer Unit Tests
Because all dashboard logic lives in the scene graph (outside React), we can write unit tests that instantiate models, trigger state changes, and assert on observable emissions — no act(), no waitFor(), no jsdom.
The query scheduler and data source plugins should be heavily tested. Mock the backend, verify that queries are batched correctly, that the semaphore limits concurrency, and that failed queries emit proper error states.
Canvas Rendering Tests
Instead of asserting on specific pixel colors (which vary by rendering engine), test structural properties: the canvas has the correct dimensions, chart renders without crashing on empty data, and threshold bands produce visible color fills.
Mount the dashboard with a mock data source plugin, simulate variable changes, and verify panels update correctly. Use Playwright to capture visual snapshots and detect rendering regressions across panel types.
Tip
Use real data in test fixtures. Synthetic data rarely exposes edge cases — NaN values, missing metrics, empty arrays, and sudden spikes all happen in real monitoring data. Generate fixtures from actual Prometheus or Datadog query snapshots.
12. Accessibility
Analytical dashboards have a reputation for being inaccessible — charts and numbers with no textual alternatives. But enterprise procurement questionnaires require accessibility compliance. Here is how we make it work.
Canvas fallback table: Each <canvas> has a visually hidden <table> sibling that represents the same data. Screen readers get the data table; sighted users see the canvas. This is the pattern Grafana uses.
ARIA live region: A hidden aria-live="polite" region announces changes — "cpu spiked to 95%", "error rate dropped below threshold". Users can toggle verbosity.
Keyboard navigation: Arrow keys move focus between panels in the grid. Tab enters the panel toolbar. Enter/Space activate controls. Every control has a visible focus ring.
High contrast mode: Charts use patterns (dashed lines, dotted markers) in addition to color to distinguish series. Threshold colors respect prefers-contrast: more and use increased luminance contrast.
Focus management: When a panel enters fullscreen mode, focus moves into the panel and is trapped. When exiting, focus returns to the panel's position in the grid. No disorienting jumps.
Key Insight
The canvas fallback table is non-trivial. It must match the displayed data range, include the same aggregation, and update when the chart updates. We generate the table HTML from the same PanelData object that feeds the canvas draw loop — one source of truth, two outputs.
13. Key Takeaways
Designing an analytical dashboard taught me more about state management architecture than any other frontend project. Here is what I wish I knew before starting:
Server state must live outside React
React destroys state on unmount. Query results are expensive network responses — cache them in a scene graph or TanStack Query, not in useState.
Canvas over SVG for chart rendering
SVG creates DOM nodes per data point. Canvas is a fixed pixel buffer — memory cost does not grow with data volume.
Downsample at query time, not on the frontend
LTTB reduces payload by 93%. Never transfer raw data just to discard it on the client — the network cost is the real bottleneck.
Virtualize panels with IntersectionObserver
Only mount visible panels (plus 200px pre-load margin). Off-screen panels are lightweight placeholders — no GPU texture, no queries, no timers.
Data source plugin pattern
Every data source (Prometheus, InfluxDB, SQL) implements the same interface. Panels never talk to databases — they talk to DataFrames.
Proxy all data queries through backend
The browser never holds API keys. Every query goes through a data source proxy — this is how Grafana prevents credential leaks.
Batch queries + RAF render scheduling
Throttle to 5 concurrent queries. Batch canvas redraws into a single requestAnimationFrame. Two schedulers, one fast dashboard.