Streaming, token budgets and cost
medium 7 minStreaming reveals progress before generation is complete.
Video lesson · Chapter 1 of 4
The sentence starts before the bill arrives
Theory
Read or listen first. About 2 min.
What it is
Streaming reveals progress before generation is complete. A transport emits framed events, a renderer decides what is safe to display, and final accounting uses completed usage records. Token counts, wall-clock latency and dollars measure different parts of that lifecycle.
Why it exists
Streaming can improve perceived responsiveness without reducing total service time. A service should measure time to first text, time to complete validated output and spend per successful task. Billing rates in the worked example are illustrative.
One request, three clocks and one bill
Inside this chapter
Chapter sources- Streaming & SSE
- Server-sent events carry a sequence of framed messages over an HTTP response. A network chunk can contain part of an event or several events. Buffer until a full event has arrived, parse its type and handle the terminal event. A closed connection can mean interruption rather than a complete answer.
TCP delivers a byte stream, so the chunk your code receives is whatever happened to be in the socket buffer. A correct SSE reader appends each chunk to a buffer, splits on the blank-line separator, parses only the complete events and keeps the leftover tail for next time. The classic bug is calling a JSON parser on each chunk: it works on a fast local network and fails randomly in production when packets split differently.
Example. Split a single SSE event across two simulated reads, then place two events in one read. The parser should emit the same ordered event sequence.
Another example. A chat widget works in the office and throws JSON errors for users on mobile networks. The fix is not a retry: it is buffering until each event's terminating blank line arrives.
Network reads are not events
Read Bytes that arrived Buffer afterwards Events emitted 1 data: {"t":"Helhalf an event 0 2 lo"}+ blank lineempty 1 ( Hello)3 two full events back to back empty 2 4 terminal event empty stream marked complete An SSE event ends at a blank line. The parser buffers until it sees one, whatever the read boundaries were. - Building the "Typing Effect"
- A typing interface appends content deltas as they arrive. It must also handle cancellation, interrupted output and text boundaries correctly. Measure time to first visible text separately from time to validated completion. Never treat a partially streamed structured object as a confirmed application record.
The UI is a small state machine. Each delta appends to the visible text, but the message only becomes a confirmed record when the terminal event arrives. If the user presses stop, or the network drops, the text on screen is a draft: label it, keep it out of anything that treats history as ground truth, and do not parse it as structured output. Measure two latencies: time to first visible token (what feels fast) and time to validated completion (what the task actually needs).
Example. Cancel a stream after its first sentence. Verify the UI distinguishes that partial draft from the completed response stored in history.
A streamed reply has more endings than one
Only Complete may be stored in history as the response. The other two keep a visible partial-draft label. - Token Counting (tiktoken)
- Count all messages and tool schemas when estimating an input, then leave space for a response. Templates and histories add overhead beyond the user’s question. Compare the estimate with the returned usage record. If the two diverge repeatedly, recheck the tokenizer, serialization format and model revision.
Count the request exactly as it will be rendered, not just the text the user typed. Tool definitions are serialised into the prompt and can easily outweigh the question. After each call, compare your estimate with the usage the provider returns; a steady gap is fine and can be calibrated, but a sudden change usually means the model revision, tokenizer or template changed.
Example. Compare a plain question with the same question plus five tool schemas. The user-visible words are unchanged but the input budget is larger.
Same question, bigger input
Input part Plain question Question + 5 tool schemas System prompt 120 120 User question 20 20 Tool schemas 0 750 Template and role markers 10 30 Input total 150 920 Reserved for the reply 500 500 Illustrative counts. The user typed the same 20 tokens both times. - Cost Estimation Math
- Compute input and output charges separately because the unit prices may differ. Multiply each token count by its price per million and divide by one million. Distinguish this illustrative estimate from the invoice, which can account for caching, batch discounts or additional billable features.
Output tokens are often priced higher than input tokens, so the same token count can cost very different amounts depending on which side it sits. Per request the numbers look tiny; multiply by daily traffic before deciding whether something matters. Keep the estimate and the invoice separate: caching, batch modes and extra features can all change what is billed.
Example. At fictional rates of 2 and 8 dollars per million tokens, replacing 100 output tokens with 100 input tokens reduces cost by 0.0006 dollars.
Another example. A summariser handles 200,000 requests a day. Shortening the average reply by 100 output tokens at the fictional 8 dollars per million saves 160 dollars a day, which is worth a prompt change; the same saving on 200 requests a day is not.
The swap in the example, worked through
Moving 100 tokens from output (8 per million) to input (2 per million) saves 6 dollars per million moved. Fictional rates. - Prompt prefix caching
- Some providers can reuse work for a prompt prefix they have recently processed, which can lower the charge for those input tokens and the time to first token. Caching only matches an identical prefix, so put stable content (system prompt, tool schemas, long reference documents) first and the changing user text last.
The cache works on the token sequence, so any change near the start (a date, a user name, reordered tools) creates a miss for everything after it. Design templates so per-request values come last. Verify hits from the usage record rather than assuming them, and remember that caching changes cost and latency, not the answer.
Example. A support bot sends the same 3,000-token policy and tool block before every question. Placing the question after that block lets repeated requests reuse the shared prefix; putting a timestamp at the top would break the match every time.
Only an identical prefix can be reused
Rules, lifetimes and discounts vary by provider. Check the usage record for a cached-token count to confirm hits.
How it works
Step through the idea, or press Play.
Input estimate. 1,200 input tokens
Understand it
Worked example
One request, three clocks and one bill
- 1
1,200 input tokens
Reserve enough context for the answer. For this example use fictional prices of 8 per million output tokens.
- 2
First text at 0.4 s
The UI receives several complete events. A partial network chunk is buffered before it becomes a text update. The visible prefix is still provisional.
- 3
300 output tokens · $0.0048
The terminal event confirms completion. Input costs 0.0024. Record actual usage separately from the original reservation.
Estimate the charge for a completed request
Follow the handoffs
- 10 s: request sent1,200 input tokens reserved
- 20.4 s: first texttime to first token
- 3Deltas stream inprefix shown as provisional
- 4Terminal eventtime to complete output
- 5Usage reconciled300 output tokens billed
Streaming improves the second clock. The total service time and the bill come from the last two steps.
Where the $0.0048 comes from
| Item | Tokens | Fictional rate per million | Cost |
|---|---|---|---|
| Input | 1,200 | $2 | $0.0024 |
| Output | 300 | $8 | $0.0024 |
| Total | 1,500 | $0.0048 |
Summary
The whole topic in one minute.
The application has evidence that generation began, not that the response finished or passed validation.
Streaming can improve perceived responsiveness without reducing total service time. A service should measure time to first text, time to complete validated output and spend per successful task. Billing rates in the worked example are illustrative.