Skip to content

    Frontend System Design

    Pagination: Offset, Cursor and Infinite Scroll

    Learn how offset and cursor pagination behave when a list changes, how to build infinite scroll with an IntersectionObserver, and how to guard against races.

    By Published 12 min read

    • frontend-system-design
    • pagination
    • infinite-scroll
    • intersectionobserver
    • cursor
    Share

    Standard lessonintermediateReact labFrontend System Design

    Before this: API Integration Basics: Fetching, Headers and Failure

    What you'll learn: By the end of this lesson you will be able to choose between numbered pages, a "Load more" button and infinite scroll, explain why offset pagination repeats or skips items when a list changes and cursor pagination does not, build an infinite list with an IntersectionObserver sentinel, make it safe against double requests and stale responses, and test it in jsdom with a fake observer.

    Think of reading a stack of newspapers from the top. If your bookmark says "I have read ten papers", a new paper dropped on top makes your next ten start with one you already read. If it says "I stopped after the paper dated the 14th", it stays right however many papers arrive. The first bookmark is an offset, the second a cursor.

    The running example is the new arrivals feed of a grocery catalogue (the front end of the ShopStream marketplace used in this course): newest products first, loaded a page at a time, with a search box on top. Items can be added or removed while a shopper reads, which is when the two bookmarks differ.

    The core idea

    1. Paging is two decisions, not one. The API decides how to ask for "the next part" (offset or cursor). The interface decides when to ask (numbered pages, a button, or scrolling). They are independent: infinite scroll can sit on either kind of API.
    2. A list that changes under the reader needs a stable bookmark. Position numbers shift when items are added or removed; an item's own identity does not.
    3. Every extra request is a race. Scrolling produces repeated triggers, queries change mid-flight and responses arrive in any order. The list needs rules for what a response is allowed to change.

    Numbered pages, a button, or scrolling

    Interface Strengths Costs
    Numbered pages Explicit position; the page can live in the URL; small DOM A click per page; needs a count or a next-page flag
    "Load more" button Works with keyboard and touch; no observer needed One click each time; the list still grows
    Infinite scroll Fluid for browsing and feeds No position to share; the list and DOM only grow

    Figure 1. Choosing an interface and an API

    flowchart TD accTitle: Choosing a pagination interface and API accDescr: A decision tree. If users need to jump to a page or share a position, use numbered pages. If the data is a browse-forever feed, use infinite scroll with a Load more fallback. Then choose a cursor API if the list changes while being read, and offset only if it is stable and random access is needed. A{"Do users jump to a page,
    or share a position?"} A -->|"yes"| N["Numbered pages
    (page number in the URL)"] A -->|"no, they browse"| F["Infinite scroll
    plus a Load more button"] N --> B{"Does the list change
    while it is read?"} F --> C["Cursor API:
    ask for items after this one"] B -->|"yes"| C B -->|"no, stable list"| O["Offset API:
    skip N, take M"]

    How to read this: the interface choice comes first because it depends on what the user is doing. The API choice follows from whether the data moves. Browse-style feeds almost always change, so they land on a cursor.

    Offset against cursor

    An offset request says "skip the first N, give me M". It is simple, supports jumping to any page, and a database can implement it directly. A cursor request says "give me M items after this one". The cursor is an opaque token from the server, the client sends it back unchanged, and a null next cursor means the end. The client never builds or inspects it.

    Illustration 1: the minimal example

    Five ids, newest first. The reader loads two, then one new item arrives at the top, then the reader loads the next two. Run in Node:

    const ids = [5, 4, 3, 2, 1];
    const page = (list, offset, limit) => list.slice(offset, offset + limit);
    const afterId = (list, id, limit) => list.filter((x) => x < id).slice(0, limit);
    
    const first = page(ids, 0, 2);
    ids.unshift(6);
    console.log("offset page 1:", first);
    console.log("offset page 2:", page(ids, 2, 2));
    
    const ids2 = [5, 4, 3, 2, 1];
    const c1 = ids2.slice(0, 2);
    ids2.unshift(6);
    console.log("cursor page 1:", c1);
    console.log("cursor page 2:", afterId(ids2, c1[c1.length - 1], 2));

    Output, from running it in Node 26.13.1:

    offset page 1: [ 5, 4 ]
    offset page 2: [ 4, 3 ]
    cursor page 1: [ 5, 4 ]
    cursor page 2: [ 3, 2 ]

    Offset page 2 starts with 4, which page 1 already showed: everything shifted down when 6 arrived. The cursor version asked for "after 4" and got 3, 2. Removing an item above the reader would make offset skip one instead.

    Figure 2. Offset drift when an item arrives

    sequenceDiagram accTitle: Offset pagination repeating an item accDescr: The client loads page one with offset zero and receives items 5 and 4. The server then adds item 6 at the top. The client asks for offset two and receives items 4 and 3, so item 4 appears twice. With a cursor after item 4 the server returns items 3 and 2. participant C as Client participant S as Server C->>S: offset 0, limit 2 S-->>C: 5, 4 Note over S: item 6 is added at the top C->>S: offset 2, limit 2 S-->>C: 4, 3 Note over C: 4 is shown twice C->>S: (cursor version) after 4, limit 2 S-->>C: 3, 2

    How to read this: the client did nothing wrong. Between the two requests the server's list changed, so the same number named a different place.

    A cursor has costs: you cannot jump to "page 40", and a total count is a separate question. The back-end side (keyset queries, ordering ties) is the paired back-end lesson; this one stays on the client.

    Infinite scroll: asking when the end comes into view

    Infinite scroll needs to know when the reader is near the end of the list. The old way is a scroll listener that measures positions. MDN notes that scroll events can fire at a high rate (its example comments on throttling the handler), and its Intersection Observer page says measuring visibility this way was unreliable and could make pages sluggish.

    The IntersectionObserver API asks the browser instead. MDN lists infinite scrolling among its use cases. The pattern is a sentinel: an empty element after the last item. Watch it, and when it intersects the viewport, request the next page.

    Facts from MDN worth keeping straight:

    • rootMargin grows the box that counts as visible, for example to start loading before something comes into view. The default is "0px 0px 0px 0px"; the lab uses 200px.
    • The callback fires once after observe(), even if the target is not visible, and its entry says whether the target is intersecting right then. A sentinel still on screen after a short page does not "re-enter", so nothing reports it again unless you start watching afresh.
    • Observing an already observed target does nothing, and the callback runs on the main thread, so it should only decide and start the request.

    Figure 3. The sentinel loop

    Infinite scroll: sentinel, observer, controller, serverReader to Sentinel (scrolls to); Sentinel to Controller (intersects); Controller to Feed API (cursor); Feed API to List state (page); List state to Feed (render)Reader: scrollsReaderscrollsSentinel: after the listSentinelafter the listController: one at a timeControllerone at a timeFeed API: cursor in, page outFeed APIcursor in, pageoutList state: merge by idList statemerge by idFeed: articles + statusFeedarticles + statusscrolls tointersectscursorpagerender

    How to read this: the accent boxes are the code you write. The browser tells the sentinel's observer about visibility; the controller turns that into at most one request; the response goes through the list state, which decides what it may change, and the view renders the result.

    What the list state must guarantee

    The observer is the easy part. The rules that matter are about responses.

    • One request at a time. A callback can fire twice, and a button can be double-clicked. While a request is in flight (or after the end) a second loadMore() does nothing.
    • A response belongs to a generation. A new query starts a new list. Each reset bumps a generation number, and a response from an older generation is ignored, even when the fetch layer never honoured the abort. This is the race react.dev describes: a slow response for an earlier query can arrive after the newer one and overwrite it.
    • Merge by id. Appending a page drops any item whose id is already in the list, and counts the drops, so a duplicate never reaches a key prop.
    • Errors keep what is shown. A failed page leaves the earlier items on screen and shows a retry; nothing retries by itself, because an observer retrying on every callback is a request storm.

    Figure 4. The states of a feed

    stateDiagram-v2 accTitle: States of an infinite feed accDescr: The feed starts idle. A request moves it to loading. A successful page returns it to idle, or to done when the next cursor is null. A failure moves it to error, and Try again moves it back to loading. A query change resets to idle and discards any in-flight response. [*] --> idle idle --> loading: loadMore loading --> idle: page, more to come loading --> done: page, cursor is null loading --> error: request failed error --> loading: Try again idle --> idle: query changed (reset) loading --> idle: query changed (reset)

    How to read this: loadMore is only accepted from idle or error, which is how "one request at a time" is enforced. A reset from any state bumps the generation so late answers have nowhere to land.

    Accessibility of a feed

    The WAI-ARIA Authoring Practices describe a feed pattern for this: a role="feed" container, each unit an article with aria-posinset, and aria-setsize of -1 when the total is unknown. The feed carries aria-busy="true" while articles are added, and the guidance stresses setting it back to false afterwards. A role="status" line such as "Loading more products" is announced politely, without taking focus. A "Load more" button gives keyboard and touch users a way forward that does not depend on scrolling; the lab keeps one.

    Illustration 2: the realistic example, from the lab

    The lab's FeedController and InfiniteFeed implement the rules above; a FakeServer holds a newest-first list and delivers each response only when the demo or test releases it, so the order of responses is chosen.

    Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/pagination-infinite-scroll, copied from examples/frontend/golden/pagination-infinite-scroll.txt), in full:

    
    === offset paging, an item is added at the top
    page 1 loaded       : 25 24 23 22 21 20 19 18 17 16
    server change       : added #26
    page 2 loaded       : 15 14 13 12 11 10 9 8 7
    repeats dropped     : 1
      request: offset 0 q="" -> #25..#16 (10 items)
      request: offset 10 q="" -> #16..#7 (10 items)
    
    === cursor paging, an item is added at the top
    page 1 loaded       : 25 24 23 22 21 20 19 18 17 16
    server change       : added #26
    page 2 loaded       : 15 14 13 12 11 10 9 8 7 6
    repeats dropped     : 0
      request: cursor (first) q="" -> #25..#16 (10 items)
      request: cursor after:16 q="" -> #15..#6 (10 items)
    
    === offset paging, an item is removed from the top
    page 1 loaded       : 25 24 23 22 21 20 19 18 17 16
    server change       : removed #24
    page 2 loaded       : 14 13 12 11 10 9 8 7 6 5
    repeats dropped     : 0
      request: offset 0 q="" -> #25..#16 (10 items)
      request: offset 10 q="" -> #14..#5 (10 items)
    
    === cursor paging, an item is removed from the top
    page 1 loaded       : 25 24 23 22 21 20 19 18 17 16
    server change       : removed #24
    page 2 loaded       : 15 14 13 12 11 10 9 8 7 6
    repeats dropped     : 0
      request: cursor (first) q="" -> #25..#16 (10 items)
      request: cursor after:16 q="" -> #15..#6 (10 items)
    
    === a query changes while a response is in flight, and the old response arrives last
    asked for "apples"   : status loading, generation 0
    query is now "cheese": status idle, generation 1
    newer response in    : 29 26 23 20 17
    older response in    : 29 26 23 20 17  (unchanged: it belonged to generation 0)
      request: cursor (first) q="apples" -> #30..#18 (5 items)
      request: cursor (first) q="cheese" -> #29..#17 (5 items)

    Blocks 1 and 2: with offset paging an item added at the top makes page 2 repeat #16, which the client drops by id (so the page adds 9 items, not 10); with a cursor page 2 is #15 to #6. Blocks 3 and 4: with offset paging an item removed from the top makes page 2 start at #14, so #15 is never shown, and no dedupe can recover an item that was never delivered; the cursor is unaffected. Block 5: the "apples" request was still in flight when the query changed to "cheese"; its answer arrives last and changes nothing (unchanged: it belonged to generation 0).

    Illustration 3: a failure, from the lab

    The failure cases are the removal and stale-response blocks above, plus a feed that observes its sentinel only once: a sentinel still on screen after the first page never "enters" again, so the list stops on a tall screen. The lab rebuilds the observer after every page and reset, and a test asserts the next page loads. Dedupe is a safety net: it hides a repeat, never a skip.

    The cost that never goes away

    An infinite list only grows. web.dev notes that a larger DOM makes initial render more expensive and that updates which insert or change elements can cause costly layout, style and paint work. Cursor paging fixes correctness, not size; the next lesson in this module, List Virtualization, covers rendering only the rows near the viewport.

    The other side of this topic

    On the back end the decision is made from the data's side: a stable sort key, a cursor that encodes a position, and a page size the server caps (the lab's server caps it at 100).

    Trade-offs

    Choice Gain Cost
    Offset paging Simple; random access Repeats or skips items when the list changes
    Cursor paging Stable while the list changes No jump to page N; opaque token
    Numbered pages Shareable position, small DOM A click per page
    Infinite scroll Fluid browsing Unbounded DOM, no shareable position
    Dedupe by id on the client Safe key props Hides repeats but cannot restore skipped items

    Build it

    The lab examples/frontend/labs/pagination-infinite-scroll has src/fakeApi.ts (the fake server, cursor and offset behind one FeedApi shape), src/pagination.ts (the reducer and controller), src/components.tsx (the feed) and a test double for IntersectionObserver in test/fakeIntersectionObserver.ts. jsdom has no IntersectionObserver of its own, so the fake decides whether the sentinel is on screen when the test says so. Nothing here measures scrolling, layout or speed.

    cd examples/frontend/labs/pagination-infinite-scroll
    ../../node_modules/.bin/vitest run
    ../../node_modules/.bin/tsc -p tsconfig.json
    node src/demo.ts

    Verified. The 33 tests in two files passed with Node 26.13.1 and Vitest 5.1.0, and the type check passed. They cover: walking the whole list once with a cursor, offset repeating and skipping, cursor neither, one request per tick, a stale response arriving last or after an ignored abort, the retry after an error, the empty result, the observer rebuilt after each page, and cleanup on unmount. The captured demo output above is identical to the golden file.

    Break it. In src/pagination.ts, in the "success" case of feedReducer, temporarily delete the generation check (action.generation !== state.generation). Tests that deliver an old response after a query change now fail, because the old items leak into the new list. Restore the line and re-run the tests.

    In practice: a new arrivals feed

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A grocery marketplace shows a "New arrivals" feed, newest first, loaded as the shopper scrolls. Merchants publish all day, and an evening promotion raises that rate. Support reports products shown twice, and merchants say some new products are never seen.

    Starting architecture

    Figure 5. Offset paging behind a scrolling list

    Starting architecture: offset paging on a moving listFeed to GET /new?offset= (offset); GET /new?offset= to Product list (slice); Feed to React keys (render)Feed: page = items.length / 20Feedpage =items.length / 20GET /new?offset=: skip N, take 20GET/new?offset=skip N, take 20Product list: gains items at the topProduct listgains items atthe topReact keys: id; duplicates warnReact keysid; duplicateswarnoffsetslicerender

    How to read this: the warning boxes are where position numbers stop meaning anything, because the list at the right changes between the shopper's requests.

    Options considered

    Option What it fixes What it costs Risk
    Dedupe by id on the client Duplicate keys Nothing on the server Skipped items stay invisible
    Cursor API (after the last id) Repeats and skips A server change; no jump to page N Old clients still call the offset endpoint

    The decision

    Field Decision record
    Context A feed that changes while it is read shows repeats and skips with offset paging.
    Decision Move the feed to cursor paging. The client treats the cursor as opaque, merges by id, allows one request at a time and ignores responses from an older generation. Keep dedupe as a safety net.
    Consequences, good No repeats or skips from list changes; the reducer is a pure function and easy to test.
    Consequences, bad No "jump to page"; the cursor format is now a contract between client and server.
    Revisit when A feature needs random access (a numbered pager) or the list becomes long enough to need virtualization.

    Rollout and verification

    1. Put both shapes behind one client interface (FeedApi), as the lab does.
    2. Test the change cases: an item added or removed at the top, and a query change with the old response arriving last.
    3. Check the end: a null cursor shows an end message and sends no further request.
    4. Keep the "Load more" button.

    The 2 a.m. failure

    During the promotion some shoppers see the loading line forever. A request failed with an error the code did not expect, and the status was left at loading, so no further request is ever accepted.

    First three checks: (1) log the status transitions for one session and look for loading with no response; (2) check that every code path ends in idle, done or error, including an error that is not an abort; (3) confirm the retry is a button, not the observer. Mitigation: make failure a reducer action that always leaves loading. Follow-up: a test that fails a request and then retries it.

    Architect's notes

    • Paging is a contract. Write down whether the cursor is opaque, how long it stays valid and what the end looks like.
    • Keep the rules in a pure reducer, testable without a DOM; the component only wires an observer to it.
    • Pair infinite scroll with a way out: a Load more button, an end message and a retry.

    Common mistakes

    • Using offset on a list that changes, then deduping and calling it fixed.
    • Observing the sentinel once, so a short page on a tall screen stops the list.
    • No in-flight guard, so two callbacks send two requests for the same page.
    • Retrying automatically on error.
    • No end state, so the sentinel keeps asking.

    Key takeaways

    • Interface (pages, button, scroll) and API (offset, cursor) are separate choices.
    • Offset names a position, which moves when the list changes; a cursor names an item, which does not.
    • A sentinel and an IntersectionObserver ask the browser when the end is near; rootMargin starts the load early.
    • Enforce one request at a time, a generation check and a merge by id in the state, not the component.
    • A failed page keeps the items and offers a retry.
    • The list only grows, so plan for rendering cost.

    Practice exercises

    Exercise 1: Starter (30 min). Predict, then check in Node, what page 2 is if two items arrive at the top between the two offset requests in Illustration 1.

    Exercise 2: Intermediate (2 hours). Add a "N new items" banner: poll the first page and show how many items are newer than the first one in the list, without inserting them.

    Exercise 3: Advanced (half day). Add a maxItems cap that drops items from the top, keep aria-posinset correct, and list what breaks for the user.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments