Suppose you are designing a product catalog where users browse products, apply filters, and move through search results using a Next button. The database contains millions of products, and the application initially uses offset pagination to retrieve them.
As users move to later pages, queries become increasingly expensive because the database must locate and skip records before returning the requested results. The problem becomes more noticeable when users browse through hundreds or thousands of pages.
The challenge is to replace offset pagination with cursor pagination, allowing the application to retrieve the next set of products efficiently while preserving a consistent ordering.
Identify the limitations of offset pagination
Avoid making the database repeatedly skip records as the user moves through the results.
Suppose a user requests the first 20 products:
The next request retrieves the following 20 products:
This works for small result sets. However, when the user reaches page 10,000, the database may need to locate and skip 199,980 records before returning the next 20.
The problem is that the amount of work grows with the offset. Even though the application only needs 20 products, the database may have to process a much larger portion of the ordered result set.
Cursor pagination approaches this differently. Instead of telling the database how many records to skip, the application tells it where the previous page ended.