Skip to main content
Node.js Intermediate Practical Coding Topic: Streams & Memory Safety

Explain Node.js Streams and handling backpressure safely with pipeline()

Quick Summary: Node.js Streams process large files or HTTP payloads in small chunks rather than buffering entire payloads in V8 heap; backpressure pauses fast readers when slow destinations fill up, managed safely with stream.promises.pipeline().

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

Reading a 1 GB file with fs.readFile() buffers the entire 1 GB inside RAM and risks crashing pods. A Stream chunks data (typically 64 KB) through Readable, Writable, Duplex, or Transform interfaces.

Backpressure occurs when a fast disk read feeds a slower network response socket; honoring internal buffer signals keeps heap memory bounded.

Detailed Technical Explanation

Prefer stream.promises.pipeline() over legacy readable.pipe(writable) because .pipe() does not automatically propagate error events or destroy upstream streams when a downstream socket aborts—leading to silent file-descriptor leaks.

Practical Walkthrough

Streaming gzip compression pipeline with automatic error cleanup.

Code Example — JAVASCRIPT
const { pipeline } = require("stream/promises");
const fs = require("fs");
const zlib = require("zlib");

async function compressAuditLog(src, dest) {
    await pipeline(
        fs.createReadStream(src),
        zlib.createGzip(),
        fs.createWriteStream(dest)
    );
}
Expected Output / Verification
Bounded ~64KB chunked RAM usage; upstream/downstream streams auto-destroy on error.

Real-World Production Use Case

Exporting 500,000-row billing CSV reports directly from PostgreSQL cursors to S3 or browser downloads inside 512 MB Kubernetes containers.

Common Interview Mistakes to Avoid

  • Using .pipe() chains in production without attaching error listeners to every stream segment.
  • Ignoring writable.write() returning false inside manual stream writers.
Topics: #nodejs #streams #backpressure #pipeline
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.