Kafka for AI
Keep a RAG index up to date from change events, and score transactions for fraud as they arrive on a Kafka topic.
A model is only as current as the data in front of it. Rebuilding a search index overnight means the policy that changed this morning is invisible until tomorrow. Scoring a payment in a batch means the fraud decision arrives after the payment has gone. Kafka is already the path those changes take. This lab hangs two consumers off it.
One consumer updates the RAG index when a document changes. The other scores a payment as the record arrives. Both are ordinary consumer groups. The model servers are the NIMs from the NeMo series, or Triton if you got here from TensorRT-LLM.
Prerequisites
- Change events on a topic, from Debezium or from the application
- The embedding NIM from Retriever, and a vector index such as pgvector or Milvus
- A fraud model with an HTTP endpoint that accepts one transaction and returns a score
- The idempotent-consumer habit from delivery guarantees
Fresh passages
A document service writes an outbox row when a policy page is published. The payload carries the document id and the text, or the id alone if the consumer should read the text from the source. Prefer the id plus a version when the text is large. The consumer then:
- Reads the current text for that id.
- Chunks it the same way the original index build did. A different chunk size here and in the batch build gives two answers for one question.
- Embeds the chunks with
input_type: passage. - Upserts by chunk id, and deletes chunks that belong to a version this event replaced.
def handle(event):
text = documents.fetch(event["id"], event["version"])
chunks = chunk(text, size=600, overlap=80)
vectors = embed(chunks, input_type="passage")
index.upsert(event["id"], event["version"], chunks, vectors)
index.delete_older_than(event["id"], event["version"])
upsert keyed by document id and chunk ordinal makes a redelivered event harmless. delete_older_than stops a reindex from leaving last quarter's paragraph in the index beside this quarter's. Commit the Kafka offset after both calls succeed. If you commit between them, a crash leaves old chunks in place and the consumer will not come back for them.
The RAG lab is the query side of this index. It does not need to know Kafka exists. It reads whatever the index holds now. That split is why the index can be rebuilt from the topic: retain the document events for as long as you are willing to replay, which is a retention decision in topic design.
A delete is an event too. Publish DocumentRemoved and have handle drop every chunk for that id. A stream that only upserts grows forever.
Score the payment in the path
The fraud consumer is a second group on payments. It does not share a group with posting. Each group has its own offset, so a slow model does not delay the ledger, and a slow ledger does not delay the score.
def score(payment):
features = {
"account": payment["account"],
"amount": payment["amount"],
"five_minute_total": totals.latest(payment["account"]),
}
decision = model.score(features) # HTTP to NIM, vLLM or Triton
if decision["action"] == "review":
reviews.publish(payment["account"], decision)
five_minute_total is the aggregate from stream processing. The model sees the same feature in the request that it saw in training, because both read payment-totals. A feature computed one way offline and another way in this function will look like a bad model.
Write the decision to a payment-reviews topic rather than blocking the original consumer on a human. The posting consumer stays idempotent on payment id. A review decision is allowed to post and flag, or to wait, and that is a product rule. The stream's job is to make the decision available while the payment is still recent. Record the model name and the feature values on the decision record. You will need them when a reviewer asks why.
Call the model with a timeout. On timeout, produce to payment-reviews with action=unknown and commit, or send the payment to the dead-letter topic after the retries you configured. Stopping the partition because the model pod restarted will back up every account that hashed onto it.
Two groups, one topic
| Group | Reads | Writes | Must stay fast because |
|---|---|---|---|
indexing |
document outbox | vector index | Stale answers in the chatbot |
fraud |
payments |
payment-reviews |
The decision is only useful before the payment settles |
posting |
payments |
the ledger | This one moves money, and it must stay idempotent |
Do not put the model call inside the posting transaction. A model outage would then stop posting, and a posting change would be coupled to a model release. Two groups keep those failures apart. Lag on each group is a separate alert in monitoring.
See that the index moved
Publish one document change, then ask the index for that document id before you ask the chatbot anything. The chunk version should match the event. Ask a question you know that paragraph answers, and confirm the retrieved passage id is the new one. Then publish DocumentRemoved and confirm the id is gone. A chatbot answer that still quotes the deleted paragraph means the delete path did not run, or the query cache is holding the old retrieval. Fix that before you tune the model.
For fraud, produce a payment you can compute the five-minute total for by hand, and compare decision with a direct call to the model endpoint using the same features. If they differ, the consumer is not sending the features you think. If they match, the path is honest, and the remaining question is whether the model is any good, which is Evaluator's job for a model you fine-tuned and a business question for a model you were given.
oc exec -n kafka lab-broker-0 -- bin/kafka-consumer-groups.sh \
--bootstrap-server lab-kafka-bootstrap:9092 --describe --group fraud
oc exec -n kafka lab-broker-0 -- bin/kafka-consumer-groups.sh \
--bootstrap-server lab-kafka-bootstrap:9092 --describe --group indexing
Lag on fraud during a model restart should fall once the NIM is Ready. Lag that stays on one partition is a record the consumer is not committing, and the dead-letter topic is where that record should have gone.
What's next
- The embedding call is the passage path in Retriever.
- The five-minute total is the Kafka Streams job in stream processing.
- Guard the chatbot that reads this index with Guardrails.