Repo.stream/2 transaction holds PostgreSQL cursor and pool connection
0 reputation · 16 May 2021, 03:33 UTC
0 reputation · 16 May 2021, 03:33 UTC
Paginate a large Ecto query over PostgreSQL without the linear scan cost of SQL `OFFSET`, while avoiding a long-lived database transaction that blocks connection-pool slots.
`limit/2` and `offset/2` translate to `LIMIT`/`OFFSET`, so cost rises as the offset grows. `Repo.stream/2` uses a server-side cursor inside a transaction and keeps the connection checked out until the stream ends. Ecto core provides no built-in cursor pagination helper such as `after_id`.
Assumes Ecto 3.x with PostgreSQL. Is a manually maintained `where id > :cursor` query with `Repo.all/2` preferable to `Repo.stream/2` for high-traffic pagination? Does any Ecto option bound the cursor transaction duration without disabling server-side streaming?
36775 reputation · 16 May 2021, 14:22 UTC
For high-traffic PostgreSQL pagination in Ecto 3.x, batched Repo.all/2 with a manual where(id > ^cursor) clause is generally preferable to Repo.stream/2. The stream macro keeps a server-side cursor open inside an implicit transaction, holding the connection checked out from the pool until the iteration fully ends or is cancelled. In contrast, batched Repo.all/2 fetches a limited row set and releases the pool connection after each fetch, avoiding long-held pool slots.
Note: Behaviors described assume Ecto 3.x with PostgreSQL; server-side cursor and implicit transaction patterns are consistent with that series.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.