<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aditya Singh on Medium]]></title>
        <description><![CDATA[Stories by Aditya Singh on Medium]]></description>
        <link>https://medium.com/@singh.aditya3190?source=rss-76455277e6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ORqBPDDPdlnGYN50.jpg</url>
            <title>Stories by Aditya Singh on Medium</title>
            <link>https://medium.com/@singh.aditya3190?source=rss-76455277e6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:29:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@singh.aditya3190/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Resumable Real-Time LLM Streaming with Redis Streams]]></title>
            <link>https://engg.glance.com/building-resumable-real-time-llm-streaming-with-redis-streams-09cfa9e79358?source=rss-76455277e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/09cfa9e79358</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Aditya Singh]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 09:40:31 GMT</pubDate>
            <atom:updated>2026-09-03T09:40:31.144Z</atom:updated>
            <content:encoded><![CDATA[<p>A user asks an agent something that takes real work to answer. It reasons about the request, loads a skill, calls a tool, waits on the result, calls another, and eventually produces something worth putting on screen. Tens of seconds can go by while a connection stays open and events trickle down as they happen.</p><p>This works beautifully in a demo. Then production happens. Networks drop mid-answer. Gateway pods get redeployed. A tool hands work to another pipeline that may not reply for another minute.</p><p>At first, these looked like separate problems. They were really one design problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kAsWaLjctqt-ic1h-INCA.png" /></figure><h3>What We Wanted</h3><p>Four constraints shaped the design.</p><ol><li><strong>Server-side streaming.</strong> A turn is not one response. It emits events over tens of seconds: tool selections, tool results, progress updates, and the final answer. The client needs to show motion throughout.</li><li><strong>Resumption at turn granularity.</strong> Our clients live on consumer networks. If one drops mid-turn, it should reconnect and continue <em>where it left off </em>without restarting or losing events.</li><li><strong>No topology coupling.</strong> The gateway should not need to know <em>which</em> agent instance is executing a turn. Any gateway pod should be able to serve any turn.</li><li><strong>Survival across deploys.</strong> A rollout should not sever every in-flight turn. Events cannot live only inside a process that may disappear, and reconnecting cannot depend on reaching the machine that started the turn.</li></ol><p>Constraint 2 turned out to be the important one. It sounds like a streaming requirement, but it is really about <strong>addressability</strong>.</p><blockquote><em>Give me this turn’s events from position N onward.</em></blockquote><p>That requires a name for the turn and a cursor within it. Many streaming transports don’t naturally expose both at the granularity we needed: one turn.</p><h3>The Journey: What We Tried, What Broke, What Worked</h3><h3>Iteration 1: Let the client talk to the agent directly</h3><p>The first version was the obvious one: no gateway. The client opened an SSE connection directly to the agent service, and events flowed back over it.</p><p><strong>What broke:</strong> everything a client needs that isn’t inference started piling up inside the inference service.</p><p>Auth. Rate limiting. Session history. Analytics. Response shaping was the straw that broke the camel’s back.</p><p>The agent and the client don’t necessarily speak the same language. The agent might emit a generic event such as a tool result or a completed response block, while different surfaces may need to render that result differently. We wanted that translation to happen at the gateway, not inside the agent. Otherwise, a UI contract change on TV, mobile, or another surface could require changing and redeploying the agent itself.</p><pre>// Agent output<br>{<br>  &quot;type&quot;: &quot;tool_result&quot;,<br>  &quot;tool&quot;: &quot;product_search&quot;,<br>  &quot;data&quot;: {<br>    &quot;items&quot;: [...]<br>  }<br>}<br><br>// Gateway -&gt; TV<br>{<br>  &quot;type&quot;: &quot;product_carousel&quot;,<br>  &quot;items&quot;: [...]<br>}<br><br>// Gateway -&gt; Mobile<br>{<br>  &quot;type&quot;: &quot;product_list&quot;,<br>  &quot;items&quot;: [...]<br>}</pre><p>So we split the system. The <strong>agent service</strong> owns the LLM loop, skills, tools, memory, guardrails, and persistence. A <strong>gateway</strong> owns auth, limits, history, analytics, and client-format translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVJlIon0YOq9sZN09-jn8g.png" /></figure><p>That immediately created the real question:</p><p><strong>How does the agent service stream a turn’s events to the gateway?</strong></p><h3>Iteration 2: gRPC Streaming Between the Two Services</h3><p>gRPC streaming was the obvious candidate. For service-to-service communication, it looks ideal: a direct hop, binary framing, low latency, and no intermediary store.</p><p>But it had one fundamental property that conflicted with our requirements: <strong>the turn lived inside the connection.</strong></p><p>Events existed only while passing through that connection. If it disappeared, the delivery and recovery path disappeared with it. The agent loop might continue running, but the gateway had no way to ask for what it missed.</p><p>A dropped connection, a replaced pod, and a slow tool look different operationally, but they expose the same flaw.</p><p><strong>A gRPC stream is a pipe, and we needed a buffer.</strong> A pipe has no memory. You cannot ask it for “everything after event 47.” To support reconnect, we would need replay storage alongside the stream.Once that store exists and is addressable by turn, though, the obvious question is: <strong>why not read from it the first time too?</strong></p><p>Both the initial connection and a reconnect are fundamentally making that same request.Keeping gRPC would still buy lower delivery latency, flow control, and backpressure. But it would also leave us with two paths. Every event would travel live over gRPC and also into replay storage.</p><p>Then we would have to decide which copy is authoritative, what happens when an event reaches one path but not the other, and how a reconnect splices replayed history onto the live stream without gaps or duplicates.</p><p>Constraint 3 broke separately. A gRPC stream belongs to a connection, and that connection belongs to one agent pod. The gateway would have to know, discover, or remain sticky-routed to the pod executing each turn.</p><p>That puts internal topology on the critical path of every reconnect.So the real comparison was never gRPC versus a shared log. It was <strong>gRPC + replay storage + pod-affinity routing versus a shared log.</strong>Framed that way, a few milliseconds of transport latency stopped deciding the architecture.</p><h3>Why Not Kafka?</h3><p>The natural next idea was Kafka. We already run it, and it gives us durability and replay. On paper, that sounds exactly right.</p><blockquote><strong>In a partitioned log, the addressable unit is the partition.<br>Our unit of resumption is the turn.</strong></blockquote><p>Kafka offsets belong to partitions. Native per-turn addressing would imply something like one partition per turn, which is not practical: turns are created continuously and usually live for seconds.Interleave many turns across shared partitions instead, and resumption becomes:</p><blockquote><strong><em>Seek to an offset, then scan forward and filter for this turn ID.</em></strong></blockquote><p>You can build the indexing and bookkeeping for that, and plenty of systems do. But then you are building the per-turn addressability the transport did not give you.That was the important realization. The requirement was never simply “durable and replayable.” It was <strong>addressable at turn granularity.</strong></p><h3>Iteration 3 (What Worked): A named rendezvous per turn</h3><p>The design that satisfied all four constraints changed one assumption.</p><p><strong>The agent service does not stream to the gateway at all.</strong> It writes to a Redis Stream named after the turn, and the gateway reads from that name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4edB1XMiXKnJH4q9.png" /><figcaption>A live turn, a reconnect, and a turn suspended across two processes.</figcaption></figure><p>The gateway generates a turn_id, sends it with the request, and receives a bare <strong>202 Accepted</strong> — an acknowledgement rather than a response.</p><p>The agent starts its loop asynchronously and appends each event to that Redis Stream. Meanwhile, the gateway blocks on a read against the same key and relays events onto the client’s SSE connection.</p><p>The relay, simplified and minus error handling:</p><pre>cursor = last_event_id or &quot;0-0&quot;<br><br>while True:<br>    entries = xread({key: cursor}, block=30_000)<br><br>    if not entries:          # the only timeout check point<br>        check_timeouts()<br>        continue<br><br>    for entry_id, event in entries:<br>        # writes to the socket; not an ack that the client received it<br>        sse.send(id=entry_id, data=event.payload)<br>        cursor = entry_id<br>        if event.type in TERMINAL:<br>            return</pre><p>There is no long-lived connection between the two services and no shared knowledge of which pod is doing what.Both services know one string: <strong>the turn ID.</strong></p><h3>Making It Work: The Details That Mattered</h3><p>A few details turned that shape into something that survives production.</p><p><strong>The reader mints the turn ID, not the writer.</strong> It is tempting to let the agent create the ID and return it, but the ID <em>is</em> the address.</p><p>The side that has to listen needs to know where to listen before anything can be written. Otherwise every turn begins with a race between the first event being written and the reader learning where to look.</p><p>Cursors then come almost for free. Every Redis Stream entry already gets an ordered ID, and that becomes the only cursor in the system.</p><p>Going out over SSE:</p><pre>id: 1755600000123-0<br>data: {&quot;type&quot;:&quot;tool_selected&quot;,&quot;tool&quot;:&quot;search&quot;}<br><br>id: 1755600000871-0<br>data: {&quot;type&quot;:&quot;response_block&quot;,&quot;block&quot;:{...}}</pre><p>Coming back in:</p><pre>GET /sessions/{sid}/turns/{tid}/stream<br>Last-Event-ID: 1755600000871-0</pre><p>Three layers agree on one identifier: Redis generates it, SSE carries it, and the client returns it. Nothing in between needs to invent or remember another sequence number.</p><p><strong>Recovery is driven by what the client received, not by what we sent.</strong> There are two positions in play: the gateway’s read position in Redis and the last event ID the client actually received.When the gateway calls send(), bytes have been written to the socket, but there is no acknowledgement that the client received them.That would be dangerous if the gateway’s local cursor were used for recovery. It isn’t.</p><p>That cursor dies with the connection. On reconnect, the client supplies its own Last-Event-ID.A failure during the handoff may therefore replay something the client already saw, but it will not silently skip something the client never received.<strong>Duplicates are recoverable. A silent gap is not.</strong></p><p><strong>Streams need an expiry policy.</strong> A Redis Stream does not have a separate “close” lifecycle; it is a Redis key, so cleanup is handled through expiry.</p><p>The Redis Stream is transport, not permanent storage. History lives in the database, and an expired stream can return a clean 410 rather than leaving the client hanging.Our first instinct was to set the TTL when the producer finished. That turned out to be wrong.</p><p>If the pod is hard-killed before reaching the completion path, the key never receives a TTL.Expiry should be a property of the stream from creation time, not something that depends on successful completion.The first event and a conservative expiry therefore need to land atomically:</p><pre># turn starts: one atomic step (MULTI/EXEC, or a Lua script)<br>xadd(key, first_event)<br>expire(key, GENEROUS_TTL)<br><br># producer finishes: bring it in<br>expire(key, RECONNECT_TTL)</pre><p>Two separate round trips still leave a hole: XADD succeeds, the pod dies, and EXPIRE never runs. The exact atomic mechanism depends on the client and deployment. The completion-time expiry is only an optimisation. The creation-time expiry is what turns a SIGKILL from “key lives forever” into “key expires later than ideal.”</p><p>Once the turn completes, we shorten the TTL to the reconnect window. After that window expires, Redis reaps the stream automatically; there is no separate stream-close operation.</p><p>Reconnect then becomes straightforward. A client comes back with its turn ID and last event ID, and the relay resumes on <strong>any gateway pod</strong>, regardless of which agent pod is writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N1gFloFf22Tl244Z.png" /><figcaption>Reconnect: the client’s last event ID is the resume point.</figcaption></figure><h3>The Case That Settled It: A Turn That Pauses for Minutes</h3><p>Everything above is about surviving failures. The case that really validated the design wasn’t a failure at all.One of the agent’s tools hands work to another team’s pipeline. It enqueues a request and returns “started.” The pipeline answers seconds or minutes later, on its own topic and on its own schedule.</p><p>One of the agent’s tools hands work to another team’s pipeline. It enqueues a request and returns “started.” The pipeline answers seconds or minutes later, on its own topic and on its own schedule.</p><p>So the agent loop <em>ends</em>. And the turn is <em>not done</em>.</p><p>The frameworks we were using naturally assume a turn is one execution context, on one machine, for one continuous span of time.This workflow is none of those.The first process marks the turn as awaiting an async result and exits. Later, a consumer receives the pipeline result <strong>on a different pod, in a different process, with none of the original turn’s in-memory state.</strong>It reconstructs what it needs from the message payload and shared storage, appends the result to the same Redis Stream, and finishes the turn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*po9eVyk9W99ijTOD.png" /><figcaption>A turn suspended across two processes, finished by a pod that didn’t exist when it started.</figcaption></figure><p>Suspending the turn now requires only two things.<strong>Don’t write the terminal event.</strong> The reader interprets it as “stop reading,” so without it, the reader keeps waiting.<strong>Extend the TTL.</strong> The key needs to survive the async round-trip.</p><p>That’s it. The gateway needs no special notion of suspension. Neither does the client. And the process that eventually finishes the turn may not even have existed when it started.It works because the rendezvous is a <strong>name</strong>, not a connection.A process that appears two minutes later can still write to a name. It cannot write to a connection that disappeared two minutes ago.</p><h3>What We Send to the Client</h3><p>One detail is worth making explicit: we do not stream model tokens to the client.An answer is a set of typed UI blocks: a card, a result set, an image, or a set of actions. Each block is sent once, whole, in a single event.Token deltas exist internally and stop at the service boundary.</p><p>A block becomes renderable only when it is complete. Sending fragments would simply make the client buffer them and reconstruct an object we already had.Token streaming earns its keep when the surface is a chat transcript you watch type itself. That isn’t our main surface.</p><p>Instead, we stream the events <em>around</em> the answer: which tool was selected, what it returned, progress through the turn, and completed UI blocks. Those happen at meaningful points in time, so they go out immediately.</p><h3>Costs, Limits, and What We’d Tell You to Watch</h3><p><strong>An in-memory transport is only safe because it isn’t the system of record.</strong> Persistence runs separately. The user’s message is written before inference starts, and completion is persisted independently of what happened on the wire.On the async path, the consumer acknowledges only after <em>both</em> the stream write and durable write succeed.Losing a stream can therefore lose <em>delivery continuity</em>, but not the underlying conversation data.</p><p><strong>The extra hop is real, and we measure it.</strong> Redis Stream IDs contain Redis’s write-time timestamp, so the gateway can estimate the delay between the append and forwarding the event to the client socket.Under normal load, p99 sits around <strong>10–20 ms</strong> and occasionally spikes to roughly <strong>40–60 ms</strong>.That is not true end-to-end latency. The clock starts when Redis generates the entry ID, so it excludes the producer-to-Redis hop and assumes reasonably synchronized hosts.Treat it as a floor, not a total.</p><p><strong>Some timeouts are polled, not precise.</strong> Turn-start, silence, and absolute-ceiling checks happen when the blocking Redis read returns empty.With a 30-second block window, a configured 60-second silence timeout may fire somewhere between <strong>60 and 90 seconds</strong>.Fine for a safety net; not fine as a precise SLA.</p><p><strong>The log preserves the turn, not the computation.</strong> Events already written survive a lost pod, and a suspended turn survives easily because nothing is executing.An actively running agent loop is different.If that process disappears mid-turn, the computation is gone. The reader eventually discovers that through a timeout rather than an explicit failure.Making the computation itself resumable would require checkpointing agent state, a much larger problem.</p><p><strong>Nobody tells the writer to stop.</strong> If the client disappears and the gateway stops reading, the agent does not know. It may continue appending events and spend compute on an answer nobody will consume until the turn’s own timeout ends it.That is a tradeoff we knowingly accept.</p><h3>The End State</h3><p>The final architecture is simple: two services share no long-lived connection and no topology knowledge, only a naming convention.A client can disconnect, reconnect to another gateway pod, and continue from the exact event it last received.</p><p>A rollout no longer destroys every in-flight delivery path.And a turn can pause for minutes and later be finished by a process that didn’t exist when it started.None of that came from choosing a faster transport.It came from realizing that recovery depends on <strong>what needs to be addressable.</strong>For us, execution happens inside a process. Recovery happens at the level of a turn. So the turn needed to be the thing with a name.</p><blockquote><strong><em>Pick your transport around the unit you need to recover, not the unit you happen to execute in.</em></strong></blockquote><p>Long-running workflows, media pipelines, coding agents, and async orchestration systems all have those two units — and they are rarely the same one.</p><p><em>If you’ve solved the resumable-turn problem a different way, I’d genuinely like to hear it. The design space here is less settled than the number of streaming tutorials suggests.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09cfa9e79358" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/building-resumable-real-time-llm-streaming-with-redis-streams-09cfa9e79358">Building Resumable Real-Time LLM Streaming with Redis Streams</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>