Try first
Frame your answer before reading the reference
Candidate prompt
Design an infinite-scroll list with cursor pagination, request recovery, bounded DOM rendering, stable scroll anchors, and accessible alternatives.
Constraints and what good looks like
Constraints
- Keep client, server, and rendering ownership explicit.
- Cover loading, failure, recovery, and accessible interaction states.
Helpful before you start
- Client-side state management
- Accessible UI fundamentals
Make these three decisions explicit
- State and ownership boundaries
- API and event contracts
- Performance and failure tradeoffs
Infinite Scroll System Design: Requirements and a 60-Second Answer
A strong 60-second answer
Choose the browsing model before the architecture
| Model | Best fit | Main cost | Decision |
|---|---|---|---|
| Infinite scroll | Exploratory feeds where the next item is more important than a precise destination | Weak sense of progress, difficult footer access, and more restoration work | Use for continuous discovery, but keep an explicit fallback control |
| Load More | Discovery where users benefit from a deliberate pause and a stable footer | Adds an action between batches | Often the most accessible default and the fallback for automatic loading |
| Pagination | Search results, audit trails, and collections that need durable page URLs | Interrupts continuous browsing | Prefer when position, sharing, search discovery, and back navigation dominate |
Clarify the contract
- Can items change during the session? Assume yes, so the server supplies deterministic order and an opaque cursor.
- Is the total known or is random access required? Assume an unknown total and forward browsing.
- Are rows fixed height? Assume variable text and media, so measurement and anchor correction are required.
- Should return navigation restore context? Assume yes, by item identity and intra-item offset.
- Must the collection be discoverable without automatic loading? For a stable-ordered catalog, assume ?page=N URLs and visible sequential links; a personalized, changing feed exposes item permalinks instead.
- Render a useful first page quickly and reserve media dimensions to prevent layout shifts.
- Load the next cursor near the viewport without issuing duplicate requests.
- Represent initial loading, incremental loading, empty, partial error, retry, and end states.
- Preserve stable order and remove duplicate IDs across overlapping or repeated responses.
- Restore filters, loaded data, focus, and the reading position after navigation.
- Keep input and scrolling responsive on a representative mid-range device.
- Bound mounted DOM nodes and retained page data for long sessions.
- Support keyboard and screen-reader operation without relying on the sentinel.
- Expose recoverable failures in context instead of replacing successful content.
- Keep important collection content reachable through discoverable URLs and links.
Frontend boundary
Architecture and data flow
The boxes to draw
- The route owns normalized filters, sort order, feed identity, the first page, and the restoration key.
- The controller owns entities, order, cursors, request generations, cancellation, errors, and cache policy.
- The page API owns deterministic ordering and opaque cursor semantics.
- The viewport owns the sentinel, virtual range, loading and retry rows, announcements, and anchor capture.
- The item renderer owns semantic row markup, a stable key, reserved media geometry, and item actions.
- Neither rendering layer mutates server cursors or invents pagination state.
Forward data flow
- Hydrate a useful first pageThe route renders initial items and the next cursor in HTML. The client normalizes them into an ID-keyed entity map plus an ordered ID array, then attaches one observer to the sentinel.
- Convert visibility into intentWhen the sentinel enters a prefetch margin, the viewport emits loadNext. The controller ignores the signal when there is no next cursor, the same cursor is already in flight, the retry delay is active, or the feed generation has changed. IntersectionObserver reports only threshold changes, so an ignored signal never repeats: after each commit and when the retry delay ends, the controller re-checks the last isIntersecting value and loads again if the sentinel is still visible.
- Start an owned requestThe controller captures the current generation and cursor, creates an AbortController, marks that cursor as pending, and calls the page API. Repeated observer callbacks therefore collapse into one request.
- Validate before mergingOn response, the controller first compares the captured generation with the active one. A response for old filters is discarded. Valid items are merged by stable ID, their ordered IDs are appended only once, and nextCursor changes only after the page commits.
- Render and announceThe viewport derives its rendered range from ordered IDs, the measurement cache, scroll position, and overscan. It removes the loading row, announces how many items were added, and leaves focus where the user placed it.
Guard duplicate sentinel triggers
Worked example: filter change during a pending next page
| Event | Store change | Visible UI | Invariant |
|---|---|---|---|
| Sentinel requests c40 | Record one pending cursor under filter generation 7. | Keep the current list and show an inline loading row. | One cursor has at most one admitted request. |
| Filter changes | Abort generation 7, start generation 8, and retain the old view as transitional content. | Move focus to the refreshed list heading only after explicit submission. | Old pages cannot join a new query. |
| Old c40 resolves | Reject it because its generation and cache key are stale. | No duplicate or wrong-filter item appears. | Transport completion is not acceptance. |
| New first page resolves | Normalize IDs, replace query order, and derive a new anchor. | Render the new results and preserve a visible Load More control. | The URL, list, and announced count agree. |
Pagination, state, and data correctness
Cursor pagination is the default for a mutable feed
| Property | Cursor | Offset |
|---|---|---|
| Changing data | Continues after an opaque ordering boundary and better resists insertions ahead of the user | A new item shifts later offsets and can create duplicates or skipped records |
| Random access | Usually sequential unless the server exposes saved boundaries | Simple page-number jumps and shareable offsets |
| Client contract | Treat nextCursor as opaque and commit it only with a successful page | Track page or offset and require a stable sort with a tie-breaker |
| Best fit | Unknown, mutable feeds and timelines | Mostly stable catalogs, admin tables, and bounded search results |
State worth naming in the interview
- Feed identity: feedKey, normalizedFilters, sort, and generation.
- Content: entitiesById, orderedIds, and loadedPages, with each ID appearing once in order.
- Pagination: committed nextCursor and hasMore.
- Request: status, requestedCursor, requestId, and AbortController.
- Failures: separate initialError, incrementalError, and failedCursor.
- Restoration: anchorItemId, anchorOffsetPx, focusedItemId, and savedRange.
- Windowing: measuredHeights keyed by ID, estimatedHeight, visibleRange, and overscan.
- Every async result carries one immutable generation.
Stable ordering and ID deduplication
- Capture request identityBefore fetching, capture generation, requestedCursor, and a unique requestId. Mark that cursor in flight without changing the committed nextCursor.
- Reject obsolete workAfter resolution, compare the captured generation and requestId with current state. If filters changed, the request was replaced, or cancellation won the race, ignore the response even when the network could not be aborted.
- Merge by stable IDFor each item, update entitiesById. Append its ID to orderedIds only when that ID has not appeared. Preserve the server page order rather than sorting again using client clocks.
- Commit the page atomicallyStore page membership, clear the matching error, and update nextCursor or hasMore in the same transition. If the server returns the same cursor again, stop and report a contract error instead of looping.
- Preserve retry semanticsOn failure, remove the in-flight marker but retain failedCursor and the committed nextCursor. Retry asks for exactly that cursor, so a transient error cannot skip a page.
Reject stale responses by generation
type FeedItemId = string;
type FeedPage = {
requestedCursor?: string;
itemIds: readonly FeedItemId[];
nextCursor?: string;
orderingVersion?: string;
};
type FeedRequestState = {
requestId: string;
generation: number;
requestedCursor?: string;
controller: AbortController;
};
type FeedState<T extends { id: FeedItemId }> = {
queryKey: string;
filters: Readonly<Record<string, string | readonly string[]>>;
sort: string;
generation: number;
entitiesById: Readonly<Record<FeedItemId, T>>;
orderedIds: readonly FeedItemId[];
pages: readonly FeedPage[];
nextCursor?: string;
hasMore: boolean;
activeRequest?: FeedRequestState;
failedCursor?: string;
anchor?: { itemId: FeedItemId; offsetPx: number };
};Cursor pages, query state, and viewport invariants
| Record | Key fields | Owner |
|---|---|---|
| PageRecord | queryKey, ids, nextCursor, admittedCursors | Server-page cache |
| EntityMap | id to validated item | Normalized cache |
| ListViewState | anchorId, offset, visibleRange | Route session |
| RequestState | generation, cursor, AbortController | Controller runtime |
Interface contracts for components and pagination
Page API contract
- Use an explicit limit and normalized filter object so cache keys are deterministic.
- Pass AbortSignal through every transport and transformation layer that can stop work.
- On Retry, send the committed cursor again instead of deriving a later cursor.
- Every item has a stable ID, and continuation uses deterministic ordering.
- nextCursor commits with its items and may be absent on the final page.
- A repeated cursor becomes a contract error instead of an automatic loop.
Component contract
- Render semantic containers, one sentinel, loading, inline Retry, and end states.
- Expose aria-busy and concise announcements from controller state.
- Capture anchor and focus identity before navigation.
- Render one semantic item without loading pages.
- Reserve media dimensions and report geometry changes.
- Use stable item ID for rendering and measurement, never array index.
Lifecycle and failure semantics
- InitializeNormalize initialPage under feedKey and render it, or issue one initial request.
- Request moreObserver visibility and Load More invoke the same guarded loadNext command.
- Cancel or replaceUnmount or a new feedKey aborts work; generation checks reject late completion.
- RecoverPrior rows remain interactive, and Retry repeats failedCursor.
- FinishNo nextCursor disables loading and emits the end event once per generation.
Observer configuration
UI-facing contract
- Observe intentIntersectionObserver is a prefetch hint; the visible Load More button invokes the same admission path.
- Admit onceReject repeat requests for a cursor already pending or committed.
- Merge safelyValidate the generation, normalize entities, append unseen IDs, and advance only after a successful page.
- Restore contextAfter navigation or variable-height measurement, mount the anchor and restore its intra-item offset.
type PageRequest = {
queryKey: string;
filters: Readonly<Record<string, string | readonly string[]>>;
sort: string;
limit: number;
cursor?: string;
signal: AbortSignal;
};
type PageResult<T> = {
items: readonly T[];
nextCursor?: string;
orderingVersion?: string;
};
interface PageLoader<T> {
load(input: PageRequest): Promise<PageResult<T>>;
}Optimizations for virtualization, accessibility, recovery, and verification
Choose whether to virtualize
| Approach | Use when | Benefits | Costs |
|---|---|---|---|
| Simple list | The loaded collection remains moderate and rows are inexpensive | Native document flow, straightforward focus and find-in-page, simple restoration | DOM and memory grow with every retained page |
| Virtualized list | Measured DOM, layout, paint, or row memory exceeds the performance budget | Mounted nodes remain near the viewport, so mounted DOM stays bounded | Requires height estimation, measurement, overscan, focus policy, and stronger restoration tests |
| Row geometry | Range calculation | Correction strategy | Risk |
|---|---|---|---|
| Fixed height | Calculate start and end indexes from scroll offset and one known row size | Usually no runtime measurement; reserve media to preserve the contract | Unexpected wrapping or user font settings can invalidate the assumption |
| Variable height | Estimate unseen rows and use measured cumulative heights for visible rows | Cache height by item ID, observe changes, and adjust relative to a stable anchor | Late media, expansion, or font changes can move content unless correction is anchored |
Bound rendering and retained data
Restore by identity, then correct geometry
- Capture a stable anchorRecord the first visible item ID, its offset within the viewport, focused item ID, feedKey, filters, and cached range.
- Reconstruct enough dataRestore the matching feed and pages; reload an evicted anchor from a durable boundary.
- Place the anchorReveal and measure the anchor, then correct to its saved intra-item offset. Use scrollY only for unchanged layouts.
- Stabilize and restore focusReserve image dimensions and restore focus only when its prior target still exists.
Accessibility is part of the loading model
- Prefer native list semantics; use ARIA feed only when its article navigation fits.
- Keep focused content mounted or move focus before recycling it.
- Provide visible Load More using the same guarded command as the sentinel.
- Keep the footer reachable without racing automatic loads.
- Set aria-busy while appending without disabling loaded items.
- Politely announce a concise result such as “20 more items loaded.”
- Do not announce observer events, skeletons, or measurement corrections.
- Keep inline Retry where loading stopped and distinguish empty, end, offline, and permission states.
Recovery and search discovery
Verification plan
- Repeat sentinel events and assert one request and commit per cursor.
- Return overlapping pages and assert stable order without duplicate IDs or gaps.
- Resolve an old-filter response last and assert it cannot write.
- Fail and retry a page without advancing its cursor.
- Change row heights and verify anchor plus intra-item offset restoration.
- Return a short first page that leaves the sentinel visible; assert the next page loads without scrolling.
- Keep DOM node count within the window budget during a long session.
- Profile long tasks, interaction latency, layout shifts, and scrolling on a mid-range device.
- Test changing row heights on slow, offline, and flaky networks.
- Load more with keyboard and screen reader.
- Find the first page and sequential links in raw HTML.
Pagination failure and viewport recovery
| Failure | Response | Invariant |
|---|---|---|
| Observer fires repeatedly | Coalesce by cursor and query generation. | No duplicate network or commit work. |
| Page fails | Keep committed items and render retry in list order. | Retry reuses the failed cursor. |
| Row height changes | Recompute from anchor identity and measured offset. | Reading position stays stable. |
| Windowing breaks focus | Mount the target before moving focus and retain a Load More path. | Keyboard navigation remains predictable. |
Accessibility behavior
Rollout and measurement
Public interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- Taro: Datadog senior frontend developer interview, Valbonne, October 2024
One senior account lists a design prompt for the frontend architecture to filter and display real-time logs (a Live Tail view). Bounded rendering of a growing list is the part of that prompt this case practises; it is not the reported wording.
- interview.tw: Binance frontend engineer interview, Taiwan, 2022
The fourth round of a 2022 Binance frontend loop asked how you would implement list recycling yourself, after a list component that calls an API. Recycling rows in a long list is the part this case practises; it is not the reported wording.
Reported in a public Datadog interview account. Datadog frontend interview questions
Reported in a public Binance interview account. Binance frontend interview questions
Use the Question Library for baseline coverage, then move into a Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.