Real-time interaction with Redis Streams: a stream of session actions, a fast path for frame state and a slow path through the model

I first drew this real-time interaction system as a box diagram: a client, an API gateway, a character service, an environment service, a model service, and Redis Streams in the middle. The diagram looked tidy. Then I built a small version in Python against a real Redis, wrote tests for it, and found four things the diagram had taken for granted.

Here is the setup. A user moves a character around a scene, and some of the things they do go to a language model that decides how the character reacts. I used Redis 7.2.5 and redis-py 8.2.0 on Python 3.12. The model is a stand-in with fixed replies and fixed delays, so the timings below measure the plumbing, not any particular LLM.

Real-time interaction at 30 FPS needs two paths

The original requirement said every real-time interaction should run at 30+ FPS. That is 33 ms per frame. No language model answers in 33 ms, so the first design decision is to split the traffic.

  • Fast path: position and animation state. The client writes it straight into a Redis hash every frame, and the latest value wins. Nothing queues and nothing waits for a model.
  • Slow path: actions that need the model, such as talking to a guard. These go into a stream, a worker picks them up, and the reply comes back on a stream for that session.
def move(r, char_id, x, y):
    """Called every frame. No stream, no model: just the latest state."""
    r.hset(f"char:{char_id}", mapping={"x": x, "y": y, "t": time.time()})

Over 5,000 calls against a local Redis, move() took 0.14 ms at the median and 0.24 ms at p99. A real network adds to that, but there is still plenty of room inside a 33 ms frame.

The slow path is a different story. With the stand-in model set to 0.8 seconds, an action took 804 ms from XADD to reply at the median. In other words, Redis and the worker added about 4 ms, and the model took the rest. So for a smooth real-time interaction, the client should keep animating while it waits, for example by showing a “thinking” pose, instead of blocking the frame loop on the reply.

The slow path: a stream, a consumer group and a reply stream

Each action is one XADD. Workers in a consumer group read with XREADGROUP, call the model, and then write everything back in one transaction:

def send_action(r, session, char_id, text, shards=1, maxlen=10_000):
    payload = {"session": session, "char": char_id, "text": text}
    return r.xadd(stream_for(session, shards), payload, maxlen=maxlen, approximate=True)


def handle(r, msg_id, fields, model):
    reply = model(fields["text"])
    pipe = r.pipeline()  # MULTI/EXEC: state change, reply and ack land together
    pipe.hset(f"char:{fields['char']}", "mood", reply["mood"])
    pipe.hincrby(f"char:{fields['char']}", "actions", 1)
    pipe.xadd(f"replies:{fields['session']}", {"for": msg_id, "say": reply["say"]},
              maxlen=1000, approximate=True)
    pipe.xack(fields["_stream"], GROUP, msg_id)
    pipe.execute()

The transaction matters. If a worker dies before EXEC, none of the four writes happen and the entry stays unacknowledged. However, the model call runs before the transaction, so a retried entry calls the model again. That makes this at-least-once delivery, and anything the model triggers outside Redis has to be safe to repeat.

Problem 1: a consumer group can reorder one player’s actions

My diagram said Redis Streams “ensure ordered processing”. A stream is ordered, but a consumer group is not ordered in the way a game needs. It hands each entry to whichever consumer asks next, so two actions from the same player can run at the same time on two workers, and the quicker one finishes first.

To test it, each of eight sessions sent “open the door” (0.3 s in the model) and then “walk through it” (0.01 s). With four workers on one shared stream, all eight sessions got the reply to “walk” before the reply to “open”. The character walked through a closed door eight times out of eight.

The fix I chose is to shard by session. Each session always maps to the same stream, and each stream has exactly one worker, so a session’s actions run one after another:

def stream_for(session, shards):
    if shards == 1:
        return "actions"
    return f"actions:{zlib.crc32(session.encode()) % shards}"
SetupSessions with replies out of order
One shared stream, 4 workers8 of 8
4 streams, one worker each0 of 8

This has a cost. A slow model call now holds up every other session on the same shard, and a busy shard cannot borrow an idle worker. Two other options are a per-session lock, or sequence numbers that the client uses to reorder replies. I went with shards because they are the easiest to reason about, and I can add more of them as load grows.

Problem 2: a crashed worker’s entries don’t come back on their own

When a consumer reads an entry with XREADGROUP, Redis puts the entry in that consumer’s pending list until it is acknowledged. If the process dies, the entry stays there. Meanwhile, new workers reading with > only ever receive new entries, so nobody picks up the orphan.

I sent five actions and let a worker die right after it read the first one. Redis then showed one pending entry, owned by the dead consumer. A fresh worker produced four replies, and the pending count stayed at one. Only XAUTOCLAIM recovered it:

def reclaim(r, stream, name, model, min_idle_ms):
    """Take over entries another consumer read but never acked."""
    start, taken = "0-0", 0
    while True:
        start, entries, _deleted = r.xautoclaim(stream, GROUP, name, min_idle_ms, start, count=100)
        for msg_id, fields in entries:
            fields["_stream"] = stream
            handle(r, msg_id, fields, model)
            taken += 1
        if start == "0-0":
            return taken

After the claim there were five replies and zero pending entries. The setting that needs care is min_idle_ms. If it is shorter than your slowest model call, the rescuer takes an entry that a live worker is still working on, and the model runs twice. One of my tests checks the other side as well: with a 60-second idle limit, a fresh pending entry is left alone.

Problem 3: streams grow until you tell them not to

XADD without a cap keeps every entry forever. After 200,000 actions, the uncapped stream held 200,000 entries in 9,028 KB. With MAXLEN ~ 10000 it held 10,046 entries in 455 KB. The ~ lets Redis trim whole internal nodes, which is cheaper, so the count lands slightly above the cap.

Trimming also has a sharp edge. It deletes old entries even if a consumer has not acknowledged them yet. In my test the pending list still showed the entry after the trim, but XAUTOCLAIM returned its ID in the deleted list instead of the data. So set the cap far above how far behind your workers could ever fall, and log the deleted IDs that XAUTOCLAIM returns rather than ignoring them.

Problem 4: real-time interaction has two speeds

The fourth problem was in the requirements rather than the code. “30+ FPS for every interaction” mixes two different promises. In a real-time interaction system, the frame rate is a client rendering promise, and the fast path keeps it. The model path is a response-time promise, and with a real LLM it is measured in hundreds of milliseconds or seconds. Once I wrote those as two separate targets, the design questions became much easier to answer.

The real-time interaction design after testing

  • Frame-rate state goes to Redis hashes and never waits for the model.
  • Model actions go to streams sharded by session, with one worker per shard, so each player’s actions stay in order.
  • State change, reply and ack go out in one MULTI/EXEC, and side effects of the model call are safe to repeat.
  • A reclaim loop runs XAUTOCLAIM with an idle limit longer than the slowest model call.
  • Every XADD has an approximate MAXLEN, sized well above the worst backlog.

If the reply should stream back to a browser token by token, my post on FastAPI middleware and streaming responses covers the HTTP side. And if the “model” is really an agent with several steps, LangGraph persistence is a better place to keep its state between steps than a Redis hash.

Testing the real-time interaction system

Nine pytest tests run against a throwaway Redis on a spare port, and all nine pass. They cover:

  • move() keeps only the latest position and never touches a stream.
  • An action updates the character’s mood and counter, sends a reply and leaves nothing pending.
  • On one shared stream with four workers, “walk” finishes before “open”.
  • With sharding, the same two actions come back in order.
  • A session always maps to the same shard, and 100 sessions spread over all four shards.
  • A crashed worker’s entry is not seen by new workers until XAUTOCLAIM takes it.
  • XAUTOCLAIM leaves entries alone that are younger than the idle limit.
  • MAXLEN ~ 1000 keeps the stream between 1,000 and 1,200 entries.
  • Trimming can drop a pending entry, and XAUTOCLAIM reports it as deleted.

The Redis Streams guide explains consumer groups and pending entries well. Even so, reading about them didn’t show me the reordering problem. Running two actions through four workers did, on the first try.

Leave A comment

Are you human? Please solve:Captcha