Anatomy of serving: latency, throughput, memory and cost per token
An LLM user perceives the first token and generation rate, while its operator pays GPU hours. We define serving metrics, build a roofline performance model for prefill and decoding latency and throughput, budget memory and concurrency, calculate cost per million tokens, and examine serving-engine components. The design considers an RTX 4060 budget; the minimal server measurements were made on an RTX 3060.
After this lesson you can
- Define and measure TTFT, TPOT, total latency, throughput and goodput with percentiles.
- Predict decoding latency per token and throughput as functions of batch and context with a roofline model.
- Calculate weight and cache memory and maximum concurrency for a model on a given GPU.
- Estimate cost per million input and output tokens.
- Build a minimal static-batching streaming server and measure it under Poisson load.
Before you start
The first token and those that follow
A response that starts quickly and then stalls may feel worse than one with the same total duration and a steady stream. The operator must also decide how many simultaneous responses fit and what serving them costs. These questions require several metrics on the same workload, not a single tokens-per-second figure.
Time to first token (TTFT) begins when the client sends a request and ends upon receiving the first token. Depending on clock placement it includes network, queue, tokenization, prefill, and transmission. Inter-token latency (ITL) measures each observed streaming interval. For a response with tokens, TPOT is : a per-request average. It does not reveal isolated pauses; the ITL distribution does. Total latency runs from request to finish, and throughput counts useful tokens in a time window.
A TTFT 95th percentile of two seconds says at least 95% of observations fall at or below that threshold, depending on percentile convention and sample. It guarantees nothing about a future request. State sample size and composition, concurrency, windows, and handling of failed responses. Bootstrapping independent requests helps estimate uncertainty, although temporal dependencies or small samples require more care.
Goodput counts requests simultaneously meeting service objectives divided by time. For example, with TTFT ≤ 2 s and TPOT ≤ 0.5 s, a slow request fails even if the server produces many aggregate tokens. The SLO is a chosen target, not a model property. Deciding how to handle one-token responses, errors, and cancellations is part of the definition.
The observation window must include idle time to estimate capacity delivered during that period. Measuring only while the GPU is busy describes a different denominator. For input throughput sum actual prompt tokens, not padding; for output count tokens actually sent. A response canceled before completion can consume compute without counting as a useful request. Recording all three numbers helps reveal that work’s cost.
TTFT and TPOT are not interchangeable. Queue waiting increases a request’s TTFT even if later steps are fast; a midstream pause increases one ITL without changing first-token time. In long responses average TPOT can hide that pause. Across requests, a percentile of per-request TPOT weights each request equally; a percentile of all ITL intervals weights long responses more. Both distributions are valid if what is counted is stated.
Physical bounds and batching
In the throughput-latency tradeoff, a batch shares weight reads across sequences. In a dense layer with weights, BF16 occupies approximately bytes and multiplication by vectors performs about FLOPs. Ignoring activations and cache, intensity is FLOPs/byte. With bandwidth and compute , ideal balance occurs near . In practice kernels, matrix sizes, communication, and effective capacity shift the knee.
For one decode step with context , cache per token , and weights , a simplified lower bound is . Each active request receives one token per step: ideal TPOT is while aggregate throughput is . Do not divide TPOT by . Prefill processes prompt tokens together; a compute approximation is , but attention, reads, activations, and CPU work matter too. Pope and colleagues analyze inference cost at scale and the JAX scaling guide develops this arithmetic.
The figure uses 1.5B parameters, 3 GB BF16 weights, and 28 KB KV per token, in decimal units. At batch one, without reading KV and with 230 GB/s measured, weights alone require seconds: 13.04 ms and at most 76.67 tokens/s. This is a bound, not a guarantee. Increasing context adds KV reads each step. Batching can improve throughput and worsen TPOT; shape depends on both maximum terms and whether data fit.
Memory budget
Inference memory comprises weights, KV cache, activations, buffers, fragmentation, and system reserve. For layers, KV heads, dimension , and bytes per element, each sequence token uses bytes for keys and values. GQA reduces relative to query head count. Cache for sequences of length occupies approximately before block rounding and metadata.
With 8 GB total, 3 GB weights, and 1 GB reserved, for 4096 tokens and 28 KB per token the maximum is sequences. This assumes equal lengths and that the reserve covers everything else. With variable inputs budget growth during generation, not just initial length. Weight quantization reduces reads and capacity, but scales, decompression, and cache can limit savings or change actual speed.
Practical systems allocate and release cache blocks as tokens arrive. A partially full block wastes space and requires a table mapping logical positions to physical blocks. That cost can be smaller than reserving the maximum for every request upfront, but accurate estimation requires block size, length distribution, and admission policy. Shared prefixes save memory only if one physical copy is shared and continuation independence is preserved.
Queuing has a cost too
Static batching groups requests and keeps the batch until the longest finishes. Prompt padding consumes work on empty positions; when a sequence finishes, its decode slots can continue being computed. With continuous batching the scheduler can remove completed requests and introduce new ones between steps, at greater cache and scheduling complexity. Orca studies iteration-level scheduling for generative models.
Little’s law relates average number in a system, output rate, and average time in steady state. It does not justify applying it to an unbounded growing queue or deducing percentiles. A longer window may fill the batch but adds waiting for requests already arrived. When the executor saturates, queuing can dominate TTFT even if compute per token is unchanged. The simulator is deliberately finite and its synthetic times do not predict a specific service.
Poisson arrivals assume independent exponential intervals at a constant rate. They are useful for reproducing simple load, but real traffic can contain bursts, user correlation, retries, and hourly variation. Identical mean rate does not imply equal p95. If the client waits for a response to finish before sending another, latency itself regulates the rate; that is a closed workload, unlike the lab’s open generator. Record scheduled and actual send times, since a saturated generator can hide congestion.
Money per token
Cost per million is hourly price divided by 3600 and multiplied by GPU time needed for one million tokens. At €2/h and sustained 2000 output tokens/s, it is € per million output tokens. For a mix, add input and output costs weighted by proportions. Throughputs must correspond to comparable load; a saturated measurement does not necessarily include idle hours, failures, network, CPU, or commercial margin.
Doubling batch size or quantizing does not automatically double throughput. Repeat measurements with similar lengths, SLOs, and load, and enter results in the calculator. Local electricity cost excludes depreciation and the rest of the system; rental may bill idle capacity. Compare cost per SLO-compliant request as well as cost per token.
Engine components
Engine architecture connects API and streaming, tokenization, queue and memory scheduling, model execution, and detokenization. Prefill produces the first distribution; each later step consumes the chosen token and KV cache. The scheduler controls admission, cancellation, and block reclamation. The API must transmit errors and apply limits, authentication, and backpressure if a client does not read. An educational server can omit these pieces without becoming a safe production implementation.
CUDA graphs and torch.compile(mode="reduce-overhead") can reduce launches and CPU overhead when patterns and shapes permit reuse. Compilation, warm-up, reservations, and variable shapes have costs; compiled execution is not assumed always faster. PyTorch documentation describes that mode and its restrictions. The lab checks availability in the real environment before attributing results to it.
To compare versions, fix model, precision, input and output lengths, seed, and stop rules. Warm both, synchronize CUDA when timing device events, and separate compilation from steady time. A change in batch shape or length can force a new specialization, so initial cost matters with few requests. A difference on a shared machine may also come from other processes; repetitions and a timing distribution help avoid mistaking noise for improvement.
Lab: analytical model
The next model uses ideal weights, KV, bandwidth, and FLOPs. Prefill includes weight reads and dense compute but not attention or activation movement; decode adds weight and KV reads. The result is a simplified bound, not a kernel simulator or complete TTFT with queuing.
import math
def latency_model(cfg,gpu,batch,ctx):
weights=cfg['params']*cfg['weight_bytes']
kv=cfg['kv_bytes']
prefill=max(weights/gpu['bw'],2*cfg['params']*batch*ctx/gpu['flops'])
decode=max((weights+batch*ctx*kv)/gpu['bw'],2*cfg['params']*batch/gpu['flops'])
memory=weights+batch*ctx*kv+gpu['reserve']
capacity=max(0,math.floor((gpu['memory']-weights-gpu['reserve'])/(ctx*kv)))
return prefill,decode,batch/decode,memory,capacity
cfg={'params':1.5e9,'weight_bytes':2,'kv_bytes':28000}
gpu={'bw':230e9,'flops':30e12,'memory':8e9,'reserve':1e9}
for b in (1,8,32):
pre,dec,rate,mem,cap=latency_model(cfg,gpu,b,4096)
print('lote',b,'prefill ms',round(pre*1000,2),'TPOT ms',round(dec*1000,2),'salida/s',round(rate,2),'GB',round(mem/1e9,2),'máximo',cap)
assert cap==34 and abs(3e9/230e9*1000-13.043478)<1e-5Local lab: server and load
The next minimal server uses SmolLM2-135M in FP32, left padding, KV cache, and static batches of up to four requests. Each response streams as line-delimited JSON; the client records receipt times. Eight exponential arrivals at nominal rate 8/s with different lengths test operation, not stable p95 or production benchmarking. Model loading and warm-up are excluded from timings; CUDA peak includes already loaded weights. The individual greedy comparison runs after measurement.
It requires Python with CUDA-compatible PyTorch, Transformers, and NumPy, plus model files in the Hugging Face cache. If not yet cached, a first load with local_files_only=False needs a connection and download; afterward the local option can be restored. The server listens only on localhost and is a demonstration without production authentication or limits.
In one run on a shared RTX 3060, there were 134515008 parameters, 538060032 bytes of FP32 weights, and 46080 KV bytes per token. Batches were 1, 1, 4, and 2, with two input padding tokens. Observed TTFT p50/p95 was 0.645/1.309 s, TPOT 0.084/0.092 s, and output throughput 20.67 tokens/s; all eight requests met the illustrative SLO. The program shows CUDA peak during request load before individual comparison. Results fluctuate with load and are not RTX 4060 measurements. As a scale comparison, assuming 230 GB/s effective and reading only those weights, the ideal bound would be 2.34 ms per step at batch one; that bandwidth was not measured here and excludes KV, kernels, and CPU. The difference from observed TPOT alone does not identify a cause.
import concurrent.futures, json, queue, random, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
import numpy as np
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer
assert torch.cuda.is_available();torch.set_num_threads(1)
model_id='HuggingFaceTB/SmolLM2-135M';tok=AutoTokenizer.from_pretrained(model_id,local_files_only=True)
tok.padding_side='left';tok.pad_token=tok.eos_token
model=AutoModelForCausalLM.from_pretrained(model_id,local_files_only=True,dtype=torch.float32).eval().cuda()
incoming=queue.Queue();batches=[];MAX_BATCH=4;WINDOW=.06
def worker():
while True:
first=incoming.get()
if first is None:break
batch=[first];deadline=time.perf_counter()+WINDOW
while len(batch)<MAX_BATCH:
timeout=deadline-time.perf_counter()
if timeout<=0:break
try:batch.append(incoming.get(timeout=timeout))
except queue.Empty:break
texts=[x['prompt'] for x in batch]
encoded=tok(texts,padding=True,return_tensors='pt').to('cuda')
mask=encoded['attention_mask'];lengths=mask.sum(-1).cpu().tolist();B=len(batch);max_input=mask.shape[1]
generated=[[] for _ in batch];active=[True]*B;past=None;elapsed=[]
with torch.inference_mode():
pos=(mask.cumsum(-1)-1).clamp_min(0)
a=torch.cuda.Event(enable_timing=True);b=torch.cuda.Event(enable_timing=True);a.record()
output=model(input_ids=encoded['input_ids'],attention_mask=mask,position_ids=pos,use_cache=True)
b.record();torch.cuda.synchronize();prefill_ms=a.elapsed_time(b);past=output.past_key_values
while any(active):
chosen=output.logits[:,-1,:].argmax(-1)
for i,req in enumerate(batch):
if not active[i]:continue
token=int(chosen[i]);generated[i].append(token)
req['stream'].put({'token_id':token,'text':tok.decode(generated[i],skip_special_tokens=True),'input_tokens':int(lengths[i])})
if token==tok.eos_token_id or len(generated[i])>=req['max_tokens']:
active[i]=False;req['stream'].put({'done':True})
if not any(active):break
next_ids=torch.tensor([[int(chosen[i]) if active[i] else tok.pad_token_id] for i in range(B)],device='cuda')
extra=torch.tensor([[1 if x else 0] for x in active],device='cuda');mask=torch.cat([mask,extra],dim=1)
pos=(mask.sum(-1)-1).clamp_min(0)[:,None]
a=torch.cuda.Event(enable_timing=True);b=torch.cuda.Event(enable_timing=True);a.record()
output=model(input_ids=next_ids,attention_mask=mask,position_ids=pos,past_key_values=past,use_cache=True)
b.record();torch.cuda.synchronize();elapsed.append(a.elapsed_time(b));past=output.past_key_values
batches.append({'size':B,'prompt_lengths':lengths,'pad_tokens':B*max_input-sum(lengths),'prefill_ms':prefill_ms,'decode_ms':elapsed,'output_lengths':[len(x) for x in generated]})
class Handler(BaseHTTPRequestHandler):
def log_message(self,*args):pass
def do_POST(self):
data=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
stream=queue.Queue();data['stream']=stream;incoming.put(data)
self.send_response(200);self.send_header('Content-Type','application/x-ndjson; charset=utf-8');self.end_headers()
while True:
message=stream.get();self.wfile.write((json.dumps(message,ensure_ascii=False)+'\n').encode('utf8'));self.wfile.flush()
if message.get('done'):break
def client(url,prompt,max_tokens):
start=time.perf_counter();body=json.dumps({'prompt':prompt,'max_tokens':max_tokens}).encode()
req=urllib.request.Request(url,data=body,headers={'Content-Type':'application/json'})
stamps=[];ids=[];input_tokens=0
with urllib.request.urlopen(req,timeout=180) as response:
for line in response:
event=json.loads(line);now=time.perf_counter()
if event.get('done'):end=now;break
stamps.append(now);ids.append(event['token_id']);input_tokens=event['input_tokens']
return {'ttft':stamps[0]-start,'latency':end-start,'tpot':(stamps[-1]-stamps[0])/(len(stamps)-1) if len(stamps)>1 else None,'itl':np.diff(stamps).tolist(),'output_tokens':len(stamps),'input_tokens':input_tokens,'ids':ids}
if __name__=='__main__':
# Warmup antes de iniciar carga; no incluye carga de modelo en la medición.
with torch.inference_mode():model(**tok('Warmup',return_tensors='pt').to('cuda'),use_cache=True)
torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats()
server=ThreadingHTTPServer(('127.0.0.1',0),Handler);server.daemon_threads=True
thread=threading.Thread(target=worker,daemon=True);thread.start()
threading.Thread(target=server.serve_forever,daemon=True).start()
url=f'http://127.0.0.1:{server.server_port}/generate';rng=random.Random(27)
prompts=['The capital of France is', 'A short story about a quiet town', 'Explain why the sky appears blue', 'The following list contains', 'One day, a scientist discovered', 'The river flows through a valley', 'A Python function that adds numbers', 'At the end of the meeting']
limits=[4,8,6,10,5,9,7,11];arrival=0.;begin=time.perf_counter();futures=[]
with concurrent.futures.ThreadPoolExecutor(max_workers=len(prompts)) as pool:
for prompt,limit in zip(prompts,limits):
arrival+=rng.expovariate(8.0);time.sleep(max(0,begin+arrival-time.perf_counter()))
futures.append(pool.submit(client,url,prompt,limit))
results=[f.result() for f in futures]
wall=time.perf_counter()-begin;server.shutdown();incoming.put(None);thread.join(timeout=30)
peak=torch.cuda.max_memory_allocated() # antes del contraste individual
# Contraste fuera de la medición: mismo greedy, cada petición por separado.
for i in (0,1):
encoded=tok(prompts[i],return_tensors='pt').to('cuda')
with torch.inference_mode():
ref=model.generate(**encoded,max_new_tokens=limits[i],do_sample=False,pad_token_id=tok.pad_token_id)[0,encoded['input_ids'].shape[1]:].tolist()
assert results[i]['ids']==ref,(i,results[i]['ids'],ref)
print('Greedy individual coincide con servidor en dos solicitudes')
pct=lambda x:np.percentile(x,[50,95]).round(4).tolist()
ttft=[r['ttft'] for r in results];tpot=[r['tpot'] for r in results if r['tpot'] is not None];itl=[x for r in results for x in r['itl']]
output=sum(r['output_tokens'] for r in results);inputs=sum(r['input_tokens'] for r in results)
good=sum(r['ttft']<=2 and r['tpot'] is not None and r['tpot']<=.5 for r in results)
params=sum(p.numel() for p in model.parameters());weight_bytes=sum(p.numel()*p.element_size() for p in model.parameters())
cfg=model.config;kv_bytes=2*cfg.num_hidden_layers*cfg.num_key_value_heads*(cfg.hidden_size//cfg.num_attention_heads)*4
print('GPU',torch.cuda.get_device_name(),'modelo',model_id,'parámetros',params,'pesos bytes',weight_bytes,'KV bytes/token FP32',kv_bytes)
print('llegadas Poisson: 8 solicitudes, tasa nominal 8/s; ventanas',WINDOW,'s; lotes',json.dumps(batches))
print('TTFT p50/p95 s',pct(ttft),'TPOT p50/p95 s',pct(tpot),'ITL p50/p95 s',pct(itl),'latencia p50/p95 s',pct([r['latency'] for r in results]))
print('tokens entrada/s',round(inputs/wall,3),'salida/s',round(output/wall,3),'duración s',round(wall,3),'goodput solicitudes/s',round(good/wall,3),'SLO TTFT≤2s y TPOT≤0.5s')
print('pico asignado CUDA GiB',round(peak/2**30,3),'sin carga de modelo, warmup ni torch.compile en tiempos')
npm run lab and open the connection link.To optionally test compiling the decode step, run the next block separately. On this test’s RTX 3060, reduce-overhead mode produced finite logits of shape 1 × 1 × 49152; versus eager, maximum absolute difference was 0.0000144 and the greedy token matched. This one-step check does not measure speed improvement. Initial compilation may take several minutes and requires backend-compatible tools.
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer
torch.set_num_threads(1)
name='HuggingFaceTB/SmolLM2-135M'
tok=AutoTokenizer.from_pretrained(name,local_files_only=True)
model=AutoModelForCausalLM.from_pretrained(name,local_files_only=True,dtype=torch.float32).eval().cuda()
ids=tok('The capital of France is',return_tensors='pt').input_ids.cuda()
with torch.inference_mode():
first=model(input_ids=ids,use_cache=True)
token=first.logits[:,-1:].argmax(-1)
compiled=torch.compile(model.forward,mode='reduce-overhead')
out=compiled(input_ids=token,past_key_values=first.past_key_values,use_cache=True)
torch.cuda.synchronize()
print('decode compilado: logits finitos',bool(torch.isfinite(out.logits).all()),'forma',tuple(out.logits.shape))
fresh=model(input_ids=ids,use_cache=True)
eager=model(input_ids=token,past_key_values=fresh.past_key_values,use_cache=True)
delta=float((out.logits-eager.logits).abs().max())
print('diferencia máxima respecto a eager',delta,'mismo token',bool(out.logits.argmax()==eager.logits.argmax()))
assert torch.allclose(out.logits,eager.logits,atol=1e-3,rtol=1e-3)
Exercises
Step 1 of 2. How many weight bytes are ideally read?
def latency_model(cfg,gpu,batch,ctx):
...