The Problem: Heavy Documents at Scale
Ingesting thousands of legacy scanned invoices, quotations, and bills of materials into a Retrieval Augmented Generation (RAG) system often breaks naive architectures. In our production environment, ingesting over 10,000 multi-page scanned PDFs caused standard memory buffers in Node.js to trigger frequent Out-Of-Memory (OOM) fatal crashes.
When you hold entire PDF documents and base64 strings in memory during synchronous extraction loops, garbage collection cannot keep pace. The solution is stream-based processing combined with backpressure control.
Key Architecture Takeaway
By switching from Promise.all() array batching to Node.js Transform streams with highWaterMark concurrency limits, memory consumption remained flat at under 140MB RSS across an entire 10,000+ document ingest pipeline.
Pipeline Architecture Overview
The end-to-end processing pipeline operates in four decoupled stream stages, maintaining rigorous backpressure between OCR extraction and vector database writes:
OCR Stream
Google Vision API text detection stream with image downscaling.
Chunk Normalizer
Recursive semantic boundary splitting with 15% overlap.
Embeddings
Gemini text-embedding-004 batched with exponential backoff.
Atlas Vector DB
Indexed in MongoDB Atlas Vector Search for sub-50ms retrieval.
Stream-Based Processing with Node.js
Here is the production implementation of our document transform stream. By piping raw file handles into isolated transform stages, the Node runtime regulates IO pace automatically:
import { Transform } from 'stream';
import { pipeline } from 'stream/promises';
export class DocumentChunkerStream extends Transform {
constructor(private chunkSize = 512, private overlap = 64) {
super({ objectMode: true, highWaterMark: 16 });
}
_transform(rawPage: { text: string; pageNumber: number; docId: string }, _, callback) {
try {
const chunks = this.splitIntoSemanticChunks(rawPage.text, this.chunkSize, this.overlap);
for (const chunk of chunks) {
this.push({
docId: rawPage.docId,
pageNumber: rawPage.pageNumber,
content: chunk,
});
}
callback();
} catch (err) {
callback(err as Error);
}
}
}Vector Storage & Indexing in MongoDB Atlas
MongoDB Atlas Vector Search allows co-locating transactional operational data with vector embeddings in the same cluster, eliminating synchronization overhead between Postgres and dedicated vector databases like Pinecone.
We created a dedicated vector search index definition targeting 768 dimensions (Gemini text-embedding-004 standard) with cosine similarity:
{
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 768,
"similarity": "cosine"
},
{
"type": "filter",
"path": "organizationId"
},
{
"type": "filter",
"path": "documentType"
}
]
}Benchmarks & Production Takeaways
| Pipeline Metric | Naive Batch Array | Stream Architecture |
|---|---|---|
| Peak Memory (10k docs) | 1.84 GB (OOM Crash) | 138 MB Flat |
| Throughput (Pages / min) | 120 pages/min | 840 pages/min |
| Mean Vector Query Latency | 120 ms | 38 ms (Cached) |
Frequently Asked Questions
Why use Node.js streams instead of batch array processing for document ingestion?
Transform streams ensure constant memory consumption regardless of input dataset size. Instead of holding thousands of parsed PDFs in RAM, chunks flow through OCR, normalization, and embedding generation with built-in backpressure.
How do you prevent MongoDB Atlas Vector Search from slowing down under load?
Create dedicated vector indexes with appropriate numDimensions matching the embedding model, pre-filter metadata with compound indexes, and cache hot semantic queries in Redis.

