Skip to main content

The Day Offset Pagination Broke My App (And How Cursor Pagination Saved It)

Updated 6 min readMarkdown

Today, I was working on a new feature and asked an AI assistant to generate some pagination code for my Node.js backend. It gave me the classic OFFSET and LIMIT approach.

In development, with just 100 rows in my database, it worked flawlessly. But when I pushed it to production with over a million rows? The API started crawling. Queries that took milliseconds were suddenly taking seconds.

After some research, I realized the villain: Offset Pagination. I quickly refactored my code to use Cursor Pagination, and the performance improvement was mind-blowing.

If you are building an app with a lot of data (like an infinite scroll feed), here is why you need to ditch OFFSET and switch to CURSOR pagination, along with the exact Node.js code to do it.


The Problem: Why is Offset Pagination Slow?

Offset pagination is what we all learn first. It looks like this in SQL:

-- Get Page 1
SELECT * FROM posts ORDER BY id ASC LIMIT 10 OFFSET 0;

-- Get Page 5
SELECT * FROM posts ORDER BY id ASC LIMIT 10 OFFSET 40;

What’s wrong with this? Imagine you are reading a book, and you want to read page 50. With offset pagination, you have to start from page 1, read pages 1 to 49, throw them away, and then read page 50.

In database terms: To get the 5th page (offset 40), the database has to fetch 50 rows, discard the first 40, and return the last 10. As the user goes deeper into the pages (e.g., Page 100), the database has to scan and discard hundreds of rows just to give you 10. This makes the query time grow linearly with the page number.


The Solution: Enter Cursor Pagination

Cursor pagination (also known as keyset pagination) changes the approach. Instead of saying "skip 40 rows", we say "give me 10 rows that come after this specific ID".

-- First Page
SELECT * FROM posts ORDER BY id ASC LIMIT 10;

-- Next Page (assuming the last ID we saw was 105)
SELECT * FROM posts WHERE id > 105 ORDER BY id ASC LIMIT 10;

Why is this lightning fast? Because id is indexed! The database doesn't scan or discard anything. It uses the B-Tree index to jump directly to id = 105 and fetches the next 10 rows. Whether you are on page 2 or page 2,000, the query takes the exact same amount of time.


The Node.js Implementation

Let’s write the actual Node.js (Express) code for this. We will use a simple SQL database (this logic works for MySQL, PostgreSQL, etc.).

The "Limit + 1" Trick

Before we write the code, there is a pro-trick you need to know: How do we know if there is a "Next Page"? Instead of running a separate COUNT() query (which is slow), we just fetch limit + 1 rows. If we get 11 rows back, we know there is a next page. We just pop the 11th row out and use its ID as the nextCursor.

The Code

const express = require('express');
const app = express();

// Mock database connection (Replace with your actual DB setup like mysql2, pg, or Prisma)
const db = require('./db'); 

app.get('/api/posts', async (req, res) => {
    try {
        // 1. Get query parameters
        const limit = parseInt(req.query.limit) || 10;
        const cursor = req.query.cursor; // This will be the ID of the last item from the previous page

        // 2. Build the SQL Query
        let query = 'SELECT id, title, content, created_at FROM posts WHERE ';
        let params = [];

        if (cursor) {
            // If we have a cursor, fetch records AFTER this cursor
            query += 'id > ? ';
            params.push(cursor);
        } else {
            // If no cursor, it's the first page
            query += '1=1 ';
        }

        query += 'ORDER BY id ASC LIMIT ?';
        
        // PRO TIP: Fetch limit + 1 to check if there's a next page
        params.push(limit + 1); 

        // 3. Execute Query
        const rows = await db.query(query, params);

        // 4. Handle Pagination Logic
        let hasNextPage = false;
        let nextCursor = null;

        if (rows.length > limit) {
            hasNextPage = true;
            // Remove the extra row we fetched just for checking
            rows.pop(); 
        }

        // The cursor for the next page is the ID of the last item in our current result
        if (hasNextPage) {
            nextCursor = rows[rows.length - 1].id;
        }

        // 5. Send Response
        return res.json({
            success: true,
            data: rows,
            pagination: {
                hasNextPage,
                nextCursor,
                // Note: In cursor pagination, we don't usually return "totalPages" 
                // because counting total rows in a million-row table is expensive.
            }
        });

    } catch (error) {
        console.error('Error fetching posts:', error);
        return res.status(500).json({ success: false, message: 'Internal Server Error' });
    }
});

app.listen(3000, () => console.log('Server running on port 3000'));

How the Frontend Calls This

First Request:

GET /api/posts?limit=10

Response gives 10 items, and nextCursor: 10.

Second Request (Load More / Infinite Scroll):

GET /api/posts?limit=10&cursor=10

Response gives the next 10 items, and nextCursor: 20.


Offset vs Cursor

Feature Offset Pagination (LIMIT/OFFSET) Cursor Pagination (WHERE id > cursor)
Performance Degrades on higher pages (Slow) Consistent across all pages (Fast)
Data Consistency Can skip/duplicate rows if data is added/removed while paginating Safe from skipping/duplicating rows
Jump to Page Easy (e.g., "Go to Page 50") Impossible (Can only go Next/Previous)
Best Used For Admin dashboards, small datasets, traditional numbered pages Infinite scrolls, feeds, large datasets, mobile apps

Final Thoughts

AI tools are great for boilerplate, but they don't always know the scale of your production database. Always evaluate the generated code against your expected data size. If your table is going to cross 100k rows, drop the OFFSET and embrace the CURSOR. Your database (and your users) will thank you!


Some extra tips

  • Indexing: Make sure the column used as the cursor (such as id or created_at) has a database index. Without an index, cursor pagination won't perform efficiently.

  • UUIDs: If you're using UUIDs as your primary key, id > cursor can be unreliable because UUIDs are randomly generated. In that case, use a sequential field like created_at (or another ordered timestamp) as the cursor. If you're using an auto-incrementing id, then id > cursor works perfectly.

  • Total Count: With cursor pagination, it's common not to return totalPages or totalItems. Counting millions of rows is an expensive operation. Instead, use a "Load More" button or infinite scrolling on the frontend.

3 views

No comments yet. Be the first to comment.