The Real Fullstack

The Slow Pagination

Same query, same index, only the page number changed. Why is page 5,000 a hundred times slower?

工程师7 分钟性能实验室代码挑战
sqlpostgresqlrestangular

此挑战尚未翻译为简体中文,你正在阅读英文版本。

任务:Serve page 5,000 in ≤ 5 ms while new rows are being inserted, without duplicates.背景 · 学习目标 ▾

Larkspur's activity feed has an infinite scroll backed by LIMIT/OFFSET. Power users and crawlers reach deep pages; the database CPU climbs with them. Users also report seeing the same event twice after new events arrive.

任务: Serve page 5,000 in ≤ 5 ms while new rows are being inserted, without duplicates.

学习目标

  • Explain why OFFSET cost grows with the page number.
  • Implement keyset (seek) pagination with a stable sort key.
  • Understand the UX trade-off: no random page jumps.
模拟
模拟数据

运行模拟以查看输出。

运行模拟
SELECT id, title, created_at FROM events ORDER BY created_at DESC, id DESC LIMIT 20OFFSET 99980;          -- reads and discards 99,980 index entries first

简化说明

Cost proportional to index entries read. Real costs also include fetching heap rows for visible columns. 教学模型——数字用于说明行为,并非基准测试。

概念

建议先完成

相关挑战

参考资料