# Batching and KV-cache: how LLM serving really works



Learn how Continuous Batching and KV-caching optimize LLM inference throughput and how to deploy these strategies using Podstack’s per-second GPU scaling.



Inference · 2026-11-11 · 3 min read



When you first move from training a model to serving it in production, the math changes. In training, your goal is raw throughput (tokens per second). In inference, you are balancing a three-way tug-of-war between **latency** (how fast a single user gets a response), **throughput** (how many users you can handle at once), and **cost**.

To optimize LLM inference, you have to look under the hood at two specific mechanisms that define modern serving: Continuous Batching and KV-Caching.

## The Bottleneck: Memory vs. Compute

LLMs are notoriously memory-bandwidth bound. During a single forward pass, the GPU spends more time moving weights from VRAM to the compute cores than it does actually performing the matrix multiplication. 

If you serve one user at a time, your GPU is mostly sitting idle, waiting for data to move. This is why we batch. By processing multiple requests simultaneously, we "reuse" the weights for multiple inputs, significantly increasing the tokens generated per dollar.

## The KV-Cache: Eliminating Redundant Math

LLMs are autoregressive—they generate one token at a time, using the entire previous context to predict the next word. Without a KV-cache, the model would have to recompute the hidden states (Key and Value vectors) for every single previous token every time it wants to generate a new one. This results in $O(n^2)$ complexity.

The **KV-Cache** stores these tensors in VRAM so the model only has to compute the representation for the *newest* token. 

**The Catch:** This cache consumes a massive amount of VRAM. For a Llama-3 70B model, the KV-cache can easily exceed 20GB for a long context window. If your VRAM is full, you can’t batch more users. This is where "Paged Attention" comes in—partitioning that cache into non-contiguous blocks to prevent memory fragmentation.

## Continuous Batching: The Gold Standard

Traditional batching (Static Batching) waits for $N$ requests to arrive, runs them together, and waits for the longest one to finish before returning any results. This is terrible for LLMs because one user might ask for a 5-word haiku while another asks for a 500-word essay.

**Continuous Batching** (or Iteration-level Batching) injects new requests into the batch as soon as others finish. This keeps the GPU cores saturated at all times without forcing fast requests to wait for slow ones.

## Practical Implementation: Deploying Optimized Serving

When deploying on a GPU cloud like Podstack, you shouldn't write these kernels from scratch. You leverage engines like vLLM or Hugging Face TGI that implement these optimizations out of the box.

Here is how you can deploy an optimized Llama-3 inference server using the Podstack API. This configuration ensures the model uses a vLLM backend to handle PagedAttention and Continuous Batching.

```python
# deploy_llm.py
import podstack

# Initialize the client (ensure PODSTACK_API_KEY is in your env)
client = podstack.Client()

# Define a GPU function with vLLM for optimized batching
@client.gpu_function(
    gpu="A100-80GB",
    image="vllm/vllm-openai:latest",
    env={"MODEL_NAME": "meta-llama/Meta-Llama-3-8B"}
)
def generate_text(prompt: str, max_tokens: int = 256):
    # This function wraps the internal vLLM engine
    # Podstack handles the per-second billing and auto-scaling
    response = client.endpoints.call(
        "llama-3-8b", 
        json={"prompt": prompt, "max_tokens": max_tokens}
    )
    return response

if __name__ == "__main__":
    # Deploy to a live endpoint
    client.deploy(generate_text, name="production-llm-api")
    print("Endpoint live: use 'podstack endpoints list' to view status")
```

## Practical Tips for Production Serving

1.  **Monitor KV-Cache Utilization:** If your "Cache Usage" is consistently at 90%+, your requests will start queuing even if GPU compute is low. Consider upgrading to a higher VRAM instance (e.g., A100 80GB) to increase your max batch size.
2.  **Tune `max_num_seqs`:** This parameter controls how many requests are batched at once. Setting it too high can increase Time To First Token (TTFT) as the initial "prefill" stage for many requests happens at once.
3.  **Use Per-Second Billing:** LLM traffic is bursty. If you use a provider that rounds up to the hour, your "idle" time—when the KV-cache is empty—costs you a fortune.

## Deploying on Podstack

At Podstack, we designed our infrastructure specifically for these workloads. Because we offer **per-second billing** on on-demand GPUs, you aren't penalized when your batch sizes are low during off-peak hours.

To get started, install the SDK:
`pip install podstack-sdk`

Set your API key:
`export PODSTACK_API_KEY='your_secret_key'`

Then, use the the console or the API. Whether you are running serverless GPU functions for intermittent tasks or dedicated endpoints for high-throughput production apps, Podstack provides the bare-metal performance needed to keep your KV-cache operations lightning-fast.

By mastering batching and KV-caching, you move from "it works on my machine" to a production-grade system that scales efficiently and stays within budget.
