AI & Architecture•8 min read

Building Streaming RAG Pipelines: OCR, Gemini Embeddings & MongoDB Vector Search

How to design a resilient Node.js transform stream pipeline to process 10,000+ scanned documents with Google Vision OCR, Gemini text embeddings, and MongoDB Atlas Vector Search.

Adil Shaikh
Adil ShaikhSoftware Developer & Product Engineer•March 15, 2026
Building Streaming RAG Pipelines: OCR, Gemini Embeddings & MongoDB Vector Search

Key Architectural Takeaways

  • Node.js Transform streams prevent OOM errors when processing thousands of heavy PDF documents concurrently.
  • Google Vision API OCR text must be cleaned and chunked using recursive sentence boundaries to maintain semantic context.
  • Embedding with text-embedding-004 and indexing in MongoDB Atlas Vector Search provides high-throughput cosine similarity retrieval.
  • Implementing exponential backoff and batch embeddings avoids LLM API throttling during large ingest jobs.

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:

01

OCR Stream

Google Vision API text detection stream with image downscaling.

02

Chunk Normalizer

Recursive semantic boundary splitting with 15% overlap.

03

Embeddings

Gemini text-embedding-004 batched with exponential backoff.

04

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:

DocumentTransformPipeline.ts
TypeScript / Node.js
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);
    }
  }
}

Benchmarks & Production Takeaways

Pipeline MetricNaive Batch ArrayStream Architecture
Peak Memory (10k docs)1.84 GB (OOM Crash)138 MB Flat
Throughput (Pages / min)120 pages/min840 pages/min
Mean Vector Query Latency120 ms38 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.

Related Technical Articles

View all articles