Speculative RAG: prefetching and drafting to save time

Speculative RAG means two things: fetching likely follow-up documents in advance, or letting a small model write several drafts that a larger model checks. Use it when waiting time matters.

Speculative RAG in 60 seconds

  • Two meanings: the name covers two different ideas, and this page treats them separately.
  • Prefetching: predict likely follow-up questions and retrieve for them in the background into a short-lived cache.
  • Drafting: a smaller specialist model writes several drafts in parallel, each from a different subset of documents, and a larger model verifies them in one pass.
  • Reported results: the drafting paper reports accuracy gains of up to 12.97 percent and latency reduced by 50.83 percent on one benchmark, and results depend on the task.
  • Risk: wasted work when guesses miss, and extra moving parts to build and monitor.

Where this type fits

Speculative RAG is in the multi-step family, alongside adaptive, agentic, and branched retrieval. Its common thread is working ahead or in parallel to cut the time the user waits. See the overview of RAG types for the other families.

The problem it solves

A RAG request has a chain of steps, and each one waits for the last: embed the question, search, read the passages, write the answer. A long prompt full of passages is slow for a large model to read and then to answer from. When users ask follow-up questions in a chat, they wait through the whole chain again, even though the next question was easy to predict.

Think of a waiter. A poor waiter takes your order, walks to the kitchen, and only then starts. A good waiter notices that most tables order coffee after dessert, and has the cups warming already. Another way of saving time: a junior cook prepares several versions of a dish at once, and the head chef only tastes them and picks the best, instead of cooking from scratch. Both are speculation, but they work in different ways.

The first idea attacks waiting between turns. The second attacks the heavy work inside one turn: instead of one large model reading every document and writing one answer, a cheaper model does the bulk of the writing in parallel and the large one only judges.

Meaning one: prefetching

How prefetching works

  • Answer the current question as usual and show it to the user.
  • Predict follow-ups: while the user reads, a small model or a rule proposes the two or three most likely next questions, using the conversation so far and common paths in past logs.
  • Retrieve in the background: run the searches for those predicted questions and store the results in a short-lived cache, keyed by the normalised question and the user's permissions.
  • Match on arrival: when the next question comes in, compare it to the predictions, for example by embedding similarity above a high threshold.
  • Hit: use the cached passages and skip the search wait. Miss: run a normal search.
  • Expire: drop prefetched entries after a few minutes or when the topic changes.
Prefetching spends idle time on likely follow-ups and falls back to normal search on a miss.

The diagram makes the economics clear. Prefetching spends extra searches, some of which are never used, to save time on the ones that hit. It pays when searches are slow or costly to wait for and when follow-ups are predictable, as in guided support flows or step-by-step product tours. It is wasteful when conversations jump around.

A prefetching example

  • Turn one: a customer asks Acme's assistant, How do I export my invoices? The answer is shown within two seconds.
  • Prediction: while the customer reads, the predictor proposes: Can I export in CSV format?, How do I schedule a monthly export?, and Who can access exports?
  • Background retrieval: three searches run and the passages are cached for five minutes, tagged with the customer's account permissions.
  • Turn two: the customer asks, Can I get that as a spreadsheet file? Its embedding is close to the CSV prediction, so the cache is used.
  • Result: the answer arrives without a search wait. If the customer had instead asked about changing a password, the system would miss and search normally.
Prefetch cache with permission-aware keys (illustrative) (python)
# Placeholders: small_llm, embed(), vector_store, cosine(). Replace with your own.
import time

TTL_S = 300             # short life: follow-up context goes stale fast
MAX_PREDICTIONS = 3     # bound the wasted background work
MATCH_THRESHOLD = 0.88  # high on purpose: a wrong hit gives a wrong answer

_cache = {}             # (user_id, prediction_text) -> (expires_at, vector, passages)

def predict_followups(history):
    raw = small_llm.generate('List ' + str(MAX_PREDICTIONS) +
                             ' likely next questions, one per line:\n' + history)  # placeholder
    return [l.strip() for l in raw.splitlines() if l.strip()][:MAX_PREDICTIONS]

def prefetch(user_id, history):
    # Run this in a background task after the answer is sent, never before.
    for q in predict_followups(history):
        vec = embed(q)
        passages = vector_store.search(vec, k=5, filter={'user': user_id})  # placeholder
        _cache[(user_id, q)] = (time.time() + TTL_S, vec, passages)

def lookup(user_id, question):
    qvec, now = embed(question), time.time()
    for (uid, text), (exp, vec, passages) in list(_cache.items()):
        if uid != user_id:
            continue              # never serve another user's prefetched data
        if exp < now:
            del _cache[(uid, text)]
            continue
        if cosine(qvec, vec) >= MATCH_THRESHOLD:
            return passages
    return vector_store.search(qvec, k=5, filter={'user': user_id})   # miss: normal path

Meaning two: drafting

How drafting works

The second idea comes from Speculative RAG: Enhancing Retrieval Augmented Generation through Drafting (Wang et al., 2024, ICLR 2025). A smaller, distilled specialist model writes several drafts in parallel. Each draft is built from a distinct subset of the retrieved documents. A larger generalist model then verifies the drafts in a single pass, so it reads each short draft and its rationale instead of reading every full document and writing from scratch.

  • Retrieve: fetch a generous set of documents, for example twenty.
  • Cluster and sample: group the documents by topic, then form several subsets, each drawing from different groups so the drafts see diverse evidence.
  • Draft in parallel: the specialist writes one answer and a short rationale from each subset. Each prompt is short, so these calls are fast and run at the same time.
  • Verify once: the generalist scores all drafts in a single pass, judging how well each rationale supports its answer.
  • Select: return the draft with the best verification score.
Small parallel drafts replace one long prompt, and one verification pass picks the winner.

Why does this help? Long prompts are slow and can bury the key passage in noise. Splitting the evidence gives each draft a short, focused prompt, and running the drafts in parallel means total time depends on the slowest draft, not the sum. The large model's work shrinks to checking. The paper's abstract reports accuracy improvements of up to 12.97 percent and latency reduced by 50.83 percent compared with conventional RAG on the PubHealth benchmark. Those numbers belong to that paper, that benchmark, and its setup. Your results depend on the task, the models, and the documents, so measure on your own data.

A drafting example

  • Question: What are the side effects of Acme's drug X and when should a patient stop taking it? Twelve passages are retrieved from a clinical leaflet library.
  • Clusters: three groups form: side effects (five passages), dosage and timing (four passages), warnings (three passages).
  • Subsets: draft A uses two from side effects and one from warnings. Draft B uses two from dosage and two from warnings. Draft C uses three from side effects and one from dosage.
  • Drafts: A answers with common side effects and a warning to stop on severe rash. B answers about timing and stopping rules but misses the side effects. C lists side effects and omits stopping rules.
  • Verification: the generalist scores A highest because its rationale links both parts of the question to quoted passages. B and C score lower for incomplete coverage.
  • Output: draft A is returned with its citations.
Parallel drafts with one verification pass (illustrative) (python)
# Placeholders: specialist, generalist, cluster(), embed(), vector_store.
from concurrent.futures import ThreadPoolExecutor
import random

N_DOCS = 20          # retrieve generously, then split
N_DRAFTS = 4         # more drafts means more diversity and more cost
DOCS_PER_DRAFT = 3   # short prompts are what make drafting fast
DRAFT_TIMEOUT_S = 6

def make_subsets(docs):
    groups = cluster(docs)                      # placeholder: topic clusters
    subsets = []
    for _ in range(N_DRAFTS):
        picks = [random.choice(g) for g in groups][:DOCS_PER_DRAFT]  # one per cluster
        subsets.append(picks)
    return subsets

def draft(question, subset):
    ctx = '\n'.join(d.text for d in subset)
    out = specialist.generate('Answer and give a rationale.\n' + ctx + '\nQ: ' + question)
    return {'text': out, 'docs': subset}

def verify(question, drafts):
    # One pass: the larger model sees all short drafts together and scores each 0..1.
    listing = '\n'.join(str(i) + ': ' + d['text'] for i, d in enumerate(drafts))
    raw = generalist.generate('Score each draft 0 to 1 for support and completeness.\n'
                              + listing + '\nQ: ' + question + '\nReply as comma-separated numbers.')
    try:
        return [float(x) for x in raw.split(',')][:len(drafts)]
    except ValueError:
        return [0.0] * len(drafts)

def answer(question):
    docs = vector_store.search(embed(question), k=N_DOCS)
    with ThreadPoolExecutor(max_workers=N_DRAFTS) as pool:
        futures = [pool.submit(draft, question, s) for s in make_subsets(docs)]
        drafts = []
        for f in futures:
            try:
                drafts.append(f.result(timeout=DRAFT_TIMEOUT_S))
            except Exception:
                pass        # a slow or failed draft is simply dropped
    if not drafts:
        return 'I could not produce an answer.'
    scores = verify(question, drafts)
    return drafts[scores.index(max(scores))]['text']

Design decisions

  • Pick one meaning first: prefetching suits chat with predictable paths. Drafting suits single hard questions over many documents. Build the one that matches your bottleneck before considering both.
  • Cache key and scope (prefetching): key by user and permissions as well as text. A shared prefetch cache is an access control leak waiting to happen.
  • Expiry (prefetching): keep entries for minutes, and clear them when the topic changes or the underlying documents update.
  • Waste budget (prefetching): cap predictions per turn and run them at low priority so they never delay live requests.
  • Model split (drafting): use a small specialist for drafts and a larger model for verification. The saving comes from the large model reading short drafts instead of long contexts.
  • Parallelism (drafting): bound the draft count and set per-draft timeouts. Drop slow drafts rather than wait for them.
  • Failure handling: both designs must degrade to plain RAG if the speculative part fails.

Measuring it

  • Prefetch hit rate: the share of next questions served from prefetched passages. Low rates mean wasted work.
  • Wrong-hit rate: hits where the cached passages did not fit the question, found by human review of a sample. This is the dangerous failure.
  • Latency saved: median and 95th percentile time with and without speculation, on the same traffic.
  • Draft diversity and winner distribution (drafting): whether the verified winner comes from varied subsets, and whether any subset is always chosen.
  • Answer accuracy against plain RAG: correctness and faithfulness on your own labelled questions, since published gains depend on the task.
Prefetch hit-rate measurement (illustrative) (python)
def hit_rate(sessions):
    # sessions: list of (user_id, history, next_question) from real logs.
    hits = 0
    for user_id, history, nxt in sessions:
        prefetch(user_id, history)
        qvec = embed(nxt)
        matched = any(cosine(qvec, v) >= MATCH_THRESHOLD
                      for (uid, _), (_, v, _) in _cache.items() if uid == user_id)
        hits += matched
    return hits / len(sessions) if sessions else 0.0

When to use it, and when not to

SituationUse this type?Why
Chat flows with predictable follow-ups, such as guided supportPrefetchingPredictions often hit, so saved waiting is common.
Open-ended chat where topics jumpNot prefetchingHit rates fall and the background work is wasted.
Hard questions over many retrieved documentsDraftingShort parallel prompts can cut time and bring in varied evidence.
Very short answers from one passageNoA single pass is already fast; speculation adds cost.
Strict data permissions per userYes, with carePrefetch caches must be scoped to the user and expire quickly.
You cannot host or distil a specialist modelNot draftingThe design relies on a smaller model that is good at drafting.

Trade-offs

DimensionEffectWhat to do about it
QualityDrafting can raise accuracy by giving each draft focused evidence; a wrong prefetch hit can lower it.Measure on your data and use a high match threshold.
LatencyPrefetching removes search waits on hits; drafting shortens the large model's work.Compare percentiles with and without, not only averages.
CostPrefetching pays for unused searches; drafting pays for several small calls.Cap predictions and drafts, and compare total spend per answer.
ComplexityPredictors, caches, clustering, two models, and parallel execution.Build one meaning at a time and keep a plain fallback.
Failure modesStale or leaked cached data; a weak verifier that picks a poor draft.Scope and expire caches, and test the verifier on its own.

Adaptive RAG saves effort by choosing a lighter route for easy questions, while speculative RAG keeps the work but moves it earlier or runs it in parallel. RAG with memory supplies the conversation history that prefetching uses to predict follow-ups.

Branched RAG also runs parallel paths, but its branches are different interpretations or sub-questions that are merged, whereas drafting branches are alternative answers to the same question, from which one is selected. Agentic RAG works step by step and tends to be slower and less predictable than either speculative meaning.

What this means for your role

Common mistakes

Further reading

Speculative RAG helps when time is the constraint and the guesses are good. Pick the meaning that fits, measure honestly, and keep plain RAG ready as the fallback.

Search topics

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