Reiteach Aigean Logo
Reiteach Aigeanblog.reiteachaigean.com
Admin
HomeAI UpdatesCodingCloudApps & ToolsTech NewsArticles

Why PostgreSQL OFFSET Pagination Becomes Slow (and Fixes)

Why does PostgreSQL OFFSET pagination get slower on deep pages? Learn how it works, see it in EXPLAIN ANALYZE, and fix it with keyset pagination in Django

S
Sizan Mahmud
Published on December 3, 2026
 Why PostgreSQL OFFSET Pagination Becomes Slow (and Fixes)

Introduction

Pagination feels like the simplest feature in any application. You add LIMIT 20 OFFSET 40, the list page works, and you move on. It stays fast in development. It stays fast in production for months. Then the table grows to millions of rows, someone (or some crawler) starts requesting page 40,000, and a query that used to take a millisecond takes seconds.

The frustrating part is that nothing looks broken. The query is correct, the index exists, and the first pages are still instant. Only the deep pages are slow, and they get slower the deeper you go.

This guide explains exactly why PostgreSQL OFFSET pagination becomes slow, shows it in a real query plan, and walks through the fixes in order of effort: capping pages, avoiding the hidden COUNT(*), the deferred join trick, and the real solution, keyset (cursor) pagination, with Django code you can use today.

How OFFSET Pagination Works

The classic approach looks like this:

SELECT id, customer_id, total, created_at
FROM orders_order
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40;

In Django, Paginator, ListView with paginate_by, the admin, and DRF's PageNumberPagination and LimitOffsetPagination all produce this shape. Page 3 with 20 items per page becomes OFFSET 40 LIMIT 20.

It is popular for good reasons: it is easy to understand, easy to implement, and it lets users jump to any page number. The cost is hidden in what OFFSET actually means.

Why OFFSET Gets Slower: It Reads Rows It Throws Away

OFFSET 1000000 does not mean "start at row 1,000,000". It means "produce the first 1,000,000 rows in this order, discard them, and then return the next 20."

PostgreSQL has no way to jump to the millionth entry of a result set by position. A B-tree index is ordered, but it does not store "this is entry number 1,000,000". To find the starting point, the executor walks the index from the beginning, passes each row up to the Limit node, and the Limit node counts and discards them until the offset is reached.

Here is what that looks like in a plan (illustrative numbers):

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, total, created_at
FROM orders_order
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 1000000;

Limit  (cost=118400.10..118400.70 rows=20 width=24) (actual time=612.400..612.480 rows=20 loops=1)
  ->  Index Scan Backward using order_created_id_idx on orders_order
        (cost=0.43..592000.00 rows=10000000 width=24)
        (actual time=0.030..575.300 rows=1000020 loops=1)
Planning Time: 0.180 ms
Execution Time: 612.540 ms

Look at the Index Scan Backward node: rows=1000020. The scan produced a million and twenty rows so that the Limit node could throw away a million of them and keep 20. The same query with OFFSET 0 would produce 20 rows and finish in a fraction of a millisecond.

If you want to learn how to read a plan like this one, see the related guide on debugging slow queries with EXPLAIN ANALYZE below.

The cost grows linearly with the offset

Page (20 per page) Rows produced and discarded Relative work
Page 1 (OFFSET 0) 0 Tiny
Page 100 (OFFSET 1,980) ~2,000 Small
Page 10,000 (OFFSET 199,980) ~200,000 Noticeable
Page 50,000 (OFFSET 999,980) ~1,000,000 Slow

The work is proportional to offset + limit. Doubling the page number roughly doubles the cost. That is why dashboards look fine in testing, where everyone looks at page 1, and fall over in production, where an export script, an SEO crawler, or a curious user walks through every page.

It Can Be Even Worse Without the Right Index

The plan above assumes an index that matches the ORDER BY. If there is none, the situation is much worse:

Limit  (actual time=4200.100..4200.110 rows=20 loops=1)
  ->  Sort  (actual time=3800.200..4195.000 rows=1000020 loops=1)
        Sort Key: created_at DESC, id DESC
        Sort Method: external merge  Disk: 412000kB
        ->  Seq Scan on orders_order  (actual time=0.040..1200.000 rows=10000000 loops=1)

Now PostgreSQL must read the whole table and sort all of it before it can return even the first page, and the sort may spill to disk. Every page request repeats that work, including page 1.

So the first step in any pagination fix is making sure the ORDER BY columns are covered by a suitable composite index. The guide on composite indexes in the related reading section explains how to design it.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

Other Problems with OFFSET (Beyond Speed)

Speed is the headline, but OFFSET has correctness problems too.

1. Duplicated and skipped rows. Pages are defined by position, and positions shift when data changes. Imagine a newest-first feed. A user loads page 1, then three new rows are inserted at the top, then the user loads page 2. Every row moved down by three, so three rows from page 1 appear again at the top of page 2. Deletions cause the opposite problem: rows slip through the gap and are never shown. For feeds, activity logs, and any frequently changing data, OFFSET pagination is subtly wrong, not just slow.

2. Unstable ordering. ORDER BY created_at is not deterministic if many rows share the same timestamp. PostgreSQL may return tied rows in different orders on different runs, so the same row can appear on two pages or on none. Always add a unique tie-breaker such as the primary key: ORDER BY created_at DESC, id DESC. And LIMIT/OFFSET without any ORDER BY returns an arbitrary, unreliable set.

3. The hidden COUNT(*). Page-number navigation needs the total, so Django's Paginator runs a second query:

SELECT COUNT(*) FROM orders_order WHERE ...;

On a large table, PostgreSQL has to scan many rows or index entries to count them, because of how its concurrency model works. For a table with millions of rows, that count can cost more than the page query itself, and it runs on every page view. The Django admin has the same issue, which I cover in a separate guide on slow admin pages.

The Fixes, in Order of Effort

Fix 1: Make Sure the Index Matches the Sort

Before anything else, confirm that an index serves your ORDER BY and filter, in the right column order:

class Order(models.Model):
    tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["tenant", "-created_at", "-id"], name="order_tenant_created_id_idx"),
        ]

This removes the sort and the full scan. It does not remove the cost of skipping rows, but it turns a catastrophic query into a merely slow one. On a big production table, create it with AddIndexConcurrently.

Fix 2: Cap How Deep Users Can Go

Humans rarely go past page 20. Deep pages are usually crawlers, scrapers, and scripts. A cheap and effective measure is to limit the maximum page, and send people to search and filters instead:

MAX_PAGE = 100

def list_orders(request):
    page_number = int(request.GET.get("page", 1))
    if page_number > MAX_PAGE:
        raise Http404("Too deep. Use filters or search.")
    ...

Google and other search engines also rarely need to crawl page 50,000 of a list. Pair this with noindex or a limit on crawlable pages if SEO is a concern.

Fix 3: Stop Running COUNT(*) on Every Request

If you do not need exact page numbers, do not count. Replace "Page 3 of 50,000" with "Next" and "Previous" links. To know whether a next page exists, fetch one extra row:

def get_page(qs, offset, size=20):
    rows = list(qs[offset : offset + size + 1])
    has_next = len(rows) > size
    return rows[:size], has_next

If you do need a total, you have options:

  • Cache it for a minute or an hour, since an exact live count is rarely necessary.
  • Cap it. Count at most the first 10,000 rows (qs[:10000].count()), and show "10,000+".
  • Use an estimate for unfiltered whole-table totals from PostgreSQL's statistics (reltuples in pg_class). This does not work for filtered queries.
  • Maintain a counter or summary table that you update as data changes.

In Django, you can replace the default paginator with one that skips or caches the count:

from django.core.paginator import Paginator
from django.utils.functional import cached_property
from django.core.cache import cache

class CachedCountPaginator(Paginator):
    @cached_property
    def count(self):
        key = "paginator_count:orders"
        value = cache.get(key)
        if value is None:
            value = self.object_list.count()
            cache.set(key, value, 300)
        return value

For a filtered list, make the cache key depend on the filters, or the numbers will be wrong.

Fix 4: The Deferred Join (Late Row Lookup)

If you must keep OFFSET, you can reduce its cost by making the part that skips rows as cheap as possible. The idea: find only the IDs of the target page using a narrow index, and fetch the full rows afterward.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

SELECT o.*
FROM orders_order o
JOIN (
    SELECT id
    FROM orders_order
    ORDER BY created_at DESC, id DESC
    LIMIT 20 OFFSET 1000000
) page ON page.id = o.id
ORDER BY o.created_at DESC, o.id DESC;

The inner query only needs the sort columns and the ID. With a covering index (for example (created_at DESC, id DESC)), PostgreSQL can run an index-only scan and skip the million table fetches, reading just the index. The expensive wide rows are fetched for only 20 IDs.

In Django, a simple two-step version works:

ids = list(
    Order.objects.order_by("-created_at", "-id")
    .values_list("id", flat=True)[offset : offset + size]
)
orders = Order.objects.in_bulk(ids)
page = [orders[i] for i in ids]  # restore the order

Be realistic about what this achieves. The cost is still proportional to the offset, because PostgreSQL still walks a million index entries. It just makes each skipped row cheaper. It also depends on the visibility map being up to date for index-only scans, which autovacuum maintains. It is a good stopgap, not a cure.

Fix 5: Keyset (Cursor) Pagination, the Real Solution

Keyset pagination, also called the seek method or cursor pagination, changes the question. Instead of "skip N rows", you ask "give me rows that come after the last one I showed".

-- First page
SELECT id, created_at, total
FROM orders_order
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- Next page: pass the last row's values from the previous page
SELECT id, created_at, total
FROM orders_order
WHERE (created_at, id) < ('2026-11-02 10:15:00+00', 987654)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The WHERE clause lets PostgreSQL descend the B-tree straight to the position after the last seen row, then read the next 20 entries. The work is the same for the millionth page as for the second. The plan (illustrative):

Limit  (actual time=0.040..0.090 rows=20 loops=1)
  ->  Index Scan Backward using order_created_id_idx on orders_order
        (actual time=0.038..0.085 rows=20 loops=1)
        Index Cond: (ROW(created_at, id) < ROW('2026-11-02 10:15:00+00', 987654))
Execution Time: 0.120 ms

Compare rows=20 here with rows=1000020 for OFFSET. That is the entire difference.

Two details are important:

  • The sort key must be unique. Use a tie-breaker (id) so that no two rows have the same sort key. Otherwise rows with equal timestamps can be skipped or repeated between pages.
  • The index must match the order, including the direction and the tie-breaker: (created_at DESC, id DESC).

Keyset Pagination in Django

Django's ORM does not offer first-class tuple comparison in every version, so the common approach expresses the same logic with Q objects:

from django.db.models import Q

def get_orders_page(last_created_at=None, last_id=None, size=20):
    qs = Order.objects.order_by("-created_at", "-id")

    if last_created_at is not None and last_id is not None:
        qs = qs.filter(
            Q(created_at__lt=last_created_at)
            | Q(created_at=last_created_at, id__lt=last_id)
        )

    rows = list(qs[: size + 1])         # fetch one extra to detect a next page
    has_next = len(rows) > size
    rows = rows[:size]
    return rows, has_next

This reads as: "older than the last timestamp, or the same timestamp with a smaller ID". It is logically the same as the row comparison. PostgreSQL's planner can handle the OR form, but it is not always as efficient as the row-value form, so confirm with qs.explain(analyze=True) that you see a narrow index scan with a small rows count. If the OR form performs poorly on your data, use a raw SQL snippet with the row comparison for this one query.

Back the query with the matching index:

class Meta:
    indexes = [
        models.Index(fields=["-created_at", "-id"], name="order_created_id_idx"),
    ]

Turning the Last Row Into a Cursor

Send the client an opaque token instead of raw values, so the API does not expose its internals and you can change the scheme later:

import base64
import json
from datetime import datetime

def encode_cursor(order):
    payload = [order.created_at.isoformat(), order.id]
    return base64.urlsafe_b64encode(json.dumps(payload).encode()).decode()

def decode_cursor(token):
    try:
        created_at_str, last_id = json.loads(base64.urlsafe_b64decode(token.encode()))
        return datetime.fromisoformat(created_at_str), int(last_id)
    except (ValueError, TypeError, json.JSONDecodeError):
        return None, None  # treat a bad cursor as "start from the beginning"

Treat the cursor as untrusted input: validate it, handle malformed values, and never put it into raw SQL by string formatting. Use query parameters.

The API response then looks like this:

{
  "results": [ ... 20 orders ... ],
  "next": "WyIyMDI2LTExLTAyVDEwOjE1OjAwKzAwOjAwIiwgOTg3NjU0XQ==",
  "has_next": true
}

Django REST Framework Has This Built In

If you use DRF, CursorPagination implements the pattern for you:

from rest_framework.pagination import CursorPagination

class OrderCursorPagination(CursorPagination):
    page_size = 20
    ordering = "-created_at"

class OrderViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    pagination_class = OrderCursorPagination

The ordering field should be unchanging, indexed, and ideally unique, such as a creation timestamp or an auto-incrementing ID. DRF handles ties with an internal offset, which works but can reintroduce some skipping cost when many rows share the same value, so a unique ordering field is the safest choice. Also, CursorPagination does not give you a total count or page numbers, which is the trade-off covered next.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

The Trade-Offs of Keyset Pagination

Keyset pagination is not free. Know what you give up:

  • No "jump to page 500". You can only move forward and backward from a known position. If your UI needs a page-number selector, keyset alone cannot provide it.
  • No cheap total count. You still need a separate strategy if you want to show a total.
  • Going backward needs extra logic. You reverse the comparison and the order, fetch, and then reverse the results again.
  • Sorting is constrained. Each sort order you support needs a matching index, and mixed-direction sorts need care. Columns that can be NULL need explicit handling (NULLS FIRST or NULLS LAST and matching conditions), or rows with NULLs can be skipped.
  • Arbitrary user-chosen sorting is harder. Sorting by any column a user clicks means many indexes and many cursor shapes.

In return, you get constant-time pages, stable results under inserts and deletes, and no deep-page performance cliff.

Which Approach Should You Use?

Situation Recommended approach
Small table, few pages (under ~10,000 rows) OFFSET is fine
Admin screens needing page numbers OFFSET with an index, a page cap, and a cached or skipped count
Public lists where crawlers hit deep pages Page cap plus keyset
Infinite scroll, feeds, activity logs Keyset (cursor) pagination
Public API over a large dataset Keyset, for example DRF CursorPagination
Must keep OFFSET but reduce cost Deferred join with a covering index
Batch jobs walking a whole table Keyset by ID range, never OFFSET
Exports of millions of rows Streaming with iterator(), not pagination at all

A hybrid is common: use keyset for "next" and "previous" navigation, and offer page numbers only for the first few pages or inside filtered subsets that are small.

Common Mistakes to Avoid

  1. Paginating with OFFSET over a growing table and never testing deep pages. Always test the last page, not just the first.
  2. Ordering by a non-unique column. Add the primary key as a tie-breaker, or pages will overlap and skip rows.
  3. No index matching the ORDER BY. It turns every page into a full scan and sort.
  4. Running COUNT(*) on every page view. Cache it, cap it, or drop it.
  5. Letting crawlers and scripts walk every page. Cap the page number and rate limit.
  6. Using OFFSET inside batch jobs. Each batch gets slower. Use key ranges instead.
  7. Putting a raw cursor value into SQL by string formatting. Use parameters, and validate the cursor.
  8. Forgetting NULL handling in keyset conditions. NULLs compare unexpectedly and can drop rows.
  9. Assuming keyset fixes everything. It still needs the right index, and it changes your UI options.
  10. Switching to keyset without checking the plan. Confirm the plan shows a narrow index scan with Index Cond.

A Practical Checklist

Before shipping or fixing a paginated list, confirm that you:

  • Order by a deterministic key that ends with a unique column such as id
  • Have a composite index matching the filter, sort columns, direction, and tie-breaker
  • Tested the query on the deepest page with realistic data volume
  • Checked the plan with EXPLAIN (ANALYZE, BUFFERS) and looked at how many rows the scan produced
  • Avoided a per-request COUNT(*), or cached or capped it
  • Capped the maximum page number for public endpoints
  • Used keyset (cursor) pagination for feeds, APIs, and infinite scroll
  • Fetched size + 1 rows to detect has_next without a count
  • Encoded cursors as opaque, validated tokens, and passed values as query parameters
  • Handled NULLs in sort columns explicitly
  • Used key ranges instead of OFFSET in batch jobs

Related Reading: Pagination Is One Part of a Fast Data Layer

Fixing pagination works best together with good indexes and query habits. These guides cover the neighboring pieces:

Conclusion

OFFSET pagination becomes slow because OFFSET N means "produce N rows and throw them away". PostgreSQL cannot jump to a position, so the work grows linearly with the page number, and without a matching index it can mean a full scan and sort on every request. It also shifts under concurrent changes, so rows get duplicated or skipped, and the COUNT(*) behind page numbers adds its own cost.

Start by giving the query a deterministic order and a matching composite index. Cap how deep users can go and stop counting on every request. For feeds, APIs, and large tables, move to keyset pagination, which asks for "rows after the last one I saw" and costs the same on page one and page one million. Verify the result in the query plan, not by assumption, and your lists will stay fast no matter how large the table becomes.

Frequently Asked Questions

Why is OFFSET slow in PostgreSQL? Because PostgreSQL must produce and discard every row before the offset. OFFSET 1000000 makes the executor walk a million rows through the plan before returning the next 20, so the cost grows with the page number. It cannot jump to a position directly.

Does an index make OFFSET fast? An index removes the full scan and sort, which helps a lot, but the database still walks the index entries and usually fetches the table rows for every skipped row. Deep pages remain slower than early pages. To remove the growth, use keyset pagination.

What is keyset pagination? It is a pagination method that uses the last seen row's sort values to find the next page, instead of skipping rows by count. For example, WHERE (created_at, id) < (last_created_at, last_id) ORDER BY created_at DESC, id DESC LIMIT 20. With a matching index, every page costs about the same.

Is keyset pagination better than OFFSET in Django? For large tables, feeds, APIs, and infinite scroll, yes. It is faster on deep pages and consistent when data changes. OFFSET is still fine for small tables or when you need to jump to arbitrary page numbers, ideally with a page cap and a cheap count.

How do I do cursor pagination in Django REST Framework? Use rest_framework.pagination.CursorPagination and set ordering to an indexed, unchanging, preferably unique field such as -created_at or id. It returns next and previous links instead of page numbers and totals.

Why does Django's Paginator run a COUNT query? It needs the total number of items to compute the number of pages. On large tables that COUNT(*) can be expensive, and it runs on every page view. You can cache the count, cap it, replace it with next and previous links, or use a custom paginator.

Why do I see duplicate or missing rows between pages? Either rows were inserted or deleted between page requests, shifting positions, or the ORDER BY is not deterministic because of ties. Add a unique tie-breaker such as id to the order, and use keyset pagination for data that changes frequently.

How can I make OFFSET faster if I can't change it? Add an index that matches the order, cap the maximum page, avoid or cache COUNT(*), and use a deferred join: select only the IDs for the page from a covering index, then fetch the full rows for those IDs. It reduces the cost per skipped row but does not remove the growth with the offset.

Share this article

Pass this technical dispatch along to fellow engineers

Did you enjoy this article?

Rate it so we know what content to bring next

Comments (0)