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…