Back to Course

Practice · Scaling · Card 4

Why is page 50,000 so much slower than page 1?

The same query, same index, same database. Page 1 returns in 5ms. Page 50,000 takes 4 seconds. The user is on the same table.

The query

Standard OFFSET pagination from Kaminari, page size 20, on a 5M-row table with an index on created_at.

# At page 50,000, Kaminari generates:
Post.order(:created_at).limit(20).offset(1_000_000)

# Which is:
# SELECT "posts".* FROM "posts"
# ORDER BY "posts"."created_at" ASC
# LIMIT 20 OFFSET 1000000

# Page 1: 5ms.
# Page 50,000: 4s.

The question

Why is page 50,000 so much slower? The index on created_at is in place.

Take a moment. Pick the best answer. Wrong picks reveal why they're wrong, which is half the point.