Streaming AI replies in Flutter: why SSE beats WebSockets for most chat apps
The user sends a prompt and watches a spinner for five seconds. Then a full answer appears in one go. Technically it works, but it feels broken.
The fix is streaming: the server sends tokens as soon as they are generated, and your Flutter app paints them one after another. The total time is the same, but the user sees text right away. Once you decide to stream, there's a protocol question: WebSockets or Server-Sent Events (SSE)?
Why plain REST feels slow
With a normal HTTP POST, the server has to finish the whole answer before it returns one big JSON payload. Ask for a 1,000-word response that takes six seconds to generate, and the app shows nothing for six seconds.
Streaming sends small chunks the moment they exist. The backend still does the same amount of work, but the user is already reading.
Put a proxy in front of the LLM
Before the protocol, one rule: the app should never call the LLM provider directly. An API key compiled into the binary will be extracted and abused.
Put a small backend between the app and the provider. It authenticates the user, adds the API key on the server, applies rate limits, and forwards the stream to the phone. A lightweight Node.js service works well here, since the job is mostly asynchronous I/O.
WebSockets: powerful, and more than chat needs
WebSockets are full-duplex. Both sides can send at any time over one connection. That's what you want for a fast multiplayer game, or for an AI that has to interrupt the user mid-keystroke.
The cost is weight. A WebSocket connection needs constant ping-pong frames to stay alive, and on a phone that drains the battery. A chat reply mostly flows one way, so you pay for a back channel you barely use.
SSE: one direction, built for this
SSE is unidirectional: data flows only from server to client. For a chat reply, that is exactly the shape of the problem. You send the prompt as a normal request, and the reply comes back as a stream.
Two properties matter on mobile:
- It runs over standard HTTP/2, so requests share connections through multiplexing instead of each one holding its own TCP connection.
- Retry is built into the protocol. When a user drives through a dead zone, reconnection is attempted automatically, without you writing the fallback logic in Dart.
Our rule of thumb: SSE fits 95% of AI apps. Reach for WebSockets when the client truly needs to push data while the server is talking.
| SSE | WebSockets | |
|---|---|---|
| Direction | Server to client | Both ways |
| Mobile cost | Shares HTTP/2 connections | Ping-pong frames drain battery |
| Reconnect | Built in | You write it |
| Best for | AI chat replies | Games, an AI that interrupts the user |
Chunks arrive broken. Buffer them.
Whatever the protocol, TCP fragments data. You won't receive clean JSON objects. You'll get half a line, then the rest of it plus the start of the next one. Parse each raw chunk and you'll get a steady stream of exceptions.
Collect bytes until you hit a message boundary (\n ends an SSE line), and only then hand complete lines to the parser:
Stream<String> completeLines(Stream<String> source) async* { var buffer = ''; await for (final chunk in source) { buffer += chunk; final lines = buffer.split('\n'); buffer = lines.removeLast(); // keep the unfinished tail for (final line in lines) { if (line.isNotEmpty) yield line; } } if (buffer.isNotEmpty) yield buffer; } Also plan for HTTP 429 (Too Many Requests) and timeouts. High-traffic AI apps hit rate limits often. Show a short "connection unstable, resuming" state instead of letting the stream error tear down the chat screen.
Don't rebuild the world 50 times a second
At 50 tokens per second, calling setState() on the screen that holds the whole message list rebuilds a big widget tree 50 times a second. On mid-range Android phones the frame rate drops to single digits and the device heats up.
Keep the rebuild small: only the Text showing the streaming message should listen to the stream.
StreamBuilder<String>( stream: replyStream, // accumulated text so far builder: (context, snap) => Text(snap.data ?? ''), ) And cancel subscriptions and close any StreamController you own in dispose(). A forgotten controller deep in the navigation stack is a permanent leak.
Saving the conversation without stutter
Writing every token to SQLite blocks the I/O thread. Instead, let the UI update instantly from the stream, accumulate text in memory, and commit to the local database in a debounced batch every 500 milliseconds. The screen stays smooth, and the history is still saved.
Checklist
- Stream tokens; don't wait for one big JSON response.
- Keep API keys on a proxy, never in the app.
- Default to SSE; choose WebSockets only for true two-way traffic.
- Buffer chunks until a full line arrives.
- Rebuild only the streaming
Text, and dispose your streams. - Debounce local writes (500 ms).
Further reading: Stop Making Users Wait: Architecting Real-Time Streaming Patterns in Flutter.
Are you streaming AI replies over SSE or WebSockets, and what made you pick it?