# Latency and throughput compete for the same memory

Date: 2025-04-16
Category: Interview Preparation
Tags: Inference, Latency, Cost, Engineering Practices
Summary: Latency, throughput, and cost on the inference chain are all part of the same ledger—change one and the other two shift with it. From time to first token and KV Cache to degradation and rate limiting, I'll lay out my current trade-offs and boundaries clearly.

When tuning, I lowered the concurrent batch size, and the time to first token immediately looked better—I thought the bill would drop along with it. After running for a while, I realized the direction was reversed: small batches mean the GPU sits idle for large stretches of time, and the cost spread across each token actually goes up.

That day I learned one thing: almost all metrics in the inference pipeline are coupled—change one, and the other two change with it, often for the worse.

## Time to first token is what users feel; total time is what you pay for

Users judge whether a system is fast by how long it takes for the first character to pop out, not by total time. These two metrics often get conflated; once they are, the optimization direction is almost certainly wrong.

Time to first token consists of two parts: how long the request waits in the queue, and how long the model takes to finish prefill (running the entire input through one forward pass) and emit the first token. The latter is directly affected by input length—the longer the material, the slower it gets; the former is affected by batching strategy. Total time, by contrast, is mainly determined by output length—the more output, the more time increases linearly.

Token interval in the middle is another dimension; it determines whether streaming output looks smooth. If the interval exceeds human reading speed, users feel it's laggy, even if the total volume isn't slow. In long-answer scenarios, this metric affects perceived performance more than time to first token, but few people instrument it separately.

Throughput is the cost-side metric. With the same GPU, the more tokens produced per second, the less money spread across each token. It directly conflicts with latency.

Batching can significantly improve throughput because it amortizes the cost of reading weights from GPU memory across more requests. But as the batch grows, requests at the back must wait for earlier requests to fill the batch, and that wait time goes straight into time to first token. Increasing batch size and reducing time to first token are two sides of the same coin; no parameter tuning can achieve both.

Queue time needs separate instrumentation. When time to first token rises, if you can't tell whether it's queueing or slow prefill, you'll optimize the wrong place: the former requires tuning scheduling and capacity, the latter requires looking at input length and operators—the costs of these two are far apart. Adding this split point early is cheap; retrofitting it later means changing instrumentation and dashboards.

Continuous batching alleviates part of this. Traditional static batching must wait for the longest sequence in a batch to finish; after short requests complete, compute is still doing useless work on padding positions. Continuous batching schedules by iteration—as soon as a sequence emits an end token, a new request comes in—so the GPU's effective compute share is much higher. This is where frameworks like vLLM truly earn their value; the point isn't that some operator is a few points faster. The cost is that scheduling itself becomes more complex—timeouts, preemption, and priorities all must be managed yourself.

## What blows up GPU memory first usually isn't the weights

Each step of autoregressive decoding needs the Key and Value of all previous tokens; caching them avoids recomputation, but this cache grows linearly with sequence length, batch size, and number of layers. Long context combined with high concurrency can easily make the KV Cache exceed the weights themselves.

The two phases of inference have different natures. Prefill must compute the entire input once—it's compute-intensive, more so the longer the input; decoding computes only one token per step but must move weights and cache from GPU memory to compute units—it's memory-bandwidth-intensive. This explains a common phenomenon: requests with very long input are slow at the beginning, requests with very long output are slow throughout—the optimization approaches differ. The former can rely on chunked computation and more efficient attention implementations; the latter depends more on bandwidth and batch size.

My current habit is to estimate this cost before discussing requirements. A feature that looks like just "upload a few more pages of documents" might directly cut concurrency capacity by more than half. The product side won't know this; if engineering doesn't say it upfront, remediation after launch is very passive.

Paged management solves the fragmentation problem. Early implementations required KV Cache to occupy contiguous GPU memory and could only pre-allocate by maximum length—short requests also occupied long requests' space, so utilization was very low. Paging cuts the cache into fixed-size blocks, physically non-contiguous, linked by a mapping table; fragmentation essentially disappears, and the same GPU memory can hold a larger batch; parallel sampling can also share prefix blocks with copy-on-write. This idea isn't new—operating systems have done this for ages—but what's interesting is that its gains in inference frameworks are more direct than many model-side optimizations.

Quantization is another path. Compressing weights from half precision to lower bit widths saves both memory and bandwidth, at the cost of precision. What's truly effective in engineering isn't uniform compression, but identifying the few channels that heavily affect output, keeping them at high precision while compressing the rest aggressively. This idea goes by different names in different implementations; the essence is acknowledging that weight importance is non-uniform. Before launch I do two things: compare output distributions before and after quantization, then run a separate hard-example set to confirm the long tail hasn't been flattened.

Model size is also decided here. Bigger isn't better; rather, look at how large a model the latency budget can accommodate, then decide which to use. A smaller model that answers reliably is usually more useful than a large model that frequently times out. The remaining hard problems can go async or to humans—they don't all need to be crammed onto the same real-time path.

Another concrete habit: any parameter change first runs on fixed traffic for a period, and I let percentiles speak. Averages mask the long tail, and the long tail is the lag the user actually remembers.

## CoT amplifies latency; streaming is just pain relief

Chain-of-thought is essentially trading more tokens for better answers. What used to be answerable in one sentence now requires writing five or six steps of reasoning first. The backend sees total time multiply; the frontend sees a long blank.

Streaming output addresses perception, not time. As soon as the first token appears, it's pushed to the client; users see text moving and feel much less waiting. In engineering, be careful not to wait until the entire reasoning finishes before establishing the connection, and don't let gateway buffering eat the stream. Neither issue shows up in local testing—only real networks expose them.

Structured streaming is a fairly practical approach these past two years: wrap the thinking process in a parseable marker, have the frontend render it in real time as a collapsible area, and output the main text as ordinary streaming. Users know the system is working without being disturbed by the reasoning process. This is a product-level tradeoff, not model capability, but its impact on retention is greater than most inference optimizations.

Chain-of-thought isn't worth enabling for every task. For factual queries, format conversion, and simple classification, adding reasoning steps only makes answers longer and latency higher without improving accuracy. I generally enable it only for scenarios with multiple constraints, requiring comparison, or requiring computation, and allow users to turn it off. Giving the switch to users is more reliable than guessing intent in the background.

Truly shortening generation time relies on techniques like speculative sampling. A small model drafts a few tokens first; the large model verifies them in parallel in one forward pass, and on a hit it swallows multiple at once. In chain-of-thought, connectives and boilerplate make up a high proportion, so draft hit rates are usually decent. But it's very sensitive to the draft model and task distribution; when draft quality is poor, verification failures make things slower. I've seen solutions that treat it as a universal acceleration switch; after launch, long-tail latency looked worse because averages were masked by the few hits.

Parallelization also has boundaries. When multiple subtasks are truly independent, splitting them concurrently turns linear accumulation into taking the maximum; if a later step depends on the previous step's conclusion, forcing a split only yields contradictory intermediate results and requires an extra merge round. The criterion isn't whether it can be parallelized, but whether there are information dependencies between the steps.

Very long requests also need to consider the connection itself. A single inference run lasting tens of seconds—gateway default timeouts, load balancer idle reclamation, client retries—any link can drop the result. My approach is to turn such requests into async tasks: return an identifier first, and the client polls or uses a long connection to fetch the result. The cost is more complex interaction—the frontend must handle the "in progress" state—but it's better than receiving a 504 after thirty seconds.

Async paths must allow retrieving results repeatedly and must be cancellable. A task still running after the user closes the page is pure waste; if a completed task's result can't be retrieved, the user retries, producing another round of computation. Without these two things, async just moves the problem from the connection layer to the cost layer.

## Degradation is a product decision, not an ops patch

The hardest thing in production is never making the system faster—it's keeping it from going down.

LLM failures are different from traditional services. An HTTP 200 can still be a failure: the model falls into repetition, emits malformed JSON, answers off-topic, or triggers risk controls. These soft failures don't set off alarms—they only show up in user complaints. So monitoring can't just look at error codes; it has to look at the output itself.

The order of handling is: classify first, then decide whether to retry or give up. For transient errors like network timeouts and rate limiting, exponential backoff retries make sense, but you need jitter—otherwise a batch of requests all retry at the same instant and hammer a service that just recovered. For logical errors like bad parameters or malformed input, retrying usually just burns another round of tokens.

Above retries you need a circuit breaker. When an upstream fails continuously past a threshold, continuing to send traffic only makes the queue longer—cut it off and take the fallback path. The threshold depends on how much false tripping the business can tolerate; there's no universal value. Set it from historical failure curves, then revisit after every incident.

I usually design degradation in three layers: semantic cache, small model, rule-based fallback.

Semantic cache is the cheapest—a hit bypasses the entire inference. But it has a hidden risk: similar is not equivalent. One user asks "can I get a refund," another asks "after a refund can I exchange"—the vectors are close, but the policy terms are completely different. The cache key must include conditions that affect the conclusion: user type, region, time window, product category. Hit rate drops, and so does the wrong-answer rate. I think that's a worthwhile trade.

The cache also has to be invalidatable. After a policy update, old answers must not keep hitting—otherwise they're uniformly wrong. My approach is to tag cache entries with a knowledge-base version number and invalidate everything when the version changes. Full invalidation briefly zeroes the hit rate, but it's safer than returning stale answers.

Small-model fallback requires changing the prompt too. The long examples and complex constraints you gave the large model can't be digested by a small one—handing them over as-is makes it drift more easily. Degradation isn't just swapping a model name; the accompanying instructions must be simplified and the output parsing loosened. Many "worse after degradation" cases aren't the model's fault—it's the missing accompanying changes.

Rule-based fallback sounds backward, but it guarantees that at the lowest point the system can still say something definite instead of showing a spinning frontend.

The degradation experience also needs design. Users don't know the model changed underneath—they just feel the answers got shorter and more conservative. If the UI still says "thinking deeply," the gap is even bigger. I lean toward explicitly shortening replies, collapsing complex features, and offering a retry entry point during degradation, rather than pretending everything is normal.

> Degraded service beats denied service, but how degraded must be written into the product doc in advance, not decided ad hoc during an incident.

On rate limiting: traditional QPS (queries per second) often fails in LLM scenarios. A short greeting occupies the GPU for a few milliseconds; a multi-thousand-word analysis can occupy VRAM for tens of seconds. Rate-limiting by request frequency means ten admitted requests can instantly exhaust VRAM, and the requests behind them—clearly under the frequency limit—all time out.

A more reasonable approach is to limit by concurrency and in-flight compute. Cap the number of requests simultaneously in inference; the excess queues or is rejected outright. Further, at the entrance you can use a tokenizer to estimate input length, combine it with historical average output length to estimate a cost, and reject new requests once cumulative in-flight cost exceeds a watermark.

Queues must be bounded and must fail fast. Making a user wait a minute in the queue only to receive a timeout is the worst experience and wastes connection resources. Re-check remaining time when a request leaves the queue—drop outright the ones that clearly can't finish, and leave the compute for requests that still have a chance. Tiered rate limiting is also common: the gateway blocks coarse-grained floods by IP, the model proxy controls fine-grained token rates—do both layers so you don't fix one and break the other.

> Better to quickly reject some than to have all requests stuck in the queue together.

Easier said than done. The rejected users really do leave, so the threshold ultimately has to be set by product and engineering together—engineering can't just decide it alone.

## After launch I only look at a few numbers

Monitoring in LLM systems is for troubleshooting, not for reporting upward.

Time to first token, cost per request, latency of retrieval or tool steps, and output token count—these four are enough. Finer metrics that nobody looks at are liabilities and slow down instrumentation changes.

The value of tracing is attribution. When a request takes a dozen seconds, is it retrieval, reranking, or model generation that's slow? Without spans you can only guess. Among the invisible bottlenecks I've seen, reranking ranks first: it's often tacked on as an afterthought, but it's actually the heaviest CPU segment, and its latency grows linearly with the number of candidates.

Cost must be recorded per tenant or per user. The total only tells you this month went over budget; breaking it down tells you which feature is burning money. Many "the model is too expensive" problems, when broken down, turn out to be a loop making repeated calls, or an entire document stuffed into the context.

For quality monitoring I use sampling plus model scoring, at a very low rate, mainly to watch trends. Its job is to catch "answers started going off-topic this week," not to produce precise scores. Scores themselves aren't comparable—swap the judge model and the whole baseline shifts—so I prefer to look at relative changes of the same sample set across versions.

I've never done capacity planning carefully enough. Load testing can find the knee of the curve, but real traffic is mixed—change the ratio of long to short requests and the same concurrency behaves completely differently. So I prefer to leave headroom for the worst case and accept some idle capacity rather than run machines at full utilization. That choice looks bad on cost and is easy on stability.

What alarms me most isn't slowness—it's regression. You change one prompt, fix three problems, and break two things that were previously correct. So before launch I run a fixed small eval set and only roll out if metrics don't drop. Maintaining this is tedious, but it's the only source of certainty I currently trust.

Alerts must also be restrained. High GPU utilization isn't necessarily a failure, a growing queue doesn't necessarily need a human, and only situations where "something must be done now" should wake someone up. Set them too densely and the on-call person starts ignoring them—more dangerous than having no alerts. I now keep only three: a sudden spike in error rate, a queue that persistently doesn't drain, and an abnormal cost curve. Everything else goes into the daily report. It's fine if nobody reads the daily report—at least it's searchable.
