DEV Community

Cover image for Why PostgreSQL OFFSET Pagination Gets Slow and How to Fix It in Django
sizan mahmud0
sizan mahmud0

Posted on

Why PostgreSQL OFFSET Pagination Gets Slow and How to Fix It in Django

Illustrative example. The numbers are made up to show the pattern, not benchmarks.

A list page that's instant on page 1 and takes seconds on page 40,000 is almost always OFFSET pagination. Here's what's happening and how to fix it.

The symptom

paginator = Paginator(Order.objects.order_by("-created_at"), 20)
page = paginator.get_page(request.GET.get("page"))
Enter fullscreen mode Exit fullscreen mode

Page 1 is instant. A deep page hangs. The query is correct and an index exists.

The evidence

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, customer_id, total, created_at
FROM orders_order
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 1000000;
Enter fullscreen mode Exit fullscreen mode
Limit  (actual time=612.400..612.480 rows=20 loops=1)
  ->  Index Scan Backward using order_created_id_idx on orders_order
        (actual time=0.030..575.300 rows=1000020 loops=1)
Execution Time: 612.540 ms
Enter fullscreen mode Exit fullscreen mode

The query returns 20 rows, but the scan produced rows=1000020.

Why

OFFSET N means "produce N rows, discard them, return the next ones". A B-tree index is sorted, but it doesn't store entry positions, so PostgreSQL can't jump to row 1,000,000. The work is proportional to offset + limit:

Page (20 per page) Rows produced and discarded
1 0
100 about 2,000
10,000 about 200,000
50,000 about 1,000,000

It gets worse without a matching index

Limit  (actual time=4200.100..4200.110 rows=20 loops=1)
  ->  Sort  (actual time=3800.200..4195.000 rows=1000020 loops=1)
        Sort Method: external merge  Disk: 412000kB
        ->  Seq Scan on orders_order  (actual rows=10000000 loops=1)
Enter fullscreen mode Exit fullscreen mode

Now every request, including page 1, reads and sorts the whole table. Fix the index first:

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

Other OFFSET problems

  • Hidden COUNT(*): Paginator runs it on every page view
  • Duplicates and gaps: positions shift when rows are inserted or deleted
  • Unstable order: ties in created_at need a unique tie-breaker (id)

Quick fixes

# Cap depth
MAX_PAGE = 100
if page_number > MAX_PAGE:
    raise Http404("Too deep. Use filters or search.")

# Skip the count: fetch one extra row to detect a next page
rows = list(qs[offset : offset + size + 1])
has_next = len(rows) > size
rows = rows[:size]
Enter fullscreen mode Exit fullscreen mode

You can also cache or cap the count (for example, "10,000+"), or use a deferred join: fetch only the page's IDs from a covering index, then load the full rows. That makes each skipped row cheaper but doesn't remove the growth with the offset.

The real fix: keyset pagination

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;
Enter fullscreen mode Exit fullscreen mode
Limit  (actual time=0.040..0.090 rows=20 loops=1)
  ->  Index Scan Backward using order_created_id_idx on orders_order
        Index Cond: (ROW(created_at, id) < ROW('2026-11-02 10:15:00+00', 987654))
Execution Time: 0.120 ms
Enter fullscreen mode Exit fullscreen mode

In Django:

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])
    return rows[:size], len(rows) > size
Enter fullscreen mode Exit fullscreen mode

The OR form isn't always planned as well as the row comparison, so check with qs.explain(analyze=True). If it's slow, use a parameterized raw query for that endpoint.

With DRF, CursorPagination does this for you:

from rest_framework.pagination import CursorPagination

class OrderCursorPagination(CursorPagination):
    page_size = 20
    ordering = "-created_at"
Enter fullscreen mode Exit fullscreen mode

Trade-offs

  • No jump to page 500
  • No cheap total count
  • Going backward needs extra logic
  • Each sort order needs a matching index
  • NULLs in sort columns need explicit handling

Which to use

Situation Approach
Small table OFFSET is fine
Admin needing page numbers OFFSET + index + page cap + cached or skipped count
Feeds, APIs, infinite scroll Keyset
Batch jobs over a whole table Indexed key ranges, never OFFSET
Exporting millions of rows Streaming, not pagination

Full story

The complete post follows Rafi's investigation chapter by chapter, with a checklist and an FAQ:

👉 https://blog.reiteachaigean.com/blog/why-postgresql-offset-pagination-becomes-slow

Related reads:

Do you test your paginated lists on the last page, or just the first?

Top comments (1)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

Ran your Django OR filter on PG17 (2M rows, the created_at/id index). One million rows deep it took 323 ms with "Rows Removed by Filter: 1000001", so OFFSET again. Adding created_at__lte=last_created_at next to the Q turns it into an Index Cond: 0.05 ms. And the tenant-first index doesn't help an order_by with no tenant filter, page 1 was a 478 ms seq scan.