PostgreSQL Cursors Slash Export Times by Replacing Random Reads with Sequential Scans
A data pipeline exporting hundreds of gigabytes from PostgreSQL in 2,000-row batches was running far slower than expected, with the bottleneck traced to how the database read data from disk. Using a WHERE id > X LIMIT 2000 pattern caused Postgres to perform up to 2,000 random page lookups per batch via a B-tree index, forcing the disk head to constantly seek across different locations. Switching to a server-side cursor allowed Postgres to scan the heap sequentially, reading each 8KB page exactly once and enabling the OS to prefetch ahead predictably. This change required no schema modifications — only a different query pattern — yet dramatically reduced I/O overhead at scale. However, cursors hold an open transaction for their entire duration, which can block vacuum and inflate write-ahead logs on very large or long-running exports.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in