DEV Community

Aman gupta
Aman gupta

Posted on

Practical Patterns for Adding a RAG Pipeline to an Existing Node.js Backend

Most teams don't get to build a RAG (Retrieval-Augmented Generation) system from a blank slate. You already have a Node.js API, a Postgres database, auth, logging, and deploy pipelines - and now someone wants "an AI assistant that answers questions about our data." Here's what actually works when you bolt RAG onto an existing service, based on a few production integrations.

1. Don't let the vector store become a second source of truth

The easiest mistake is treating the vector database (pgvector, Pinecone, Qdrant, whatever) as an independent system you sync "eventually." It drifts. Documents get edited, deleted, or permission-scoped in your primary DB and the embeddings don't know it.

Instead, treat embedding generation as a side effect of your existing write path, not a separate pipeline:

async function saveDocument(doc) {
  const saved = await db.documents.upsert(doc);
  await enqueueEmbeddingJob(saved.id); // async, retryable
  return saved;
}
Enter fullscreen mode Exit fullscreen mode

If you're on Postgres already, pgvector keeps this in one transaction boundary conceptually, even if the embedding job itself runs out-of-band in a queue (BullMQ, pg-boss - anything you already run). This matters more than picking the "best" vector DB.

2. Chunking is a product decision, not a hyperparameter

Teams spend days tuning chunk size (500 tokens? 1000? overlap 10%?) when the real question is: what's the smallest unit of your data that answers a question on its own? For support tickets, that's a resolved thread. For a knowledge base, it's a heading section. For contracts, it's a clause.

Generic recursive text splitting works as a fallback, but if your data has natural structure (Markdown headings, DB rows, ticket threads), chunk along that structure first and only fall back to token-based splitting for oversized chunks. This alone fixes more retrieval quality issues than switching embedding models.

3. Retrieval is a ranking problem, not a similarity-search problem

Cosine similarity on embeddings gets you a candidate set, not an answer. In every production RAG system we've shipped, a reranking step (even a cheap cross-encoder, or just a second LLM call scoring relevance) made a bigger quality difference than swapping embedding models. A simple two-stage pipeline:

  1. Vector search top-K (K=20-50, cheap, approximate)
  2. Rerank down to top-N (N=3-5, more expensive, precise)

If latency budget allows, this is the single highest-leverage change you can make to answer quality.

4. Keep the LLM call stateless and the context assembly explicit

Resist building a framework. A RAG call in an existing Express/Nest service can be a plain function:

async function answerQuestion(question, userId) {
  const candidates = await vectorSearch(question, { scope: userId });
  const reranked = await rerank(question, candidates);
  const context = reranked.slice(0, 4).map(c => c.text).join('\n---\n');
  const prompt = buildPrompt(question, context);
  return llm.complete(prompt);
}
Enter fullscreen mode Exit fullscreen mode

No hidden agent loop, no implicit memory. When something looks wrong in production, you can log candidates, reranked, and prompt and see exactly why the model said what it said. This debuggability is worth more than any abstraction a RAG framework gives you, especially in the first 6 months of running it live.

5. Scope retrieval by permissions at query time, not index time

If your app has row-level security or per-tenant data, don't build a separate vector index per tenant unless scale forces it - you'll be maintaining N indexes forever. Instead, store the tenant/user/ACL fields as metadata on each embedded chunk and filter at query time:

SELECT * FROM document_chunks
WHERE tenant_id = $1
ORDER BY embedding <=> $2
LIMIT 20;
Enter fullscreen mode Exit fullscreen mode

This keeps your existing authorization model as the source of truth instead of duplicating it into the retrieval layer, which is where RAG security bugs actually come from in practice.

6. Evaluate with real questions before you ship, not after

Write down 20-30 real questions your users will actually ask, with what a correct answer looks like, before you start tuning. Re-run this fixed set every time you change chunking, the embedding model, or the prompt. Without this, "it feels better" is the only signal you have, and that's how teams end up tuning against vibes for weeks.

Takeaway

None of this requires a new framework or rewriting your backend. RAG fits into an existing Node.js service as: a side-effect on write, a queue worker for embeddings, a two-stage retrieve-then-rerank function, and metadata-scoped filtering reusing your existing auth model. The failure mode to avoid is treating RAG as its own application instead of a feature of the one you already have.


I'm Aman, a full-stack engineer working on StackVise, where we build custom software and AI/LLM integrations for teams. Happy to compare notes on RAG implementations - drop a comment.

Top comments (0)