Menu

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

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

DEV Community: django·sizan mahmud0·about 6 hours ago
#HdrhyEZa
#devtodjango#devto#dev#rows#offset
Long article (835 words) — no AI summary yet.
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.