Modular RAG: swappable parts with fixed interfaces

Modular RAG splits a pipeline into parts such as a rewriter, retriever, reranker, generator, and checker, joined by fixed interfaces. Use it when many teams or many use cases share one system.

Modular RAG in 60 seconds

  • What: a RAG system made of independent modules with fixed input and output shapes, connected by a flow you can change.
  • Four flow patterns: linear, conditional, branching, and looping, as named in the research that introduced the term.
  • Why it helps: you can swap, test, and measure each module on its own, and different use cases can share the same parts.
  • Costs: upfront design, interface discipline, and an orchestration layer to maintain.
  • Best for: platforms serving several products, teams that iterate often, and systems where parts change at different speeds.

Where this type fits

Modular RAG sits in the structure-or-media family, alongside graph RAG, multimodal RAG, and vectorless RAG. It differs from the others in one respect: it describes how the system is organised, not what kind of data it reads. It is also less a single technique than a way of building any of the others. The overview of RAG types shows the full list.

The term comes from a widely cited survey (Gao et al., 2023), which groups RAG into Naive, Advanced, and Modular paradigms. A later paper (Gao et al., 2024) develops the idea: it breaks RAG into independent modules and operators, and identifies four flow patterns, which are linear, conditional, branching, and looping. In practice, the idea reduces to a simple rule: fixed interfaces between a rewriter, a retriever, a reranker, a generator, and a checker, so that each can be swapped and measured.

The problem it solves

Pipelines grow. A team begins with simple RAG, adds a reranker, then a rewriter, then a verification step, then a special path for questions about prices. After a year, the code is one long function where every stage knows how the others behave. Swapping the reranker means touching the retriever's output format. Testing the generator needs the whole system running. A change that helps one product quietly breaks another.

This is a familiar software problem, solved by familiar means: define interfaces, hide implementation behind them, and compose. Modular RAG applies that to retrieval systems. Each module promises a shape of input and a shape of output. If a new reranker keeps the promise, nothing else needs to change.

The second problem is variety. A support bot, an internal policy search, and a sales assistant all need retrieval, but not the same retrieval. One needs strict citations, another needs speed, another needs access to a product database. Without modules, each product becomes its own fork. With modules, each product is a different arrangement of shared parts.

How it works

  • Define module contracts: each module has a typed input and a typed output. For example, a retriever takes a query and filters and returns a list of passages with ids, text, scores, and metadata.
  • Build or choose implementations: several implementations can satisfy one contract, such as keyword, vector, or hybrid retrievers.
  • Describe the flow as configuration: a flow definition lists modules and the order or conditions that connect them, kept outside module code.
  • Run through an orchestrator: a small engine reads the flow, calls each module, passes outputs along, and enforces budgets and timeouts.
  • Trace every module: record each module's input, output, version, time, and cost under one request id.
  • Swap and compare: change one module or one flow line, run the same evaluation set, and compare.
Fixed slots with swappable parts, so one module can change without touching the rest.

The four patterns cover most real designs. A linear flow runs the modules in a fixed order, which is how advanced RAG usually runs. A conditional flow sends a request down one of several routes based on a decision, such as skipping retrieval for a greeting, which is the idea behind adaptive RAG. A branching flow runs several paths in parallel and merges the results, as in branched RAG. A looping flow repeats a step until a condition is met or a limit is reached, as in agentic RAG and corrective RAG.

Seen this way, several other types on this site are particular flows over a shared set of modules. That is the strongest argument for the approach: the investment in good interfaces pays back every time you try another type.

A worked example

Acme runs one RAG platform for two products. The support bot needs cited answers. The sales assistant needs quick answers and a product price lookup. Both use the same module library.

  • Module library: rewriter, hybrid_retriever, vector_retriever, reranker_small, reranker_large, generator, checker, price_lookup.
  • Support flow (linear plus loop): rewriter, then hybrid_retriever, then reranker_large, then generator, then checker. If the checker fails, loop back to generator once, then decline.
  • Sales flow (conditional): a router sends price questions to price_lookup, and everything else through vector_retriever, reranker_small, and generator, with no checker, for speed.
  • A change request: the ML team wants to try a new reranker. They add reranker_v3 that honours the same contract, change one line in the support flow, and run the evaluation set. Recall at 4 rises on support questions, so it ships. The sales flow is untouched.
  • A rollback: two weeks later the traces show higher latency. The flow line is reverted. No module code changes.
Two flows over the same modules, as configuration (illustrative) (python)
flows = {
    'support': {
        'steps': ['rewriter', 'hybrid_retriever', 'reranker_large', 'generator', 'checker'],
        'loop': {'from': 'checker', 'to': 'generator', 'max_times': 1},
        'budget': {'max_model_calls': 5, 'timeout_seconds': 30},
    },
    'sales': {
        'route': {'price_question': ['price_lookup', 'generator'],
                  'default': ['vector_retriever', 'reranker_small', 'generator']},
        'budget': {'max_model_calls': 2, 'timeout_seconds': 10},
    },
}

The configuration is small on purpose. If a flow needs a long program to describe it, the modules are probably too tangled, or the flow is trying to be an agent. See orchestrator types for that boundary.

Building it

The code below shows the bones: a shared request context, a registry of modules that follow one call signature, and a runner that executes a linear flow with a traced loop. embed(), vector_store, and llm are placeholders, and the module bodies are minimal on purpose.

A minimal module registry and flow runner (illustrative) (python)
# Illustrative only. Module bodies call placeholders: embed(), vector_store, llm.
import time

REGISTRY = {}


def module(name, version):
    def register(fn):
        REGISTRY[name] = {'fn': fn, 'version': version}
        return fn
    return register


# Contract: every module takes a context dict and returns a dict of updates.
# Keys used: question, passages, answer, check_ok, user.

@module('vector_retriever', 'v1')
def vector_retriever(ctx):
    hits = vector_store.search(embed(ctx['question']), top_k=20,
                               filter={'audience': ctx['user'].allowed_audiences})
    return {'passages': hits}


@module('generator', 'v1')
def generator(ctx):
    return {'answer': llm.generate(ctx['question'], ctx['passages'])}  # placeholder


@module('checker', 'v1')
def checker(ctx):
    return {'check_ok': check_support(ctx['answer'], ctx['passages'])}  # placeholder


def run_flow(steps, ctx, max_model_calls=5, max_loops=1):
    trace, calls, loops, i = [], 0, 0, 0
    while i < len(steps):
        name = steps[i]
        entry = REGISTRY[name]
        started = time.time()
        ctx.update(entry['fn'](ctx))   # modules only add keys, never edit others
        calls += 1
        trace.append({'module': name, 'version': entry['version'],
                      'seconds': round(time.time() - started, 3)})
        if calls >= max_model_calls:   # hard stop on cost
            break
        if name == 'checker' and not ctx.get('check_ok') and loops < max_loops:
            loops += 1
            i = steps.index('generator')   # loop back, but only max_loops times
            continue
        i += 1
    return ctx, trace

Notice the call limit and the loop limit. A flow definition makes loops easy to write and, therefore, easy to write wrongly. Budgets belong in the runner, where no individual flow can forget them.

Design decisions

  • Contract granularity: define contracts at the level of rewriter, retriever, reranker, compressor, generator, and checker. Finer contracts add overhead, and coarser ones lose the benefit. Default: start coarse and split when a part changes at a different pace.
  • Data shapes: use one passage record (id, text, score, source, version, permissions) across all modules. A shared shape is what makes swapping cheap.
  • Flow as configuration: store flows in version control, review them like code, and reference module versions explicitly. Roll out a flow change to a small share of traffic first.
  • Orchestration: use a small purpose-built runner or an existing workflow engine. Keep it simple, with budgets, timeouts, and tracing built in. See orchestrator types.
  • Access control: enforce permissions inside retriever modules and carry the user's scope in the context. No module should be able to bypass it, and the runner should refuse a flow that has no permission-aware retriever.
  • Failure handling: each module declares a fallback: skip, use a default, or fail the flow. The runner applies it uniformly, so a slow reranker never takes the whole system down.
  • Tracing and cost: record module name, version, latency, and tokens per call under one request id, so you can attribute cost and quality changes to a specific module version. See evaluation and observability.

Measuring it

  • Per-module quality: measure each module against its own labelled set: recall at k for retrievers, ranking quality for rerankers, faithfulness for generators, and agreement with human labels for checkers.
  • Swap comparison: when replacing a module, run old and new on the same evaluation set and report the change in the module's metric and in end-to-end correctness.
  • Flow-level ablation: disable one module at a time and measure the drop. A module with no measurable effect is a candidate for removal.
  • Latency and cost per module: from traces, compute the median and 95th percentile time and the tokens per module. Look for the module that dominates.
  • Interface violations: count requests where a module returned data outside its contract, such as missing ids or empty text. These are early signs of silent breakage.
Compare two implementations of one module (illustrative) (python)
# test_set: list of {'question': str, 'source_id': str} (placeholder data)
# retriever(question) returns ranked passage ids (placeholder)

def compare_retrievers(test_set, old, new, k=4):
    def recall(retriever):
        hits = sum(1 for c in test_set if c['source_id'] in retriever(c['question'])[:k])
        return hits / len(test_set)
    return {'old': recall(old), 'new': recall(new)}

When to use it, and when not to

SituationUse this type?Why
One platform serving several productsYesShared modules avoid forks, and each product gets its own flow.
Frequent experiments with rerankers, retrievers, or promptsYesFixed interfaces make swaps cheap and measurable.
Several teams own different parts of the pipelineYesContracts let teams work without breaking each other.
Single product with a stable, small pipelineNoInterfaces and an orchestrator add work you may never use.
Early prototype still finding its shapeNot yetBuild simple RAG first, and extract modules when patterns settle.
Open-ended tasks needing dynamic tool choiceNot aloneUse agentic RAG for decisions, and modules for the parts.
Strict audit needs on each stepYesPer-module traces and versions give a clean record.

Trade-offs

DimensionEffectWhat to do about it
QualityDoes not raise quality by itself. It makes quality work faster to test and safer to ship.Pair it with an evaluation set, so swaps are decided by data.
LatencyA small overhead from the runner, and flows can accumulate steps.Set a latency budget per flow, and trace each module.
CostHigher upfront engineering cost, lower cost of change later.Introduce modules when the second use case or the third experiment appears.
ComplexityMore concepts: contracts, registry, flows, orchestrator.Keep contracts few and boring, and keep flows short.
Failure modesContract drift, flows that grow into hidden programs, and version mismatch between modules and indexes.Validate module outputs, review flow changes like code, and pin versions together.

Advanced RAG is a specific set of stages in a fixed order. Modular RAG is the structure that lets you assemble that set, or any other, from interchangeable parts. Adaptive RAG is a conditional flow where a classifier picks the route, so it fits naturally inside a modular system. Agentic RAG lets a model decide the next step at run time, while modular RAG usually keeps the flow predefined, which makes behaviour easier to predict and test.

What this means for your role

Common mistakes

Further reading

Modular RAG is a way of building, and it earns its keep when change is frequent. Fix the interfaces, trace every module, and let data decide which parts to swap.

Search topics

↑↓ to move · Enter to open · Esc to close