Streaming LLM Responses to Users
Deliver tokens to your users in real time. Learn how streaming works, why it improves perceived latency, and how to consume a streamed completion in code.
Streaming LLM Responses to Users is a free Prompt Engineering & LLM Optimization for Developers lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Prompt Engineering & LLM Optimization for Developers learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Stream?
By default an LLM call returns the entire response only after generation finishes. For long answers this feels slow.
Streaming sends tokens as they are produced, so the user sees text appear word-by-word — drastically improving perceived responsiveness.
Time to First Token
Two latency numbers matter:
- TTFT (time to first token): how long until the first word appears
- Total time: until the full answer is ready
Streaming barely changes total time but makes TTFT the number your users actually feel.
Server-Sent Events
Most LLM APIs stream over Server-Sent Events (SSE): a long-lived HTTP response where each chunk is a small JSON event prefixed with data:.
The stream ends with a special [DONE] marker.
Enabling Streaming
You opt in by setting a flag on the request. The API then returns an iterable stream instead of a single object.
const stream = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: messages,
stream: true
});Reading Chunks
Each chunk carries a delta — the new piece of text. You concatenate deltas to rebuild the full message.
let full = "";
for await (const chunk of stream) {
const piece = chunk.choices[0].delta.content || "";
full += piece;
process.stdout.write(piece);
}Updating the UI
On the frontend you append each delta to the visible message. A simple approach: keep state and re-render on every token.
function onToken(token, setText) {
setText(prev => prev + token);
}Handling the Done Signal
When the stream closes, finalize: stop the typing indicator, persist the full message, and re-enable the input box.
stream.on("end", () => {
saveMessage(full);
hideTypingIndicator();
});Errors Mid-Stream
A stream can fail halfway. Always wrap consumption in try/catch and show whatever partial text you already received rather than discarding it.
try {
for await (const c of stream) { /* ... */ }
} catch (e) {
showPartial(full);
reportError(e);
}Cancellation
Users may want to stop a long answer. Pass an AbortController signal so you can cancel the request and free server resources.
const controller = new AbortController();
client.chat.completions.create({ ...opts, signal: controller.signal });
// later
controller.abort();Streaming with Tools
When the model is calling a function, tool-call arguments also arrive as deltas. Buffer them until the call is complete before executing the tool.
Cost & Token Counting
Streaming does not change cost — you still pay per token. To count usage, sum the tokens you received, or request a final usage event if the API supports it.
Quick Check
Test your streaming knowledge.
Recap
You learned to stream LLM responses: opt in with a stream flag, read incremental delta chunks over SSE, update the UI per token, handle the done signal, manage errors and cancellation, and remember streaming improves perceived latency without changing cost.
Frequently asked questions
Is the “Streaming LLM Responses to Users” lesson free?
Yes — the full text of “Streaming LLM Responses to Users” is free to read here on the web, and the Prompt Engineering & LLM Optimization for Developers course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Prompt Engineering & LLM Optimization for Developers course, upgrade to CoddyKit PRO.
What will I learn in “Streaming LLM Responses to Users”?
Deliver tokens to your users in real time. Learn how streaming works, why it improves perceived latency, and how to consume a streamed completion in code. You practise Prompt Engineering & LLM Optimization for Developers with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Prompt Engineering & LLM Optimization for Developers?
No prior experience is required. Prompt Engineering & LLM Optimization for Developers on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Streaming LLM Responses to Users” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Prompt Engineering & LLM Optimization for Developers lesson?
Yes. Every Prompt Engineering & LLM Optimization for Developers lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Retrieval Augmented Generation (RAG)
- Function Calling & Tool Use
- Building Simple LLM Agents
- Streaming LLM Responses to Users