Quick revision
The short answer
A transformer first processes all input tokens in parallel (prefill), computing attention keys and values for each, and then generates the answer one token at a time (decode), each new token attending to all earlier ones. The KV cache keeps those keys and values so they are not recomputed, but it grows with context length and limits how many requests a GPU can serve. So time to first token depends on prompt length, speed after that depends on decode, and streaming lets a Java service show tokens as they arrive.
What to remember
In this answer, we saw that a transformer processes the prompt in parallel during prefill and then decodes one token at a time, each attending to all earlier tokens through stored keys and values. The KV cache avoids recomputation but grows with context length and limits concurrency on a GPU. Time to first token depends on prefill and queueing, output speed on decode and load, and long contexts cost more and are used less reliably in the middle. Streaming over server-sent events, with Spring AI's stream() returning a Flux or java.net.http reading lines, lets users see tokens as they are generated.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A transformer first processes all input tokens in parallel (prefill), computing attention keys and values for each, and then generates the answer one token at a time (decode), each new token attending to all earlier ones. The KV cache keeps those keys and values so they are not recomputed, but it grows with context length and limits how many requests a GPU can serve. So time to first token depends on prompt length, speed after that depends on decode, and streaming lets a Java service show tokens as they arrive.
Why this question is asked
We do not need to build a model to use one well, but a rough picture of how it produces text explains almost every latency number we see in production. Why does a long prompt make the user wait before anything appears? Why does the answer then arrive at a steady pace? Why does the provider limit concurrent requests, and why does a 200,000-token prompt cost so much? Interviewers ask this to see whether we can reason about those effects from the Java side. In this answer, we will recap the transformer at a high level, walk through prefill and decode, see what the KV cache does, connect it to latency metrics, and then build streaming in Spring.
1A Quick Recap: What a Transformer Does With Tokens
A transformer turns each input token into a vector, a list of numbers, and passes those vectors through many identical layers. Inside each layer, the important step is attention: every token looks at the other tokens before it and decides how much each of them matters for its own meaning. To do that, each token produces three vectors, a query (what am I looking for), a key (what do I contain) and a value (what do I pass on). A token's query is compared with the keys of earlier tokens, and the matching values are mixed into its new representation.
At the top of the last layer, the model turns the final token's vector into a probability for every possible next token. One token is chosen, appended to the text, and the process repeats. That loop is the whole generation process.
2Prefill and Decode: Two Very Different Phases
When our request arrives, the model already has all the input tokens, so it can process them in parallel, layer by layer, in one big batch of matrix operations. This is the prefill phase. GPUs are very good at this kind of parallel work, so even thousands of tokens are processed quickly, but the time still grows with the prompt length. Prefill produces the first output token.
After that comes decode. The model cannot write token 2 of the answer before it knows token 1, so output is produced strictly one token at a time. Each step is a full pass through all layers for just one new token, attending to everything before it. Decode steps are small, so the GPU spends much of its time reading weights and cached data from memory rather than computing; that is why decode speed, measured in tokens per second, is limited by memory bandwidth and by how many other requests share the GPU.
8 messages in order. Play them, or step through them one at a time.
Prefill happens once and decides time to first token; decode repeats once per output token.
3The KV Cache: Why Earlier Tokens Are Not Recomputed
Notice that during decode, every new token needs the keys and values of all previous tokens in every layer. Recomputing them for each step would make generation get slower and slower. Instead, the server keeps them in GPU memory in the KV cache: computed once during prefill, then extended by one entry per layer for every generated token. Each decode step only computes the new token and reads the rest from the cache.
The catch is size. The cache grows linearly with the number of tokens in the request, and it lives in the same limited GPU memory as the model weights. When the GPU's spare memory is full of caches, the server cannot admit more requests, so long contexts directly reduce how many users one GPU can serve. This is also why providers charge more for long prompts and why serving systems such as vLLM manage the cache in pages to avoid wasting memory.
So a single very long request can occupy as much GPU memory as dozens of short ones. That cost is real for the provider, and it shows up for us as price, rate limits and queueing.
4What This Means for Latency Numbers
Two numbers describe the latency of a model call. Time to first token (TTFT) is mostly queueing plus prefill, so it grows with the prompt length; a short prompt might start in a few hundred milliseconds, while a prompt with 100,000 tokens of documents can take several seconds. Output speed, often quoted as tokens per second, is decided by decode and by how busy the server is. Total time is roughly TTFT plus output tokens divided by tokens per second, so a 600-token answer at 40 tokens per second adds 15 seconds no matter how fast prefill was.
There is one more effect of long contexts on quality rather than speed. Models tend to use information at the beginning and end of a very long prompt better than information buried in the middle, often called the lost-in-the-middle effect. So stuffing everything into a huge context is both expensive and not always more accurate; retrieving fewer, better passages usually wins.
5Streaming the Answer to the User
Since tokens are produced one at a time anyway, there is no reason to make the user wait for the last one. Providers support streaming over server-sent events (SSE), a simple HTTP format where the server keeps the response open and sends small events, each carrying the next piece of text. In Spring AI, stream() returns a Reactor Flux that emits pieces as they arrive, and a WebFlux or MVC controller can pass them straight through to the browser.
Streaming does not make the full answer faster; it makes the first words appear after TTFT instead of after the whole generation, which is what users perceive. Two details matter in a Java service: set timeouts that allow long streams (a read timeout of 10 seconds between events, not 10 seconds for the whole response), and remember that token usage usually arrives only in the final event, so log it at the end of the stream.
6Follow-up questions
Why are output tokens priced higher than input tokens?
Because they are more expensive to produce. Input tokens are processed together in one efficient parallel prefill, while each output token needs its own pass through the whole model and keeps a request occupying GPU memory and capacity for longer. Providers price that difference.
If we stream, does the request still count against concurrency limits for the whole time?
Yes. The request occupies a slot on the provider and an open connection on our side until the last token. With virtual threads or reactive code in Java, holding many open streams is cheap for our service, but the provider's concurrency and rate limits still apply.
How does prompt caching relate to the KV cache?
Prompt caching is essentially reusing the KV cache of a shared prefix across requests. If many requests start with the same long instructions, the provider can keep that prefix's keys and values and skip most of the prefill, which lowers both cost and time to first token.
7Conclusion
In this answer, we saw that a transformer processes the prompt in parallel during prefill and then decodes one token at a time, each attending to all earlier tokens through stored keys and values. The KV cache avoids recomputation but grows with context length and limits concurrency on a GPU. Time to first token depends on prefill and queueing, output speed on decode and load, and long contexts cost more and are used less reliably in the middle. Streaming over server-sent events, with Spring AI's stream() returning a Flux or java.net.http reading lines, lets users see tokens as they are generated.
Open with
At a high level, the model works in two phases. In prefill it takes all the prompt tokens at once and runs them through the layers in parallel, and attention in each layer produces keys and values for every token.
Then, if they want more
That produces the first output token. Then in decode it generates one token at a time: each new token goes through all layers and attends to the keys and values of everything before it.
Those keys and values are kept in the KV cache so they are not recomputed, but the cache grows linearly with context length and sits in GPU memory, so long requests limit how many requests a GPU can serve, which is part of why long prompts are expensive.
For latency, I think in two numbers: time to first token, which is mostly queueing plus prefill and grows with the prompt, and tokens per second, which depends on decode speed and server load. Total time is roughly first-token time plus output length divided by speed, so long answers dominate.
That is why I stream: providers send server-sent events, and in Spring AI I use stream() which gives me a Flux of text that I pass to a text/event-stream endpoint; with plain java.net.http I can read lines as they arrive. I also keep contexts focused, because very long prompts cost more and models attend poorly to the middle.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring AI reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "At a high level, how does a transformer-based LLM generate a response, and what does...": https://scrivio-interview-library.netlify.app/spring-boot/llm-fundamentals/966c8d36fe/