Design a Virtualized Grid – Frontend System Design

We’ll walk through the frontend system design for a reusable data table. Our goal is a component that shows a sticky header, sorts columns, optionally filters and pages, and stays fast at 10,000 rows. Interviewers are not looking for a dump of <tr> tags. They want a public API, a virtualization plan, and a clear owner for sort and selection state. Put simply, the task is to design a virtualized grid that keeps scrolling smooth at any row count.
You’ll see how the table stays presentational, how the View Model owns the window over the array, and how accessibility changes when you leave a real <table> for a virtualized grid. We’ll stay honest about scale: 10,000 row objects are fine in memory. 80,000 DOM cells are not.
Problem Statement
Design a reusable data table.
Requirements:
- Fixed header while the body scrolls
- Sortable columns, optional filter and pagination (or virtualization)
- Custom cell renderers (status chips, links, actions menu)
- Stay fast at 10,000 rows
Describe the public API, virtualization, and accessibility.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Server or client pagination? | Both. Virtualize when all rows are on the client; page when the API pages. |
| 2 | Row selection? | Optional multi-select. |
| 3 | Column resize / reorder? | Nice to have. Mention it. |
Two more that pay off: are row heights fixed (yes, unless they force otherwise), and is the table the only scroll container or does the page scroll too. Fixed row height is the default you defend. Variable height is a prefix-sum problem you can name without implementing.
Requirements
Functional Requirements
- Sticky header that stays aligned with body columns while the body scrolls
- Sortable columns with a visible direction and a single active sort
- Optional text filter and either client virtualization or server pagination
- Custom cell renderers for status, links, and a row actions menu
- Optional multi-select with a header checkbox that can be mixed
- Stay interactive at 10,000 rows on the client
Non-Functional Requirements
- Only the visible window plus a small overscan is in the DOM
- Sort and selection do not mutate the
rowsprop - Keyboard: arrows move a focus cell, Space toggles selection, Enter activates the cell control
- Header stays in the accessibility tree when it is sticky
- Empty, loading, and error states are first-class, not an afterthought
Scalability Estimates
The interview number is 10,000 rows. Do the arithmetic on DOM nodes, not on a made-up backend.
| Metric | Estimate | Calculation | Notes |
|---|---|---|---|
| Rows in memory | 10,000 | Interview target | Plain objects. The table does not fetch them. |
| Row object size | ~200 bytes | 10,000 × 200 B ≈ 2 MB | Fine in JS heaps. DOM is the cost, not JSON. |
| Row height | 40px | 10,000 × 40px = 400,000px scroll height | A tall spacer is cheap. 10,000 real rows are not. |
| Visible rows | 20 | 800px viewport / 40px | Add 5 overscan either side ≈ 30 row nodes. |
| Columns | 8 | Typical admin table | CSS grid template shared by header and body. |
| Mounted cells | 240 | 30 rows × 8 columns | Versus 10,000 × 8 = 80,000 if you render everything. |
| Server page size | 50 | When the API pages | Virtualize inside the page only if a page is huge. |
Component API
type Column<T> = {
id: string;
header: string;
accessor: (row: T) => React.ReactNode;
width?: number;
sortable?: boolean;
sortFn?: (a: T, b: T) => number;
};
type TableProps<T> = {
columns: Column<T>[];
rows: T[];
rowId: (row: T) => string;
height: number; // viewport height for virtualization
rowHeight?: number; // default 40
onSort?: (col: string, dir: "asc" | "desc") => void;
};
The table doesn’t fetch. The parent (or a View Model) owns the data.
That last sentence is the design. DataTable is a window: columns, a viewport height, and a slice of rows. The View Model owns the source array, the active sort, the filter text, the cursor for server pages, and the selection Set. If you let the table call fetch, you cannot reuse it for a static report and a live admin view.
Extend the props only when the interviewer asks. Selection is selectedIds plus onToggle(id). A filter is onFilter(text) raised from a toolbar the parent renders above the table. Column resize is onColumnResize(id, width) — mention it, do not build it first.
Cell renderers belong in accessor (or a cell render prop). They must be referentially stable. An inline (row) => <StatusChip value={row.status} /> created during render will break memoized rows and you will drop frames at 10k.
Frontend Architecture Overview
Think of the table as three layers. The View is HeaderRow plus a virtualized Body. The View Model holds sort, filter, selection, and the derived window. A Data Manager (not the table) talks to the network when the API pages. Interviewers want that split drawn before you write JSX.
When every row is already on the client, the Data Manager is a no-op and the View Model sorts a copy of rows. When the API pages, onSort and page changes become requests, the table shows a header spinner, and the View Model replaces the current page. Same component, two owners for the array.
Component Structure and Responsibilities
<DataTable>
<Toolbar /> // filter, page size — parent-owned, optional
<HeaderRow /> // position: sticky; top: 0
<Body>
<Row /> // only the window
</Body>
<StatusBar /> // "12,480 rows · 3 selected"
</DataTable>
- DataTable: Presentational shell. Receives
columns,rows,height. Computes the visible window fromscrollTop. Does not fetch. - HeaderRow: One cell per column. Sortable headers are buttons with
aria-sort. Stays sticky. Rendered as a real row in the a11y tree, not a twin table that the screen reader never sees. - Body: The scroll container. A top spacer and a bottom spacer (or a single transform) stand in for unmounted rows.
- Row: Memoized. Receives the row object, the column list, selected boolean, and a stable
onToggle. Re-renders when that row’s data or selection changes, not when a different row is selected. - Cell: Calls
column.accessor(row). No extra wrapper state. Actions menus portal into a layer that is still labelled by the row. - Toolbar / StatusBar: Parent UI. Filter input and “N selected” live here so the table API stays small.
- TableViewModel: Source of truth for sort key, direction, filter, page cursor, and
Set<string>selection. Exposes derivedvisibleRows. - Data Manager: Only when the server pages. Owns
GET /v1/rows, abort of in-flight sorts, and the loading flag the header reads.
Network Layer and Data Management
The Data Manager is a single module the View Model calls. It is not inside DataTable.
- Fetch a page:
GET /v1/rows?cursor=&limit=50&sort=name&dir=asc&q= - Abort the previous request when sort or filter changes (
AbortController) - Surface
loading,error, andnextCursorto the View Model - Never write into
rowsfrom a cell renderer
Client-side mode skips this module. The View Model slices a sorted copy and the table virtualizes that copy. Say both paths in the interview; they share the same component API.
Render and Sort Workflow
- The parent passes
columnsand the currentrows(full set or one page). - The user clicks a sortable header. If
onSortis provided, the table raises it and shows a spinner in that header. If not, the View Model sorts a copy locally. - Body reads
scrollTop, computesstartandvisibleCount, and renders that slice plus overscan. - Row click or Space toggles an id in the View Model’s
Set. Header checkbox writes all visible ids, or all ids if the interviewer wants select-all-across-pages (that is a product call — say so). - Filter text debounces in the toolbar, then either filters the copy or becomes
q=on the next GET. - A cell renderer that needs a network action (delete, assign) calls a parent command. The table does not know about those APIs.
Layout
<DataTable>
<HeaderRow /> // position: sticky; top: 0
<Body>
<Row /> // only the window
</Body>
</DataTable>
Two ways to virtualize:
- Fixed row height:
start = floor(scrollTop / rowHeight). Use this unless they force variable height. - Variable height: keep a prefix-sum of row heights (or a library like TanStack Virtual).
Don’t use display:table if you virtualize — it fights absolute/windowing. Use CSS grid for the columns so cells stay aligned.
Building the window

This is the same camera idea as Sheets, with DOM rows instead of a canvas. Write the function.
function windowFor(scrollTop: number, viewH: number, rowH: number, n: number, overscan = 5) {
const start = Math.max(0, Math.floor(scrollTop / rowH) - overscan);
const count = Math.ceil(viewH / rowH) + overscan * 2;
const end = Math.min(n, start + count);
return { start, end, topPad: start * rowH, bottomPad: (n - end) * rowH };
}
The body is a tall spacer of n * rowH. Inside it, a block offset by topPad renders rows start..end. Overscan of ~5 rows is so a fast flick does not flash empty space. Do not render n and hide the rest with CSS — that is not virtualization.
scroll only writes scrollTop into a ref and sets dirty. A rAF (or useSyncExternalStore on that ref) produces the next window. Setting React state on every scroll event will drop frames.
Sticky columns are a second camera on the x-axis. Pin column 0 with position: sticky; left: 0 on both the header cell and each body cell in that column. Horizontal scroll then moves the rest. If you also virtualize columns (rare unless they have 80+), you need a column prefix-sum and a horizontal pad — mention it, do not build it first.
Measure variable-height rows only when they enter the window. Cache the height. A prefix-sum (or a running total you update when a cached height changes) gives start. First pass can assume a guess (say 48px) and correct; that is why you overscan.
Alignment is the layout bug that shows up after virtualization works. Header cells and body cells must share one column template: grid-template-columns: 40px 2fr 1fr 120px (checkbox, name, status, updated). If you size them independently, the sticky header drifts by a few pixels as soon as a cell wraps.
Sticky header: position: sticky; top: 0; z-index: 1 on the header row inside the same scroll container as the body. A second table for the header is easier to get visually right and harder to get accessible — the screen reader then sees two tables. Prefer one grid. If you split, wire aria-labelledby and do not drop the header out of the tree.
Horizontal scroll is a second axis. Pin the checkbox column and let the rest scroll together. Header and body share the same scrollLeft — listen on Body and set it on Header, or put both in one overflow-x container.
Sorting and Selection
Client sort: slice a copy, never mutate rows. Server sort: lift it (onSort) and show a spinner in the header.
Selection: a Set of ids in the View Model. Header checkbox is mixed (aria-checked="mixed") when some rows are selected.
Sort state is { columnId, dir } with dir cycling none → asc → desc → none. Only one column is sorted. The active header gets aria-sort="ascending" or "descending"; every other sortable header is aria-sort="none". Use the column’s sortFn on the client. On the server, send the column id and trust the API’s collation — do not re-sort the page you just received unless you are combining client filter on top of a page (usually a mistake; say you would filter server-side too).
Selection must not live in the row component. A Set in the View Model gives O(1) lookup. Select-all on the current window writes those ids. Select-all across 10,000 local rows is cheap (walk ids once). Select-all across a server-backed set is a different API (POST /v1/rows/select-all?q=) — mention it, do not pretend the header checkbox can fetch every id.
State and Data Flow
Keep derived data out of the table and out of React state when a useMemo on the View Model will do.
- User action: sort click, filter keystroke, page change, or row toggle.
- View Model updates sort,
q, cursor, or the selectionSet. - If the API pages, the Data Manager fires a GET with an
AbortController. A stale response is ignored. - View Model produces
visibleRows(sorted copy, or the new page). - DataTable maps
scrollTopto a window and renders those rows. - Loading and error flags render in the header or a body overlay. The previous rows stay on screen so the table does not flash empty.
This is the same unidirectional flow you would use for a list, with a window function in the middle. Do not store visibleRows in the table’s local state if the parent already has them — you will desync on sort.
Data Model
The row type is the caller’s. The table adds sort, selection, and a window. Keep those in one place.
type SortDir = "asc" | "desc";
type SortState = {
columnId: string;
dir: SortDir;
};
type TableQuery = {
q: string;
sort: SortState | null;
cursor: string | null;
limit: number;
};
type TableVM<T> = {
rows: T[]; // current page or full client set
total: number; // server total, or rows.length
selected: Set<string>;
query: TableQuery;
loading: boolean;
error: string | null;
};
type Window = {
start: number;
end: number; // exclusive
padTop: number;
padBottom: number;
};
type RowSelectionState = "none" | "some" | "all";
total is what the status bar prints. selected.size can be larger than rows.length if the user selected on a previous page — that is why selection is a Set of ids, not a boolean on the row object. Window is computed on scroll, not stored as source of truth.
API Design
When all rows are local, the “API” is the component props. When the interviewer wants server pages, add a small query surface and keep it boring.
| Action | Method / Endpoint | Description |
|---|---|---|
| List rows | GET /v1/rows?cursor=&limit=50&sort=&dir=&q= | Returns { rows, nextCursor, total }. total may be approximate. |
| Sort / filter | Same GET, new query | Abort the in-flight request. Keep the last good page on screen. |
| Row action | POST /v1/rows/:id/actions | Body { type }. The cell renderer calls a parent command, not the table. |
| Bulk action | POST /v1/rows/batch | Body { ids, op }. Used when selection is multi-page. |
| Client-only mode | props only | No GET. View Model sorts and filters a copy of rows. |
Example: Consuming a Page on the Frontend
async function loadRows(query: TableQuery, signal: AbortSignal): Promise<{ rows: Order[]; nextCursor: string | null; total: number }> {
const params = new URLSearchParams();
params.set("limit", String(query.limit));
if (query.cursor) params.set("cursor", query.cursor);
if (query.q) params.set("q", query.q);
if (query.sort) {
params.set("sort", query.sort.columnId);
params.set("dir", query.sort.dir);
}
const res = await fetch(`/v1/rows?${params}`, { signal });
if (!res.ok) throw new Error("rows_failed");
return res.json();
}
The View Model holds the controller. A new sort does controller.abort(), allocates a new one, and calls loadRows again. The table only sees loading: true on that header cell.
Optimizations
Virtualization is the optimization. Everything else is how you keep the window cheap to paint.
Fixed-height window
function getWindow(scrollTop: number, height: number, rowHeight: number, count: number, overscan = 5): Window {
const start = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const visible = Math.ceil(height / rowHeight) + overscan * 2;
const end = Math.min(count, start + visible);
return {
start,
end,
padTop: start * rowHeight,
padBottom: Math.max(0, (count - end) * rowHeight),
};
}
// Body render
// <div style={{ height: padTop }} />
// rows.slice(start, end).map(...)
// <div style={{ height: padBottom }} />
Read scrollTop from the scroll container, not window, and update the window in requestAnimationFrame so a fast flick does not setState 60 times with 60 different slices. Memoize Row on rowId + selected + the column identity.
If they force variable height, you keep a prefix-sum array offsets[i] = pixel start of row i. Binary-search scrollTop to find start. Measure newly mounted rows and patch the prefix sums. That is why you do not volunteer variable height.
Accessibility
role="table"or a real<table>if you are not virtualizing. Virtualized grids often userole="grid".- Sortable headers are buttons:
aria-sort="ascending" - Keyboard: arrows move a focus cell; Space toggles selection
- Don’t drop the header out of the a11y tree when it is sticky
A virtualized body must still advertise the full size: aria-rowcount={total} on the grid and aria-rowindex={absoluteIndex + 1} on each mounted row (1-based, header is row 1). Screen readers then say “row 482 of 10,000,” not “row 7 of 30.”
Roving focus lives on one cell at a time. Arrow keys move that focus cell; the rest of the grid is not in tab order. Tab leaves the grid for the next page control. This is why a virtualized table usually becomes role="grid" — a static <table> with 240 mounted cells and 10,000 implied rows does not give you cell-level keyboard semantics for free.
The header checkbox needs a name (“Select all rows”) and aria-checked="mixed" when the View Model reports "some". Row checkboxes take their name from the row’s label column, not “checkbox 14.”
Security
Cell renderers are the XSS surface. The table will happily mount whatever accessor returns.
- Treat cell strings as text. If a renderer must output HTML (a highlight of the filter query), escape the source and only wrap the match.
- Row actions that mutate go through the same CSRF-protected POST as the rest of the app. A table is not an excuse for a GET-with-side-effect.
- Do not put secrets in row objects you cache in
sessionStorageto survive a refresh.
Handling User Edge Cases
| Case | Strategy |
|---|---|
| ❌ Empty result | Keep the header. Body is a single empty state, not a zero-height grid. |
| ❌ Sort while a page is in flight | Abort the old GET. Leave the last rows visible. Spinner on the active header only. |
| 🔄 Filter debounce | 250ms. Reset cursor to null. Do not fire a request per keystroke. |
| 🔁 Selection after sort | Ids stay in the Set. Rows re-render selected wherever they moved. Do not store selected index. |
| 📶 Server 500 on page 2 | Keep page 1 on screen. StatusBar shows the error and a retry that reuses the same cursor. |
| ⏳ 10,000 rows, user jumps the scrollbar | Recompute the window from the new scrollTop. Overscan hides the blank gap. |
| 🚫 Custom cell throws | Error boundary per row or per cell. One bad chip must not blank the table. |
Pro-Level Optimizations
| Area | Suggestion |
|---|---|
| Scroll handler | Compute the window in requestAnimationFrame. Ignore intermediate events in the same frame. |
| Row memo | Compare rowId, selected, and column identity. Do not pass a new columns array every render. |
| Event delegation | One click listener on Body for row select. Per-cell handlers at 240 nodes are fine; at 80,000 they are not. |
| Column resize | Pointer capture on the handle, write widths into the shared grid template. Persist in the View Model. |
| Prefetch | When the user is near the end of a server page, prefetch nextCursor and swap without an empty flash. |
| Variable height | Prefix sums + binary search. Do not volunteer it. TanStack Virtual is an acceptable named exit. |
Interview details people skip
A table interview is usually a read-heavy component-library primitive, not Sheets. Say that out loud. Formulas, cell editing, and two-axis canvas are a different question. Sort, filter, resize, and frozen columns are extensions — get the window and the column model right first.
Default to a real <table>. Header-to-cell relationships come free. Virtualize by mounting only the window plus two spacer rows inside the same <tbody>: one empty colSpan={columns.length} cell above, one below, both aria-hidden and with no focusable descendants. One scroll container owns vertical and horizontal overflow. A sticky <thead> lives in that container. Splitting header and body into two scrollers is how columns drift. Switch to a div + role="grid" only when you need cell-level editing or two-axis virtualization — that is the follow-up, not the default.
Height turns scrolling on. height is required for a sticky header and for row virtualization. Omit it and the table grows with the page; sticky has nothing to latch onto. width sizes the viewport, not the sum of the columns. The inner table can still be wider and scroll horizontally.
Column widths are a shared map. Each column has width, minWidth, maxWidth, flex, align, and overflow. Estimate missing widths from the header plus a small sample of rows — not from every virtualized cell as it mounts. Clamp. Sum to a natural width. If the viewport is larger, grow flexible columns (flex > 0). If it is smaller, shrink them to minWidth. If it is still wider, allow horizontal overflow. Do not crush labels to fit. Publish the map through a <colgroup> and table-layout: fixed so later cells cannot reopen the width negotiation. Remeasure when the column model or the viewport changes, not when a late row arrives.
Fixed-height virtualization and wrapping fight each other. Truncate or clip in the base design. If a column must wrap, turn virtualization off or measure row heights — say that trade-off.
Status is a prop, not a guess. idle | loading | ready | refreshing | error. Loading with no rows is a skeleton. Refreshing keeps the last rows and sets aria-busy="true". Ready with no rows is emptyState. Error with no rows is errorState. A refresh error with retained rows keeps them and announces the failure separately.
Name the table once: a visible <caption>, or aria-labelledby, or aria-label — not all three. The scroll container may need tabindex="0" if the browser would otherwise skip it. Key rows by getRowId, never by the visible index. If a cell holds focus, keep that row mounted until focus leaves.
Conclusion: How to Design a Virtualized Grid
A data table is a window over an array, not a dump of rows. Sticky header, column config, virtualize by default, and treat sort/selection as state the parent can own.
We’ll have drawn the line interviewers care about: DataTable renders a window, the View Model owns sort, filter, and a Set of ids, and a Data Manager exists only when the API pages. Fixed row height plus a pair of spacers keeps 10,000 rows at ~240 mounted cells. CSS grid, not display: table, is what keeps the sticky header aligned.
Accessibility is the other half of the answer. A real <table> is fine until you virtualize; then you switch to role="grid", set aria-rowcount / aria-rowindex, and move a single focus cell with the arrows. If Tab leaks through 240 checkboxes or the header disappears from the tree because it is sticky, the table is wrong no matter how smooth the scroll is.
