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

Why PostgreSQL OFFSET Pagination Becomes Slow

Django page that was fast until page 40,000. See why PostgreSQL OFFSET pagination gets slow, how to prove it, and how keyset pagination fixes it.

S
Sizan Mahmud
Published on December 6, 2026
 Why PostgreSQL OFFSET Pagination Becomes Slow

Introduction

The story below is an illustrative composite, and every number in it is an example, not a benchmark. The technical behavior, though, is exactly how PostgreSQL works.

Chapter 1: The Page That Was Always Fast

Rafi had built the orders list for a growing SaaS product, and he was quietly proud of it. A table of orders, 20 rows per page, newest first, with next and previous links. It took him an afternoon.

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

In development it was instant. In production, month after month, it stayed instant. The product grew, the table grew, and nobody ever complained, because everybody looked at the same place: page 1.

That is the first thing to understand about this story. OFFSET pagination doesn't fail where you test it. It fails where you don't look.

Chapter 2: The Ticket

One Monday morning, a message arrived from support: "A customer says the orders list freezes when they scroll to the old stuff. Also the dashboard feels sluggish today."

Rafi opened the list and clicked through the first few pages. Fast. He jumped to page 500. Fast enough. Then he typed page 40,000 into the URL, just to see.

The page hung for almost a second, then another, then finally rendered. He reloaded. Same wait. He tried page 45,000. A little slower.

Nothing was broken. The query was correct, the index existed, and the first pages were still instant. But something was clearly growing with the page number, and he wanted to know what.

Chapter 3: Reading the Evidence

Rafi had learned the hard way not to guess. He didn't add an index or rewrite the query. He asked PostgreSQL what it was doing.

First he found the query in pg_stat_statements, where it sat near the top by total execution time. Then he ran the exact SQL Django generated for page 50,000 under EXPLAIN (ANALYZE, BUFFERS):

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

The plan (illustrative numbers):

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

He stared at one number: rows=1000020.

The query asked for 20 rows, but the scan underneath had produced one million and twenty. Almost all of its time was spent on rows that nobody would ever see.

If reading a plan like this feels unfamiliar, my step-by-step guide on debugging slow PostgreSQL queries with EXPLAIN ANALYZE walks through every part of the output, including why loops and estimated-versus-actual rows matter. Rafi's whole investigation came down to those habits.

Chapter 4: What OFFSET Really Means

Rafi realized he had misunderstood a word.

He had read OFFSET 1000000 as "start at row one million". It actually means "produce the first million rows in this order, throw them away, then return the next twenty."

Picture a librarian asked for books 1,000,001 to 1,000,020 on a very long shelf. She cannot walk straight to the spot, because the shelf has no numbers on it. She has to start at the first book and count, one by one, until she reaches a million. Only then does she start handing over books.

PostgreSQL is that librarian. A B-tree index keeps entries in sorted order, but it does not store "this is entry number 1,000,000". To reach the starting point, the executor walks the index from the beginning and passes each row to the Limit node, which counts and discards them.

The consequence is simple and brutal: the work is proportional to offset + limit.

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

Double the page number, roughly double the cost. That is why the list felt perfect in testing and awful in the one place nobody tested.

Free tech newsletter

Free

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

Chapter 5: Plot Twist One, the Missing Index Match

Rafi was relieved that an index existed. Then he remembered that the index in the plan had come from an earlier cleanup, and it was only there by luck.

Had the ORDER BY not matched an index, the plan for the same page would have looked like this instead:

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 reads the entire table and sorts all of it, possibly spilling hundreds of megabytes to disk, before it can return even page 1. Every request repeats that work.

So the first fix is not about pagination at all. It is making sure the filter and sort are covered by one composite index, in the right column order, including the tie-breaker:

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",
            ),
        ]

Choosing that column order is a skill in itself, covered in my guide on PostgreSQL composite indexes with Django: equality columns first, then the sort column, with matching directions. On a big production table, create the index with AddIndexConcurrently so writes are not blocked.

The index turns a catastrophe into a merely slow query. It does not remove the cost of skipping rows. For that, Rafi needed to keep digging.

Chapter 6: Plot Twist Two, the Silent COUNT

The list page didn't run one query. It ran two.

Django's Paginator needs the total number of rows to draw "Page 3 of 50,000", so it quietly runs this before every page view:

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

In PostgreSQL, counting a large table is not free. Because of how its concurrency model works, the database has to visit many rows or index entries to know how many are visible to your transaction. On a table with millions of rows, the count can cost as much as the page query itself, and it ran on every page view, even page 1.

Rafi had seen this pattern before in the admin. The same hidden count is behind many slow admin list pages, which I explained in my guide on fixing slow Django admin pages, where turning off the full result count was one of the easiest wins.

He also revisited how counts behave on large tables, and why filtering before counting and using Exists() for yes-or-no questions matters. That whole topic is covered in Django ORM annotate vs aggregate performance.

His options for the count were:

  • Cache it for a few minutes, because an exact live number is rarely necessary.
  • Cap it, for example count at most 10,000 rows and display "10,000+".
  • Drop it, and replace "Page 3 of 50,000" with Next and Previous links.
  • Maintain a counter in a summary table if a real total matters.

For "Is there a next page?", no count is needed at all. 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

Chapter 7: Plot Twist Three, Rows That Appear Twice (or Never)

While testing, Rafi noticed something odd that had nothing to do with speed.

He loaded page 1 of the newest-first list. Then, in another tab, he created three new orders. Then he loaded page 2. Three orders from page 1 appeared again at the top of page 2.

Pages in OFFSET pagination are defined by position, and positions shift when data changes. Insert three rows at the top, and everything slides down by three. Delete rows, and the opposite happens: items slip through the gap and are never shown to the user at all. For a busy feed, an activity log, or an audit trail, OFFSET pagination isn't just slow. It is subtly wrong.

There was a second correctness trap. His sort was ORDER BY created_at, and many orders shared the same timestamp, because they came from batch imports. When sort keys tie, PostgreSQL is free to return the tied rows in any order, and it can differ between runs, so a row can show up on two pages or on none. The fix is a unique tie-breaker, which is why every query in this story ends with id DESC.

Chapter 8: Who Was Actually Requesting Page 40,000?

Customers don't browse to page 40,000. Rafi checked the access logs.

Two things were doing it. One was a search engine crawler, patiently following Next links through the entire list. The other was an internal script someone had written to "export everything", which looped through pages one by one: page 1, page 2, page 3, all the way to the end. And since each page cost more than the last, the script made itself slower with every request.

Free tech newsletter

Free

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

That second case has its own proper solutions, and pagination isn't one of them:

Notice that both approaches rely on the same underlying idea as the fix coming up in the next chapter: ask for rows after a known key, never "skip N rows".

Chapter 9: The Quick Fixes

Rafi didn't want to rewrite everything on a Monday. So he shipped the cheap fixes first.

Cap how deep people can go. Humans rarely go past page 20.

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.")
    ...

Cache or remove the count, as above.

Try the deferred join. If OFFSET has to stay, make the skipped rows as cheap as possible by finding only the IDs of the target page from a narrow index, and fetching the full rows afterward:

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

With a covering index, PostgreSQL can walk index entries without touching the wide table rows for each skipped position. It helps, but be honest about what it is: the cost still grows with the offset, because PostgreSQL still walks a million index entries. It only makes each skipped row cheaper. It is a bandage, not a cure.

Chapter 10: The Real Fix, Keyset Pagination

The cure starts with a change of question.

OFFSET asks: "Skip this many rows." Keyset pagination, also called cursor pagination or the seek method, asks: "Give me the 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, and then read the next 20 entries. The work is the same for page one million as it is for page two. Here is 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 with the earlier rows=1000020. That single difference is the whole story.

Two details are essential:

  • The sort key must be unique. That is why id is the tie-breaker. Without it, rows sharing a timestamp can be skipped or repeated.
  • The index must match the order, including direction and the tie-breaker: (created_at DESC, id DESC), optionally with a tenant column in front.

Keyset Pagination in Django

Django's ORM expresses this 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])        # one extra row detects a next page
    has_next = len(rows) > size
    return rows[:size], has_next

It reads as "older than the last timestamp, or the same timestamp with a smaller ID". Logically it is the same as the row comparison. PostgreSQL does not always plan the OR form as efficiently as the row-value form, so check 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 parameterized raw SQL query with the row comparison for this one endpoint.

Turning the Last Row into a Cursor

Rafi didn't want to expose raw timestamps and IDs in his API, so he wrapped the position in an opaque token:

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"

A cursor is untrusted input. Validate it, handle malformed values, and never place it into SQL by string formatting. Use query parameters.

The response then looks like this:

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

If You Use Django REST Framework

DRF already ships the pattern:

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 indexed, unchanging, and ideally unique. DRF handles ties with an internal offset, which works but can bring back some skipping cost when many rows share the same value, so a unique field is the safest choice. And as with any keyset approach, there is no total count and no page numbers.

Chapter 11: The Price of the Fix

Rafi was honest with his team about what keyset pagination takes away:

Free tech newsletter

Free

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

  • No "jump to page 500". You can only move forward and backward from a known position.
  • No cheap total count. If you want a total, you still need one of the strategies from Chapter 6.
  • Going backward needs extra logic. You reverse the comparison and the order, fetch, and flip the results.
  • Sorting is constrained. Each supported sort order needs a matching index, and columns that can be NULL need explicit handling, or rows with NULLs can be dropped.
  • User-selected sorting is harder. "Sort by any column I click" means many indexes and many cursor shapes.

In return, the team got constant-time pages, stable results under inserts and deletes, and no deep-page cliff. For feeds, APIs, and infinite scroll, it was an easy trade. For a small admin table with 5,000 rows, plain OFFSET stayed, and that was fine too.

Chapter 12: The Side Effects Nobody Mentions

While the slow pages were hanging, something else was quietly happening in the background. Each slow page query held a database connection for its whole duration. With a crawler and an export script hammering deep pages, connections were piling up, and normal requests had to wait for a free one. Part of that "sluggish dashboard" feeling on Monday morning was simply a connection pool drained by slow queries. If that sounds familiar, Django database connection pooling with PostgreSQL explains how to count and cap connections, and why long queries make pool problems worse.

And while he was reading the list page's query log, Rafi noticed the page ran one extra query per order to load each customer's name. A paginated page should cost a fixed number of queries no matter how many rows it shows, so he fixed it the usual way, which I explain in select_related vs prefetch_related: practical examples. That one was a separate problem, but fast pages need both fixes.

Finally, he put the lessons into his general toolbox: the keyset pattern, only(), iterator(), and the other habits that keep list queries cheap at scale, all covered in Django ORM optimization for millions of records.

Chapter 13: What the Story Teaches

Here is Rafi's decision table, which you can reuse:

Situation Recommended approach
Small table, few pages (under about 10,000 rows) OFFSET is fine
Admin screens that need page numbers OFFSET with a matching index, a page cap, and a cached or skipped count
Public lists that crawlers can walk 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 Indexed key ranges, never OFFSET
Exporting millions of rows Streaming with iterator(), not pagination

And the mistakes to avoid:

  1. Paginating with OFFSET over a growing table and only testing page 1. Always test the last page.
  2. Ordering by a non-unique column. Add the primary key as a tie-breaker.
  3. Having no index that matches the ORDER BY.
  4. Running COUNT(*) on every page view.
  5. Letting crawlers and scripts walk every page.
  6. Using OFFSET inside batch jobs.
  7. Putting cursor values into raw SQL by string formatting.
  8. Forgetting NULL handling in keyset conditions.
  9. Switching to keyset without checking the plan for a narrow Index Cond scan.

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 deepest page with realistic data volume
  • Checked 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 on public endpoints
  • Used keyset pagination for feeds, APIs, and infinite scroll
  • Fetched size + 1 rows to detect has_next without a count
  • Encoded cursors as opaque, validated tokens, with values passed as parameters
  • Handled NULLs in sort columns explicitly
  • Used key ranges instead of OFFSET in batch jobs

Conclusion

OFFSET pagination becomes slow because OFFSET N means "produce N rows and throw them away". PostgreSQL cannot jump to a position, so the cost grows with the page number. It is also fragile: without a matching index it can mean a full scan and sort on every request, a hidden COUNT(*) adds its own cost, and rows can be duplicated or skipped as data changes.

Rafi's fix followed a simple order. Prove the problem with the query plan, give the query a deterministic order and a matching composite index, cap the depth and stop counting on every request, and move feeds and APIs to keyset pagination, which asks for rows after the last one seen and costs the same on page one and page one million. Then check the plan again, because the only proof that matters is rows=20.

The next time a list feels fast in testing, don't stop at page 1. Type a big number into the URL.

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 straight to a position.

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 table rows for the skipped positions. Deep pages stay 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 use 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 it, cap it, replace it with next and previous links, or write a custom paginator.

Why do I see duplicate or missing rows between pages? Either rows were inserted or deleted between 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 often.

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.

Related Reading

If you want to go deeper into any part of this story, these guides continue where each chapter left off:

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)