Skip to main content
Streaming Large CSV Exports from Postgres in Node.js and NestJS: Backpressure, pipeline(), and the Connection a Slow Download Holds

Streaming Large CSV Exports from Postgres in Node.js and NestJS: Backpressure, pipeline(), and the Connection a Slow Download Holds

November 21, 2026
Backend Engineering
9 min read

Headline: A CSV export that loads every row into an array uses memory in proportion to the table, so it works in staging and dies in production. At Devya we stream exports with pg-query-stream and pipeline() from node:stream/promises, which keeps memory flat through backpressure, and we plan for the cost streaming adds: one Postgres connection and one open transaction held for as long as the slowest client downloads.

The first export endpoint a team writes for an admin panel usually looks the same: query everything, join the rows into a string, send it. That version passes review and every test, because the test table is small. These notes cover the version we replace it with, and what the streamed version still gets wrong when a team stops at the happy path.

Key takeaways

• Buffered exports scale with the table: a SELECT into an array plus a joined CSV string holds the whole result in the Node.js heap at least twice.

• Backpressure keeps memory flat: writable.write() returns false when the buffer passes highWaterMark, and the producer must wait for the drain event.

• pipeline() replaces pipe(): pipeline() from node:stream/promises handles backpressure, destroys every stream when one fails, and accepts an AbortSignal; readable.pipe() does not clean up or forward errors.

• A streamed export holds a database connection: pg-query-stream reads through a Postgres cursor, so one pool connection and one transaction stay open until the client finishes or disconnects.

• Errors after the first byte cannot become a 500: once the headers are sent, the only honest failure signal is an aborted download.

Why does a CSV export endpoint run out of memory in Node.js?

A CSV export endpoint runs out of memory when it materializes the full result set before sending the first byte. In node-postgres, pool.query() returns every row as a JavaScript object in one array, and mapping and joining those rows then builds a second full copy as a string. Memory use grows linearly with the row count, and several admins exporting at the same time multiply it.

The process then hits the V8 heap limit or the container memory limit and restarts, taking every in-flight request with it. Raising --max-old-space-size moves the cliff; it does not remove it. The fix is to never hold more than a small window of rows.

What is backpressure in Node.js streams?

Backpressure is the signal a slow consumer sends upstream to make a fast producer pause. In Node.js, writable.write(chunk) returns false once the stream's internal buffer exceeds its highWaterMark, and the stream emits drain when the buffer empties. The default highWaterMark is 16 objects for object-mode streams and 64 KiB for byte streams in Node.js 22 and later (16 KiB before Node.js 22).

Postgres on a local network produces rows much faster than a browser on a weak connection downloads them. A loop that ignores the return value of res.write() does not crash; it queues every unsent chunk in memory, which is the same out-of-memory failure with extra steps.

A hand-written loop that awaits once(res, 'drain') after a false write has a bug. once(res, 'drain') never settles when the client disconnects mid-wait, because a closed socket emits close, not drain. The request handler hangs, and its database connection never returns to the pool.

Why should we use pipeline() instead of pipe()?

pipeline() from node:stream/promises handles backpressure, error propagation, and cleanup in one call. readable.pipe(writable) handles backpressure only: when the destination fails or closes, pipe() leaves the source stream open, and errors do not travel between the two streams. For a database-backed export, a source left open is a leaked connection.

• pipeline() returns a promise that rejects when any stream fails, including a client disconnect, which surfaces as ERR_STREAM_PREMATURE_CLOSE.

• pipeline() destroys every stream in the chain on failure, so the Postgres cursor closes when the browser tab closes.

• pipeline() accepts async generator functions as transform steps and { signal } as its last argument, so a row-to-CSV transform is a plain async function* and a deadline is AbortSignal.timeout().

How do we stream rows from Postgres to an HTTP response in NestJS?

We stream rows with pg-query-stream, the node-postgres companion package that exposes a query as an object-mode Readable backed by a Postgres cursor. The cursor fetches batchSize rows at a time, and only when the stream asks for more.

Our transform is an async generator named toCsv. toCsv first yields a UTF-8 byte order mark and the header line, then yields one CSV line per row. A csvCell helper turns null into an empty cell, formats Date values with toISOString(), doubles inner quotation marks, and wraps any value that contains a comma, a quotation mark, or a line break in quotation marks.

Our NestJS controller checks out one client with pool.connect(), creates a QueryStream with a batchSize of 500, sets the Content-Type and Content-Disposition headers, and awaits pipeline(rows, toCsv, res, { signal: AbortSignal.timeout(120_000) }). A finally block always calls client.release().

@Res() switches the NestJS handler into library-specific mode, so NestJS interceptors no longer shape that response and the handler owns the headers and the ending. NestJS also offers StreamableFile, which is simpler for sending a file that already exists; we call pipeline() directly because we want the rejection, the cleanup, and the abort signal in one place. Passing an error to client.release() tells node-postgres to destroy the connection instead of returning it to the pool, which we prefer after an aborted cursor.

What still goes wrong with a streamed CSV export?

A streamed CSV export fails in four places that the buffered version never reached.

• Errors after the first byte: the HTTP status line is sent with the first chunk, so a query failure halfway through the table cannot become a 500 response. pipeline() destroys the response and the browser reports a failed download. A failed download is the correct outcome, because ending the response quietly would deliver a truncated file that looks complete. We validate authorization and parameters before the pipeline starts, while a 4xx is still possible.

• The connection a slow download holds: the Postgres cursor keeps one pool connection and one transaction open for the entire download. A slow client makes the export slow, and a long-open transaction holds back vacuum cleanup of dead rows in Postgres. We cap the duration with AbortSignal.timeout() and limit concurrent exports so exports cannot drain the pool the rest of the API needs.

• Proxy buffering: nginx buffers proxied responses by default, which hides backpressure from Node.js and can spill large responses to temporary files on disk. Sending the X-Accel-Buffering: no header on the export response turns nginx buffering off for that response.

• Spreadsheet behaviour: Excel opens a UTF-8 CSV without a byte order mark in a legacy code page, which corrupts Arabic and other non-Latin text; a U+FEFF prefix fixes that. Excel and Google Sheets also evaluate cells that start with =, +, -, or @ as formulas, an attack known as CSV injection. Our csvCell helper prefixes string values that start with those characters with a single quote and leaves numbers alone, so negative totals stay numeric.

When should we stream, paginate, or move the export to a background job?

We choose the export strategy by how large the result can grow and how long a client may take to download it.

• Buffer the full result: memory grows with the row count and the query is short. Use buffering only when the export has a hard, small row cap.

• Keyset-paginated loop: memory stays at one page and the connection is released between pages, but each page sees a newer snapshot of the data. Use keyset pagination when the connection pooler or the workload cannot tolerate long transactions.

• Cursor stream with pg-query-stream: memory stays at one batch and the whole file comes from one snapshot, at the cost of one connection and one transaction for the whole download. Use a cursor stream for interactive exports with a bounded duration.

• Background job to object storage: memory stays at one batch and no HTTP request is held open. Use a background job for very large exports or slow, unreliable clients.

The cursor stream is our default for admin-panel exports. We move an export to a background job that writes to object storage and sends a download link when the export regularly runs into the pipeline deadline.

FAQ

Q: Does streaming make a CSV export faster?

A: Streaming makes the first byte arrive sooner and keeps memory flat. Total export time is still bounded by the Postgres query and the client's download speed.

Q: Can we use NestJS StreamableFile instead of @Res() and pipeline()?

A: Yes. StreamableFile accepts a Readable and keeps the handler in standard NestJS mode. We call pipeline() directly when the source holds a database connection, because we want explicit cleanup and a deadline.

Q: How do we stream a CSV from a Next.js Route Handler?

A: Convert the Node.js stream with Readable.toWeb() and return it as the body of a Response. A Next.js Route Handler on the Node.js runtime streams a web ReadableStream body to the client.

Q: Why does a CSV show garbled Arabic text in Excel?

A: Excel does not assume UTF-8 for a CSV file without a byte order mark. Writing U+FEFF as the first character of the file makes Excel read the file as UTF-8.

Q: How many rows justify streaming an export?

A: No fixed row count applies, because the limit depends on row width and the memory available to the process. We stream any export whose row count grows with customer data and has no hard cap.