Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 55

Pagination Strategies: UX & System Trade-offs

Recommended resources

Welcome back. In our previous lesson, we mastered list virtualization, a crucial technique for efficiently rendering massive datasets without overwhelming the DOM. You now know how to build UIs that remain performant even with tens of thousands of items. But how do we get that data to the client in the first place?

This lesson addresses that exact question. We will dissect the strategies for fetching large datasets in manageable chunks, a process broadly known as pagination. You will learn to compare and contrast the primary approachesβ€”traditional page numbers, infinite scroll, and the underlying data-fetching mechanisms that power them. Crucially, we will analyze the trade-offs at both the user experience (UX) and system levels, preparing you to make and defend architectural decisions on this topic in a senior-level interview.

1. The Two Sides of Pagination: Presentation vs. Data Fetching

A common mistake in system design interviews is to conflate how pagination looks with how it works. A senior engineer must clearly distinguish between the frontend presentation pattern and the backend data-fetching strategy.

  • Presentation Patterns (The "What"): This is what the user interacts with. The main patterns are:

    • Page Numbers: Classic numbered links ([1], [2], [3], ...), like on Google search results or an e-commerce catalog.
    • "Load More" Button: A button the user clicks to append the next set of results. Common in comment threads or product lists.
    • Infinite Scroll: New content loads automatically as the user scrolls near the bottom of the visible items. This is the signature pattern of social media feeds like Instagram and X (formerly Twitter).
  • Data Fetching Strategies (The "How"): This is how the frontend API asks the backend for a specific chunk of data. The two dominant strategies are:

    • Offset-based Pagination: The client tells the server how many items to skip (the offset) and how many to take (the limit). It's like saying, "Give me 20 items, starting from item #40."
    • Cursor-based Pagination: The client provides a "cursor"β€”an opaque identifier representing the last item it sawβ€”and asks for the next set of items after that one. It's like saying, "Give me the 20 items that come after item XYZ."

Let's begin with a concise overview of these concepts.

API Pagination: Making Billions of Products Scrolling Possible

This short video from ByteByteGo provides a clear, animated explanation of why pagination is necessary and introduces the core differences between offset-based and cursor-based approaches.

Watch the entire video from start to finish. Pay close attention to the visual explanations of the performance degradation in offset pagination and how cursor-based pagination resolves the data consistency problem.


2. Offset-Based Pagination: Simple, Familiar, but Deceptively Flawed

Offset-based pagination is the most intuitive approach. The API typically exposes page and per_page parameters, which the backend translates into a SQL query with LIMIT and OFFSET.

Its primary advantage is enabling the page number presentation pattern. Because you can calculate the offset for any page (offset = (page - 1) * limit), you can allow users to jump directly to any page, like page 15 of a product search result.

However, this simplicity hides two severe scalability problems.

The Performance Trap: O(offset) Degradation

The database cannot just jump to the offset. It must first retrieve all the rows up to the offset and then discard them. This means fetching page 2 is fast, but fetching page 50,000 is disastrously slow, as the database has to scan and discard potentially millions of rows.

This visual starkly contrasts the two approaches. Limit-offset pagination leads to "slow queries" and "data overload" as the page number increases because the database must scan an increasing number of rows. Cursor-based pagination, using an index, maintains fast, constant-time performance, making it suitable for infinite scrolling on large datasets.

The Consistency Trap: Page Drift

In a system with frequent writes (e.g., a social feed where new posts are added), the dataset can change between two requests.

  • If an item is deleted from a previous page, an item at the start of the next page will "shift" back and be skipped entirely.
  • If a new item is inserted at the top of the list, an item at the end of the current page will be pushed to the next page and appear as a duplicate.

This makes offset-based pagination unsuitable for real-time, dynamic datasets.

The following reading provides a detailed look at the implementation and the problems.

Frontend System Design: Pagination Patterns β€” Guide - DEV Community

This article from DEV Community offers a fantastic breakdown of offset-based pagination, including code examples and clear illustrations of its flaws.

Please read the section "Offset Based Pagination". Focus on the subsections "The Offset Problem β€” Skipping & Duplication" and "Performance Problem" to solidify your understanding of why this method fails at scale.


3. Cursor-Based Pagination: The Scalable Standard

Cursor-based (or keyset) pagination solves the problems of offset by changing the question. Instead of asking "what's on page 5?", it asks "what comes after item X?". The "cursor" is a stable pointer to a specific item in the sorted set. It's typically a Base64-encoded value of the sort key(s), like {"created_at": "2023-10-27T10:00:00Z", "id": 12345}.

How It Works

  1. The client makes an initial request without a cursor to get the first page.
  2. The API response includes the list of items and a nextCursor token, which points to the last item in the list.
  3. For the next page, the client sends this nextCursor back to the API.
  4. The backend decodes the cursor and constructs a query like WHERE (created_at, id) < ('2023-10-27T10:00:00Z', 12345) ORDER BY created_at DESC, id DESC LIMIT 20.

This approach leverages a database index to seek directly to the starting point, resulting in constant-time (O(1) or O(limit)) performance, no matter how deep the user scrolls. Because it's anchored to a specific item's values, it is immune to the page drift problem.

The natural UX patterns for cursor-based pagination are infinite scroll and "load more" buttons, as they follow a sequential-access model.

Keyset Cursors for Postgres Pagination: Fast, Accurate, Scalable

This article from Stacksync provides the crucial backend perspective, explaining why keyset/cursor pagination is so much more performant from a database point of view.

Read the introduction and the first two main sections, ending just before "Keyset Pagination: The Technical Solution". Pay close attention to the comparison table and the section on performance and consistency problems. This gives you the system-level ammunition for your interview answer.


4. Trade-Off Analysis: Choosing the Right Strategy

As a senior engineer, your job is to choose the right tool for the job. The choice between pagination strategies is a classic trade-off between functionality, performance, and complexity.

This table summarizes the core trade-offs. Limit-offset is simple and allows random page access, making it suitable for small or static datasets. Cursor-based pagination is efficient and consistent for large, dynamic datasets like those used in infinite scrolling, but it only supports sequential access.

Here is a more detailed breakdown for your interview toolkit:

Feature Offset-Based Pagination Cursor-Based Pagination
Primary Use Case Datasets where users need to jump to specific pages (e.g., e-commerce search, admin tables). Exploratory, chronological feeds where sequential browsing is natural (e.g., social media, news feeds, activity logs).
Performance Poor (O(offset)). Degrades linearly as the page number increases. Unusable for deep pagination. Excellent (O(1)). Performance is constant regardless of how deep the user scrolls.
Data Consistency Poor. Prone to skipping or duplicating items in datasets with frequent writes. Excellent. Provides a stable, consistent view of the data, even as items are added or removed.
UX Pattern Enables page number navigation ([1], [2], ... [50]). Enables infinite scroll and "load more" buttons.
Implementation Simpler. The logic is straightforward on both client and server. More complex. Requires encoding/decoding cursors and careful backend query construction.
Key Limitation Fails at scale due to performance and consistency issues. Cannot jump to an arbitrary page (e.g., "go to page 17"). Access is strictly sequential.

This decision is frequently a topic in system design interviews. The key is to first clarify the product requirements. If the interviewer says, "Design the Amazon search results page," you should immediately recognize the need for random page access, leading you to offset-based pagination while also mentioning its limitations and potential mitigation strategies (e.g., capping the maximum page depth). If the prompt is "Design the Instagram feed," you should immediately pivot to cursor-based pagination to ensure performance and consistency.

Frontend System Design: Pagination Patterns β€” Guide - DEV Community

Let's round out our understanding by reviewing the frontend implementation patterns and some common interview questions.

First, read the section on "Cursor Based Pagination" to see how it's implemented with useInfiniteQuery. Next, review the section on "Frontend Patterns", which discusses infinite scroll and "load more" buttons. Finally, read through the "Interview Questions and Answers" section. This provides canned but accurate answers to the most common questions on this topic, which is excellent preparation.


Conclusion

You've now dissected one of the most fundamental scalability patterns in frontend systems. You can confidently articulate the difference between presentation patterns (page numbers, infinite scroll) and data-fetching strategies (offset, cursor), and you understand the deep system-level trade-offs that inform which to use.

Key Takeaways:

  • Separate the UX from the System: Pagination involves a frontend UX pattern and a backend data-fetching strategy; they are not the same but are deeply linked.
  • Offset-based is for Random Access: Its only major advantage is allowing users to jump to any page. This comes at a steep cost of poor performance and data inconsistency at scale. Use it for small datasets or when random access is a non-negotiable product requirement.
  • Cursor-based is for Scale: It provides fast, consistent, and stable pagination, making it the default choice for infinite scrolling feeds and any large, dynamic dataset. Its main limitation is that it only supports sequential access.
  • The Gold Standard: For the most demanding applications, the winning combination is Infinite Scroll (UX) + Cursor-based Pagination (Data Fetching) + List Virtualization (Rendering). This ensures data is fetched efficiently, consistently, and rendered without overwhelming the browser.

In our next lesson, we will tackle another common performance bottleneck: CPU-intensive tasks on the main thread. We will evaluate when to offload work to a Web Worker and explore the architectural patterns for communicating between the main thread and background threads.