LLM Chat Request Lifecycle: From Send Click to Token-by-Token Streaming

    This article breaks down the end-to-end path of an LLM chat request, covering client-side input handling and request assembly, network access and gateway routing, inference with prefill and autoregressive decoding, streaming delivery, key performance and reliability metrics, and practical engineering recommendations. The goal is to help developers locate latency sources, design more stable interactions, and identify which layer is responsible when something goes wrong.

    1. Starting with a Single Click

    A user enters a prompt on a mobile device and taps Send. Text soon begins to appear on the screen. This process may look like only three steps—ask, wait, display—but it actually involves the client, the access network, the inference service, and streaming delivery. Understanding this path helps developers locate sources of latency, design more stable interaction experiences, and quickly determine which layer is responsible when an abnormality occurs.

    This article follows the order of data flow and breaks down the responsibilities of each stage and common industry implementation approaches. The discussion covers general technical practices and does not involve any product-specific proprietary implementation.

    2. Client: Collecting Input and Assembling the Request

    The client mainly handles three tasks: collecting input, supplementing context, and assembling the request.

    1. Input handling: Trim leading and trailing whitespace, check length limits, and filter clearly invalid content. Length validation should be performed as a pre-check on the client to reduce invalid requests consuming server resources.
    2. Context assembly: Multi-turn conversations need to carry historical messages. The client typically stores a session list and organizes messages according to the role format required by the API (system, user, assistant). When history is too long, the context needs to be compressed using truncation or summarization strategies.
    3. Parameters and authentication: Requests generally include parameters such as the model identifier, output length limit, and sampling temperature, along with an access token. Tokens should be stored in secure system storage, not written to logs, and not saved in plaintext in configuration files.

    Below is an illustrative request structure (fields are for illustration only and do not correspond to any specific API):

    1. {
    2. "session_id": "s-20261124-0001",
    3. "messages": [
    4. {"role": "system", "content": "You are a concise writing assistant"},
    5. {"role": "user", "content": "Tell me a story about a mischievous cat"}
    6. ],
    7. "max_output_tokens": 1024,
    8. "temperature": 0.8,
    9. "stream": true
    10. }

    3. Network Access: From Device to Server

    Requests enter the server through an encrypted channel and generally pass through the following layers:

    • Edge nodes: Complete the Transport Layer Security handshake, domain name resolution, and basic protection.
    • Gateway layer: Perform identity verification, rate limiting, and request body size checks.
    • Scheduling layer: Allocate requests to an appropriate inference cluster based on model version, region, and current load.

    The key metrics at this layer are connection establishment time and first-byte arrival time. If the user is on a weak network, the client should adopt strategies such as connection reuse, timeout retries, and exponential backoff. For non-idempotent operations, retries must first confirm whether the original request has already been processed, avoiding duplicate content generation or duplicate billing.

    4. Inference Service: Generating the Response Token by Token

    The inference service is the most compute-intensive part of the entire path. Its core flow can be divided into four steps:

    1. Tokenization: Split text into tokens that the model can recognize, with each token corresponding to an integer ID.
    2. Prefill: Process all input tokens at once, compute attention states for each layer, and cache intermediate results in GPU memory as the key-value cache (KV cache). The cache allows subsequent generation to avoid recomputing the historical portion.
    3. Autoregressive decoding: The model predicts the probability distribution of the next token based on the existing sequence, selects a token according to the sampling strategy, appends it to the end of the sequence, and then proceeds to the next round of computation.
    4. Stop determination: Generation terminates when an end token is encountered or the output length limit is reached.

    It is particularly important to note that the model does not retrieve ready-made answers from a database. It computes probability distributions step by step based on parameters learned during training and samples from them. Therefore, multiple requests with the same prompt may produce different text, and parameters such as temperature and random seed directly affect output diversity.

    5. Streaming Return: Why Text Appears in Chunks

    If all content were returned only after generation is complete, users would need to wait for the entire generation time, resulting in a poor interaction experience. Therefore, most chat systems use streaming output, where the server pushes each small segment of tokens to the client as soon as it is generated.

    There are two common implementation approaches:

    • HTTP-based chunked transfer or Server-Sent Events (SSE): The connection remains open, and the server continuously writes data fragments. This is simple to implement and suitable for one-way output.
    • Message channels based on bidirectional persistent connections: Suitable for scenarios that require frequent bidirectional interaction, cancellation, or mid-stream parameter changes.

    When receiving data, the client must handle fragment boundaries. A multibyte character or a complete JSON object may be split across two packets, so incomplete parts need to be buffered first and parsed after subsequent data completes them. The illustrative logic is as follows (pseudocode):

    1. buffer = ""
    2. on_chunk(raw):
    3. buffer += raw
    4. while has_complete_event(buffer):
    5. event, buffer = extract_first_complete_event(buffer)
    6. text = parse_text_field(event)
    7. append_to_ui(text)
    8. on_finish():
    9. mark_ui_as_complete()
    10. release_connection()

    The rendering layer also needs to control overhead. If the entire page is redrawn every time a token is received, the interface will frequently stutter. A common approach is to merge fragments received within a short period and update the interface in batches at a fixed frame rate.

    When a user cancels generation mid-stream, the client should actively disconnect. After detecting the disconnect, the server should stop subsequent computation. Otherwise, the server will continue consuming compute resources to generate content that no one will receive.

    6. Key Performance and Reliability Metrics

    • Time To First Token (TTFT): The time from sending the request to the appearance of the first text segment, which directly affects the user’s subjective perception of responsiveness.
    • Generation rate: The number of tokens output per second, which determines how fast text scrolls.
    • End-to-end completion time: The time required for the entire reply to finish, related to output length and service load.
    • Error rate and disconnect rate: Reflect network path and service stability.

    When troubleshooting, problems should be located by stage. A high TTFT is usually related to access queuing or prefill time. A low generation rate may be affected by the decoding batching strategy or service load. Interface stutter mostly comes from excessive client rendering frequency. Recording latency by stage is the basis for locating problems.

    7. Engineering Practice Recommendations

    1. Design an explicit session state machine: States include pending send, receiving, completed, canceled, and failed. The transition conditions and interface behavior for each state should be defined in advance.
    2. Set tiered timeouts: Configure connection timeout, first-packet timeout, and inter-fragment idle timeout separately. The thresholds for the three should be adjusted independently according to the network environment and business scenario.
    3. Control log content: Logs should record only request identifiers, latency, and error codes, avoiding full user input to reduce privacy leakage risk.
    4. Content safety on both sides: Perform content filtering on both the server and the client. The server is responsible for the primary decision, and the client is responsible for fallback handling at the presentation layer.
    5. Preserve received content on weak networks: When the network is interrupted, retain the partial reply already displayed and allow the user to choose whether to continue receiving or regenerate, avoiding the loss of the entire content.