Almost every developer who builds AI agents ends up connecting it to Pusher, Laravel Reverb, or Mercure to show the answer in the browser. I did the same when I designed streaming channels in Neuron AI. It’s the natural choice: these tools are mature, you probably already use one of them for notifications, and they work perfectly in development. The problems show up later, when real users arrive, and they tend to show up all together: the cloud bill, the CPU graph, answers that freeze in the browser, and chats that lose their stream as soon as the user switches page.
Why we built IQ-Stream
The reason is simple once you see it. Broadcasting events and streaming the response of an AI agent look like the same job, pushing data from the server to the browser in real time, but the traffic they produce has opposite shapes. A broadcasting service sends small, occasional events from one publisher to many subscribers. An agent sends a dense, continuous flow of tokens to a single subscriber, sometimes for minutes. Infrastructure designed and priced for the event broadcasting struggles with its throughput, and can’t resume a stream after a disconnection without storing every single event.
In this article I’ll go through why this happens, what it means for your costs, and how our solution built specifically for agent streams solves it, with the code to try it in Neuron AI at the end. Everything starts from the architecture, so let’s begin there.
Why AI agents don’t run in your controller
Every tutorial starts the same way: a route, a controller, the agent called inside it, and the tokens written into the HTTP response as they arrive. You see the answer appear word by word in the browser and you think: this is easy.
// The version everyone builds first: the agent lives inside the HTTP request
#[Route('/chat', methods: ['POST'])]
public function chat(Request $request): StreamedResponse
{
$payload = $request->getPayload();
return new StreamedResponse(function () use ($payload) {
$stream = MyAgent::make()
->setThreadId($payload->getString('chat_id'))
->stream(new UserMessage($payload->getString('message')));
foreach ($stream as $chunk) {
if ($chunk instanceof TextChunk) {
echo $chunk->content;
flush();
}
}
});
}
It is easy, as long as the agent answers in a few seconds. Real agents rarely do. An agent reads a document, calls a tool that queries your database, waits for an external API, reasons about the result, calls another tool, and only then starts writing the final answer. That can take a minute or more, and the HTTP request is the worst place to wait that long. PHP’s max_execution_time, the 60 second default timeout of Nginx, and the idle timeout of your load balancer can each cut the answer in half without telling anyone. Every user waiting for an answer also keeps a PHP-FPM worker busy for the entire run, so a handful of long conversations is enough to exhaust the pool and make the rest of your application wait in line. And if the user closes the tab, or you deploy a new version, the run dies with the request, together with the tokens you already paid the model provider for.
So in a real application the agent moves where PHP has always put long-running work: a background job. The controller receives the message, dispatches a job to the queue, and returns immediately. A worker process picks up the job and runs the agent, free from the time limits of the web stack. Symfony Messenger handlers, Laravel jobs, a custom worker: the pattern is the same everywhere.
This solves the timeouts and creates a new problem. The worker has no browser attached. It produces tokens, and nobody is listening. You need something in the middle: a server the worker can publish events to, and the browser can stay connected to.
That’s the reason streaming channels exist in Neuron AI. A channel takes the events produced by the agent and forwards them to an external transport, so the same agent code works in a controller, a queue worker, or a cron job. Neuron ships channels for Redis, Pusher (and Pusher-compatible servers like Laravel Reverb), Mercure, and IQ-Stream, and you can write your own.
Wiring a channel takes two methods in your agent class. The stream adapter decides the format of the events, in this case AG-UI, an open protocol for agent user interfaces. The channel decides where the events go, in this case a Mercure hub, with one topic for each conversation:
namespace App\Neuron;
use NeuronAI\Agent\Adapters\AGUIAdapter;
use NeuronAI\Agent\Agent;
use NeuronAI\Workflow\Streaming\Adapter\StreamAdapterInterface;
use NeuronAI\Workflow\Streaming\Channel\MercureChannel;
use NeuronAI\Workflow\Streaming\Channel\StreamingChannelInterface;
use Symfony\Component\Mercure\Hub;
use Symfony\Component\Mercure\Jwt\StaticTokenProvider;
class MyAgent extends Agent
{
// provider(), instructions(), tools()...
protected function streamAdapter(): ?StreamAdapterInterface
{
return new AGUIAdapter($this->getThreadId());
}
protected function channel(): ?StreamingChannelInterface
{
return new MercureChannel(
hub: new Hub($_ENV['MERCURE_URL'], new StaticTokenProvider($_ENV['MERCURE_PUBLISHER_JWT'])),
topic: 'https://example.com/chats/'.$this->getThreadId(),
);
}
}
From now on, when the agent runs in a background worker and streams its answer, every event goes through the adapter and out through the channel. The code that runs the agent doesn’t contain a single line about streaming.
The real question is which kind of server should sit in the middle. Most developers pick the one they already know from notifications and chat features: an event broadcasting service. That’s where the trouble begins.
Two shapes of real-time traffic
Think of an app that shows live football scores. When a team scores, your backend sends one small event, a few hundred bytes with the new result, to a broadcasting service like Pusher. The service delivers that event to every browser following the match: ten thousand, maybe a hundred thousand. One publish, a huge fan-out. Fan-out is the number of receivers a single message reaches, and it’s the whole point of a broadcasting service: you send once, and it does the heavy lifting of delivering to everyone.
Now think of an AI agent answering a question. The model writes its answer in tokens, small pieces of text roughly the size of a word, and it can easily produce something like 70 of them per second. Every token is an event your worker sends to the streaming server. Between the tokens there are tool calls with their arguments, and tool results that can weigh several kilobytes each, like the content of a file or the rows returned by a query. The answer lasts from a few seconds to several minutes, and it goes to one browser: the person who asked. Maybe two, if the same user has the chat open on the laptop and on the phone.
| Event broadcasting | AI agent streaming | |
|---|---|---|
| Fan-out | One event reaches many browsers | One stream reaches one browser, rarely more |
| Frequency | Occasional events | Dozens of events per second, without pause |
| Event size | Small and predictable | From a few bytes (a token) to tens of KB (a tool result) |
| Lifecycle | Independent events, no beginning or end | A session with a start and an end |
| A missed event | Usually harmless, the next update replaces it | A hole in the middle of a sentence |
The two shapes are almost mirror images. A broadcasting service is optimized for the left column: its whole architecture, from how it manages connections to how it prices its plans, assumes small events with a big fan-out. Push the right column through it and every one of those assumptions turns against you. The first place you notice it is the bill.
Follow the bytes: why agent streaming costs you twice
To understand the cost, you need one concept from cloud pricing: egress. Cloud providers charge you for data that leaves their network toward the internet, while data coming in is usually free. Every byte your servers send to a browser, or to an external service, is egress on your bill.
Every real-time message travels two legs. The publish leg goes from your backend to the broadcasting service. The delivery leg goes from the service to the browsers.
In the football app, the publish leg is tiny. A few hundred bytes leave your cloud, and the broadcasting service turns them into ten thousand deliveries. The delivery leg is thousands of times larger than the publish leg, and it’s the service’s job: it pays for that traffic and charges you for it through its message quota. Your own egress for the publish leg is so small that you never think about it. This is the deal broadcasting services offer, and for this kind of traffic it’s a fair one.
With an agent, the fan-out is gone. Every token your worker publishes is delivered once, to one browser, so the publish leg is as large as the delivery leg. Actually, it’s often a bit larger, because every event travels wrapped in an envelope with its metadata. This means every byte of every answer is paid twice. The first time as egress on your cloud bill, when the worker sends it out of your network toward the service. The second time on the service’s bill, when it delivers the same byte to the browser. And if the service counts messages, as Pusher does, both legs count: one token published and delivered to one browser is two messages.
None of this matters with ten test users. It matters a lot when the cost grows with every token your agents produce, and agents are getting more talkative, not less. Reasoning models think out loud before answering, and tool calls stream their arguments piece by piece.
VPC peering: pay for the bytes once
The publish leg is the part you can fix, because it’s traffic between two servers, not between a server and a browser. There’s no reason for it to cross the public internet at all.
That’s what VPC peering is for. A VPC (Virtual Private Cloud) is the private network where your servers live inside a cloud provider like AWS, Google Cloud, or Azure. Peering connects two VPCs directly, so the servers in one can talk to the servers in the other over the provider’s private network, without the traffic ever going out to the internet.
IQ-Stream offers VPC peering out of the box with every paid plan. You request the peering from the dashboard, accept it in your cloud account, route IQ-Stream’s address range through it, and point your workers to the peering URL with the same app keys. From that moment the publish leg stays on your cloud provider’s private network, and it stops showing up as internet egress on your cloud bill. The only egress left is the delivery leg, the bytes that actually reach your users, and that’s what IQ-Stream bills. Messages are never counted: plans are defined by how many answers can stream at the same time and by the data delivered, so the number of tokens in an answer doesn’t change the price.
In your application it comes down to two environment variables. The workers publish through the private address, while the tickets your backend gives to the browser point to the public one:
# Workers publish to IQ-Stream through the VPC peering
IQ_STREAM_URL=https://<your-peering-url>
# Browsers subscribe through the public address
IQ_STREAM_PUBLIC_URL=https://<region>.iq-stream.dev
IQ_STREAM_APP_KEY=my-app
IQ_STREAM_APP_SECRET=a-secret-of-at-least-32-bytes
Nothing else changes in your code.
It works on your laptop, until it doesn’t
The tricky part is that broadcasting services don’t fail on day one. You connect Pusher or Reverb to your agent, you try it with a couple of colleagues, and it works. The tokens arrive, the demo goes well, the feature ships. It’s an illusion that lasts exactly until real users show up. Then the chickens come home to roost, and they all arrive at the same time.
The cloud bill grows faster than your usage, for the reasons we just saw: double egress on every token, plus a message count that grows with every word your agents write.
If you host the server yourself, with Laravel Reverb, Soketi, or Mercure, the bill turns into CPU. These servers spend a lot of work on every single event, which is irrelevant when events are occasional and becomes the bottleneck when every answer produces dozens of them per second. We benchmarked them on AWS Graviton4 machines with realistic agent runs. On two virtual CPUs, Laravel Reverb used almost 600 microseconds of CPU per event and couldn’t keep up with 200 concurrent answers. Mercure, the most efficient of the general-purpose servers, used about 150. IQ-Stream used about 40 on the same machine and held 1,100 concurrent answers. These are our own measurements, so read them with that in mind: the full methodology is on the performance page, and I’d be happy to hear from anyone who reproduces the test.
The browser suffers too. When the server falls behind, events stop arriving at a steady pace: they pile up in a queue and come out in bursts. In the same benchmark, with 100 concurrent answers on a single core, some events reached the browser through Reverb more than 12 seconds after they were sent. The user sees the answer freeze, then a wall of text appears all at once. On top of that, when the transport limits the size of events and doesn’t guarantee their order, the browser has to buffer events, put them back in sequence, and stitch the fragments of large events together before it can render anything. That’s work running on your user’s device, on every token.
Finally, the agent itself starts breaking. Broadcasting services have limits designed for their typical traffic: Pusher caps each event at 10 KB, and managed Mercure plans limit how many publish requests you can make per second. A tool result bigger than the limit gets rejected, a burst of tokens hits the rate limit, a request times out because the server is saturated. Each of these is an error inside your worker, in the middle of a run. If your code doesn’t isolate it, the job fails and the user gets half an answer. Neuron’s channels catch these errors and let the agent finish its work, and the Neuron frontend package detects the missing events and reloads the conversation. But detecting a hole isn’t the same as not having one.
The hardest part: reconnection and replay
There’s one more problem, and it shows up even when costs and performance are under control. It’s also the one your users will notice first.
Picture a user with two conversations open in your app. In the first one, the agent is writing a long report. While it works, the user switches to the second chat to ask something else. When the page changes, the browser closes the connection that was receiving the first answer. A minute later the user goes back to the first chat. The agent is still running in its background job, but the page has no way to show what it wrote in the meantime. At best it shows a spinner with “the agent is still working” until the job ends and the complete answer can be loaded from the database. The live stream is gone.
The same happens without any navigation at all: a phone switching from Wi-Fi to mobile data, a laptop waking up, a train entering a tunnel. Every connection drop in the middle of an answer means the events sent during the drop are lost.
To fix this, the server in the middle has to remember the events it relayed, so a browser that comes back can ask for everything it missed. And here broadcasting services hit a wall, because they don’t have the concept of a streaming session. They have channels, or topics, which live indefinitely, and events, which are delivered and forgotten. There’s no notion of “this answer started here and ended there”. Pusher, Reverb, Soketi, and Mercure with its in-memory transport keep no history at all. The only way a broadcasting server can offer replay is event history: store every event that passes through a channel for some retention period, and let clients read it back.
Event history brings its own set of problems. The first is data retention and privacy. The content of your users’ conversations with your agent, including whatever your tools pulled out of your database, now sits in a log on a server for as long as the retention period lasts. You need to know where it’s stored, for how long, who can read it, and you need to explain it in your privacy policy. The second is performance. Storing an event is much slower than relaying it, and history features were designed for the broadcasting shape: few events, a few kilobytes each. Mercure is a good example, because it’s an excellent tool and it does offer history through its Bolt transport, which writes every event to disk before relaying it. In our benchmark, Mercure with Bolt never went above about 460 events per second, while Mercure without history peaked at almost 7,000 on the same single core. The third is cost: whatever a managed service charges for keeping history, it charges it on every token of every answer, which is by far the largest volume of events your application produces.
Agent streams are exactly the opposite of what event history was built for: an agent can push something like 70 tokens per second into a single stream, plus tool results of tens of kilobytes, with no fan-out to spread the cost over. You end up asking a feature designed for rare, small, widely shared events to store a dense flow of data meant for a single person.
What a server designed for agent streams does differently
When I built IQ-Stream, I started from the right column of that table instead of the left one.
The central idea is the stream: one answer from one agent, with a beginning and an end. Your backend creates it when the user sends a message, the worker writes events into it while the agent runs, and closes it when the answer is complete or has failed. IQ-Stream keeps the events of a running stream in memory, numbered in order, and releases them as soon as the stream ends. That’s all the history it has: no topics that live forever, no retention period, no disk. Your database stays the source of truth for the conversation, as it already is, and the live stream is a layer on top of it that exists only while the answer is being written.
Because the server knows where a stream starts, and keeps all of it while it runs, replay comes naturally. The browser connects with Server-Sent Events (SSE), a standard part of the web platform, using the EventSource object every browser already has. When the connection drops, EventSource reconnects by itself and sends the ID of the last event it received, and IQ-Stream sends everything after that point, then continues live. A browser that connects late, like our user coming back to the first chat, receives the stream from its very first event and catches up in a moment. A browser that arrives after the end is told immediately, so it can load the final answer from your backend instead of waiting for nothing.
The publish side follows the same logic. Instead of an HTTP request for every event, or for every batch of events, the worker opens one request for the whole answer and writes each event into it as a line of JSON, as soon as the agent produces it. There’s nothing to pace and no messages to count. Events up to 32 KiB travel in one piece on the free plan, and up to 128 KiB on larger plans, so most tool results arrive whole and the browser has nothing to reassemble.
For you as a developer, this removes a whole category of code. With Pusher, you must wait for the browser’s subscription to be confirmed before starting the agent, otherwise the first events are lost because nobody was listening yet. With IQ-Stream, the browser can connect before or after the worker starts. There’s no logic to reorder events or rebuild fragments in the page. And going back to a chat that’s still streaming becomes an ordinary request: your backend hands the page a new ticket for the same stream, and the page picks it up from the beginning. You’ll see it in the code below.
When a broadcasting service is still the right choice
Not every application needs a dedicated streaming server. If your agent answers in a few seconds and can comfortably run inside the HTTP request, stream it directly from the controller with SSE: Neuron supports it natively and you need no extra infrastructure. If you need presence, notifications, live dashboards, or chat between users, that’s the traffic Pusher, Reverb, Soketi, and Mercure were built for, and they handle it well. Many applications will end up using both: a broadcasting service for notifications and a streaming server for agent answers. They solve different problems, and that’s the point of this whole article.
Streaming a Neuron AI agent with IQStreamChannel
Here is the complete setup in a Symfony application, with Messenger running the agent in the background. The same structure works with Laravel queued jobs, or in any PHP application with a queue.
There’s one difference from the agent class we saw at the beginning. There, the channel was defined inside the agent with the channel() method, because the Mercure topic could be derived from the thread ID. IQ-Stream uses a new stream for every answer, and the stream ID is created by the controller when the user sends the message. So the channel is attached from the outside with setChannel(), which takes precedence over the channel() method of the class. The agent keeps its streamAdapter() method as it is and doesn’t need to know anything about IQ-Stream.
Install the IQ-Stream PHP client next to Neuron AI:
composer require neuron-core/iq-stream-php
Register the client as a service. It reads the IQ_STREAM_* variables we saw earlier from your .env file, so controllers and handlers share one instance:
# config/services.yaml
services:
# ...
IQStream\IQClient:
factory: ['IQStream\IQClient', 'fromEnvironment']
The message that travels to the worker carries three strings: the chat, the user’s message, and the stream ID. Never the client or the ticket: the client holds your app’s secret, and a Messenger message waits in its transport as plain data.
namespace App\Message;
final readonly class RunAgent
{
public function __construct(
public string $chatId,
public string $message,
public string $streamId,
) {}
}
The controller receives the user’s message. It creates a ticket, which picks a new stream and signs the token the browser will use to read it. It saves the stream ID on the chat (a nullable streamId field on your Chat entity is enough), dispatches the message, and returns the ticket to the browser. The second action is for the user who comes back to a chat while the agent is still working: it signs a new ticket for the same stream.
namespace App\Controller;
use App\Entity\Chat;
use App\Message\RunAgent;
use Doctrine\ORM\EntityManagerInterface;
use IQStream\IQClient;
use IQStream\StreamId;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
final class ChatController
{
public function __construct(
private IQClient $iq,
private EntityManagerInterface $em,
private MessageBusInterface $bus,
) {}
#[Route('/chats/{id}/messages', methods: ['POST'])]
public function send(Chat $chat, Request $request): JsonResponse
{
$ticket = $this->iq->ticket();
$chat->setStreamId($ticket->streamId->value);
$this->em->flush();
$this->bus->dispatch(new RunAgent(
chatId: (string) $chat->getId(),
message: $request->getPayload()->getString('message'),
streamId: $ticket->streamId->value,
));
// {"streamId": ..., "token": ..., "url": ..., "expiresAt": ...}
return new JsonResponse($ticket);
}
#[Route('/chats/{id}/stream', methods: ['GET'])]
public function resume(Chat $chat): JsonResponse
{
// No answer in progress: the chat history already has everything
if ($chat->getStreamId() === null) {
return new JsonResponse(['ticket' => null]);
}
return new JsonResponse(['ticket' => $this->iq->ticket(new StreamId($chat->getStreamId()))]);
}
}
The handler runs the agent in the Messenger worker, with an IQStreamChannel bound to the stream the controller created. When the run ends, it clears the stream ID, because from that moment the answer lives in the chat history.
namespace App\MessageHandler;
use App\Entity\Chat;
use App\Message\RunAgent;
use App\Neuron\MyAgent;
use Doctrine\ORM\EntityManagerInterface;
use IQStream\IQClient;
use NeuronAI\Chat\Messages\UserMessage;
use NeuronAI\Workflow\Streaming\Channel\IQStreamChannel;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
final class RunAgentHandler
{
public function __construct(
private IQClient $iq,
private EntityManagerInterface $em,
) {}
public function __invoke(RunAgent $message): void
{
try {
MyAgent::make()
->setThreadId($message->chatId)
->setChannel(fn (): IQStreamChannel => new IQStreamChannel($this->iq, $message->streamId))
->chat(new UserMessage($message->message), stream: true);
} finally {
$this->em->find(Chat::class, $message->chatId)?->setStreamId(null);
$this->em->flush();
}
}
}
In the browser, subscribeToIQ from the @neuron-core/streaming package reads the stream through a standard EventSource. The same function serves both cases: following a new answer, and picking up an answer that’s already running.
import { subscribeToIQ } from '@neuron-core/streaming';
let subscription = null;
function follow(chatId, ticket) {
subscription?.close();
subscription = subscribeToIQ(ticket.url, {
onEvent: ({ type, data }) => renderEvent(type, data),
// The page arrived after the end, or the stream was cut:
// load the answer the agent saved in the chat history
onGap: () => reloadConversation(chatId),
});
}
// The user sends a message
async function sendMessage(chatId, message) {
const response = await fetch(`/chats/${chatId}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
follow(chatId, await response.json());
}
// The user opens a chat: is the agent still writing in it?
async function openChat(chatId) {
const { ticket } = await (await fetch(`/chats/${chatId}/stream`)).json();
if (ticket) {
follow(chatId, ticket);
}
}
// The user leaves the chat
function leaveChat() {
subscription?.close();
}
That’s all. The agent runs in the background with no timeouts to fight, the publish leg travels over the private network when you enable VPC peering, and the browser gets every event, in order, even when the connection drops or the user switches chat. The configuration of every channel is in the Neuron AI streaming documentation, and you can try IQ-Stream on your own agents with the free plan at iq-stream.dev.
