# Implement a Paged KV-Cache Block Manager

> How to build the memory manager behind PagedAttention: blocks, block tables, a free list and what to do when memory runs out, for your AI interview.

**In short:** A paged KV-cache block manager hands out fixed-size blocks of GPU memory to each chat as its reply grows, keeps a block table that maps each chat's blocks in order, and returns them when the chat ends. It needs a free list, a table and a plan for when the pool is full.

AI and LLM interview question Q481, Coding and practical. Advanced, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/implement-a-paged-kv-cache-block-manager

## Say it in 30 seconds

I'd build it from three pieces. A free list of block numbers that nobody is using. A block table for each request, which maps its blocks in order. And a token count, so I know when the last block is full. A new block is taken only at that moment, and all of a request's blocks go back on the free list when it ends. When the free list runs dry, the scheduler has to make the request wait or pause another one.

## Say it in 2 minutes

Each chat gets memory blocks only as its reply grows, and gives them back when it ends. The old approach reserved one chunk for the longest allowed reply, so much of it sat empty. The vLLM paper fixes that by allocating small blocks on demand, an idea borrowed from operating system paging.

I'd keep three structures. A free list of physical block numbers. A block table per request, which maps its logical blocks, in order, to physical ones. And a count of tokens stored so far. When a token arrives, I check whether the last block has room. If the request is new or the last block is full, I pop a block off the free list and add it to the table. Otherwise the token goes straight into the existing block.

The hard part is the full pool. When the free list is empty, the manager must refuse the new block. It must never overwrite memory another chat is still reading. The scheduler then makes the request wait, or it pauses a running request and frees all of that request's blocks at once. If two requests share the same opening text, each shared block gets a reference count, and a request that must write to it gets a private copy first.

I'd test the edge cases: the first token, a token that lands exactly on a block boundary, a finished request, and a pool that runs dry. Then I'd say what the sketch leaves out: threads, the order in which requests get paused, and the GPU code. I'd also check the current vLLM code, since its paging has moved into the attention backends.

## What is a paged KV-cache block manager, in plain words?

A chat model keeps a memory of the conversation so far, called the KV cache (short for key-value cache, the stored key and value vectors for each token). It grows by one entry for every token, and nobody knows in advance how long a reply will be. That memory sits on the GPU, the graphics chip that runs the model.

A block manager is the part of the serving software that decides which pieces of that memory belong to which chat. It hands out small fixed-size blocks as a chat needs them, and takes them back when the chat ends.

Think of a hotel front desk. Each guest gets a room at check-in, and the room goes back into the pool at checkout. The desk keeps a list of empty rooms and a card for each guest. In an AI setting the guests are chats, the rooms are blocks, and a bank's support bot might have many chats open on one GPU at once.

- **Block:** A fixed-size slice of cache memory. The example below uses 16 token slots per block.
- **Free list:** The block numbers that no chat is using right now.
- **Block table:** For one chat, its blocks in order, so the model can find every token it has seen.
- **Reference count:** How many chats share a block. A shared block goes back on the free list only when the count reaches zero.
- **Preemption:** Pausing a running request to free its memory, then resuming it later.

## How does the manager hand out blocks?

The old way reserved one unbroken chunk of memory per chat, sized for the longest reply allowed. Replies can be much shorter than that limit, so much of the chunk sits empty and no other chat can use it. The vLLM paper describes that waste as internal fragmentation: space that is reserved but never filled. It also measured how little of that space held real data: only 20.4% to 38.2% of the cache memory in existing systems stored actual token states.

The paper's abstract says that inefficient management wastes this memory through fragmentation and redundant duplication. Its headline is near-zero waste, plus flexible sharing of the cache between requests.

PagedAttention cuts the cache into fixed-size blocks and adds one only when the last block fills. The paper says this design eases internal fragmentation by using small blocks and allocating them on demand. Here is the path every new token takes.

1. **Check the last block:** A request with no blocks yet, or a last block that is full, needs one more. If the last block has room, the token goes straight in.
2. **Take a free block:** Pop one block number off the free list and add it to the request's block table.
3. **Write the token:** Store the token's cache entry in the chosen slot, then count it.
4. **Give blocks back:** When a request finishes or is paused, put all its block numbers back on the free list and drop its table.

*Diagram, What happens to each new token: Most tokens fill a slot that already exists, so they need no memory. Only a full last block makes the manager take another block. If the free list is empty, the request waits or another one is paused.*
1. The model writes one more token for this request.
2. Yes: the token goes into the last block.
3. No: the last block is full, so one more is needed.
4. Yes: one free block number goes to the request.
5. No: nothing is free, so the request waits or another is paused.

## What does the block table hold?

Each chat has its own block table. It maps the chat's logical blocks, numbered 0, 1, 2 in the order the tokens arrived, to physical blocks in GPU memory. The paper puts the design in two sentences:

> "The KV block manager also maintains block tables-the mapping between logical and physical KV blocks of each request." (The vLLM paper)
>
> "Each block table entry records the corresponding physical blocks of a logical block and the number of filled positions." (The vLLM paper)

The paper's table row holds two things: which physical block it points to, and how many of its slots are filled. My sketch skips the fill count and keeps one token count per chat instead. From that count and the block size, the filled slots follow, so it gives the same answer.

*Diagram, One chat's block table, mapped to GPU blocks: The block table is the only link between a chat and its memory. Logical blocks follow the chat's own order, 0 then 1, and physical blocks are the GPU slots they point to. The made-up chat holds 20 tokens in two blocks.*
1. Tokens 1 to 16 of chat A sit in physical block 5.
2. Tokens 17 to 20 of chat A sit in physical block 4.

The example uses 16 slots per block, the default block size the 2023 vLLM paper gives.

> **Tip:** Describe the table as a map of where each block lives. The token data stays in place, and only the table grows when the chat does.

## What happens when the free list is empty?

The manager must refuse the new block. Overwriting memory another request still reads would corrupt its answers. The paper says vLLM itself can run out of GPU blocks, and then the scheduler must decide what to drop:

> "vLLM can run out of the GPU's physical blocks to store the newly generated KV cache." (The vLLM paper)
>
> "The system needs to make scheduling decisions, such as deleting or swapping out the KV cache of some requests from GPU memory." (The vLLM paper)

The scheduler then has three moves. It can make the new request wait. It can pause a running request and free all of its blocks. The paper calls this eviction, and its rule is all-or-nothing: either all of a request's blocks leave the GPU, or none do. Or it can drop the paused cache and recompute it later, as the paper also does.

The paper says vLLM pairs block-level memory with preemptive scheduling. When traffic surpasses capacity, it must prioritise some requests. Sharing adds two rules. A block used by several requests carries a reference count and goes back on the free list only when the count reaches zero. If a request must write into a shared block, it first gets its own copy of that block. This trick is called copy-on-write, and operating systems use it too.

> **Tip:** Name the options (wait, pause or refuse), say which one your product picks, and why. Silently dropping a user's tokens is never the right answer.

## Can you see it run on a small example?

Here is the manager in 28 lines of standard-library Python, with a made-up pool of six blocks. Three chats use it. The first two fill the pool, the third is refused, and a finished chat frees room for it.

```python
# A paged KV-cache block manager, simplified. A block holds 16 token slots.
BLOCK = 16
class BlockManager:
    def __init__(self, num_blocks):
        self.free = list(range(num_blocks))  # block numbers nobody uses yet
        self.table = {}                      # request -> its block numbers, in order
        self.length = {}                     # request -> tokens stored so far
    def append_token(self, req):
        n = self.length.get(req, 0)
        if n % BLOCK == 0:                   # new request, or last block is full
            if not self.free:
                raise MemoryError(f"no free block for {req}")
            self.table.setdefault(req, []).append(self.free.pop())
        self.length[req] = n + 1
    def free_request(self, req):             # the request finished or was preempted
        self.free.extend(self.table.pop(req, []))
        self.length.pop(req, None)
mgr = BlockManager(num_blocks=6)                          # made-up pool: six blocks in all
for _ in range(20): mgr.append_token("bank-support-A")    # 20 tokens need 2 blocks
for _ in range(50): mgr.append_token("claims-triage-B")   # 50 tokens need 4 blocks
print("free blocks:", len(mgr.free))
try:
    mgr.append_token("bank-support-C")
except MemoryError as e:
    print("error:", e)
mgr.free_request("bank-support-A")                        # chat A finishes
mgr.append_token("bank-support-C")
print("free blocks:", len(mgr.free), "bank-support-C blocks:", mgr.table["bank-support-C"])
```

Output:

```text
free blocks: 0
error: no free block for bank-support-C
free blocks: 1 bank-support-C blocks: [4]
```

Look at two things. The refused chat leaves the pool unchanged, because the check runs before any state changes. And the freed block numbers go back on the free list, so the next chat reuses them. A production engine adds threads, the order in which requests are paused and the GPU code that does the maths, which this sketch leaves out.

### How would you size the pool for a bank's support bot?

Start with numbers you can measure: the usual length of a chat, how many chats are open at the same time, and the block size. Each chat needs its tokens divided by the block size, rounded up to whole blocks. Add those across the chats, then keep spare blocks for the busiest hour.

1. **Measure real lengths:** Use logs of past chats, since replies can end far short of the longest allowed reply.
2. **Round up per chat:** A 20-token chat takes two 16-token blocks, because the manager hands out whole blocks only.
3. **Keep spare blocks and a policy:** Hold spare blocks for bursts, and decide in advance whether a new chat waits or an idle one is paused.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Blocks are fixed size, and one is taken only when the last one is full.
- [ ] A block table maps a request's logical blocks to physical ones.
- [ ] Finishing or pausing a request returns all of its blocks together.
- [ ] A full pool is handled on purpose: wait, pause or refuse.
- [ ] Shared blocks use a reference count and copy-on-write.
- [ ] Edge cases to test: first token, exact block boundary, finish and a full pool.

**Common traps**

- Trap: "Just reserve the longest reply for each chat." Better: That wastes memory, since replies can be much shorter than the limit. Allocate blocks as the reply grows.
- Trap: "When the pool is full, evict any block." Better: Never drop a block some request still reads. Pause whole requests instead, all of their blocks together.
- Trap: "Let every request grab blocks until the GPU fails." Better: Check whether there is room before the free list runs dry, and refuse or queue new work first.

## Can you spot the bug?

**Spot the bug:** A finished chat's blocks should go back on the free list. Which line gets it wrong?

A. self.free.extend(self.table.pop(req, []))
B. self.free.append(self.table.pop(req, []))
C. self.length.pop(req, None)
D. for b in self.table.pop(req, []): self.free.append(b)

**Answer:** B. append adds the whole list as one item, so the free list would hold a list instead of block numbers, and the next pop would hand out a list. extend adds each number on its own.

**Quick check:** The pool is full. A running chat needs its next token, and its last block still has room. What should the manager do?

A. Refuse the token, because the pool is full
B. Write the token into the last block, which takes no new memory
C. Copy the whole cache into a bigger block
D. Restart the chat from its first token

**Answer:** B. A token needs a new block only when the last one is full. With room left, the write costs no memory, so the full pool does not matter for that token yet.

## Can you answer these from memory?

**Flash cards**

- **What does the manager keep?** A free list, a block table per request, and a token count per request.
- **When does a request take a new block?** When it has no blocks yet, or its last block is full.
- **Where do blocks go when a request ends?** Back on the free list, all at once, and its table is dropped.
- **What if the free list is empty?** Refuse, make the request wait, or pause another request.
- **Why keep a reference count?** A shared block goes back on the free list only when no request uses it.
- **What is copy-on-write?** A shared block gets a private copy before a request writes to it.

## Likely follow-up questions

- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache
- Q314 Static vs continuous batching? https://designervenkat.online/interview/ai/static-vs-continuous-batching
- Q317 The latency vs throughput trade-off? https://designervenkat.online/interview/ai/the-latency-vs-throughput-trade-off
- Q319 What is PagedAttention / vLLM? https://designervenkat.online/interview/ai/what-is-pagedattention-vllm
- Q345 Design single-GPU inference batching. https://designervenkat.online/interview/ai/design-single-gpu-inference-batching
- Q479 Implement an LRU cache. https://designervenkat.online/interview/ai/implement-an-lru-cache
