Most LLM agents start as a single loop. You wire up one prompt with a list of tools, then let it read user messages while writing directly to your database.

In a quick demo, that setup feels great. Once real users start using it, the cracks show up fast. Responses get slow because the model has to sort through twenty tool definitions on each turn. Your token bill climbs because simple data entry is going through an expensive reasoning model. Worse, giving a probabilistic model direct write or delete access to your database means one strange prompt or bad argument can mess up real records.

Letting an LLM run unrestricted writes against your core data is a risky bet.

Command Query Responsibility Segregation (CQRS) is an old backend pattern, and it fits this problem well. When you separate writing data from reading and analyzing it, your agent runs faster and costs less. It also stays much safer around production state.


The Danger of the Monolithic Loop

Picture a simple expense tracking assistant in Slack. A team member types:

User: “I just spent €45 on dinner with clients.”

In a typical single-loop setup, that message goes straight to a heavy reasoning model with twenty tool schemas attached. You wait. Once it picks a tool and writes to the database, it runs another full model pass just to check the balance and write a reply.

Three annoying things happen here. First, the user sits there waiting through multiple round-trips just to save one row of text. Second, you are paying for a top-tier model to extract a number and a category, which is overkill. Third, because the agent has full write access, an ambiguous message or a weird prompt can easily turn a simple question into an accidental update or delete.


Applying CQRS to LLM Architectures

CQRS splits your application into two separate paths: Commands and Queries. Commands change state. Queries read stored data to answer questions without modifying the database.

For an LLM agent, this gives us a clean boundary between saving data and analyzing data.

CQRS Agent Architecture

The split matches the actual difficulty of each job. Logging an expense is mostly extraction and validation. You want that to be fast and predictable. Answering a question like “how much did we spend on client dinners last quarter?” is where you actually want the model’s reasoning and broader context. Keeping those two paths apart stops an exploratory read pass from ever touching your transaction log.


Redesigning the Assistant Workflow

To keep things simple, imagine we are just using an append-only spreadsheet or a PostgreSQL table as our transaction log. No need for complex infrastructure to see how this works.

1. The Write Pathway (Command)

When someone posts “I just spent €45 on dinner with clients.”:

  1. A lightweight router classifies the message as a command.
  2. A small, fast model extracts the structured fields: the amount and the category.
  3. The backend appends a new row with an ISO timestamp to the log.
  4. The bot replies right away: “Logged €45 under Dining.”

Notice what this path skips. It does not load months of history, and it does not evaluate twenty open-ended tools. It runs in tens of milliseconds. Because there are no update or delete endpoints exposed on this path, old records stay safe.

2. The Read Pathway (Query)

When someone asks “How much did I spend on dining out this month?”:

  1. The router marks the message as a query.
  2. The backend reads the relevant entries from the log.
  3. It passes those rows into the context of an analytical model.
  4. The model calculates the totals and summarizes the spending.

This path has no write endpoints. Even if the model hallucinates or goes down a strange reasoning path, it cannot alter a single row in the log.


Implementing the Separation

Here is a minimal Python sketch showing how clean that routing looks in code:

from typing import Dict, Any

def route_message(message: str) -> str:
    # Lightweight classifier returning "COMMAND" or "QUERY"
    ...

def handle_command(message: str) -> str:
    # 1. Parse entities with a fast utility model
    details = extract_expense_details(message)
    
    # 2. Append-only write to immutable ledger
    append_to_ledger(details)
    return f"Logged €{details['amount']} to {details['category']}."

def handle_query(message: str) -> str:
    # 1. Fetch raw records via read-only access
    raw_history = read_ledger()
    
    # 2. Allow analytical model to synthesize response
    return synthesize_report(message, raw_history)

def handle_slack_event(event: Dict[str, Any]):
    message = event["text"]
    intent = route_message(message)
    
    if intent == "COMMAND":
        return handle_command(message)
    elif intent == "QUERY":
        return handle_query(message)

Scaling Read Projections

The real payoff of CQRS shows up once your log grows from fifty rows to fifty thousand. At that point, dumping raw rows into a prompt stops working.

With CQRS, the write path stays untouched. New entries keep appending to the log quickly and cheaply. On the read side, background jobs can project that append-only log into whatever read model fits your queries best.

For numbers and aggregations, a background worker can sync entries into PostgreSQL or another SQL store. When someone asks for average monthly spend, your backend runs SELECT AVG(amount)... and hands only the final number to the model.

For semantic search, an embedding job can index descriptions into a vector store or a simple lexical index like TF-IDF. Queries about specific purchases pull only the matching rows into the prompt.

For relational questions across vendors or projects, a projection can feed a graph database to surface those links without touching the write log.

CQRS Event-Sourced Agent Architecture

System Pattern
Entry Point

User Message → Deterministic Router

Classifies incoming intent upfront so state mutations stay isolated from analytical reads.

↙ Command (Write Path)
↘ Query (Read Path)
Write Pipeline & Event Store
  • Extraction: Lightweight model parses structured payload
  • Persistence: Append-only immutable event store
  • Isolation: No update or delete endpoints exposed
Read Pipeline & Synthesis
  • Context: Fetches pre-computed projections only
  • Reasoning: Analytical model synthesizes reports
  • Safety: Read-only access, separated from the core transaction log
↓
Async Read Projections from Event Store

Vector Store

Semantic similarity lookups for relevant entries

SQL DB

Exact aggregates (SUM, AVG) before model synthesis

Graph DB

Multi-vendor and relational dependency queries

Treating the write log as the source of truth means you can rebuild or throw away read models anytime without risking your core data.


Open Trade-Offs and Where I’m Still Testing This

Language models are great at reasoning and summarizing, but they are a poor fit for managing database state directly. Keeping append-only writes separate from read-only queries makes latency more predictable and lowers token costs. Your core data also stays safe from accidental mutations.

That said, splitting the paths introduces its own edge cases, and I am still testing where the boundary gets messy in practice.

The first tricky case is mixed intent. People rarely speak in clean commands or clean queries. Someone might type “I just spent €45 on dinner, how much is left in our team budget this month?” If the router only picks one branch, you either miss the write or skip the answer. Right now, I lean toward splitting compound messages into two independent tasks at the router level, or asking a quick confirmation before writing, though both add a bit of complexity to maintain.

The second open question is handling corrections without breaking the append-only rule. Users make typos. If someone logs €45 and five minutes later says “actually that dinner was €54”, an append-only log handles it with a compensating reversal entry rather than an UPDATE. That keeps the audit trail intact, yet it makes read projections slightly more complex to keep accurate.

How are you handling write safety and mixed-intent messages in your own agent workflows? I would be curious to compare notes on where you draw the line between deterministic routing and letting the model decide.