Event-Driven and Real-Time RAG

Keep indexes current with change events and streams, for real-time RAG over fast-moving data.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 23 · Lesson 1 of 1 · Advanced

Event-Driven and Real-Time RAG

Keep indexes current with change events and streams, for real-time RAG over fast-moving data.

Nightly re-indexing is fine for a policy library, but not for support tickets, product prices, incident runbooks or chat messages that users expect the assistant to know about within minutes. Event-driven RAG keeps the index current by reacting to change events as they happen: a document is created, updated, re-permissioned or deleted, an event is published, and an indexing worker processes it. This lesson explains the pattern and builds an idempotent, ordered indexing consumer.

What you will learn

  • When real-time indexing is worth it, and the sources of change events
  • An event schema for document changes, including deletions and permission changes
  • How to build an idempotent, ordered indexing worker with version checks
  • How to consume events from Kafka, and how to monitor freshness

Prerequisites

Batch, incremental or real-time?

ApproachFreshnessComplexityGood for
Full batch re-indexHours to daysLowSmall, slow-changing corpora
Scheduled incremental syncMinutes to hoursMediumMost document repositories
Event-drivenSeconds to minutesHigherTickets, chats, catalogues, incidents, permission changes

Even with events, keep a scheduled reconciliation job that compares the source with the index. Events get lost; reconciliation catches what they miss.

Where events come from

  • Webhooks from SaaS tools (ticketing, wiki, CRM) when records change.
  • Change data capture (CDC) from databases, for example with Debezium streaming row changes into Kafka.
  • Storage notifications: object created or deleted events from S3, Azure Blob or Google Cloud Storage.
  • Change feeds polled from APIs (Microsoft Graph delta queries, Google Drive changes).
  • Application events your own services publish (an outbox table written in the same transaction as the business change).

Step 1: An event schema

Use one schema for every source. Events should identify the document and its version, not carry the whole content: the worker fetches the current content itself, which avoids processing stale payloads.

events.py
from dataclasses import dataclass
from typing import Literal

@dataclass(frozen=True)
class DocumentEvent:
    event_id: str                      # unique, for deduplication
    source: str                        # "helpdesk", "sharepoint-hr", ...
    doc_id: str                        # stable id in the source system
    action: Literal["upsert", "delete", "permissions_changed"]
    version: int                       # monotonically increasing per document (or a timestamp)
    occurred_at: str                   # ISO 8601, UTC

Step 2: An idempotent, ordered worker

Events can arrive twice, late or out of order. Three rules make processing safe:

  1. Deduplicate by event_id.
  2. Ignore stale events: if the index already holds a newer version, skip.
  3. Make every write replace: delete the document's chunks and insert the new ones under deterministic ids, so repeating an event gives the same result.
import sqlite3

class IndexState:
    """Tracks the version indexed for each document and the events already processed."""
    def __init__(self, path: str = "index_state.db"):
        self.db = sqlite3.connect(path)
        self.db.execute("CREATE TABLE IF NOT EXISTS docs (doc_key TEXT PRIMARY KEY, version INTEGER, deleted INTEGER)")
        self.db.execute("CREATE TABLE IF NOT EXISTS seen (event_id TEXT PRIMARY KEY)")

    def seen(self, event_id: str) -> bool:
        return self.db.execute("SELECT 1 FROM seen WHERE event_id = ?", (event_id,)).fetchone() is not None

    def version(self, doc_key: str) -> int:
        row = self.db.execute("SELECT version FROM docs WHERE doc_key = ?", (doc_key,)).fetchone()
        return row[0] if row else -1

    def mark_seen(self, event_id: str) -> None:
        self.db.execute("INSERT OR IGNORE INTO seen VALUES (?)", (event_id,))
        self.db.commit()

    def record(self, event: DocumentEvent, doc_key: str) -> None:
        self.db.execute("INSERT OR REPLACE INTO docs VALUES (?, ?, ?)",
                        (doc_key, event.version, int(event.action == "delete")))
        self.db.execute("INSERT OR IGNORE INTO seen VALUES (?)", (event.event_id,))
        self.db.commit()

def handle(event: DocumentEvent, state: IndexState, fetch, index_document, delete_document,
           update_permissions) -> str:
    """fetch/index/delete/update_permissions are your connector and index functions."""
    doc_key = f"{event.source}:{event.doc_id}"
    if state.seen(event.event_id):
        return "duplicate"
    if event.version < state.version(doc_key):
        state.mark_seen(event.event_id)
        return "stale"
    if event.action == "delete":
        delete_document(doc_key)
    elif event.action == "permissions_changed":
        update_permissions(doc_key, fetch(event.source, event.doc_id, permissions_only=True))
    else:
        document = fetch(event.source, event.doc_id)          # current content and access list
        if document is None:                                   # deleted since the event was sent
            delete_document(doc_key)
        else:
            index_document(doc_key, document)                  # delete old chunks, insert new ones
    state.record(event, doc_key)
    return "processed"

Permission changes deserve their own event type and the fastest path: a user who loses access to a document must stop retrieving it right away. Updating the allowed_groups metadata on existing chunks is much cheaper than re-embedding.

Step 3: Consume from Kafka

Kafka keeps events for each key in order within a partition. Using the document key as the message key therefore gives per-document ordering, while different documents are processed in parallel. Commit the offset only after processing succeeds:

pip install confluent-kafka
import json
import os

from confluent_kafka import Consumer

consumer = Consumer({
    "bootstrap.servers": os.environ["KAFKA_BOOTSTRAP"],
    "group.id": "rag-indexer",
    "auto.offset.reset": "earliest",
    "enable.auto.commit": False,                 # commit manually after successful processing
})
consumer.subscribe(["document-events"])
state = IndexState()

try:
    while True:
        msg = consumer.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            print("kafka error:", msg.error())
            continue
        event = DocumentEvent(**json.loads(msg.value()))
        try:
            result = handle(event, state, fetch, index_document, delete_document, update_permissions)
        except Exception as error:
            print(f"failed {event.event_id}: {error}")       # send to a dead-letter topic in production
            continue
        consumer.commit(message=msg, asynchronous=False)
finally:
    consumer.close()

The same worker logic runs on other queues (Amazon SQS, Azure Service Bus, Google Pub/Sub, Redis Streams); only the consume-and-acknowledge loop changes.

Step 4: Debounce bursts

A wiki page saved twenty times in five minutes should not be embedded twenty times. Buffer events per document for a short window and process only the latest version. Because events carry ids rather than content, processing only the last one is always correct.

Step 5: Measure freshness

  • Indexing lag: time from occurred_at to indexed, as a histogram per source. Alert when p95 exceeds your target.
  • Consumer lag: unprocessed messages in the topic.
  • Dead letters: events that failed repeatedly, with reasons.
  • Reconciliation drift: documents that differ between source and index at the nightly check.

Common errors and troubleshooting

  • Old content reappears: out-of-order events without a version check.
  • Duplicate chunks: random chunk ids; use deterministic ids from document key and chunk number.
  • Deleted documents still answered: delete events were not emitted or not handled; reconciliation catches these.
  • Embedding API rate limits during bursts: debounce, batch and bound worker concurrency.

Key takeaways

  • Event-driven indexing keeps RAG fresh within seconds or minutes for fast-changing sources.
  • Events carry ids and versions; workers fetch current content and process deletes and permission changes too.
  • Make processing idempotent and ordered: dedupe, version checks, replace-style writes, per-document partition keys.
  • Monitor indexing lag and keep a reconciliation job as a safety net.

Frequently asked questions

Do I need Kafka?

No. Any durable queue works. Kafka helps at high volume and when many consumers need the same change stream.

Can the LLM use real-time data without indexing it?

Yes, for data that changes every second (stock levels, live status), call an API as a tool at question time instead of indexing it (Agentic RAG).

Practice exercises

  1. Write a test that sends the same event twice and an older version after a newer one, and asserts the index is correct.
  2. Add a debounce buffer that processes each document at most once per 60 seconds.

Related tutorials