23.7 Disaggregated prefill and decode
By the end of the OpenAI-compatible server on tokio, one engine runs both phases of every request: the compute-bound prefill of the prompt and the memory-bound decode of each new token. The two phases compete for the same batch. A long prompt that arrives while thirty streams are decoding makes every one of them stall for its prefill, so time per output token (TPOT) spikes. A burst of decodes makes a new prompt wait, so time to first token (TTFT) spikes. Production systems therefore split the phases onto separate workers: prefill engines that only build KV caches, and decode engines that only extend them.
Concepts from other sections (18)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- memory-bound: limited by the rate at which data can be read, not by arithmetic throughput. Read more: 22.7 Fused int4 and int8 dequantize-matmul in C
- TPOT (time per output token): time between successive tokens of a running request, about one step. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- time to first token (TTFT): the time until the first body byte of an answer is ready to send to the client. Read more: 25.3 The SSE streaming proxy
- TTFT (time to first token): time from a request’s arrival to its first generated token. Read more: 23.4 Chunked prefill (mixed prefill + decode batches)
- KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- Block pool: one slab of fixed-size KV blocks handed out by id. Read more: 21.8 A paged KV block pool in C
- RPC: a remote call presented as a local function call through a generated stub. Read more: Chapter 3: RPC and Protocols in Systems Engineering
- Block hash: a hash over token ids chained with the parent hash, independent of the payload format. Read more: 12.5 The KV format v2 migration in Systems Engineering
- Prefix index: the map from block hash to block id. Read more: 21.8 A paged KV block pool in C
- model runner: the component that loads a checkpoint and runs one batched forward step, writing K and V into the pool and returning last-token logits. Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32
- CRC-32C: the Castagnoli cyclic redundancy check, reflected polynomial
0x82F63B78. Read more: 21.8 A paged KV block pool in C - logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- KV pool: the GPU memory left for KV cache after weights and activation headroom; it sets maximum concurrency. Read more: 20.4.6 Load tests and the deployment runbook
- FNV-1a: a byte hash that xors each byte in and then multiplies by a fixed prime mod . Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python in Mathematics
- block table: a sequence’s list of pool block ids; position lives in entry , slot . Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32
- KV format v2: fp8 (E4M3) payloads with one f32 scale per (layer, K or V, head) slab. Read more: 12.5 The KV format v2 migration in Systems Engineering
- Export envelope: the format v1 wire encoding of a sequence’s blocks, with a CRC-32C trailer. Read more: 21.8 A paged KV block pool in C
- cached block: a block with no running request on it that is still findable by hash or in the radix tree, and can be evicted. Read more: 23.5 Block manager with prefix cache (none, hash, radix)
Splitting the work needs three things the engine does not have yet. The gateway needs a way to ask a prefill engine to run one prompt (EngineControl.Prefill). The prompt’s KV blocks have to move to the decode engine without re-sending the ones it already holds (the tl.kv.v1 service). And the gateway needs to know which engines exist and how loaded they are, which is the heartbeat to tl.control.v1. This section writes all three on top of the block pool and the sampler from the model runner and sampler.
You should be comfortable with the Rust pool’s export, import, register, and lookup operations from the paged KV block pool, and with the serve loop this plugs into: continuous batching, the block manager and prefix cache, and the tokio server. The primers on async Rust and tokio and Protocol Buffers and gRPC in Programming and Algorithms cover the runtime and the RPC layer.
The wire contracts are the gRPC services in proto/tl/engine/v1/engine.proto, proto/tl/kv/v1/kv.proto, and proto/tl/control/v1/control.proto, with generated code in rust/tl-proto; the block bytes follow formats/kv-block.md, and the conformance suite parity/kv.wire.v1 pins them. The solution lives in tl-engine/src/kv_transfer.rs (hashing, checksums, the envelope, the decode side KvReceiver and KvService, the prefill side’s deduplicated push build_chunks and transfer, and resume_rng), tl-engine/src/heartbeat.rs (worker_status, beat_once, Heartbeat), tl-serve/src/control.rs (ControlService for tl.engine.v1.EngineControl: Prefill, Info, Cancel, Drain, over a PrefillBackend), and the serve loop’s EngineBackend and resume_generate in tl-serve/src/server.rs.
Learning objectives
- Explain why a chained block hash lets two engines agree on which KV blocks they share, and compute the bytes one transfer moves.
- Validate an untrusted KV envelope in the right order and map each failure to the gRPC status that drives the gateway’s routing.
- Write a push that is all-or-nothing, so that no error path on either engine leaks a block.
- Hand a seeded sampler from one engine to another so that disaggregated output equals colocated output token for token.
- Build a heartbeat client that never blocks the engine and never stops beating.
How a disaggregated request flows
Section titled “How a disaggregated request flows”Before looking at bytes, it helps to see the whole conversation. Three parties are involved: the gateway, a prefill engine P, and a decode engine D.
gateway prefill engine P decode engine D | Prefill(prompt, seed, decode_target=D) | | |--------------------------------------->| prefill, sample first token | | |-- HasBlocks(h_0..h_{F-1}) -->| lookup each hash (no reference kept) | |<-- present[] ----------------| | |== PushKv(stream of chunks) =>| import missing blocks, reference present ones, | |<-- KvAck --------------------| hold them under the handle id |<-- KvHandle{first_token, hashes, draws}| drop P's own references | |-- POST /v1/chat/completions, X-TL-KV-Handle ------------------------->| claim the handle's blocks, resumeThe gateway emits first_token to the client at once and then streams the rest from D. If the client aborts, the gateway calls Release on D. Everything in this section is about making each arrow in that diagram cheap, safe, and exact.
A handful of symbols recur in the rest of the section, so here they are in one place.
| Symbol | Meaning | Type |
|---|---|---|
tokens per block (block_tokens; the engine uses 16, the small examples 4) | u32 | |
| layers, KV heads, head dimension | u32 | |
| payload bytes of one block in format v1 (K and V, f16) | usize | |
| bytes of an envelope of blocks | usize | |
| hash of full block ; | u64 | |
| full blocks the decode engine already caches | count | |
| , | full blocks of the prompt; when a partial tail exists, else 0 | count |
Naming blocks by content
Section titled “Naming blocks by content”The first problem is that two engines must agree on what a block is without comparing contents. Sending a block just to ask “do you have this?” defeats the purpose. Each full block needs a short name that depends only on its tokens and on everything before them, because a block’s K and V depend on the whole prefix that attention saw. That requirement forces a chained hash.
The model runner and sampler already hashes a full block as
with a result of 0 replaced by 1. Chaining the parent makes name the whole prefix up to block : two prompts that share their first blocks share and nothing after. The decode engine’s prefix index (the Swiss table from Programming and Algorithms, used inside the model runner) answers “do I hold ?” in O(1).
A partial block has no hash, since its contents will still change as tokens are appended. It has hash 0, is never deduplicated, and is always sent.
What crosses the wire
Section titled “What crosses the wire”Each KvChunk carries one block as a one-block envelope of kv-block.md: the 28-byte header, the record (a u64 hash, a u32 fill, then payload bytes, zeros past the fill), and a CRC-32C over everything before it. The chunk repeats the hash and carries its own CRC-32C of the payload. A block that D reported present travels as an empty payload with its hash set, and D takes a reference on its cached copy instead of importing anything. So the payload bytes of one transfer are
That formula is the whole economic argument for deduplication: only the missing full blocks and the partial tail cost anything.
Trusting nothing from the network
Section titled “Trusting nothing from the network”The decode side reads bytes from the network, so they are untrusted. D refuses an envelope, with nothing allocated, when its length is not , its magic is not TLKV, its CRC fails, its version or dtype is not one D reads, its dimensions differ from D’s pool, a fill is outside , or a hashed block is not full.
The kind of refusal matters as much as the refusal itself, because error kinds drive the gateway’s routing. Corruption is DATA_LOSS: the gateway may retry, perhaps elsewhere. A version D does not read is FAILED_PRECONDITION: it will never work on this worker, so route elsewhere.
One subtlety concerns blocks P never registered. If another block already held a full block’s hash in P’s index, that block travels with hash 0 in its envelope; the chunk’s hash names it, and D registers it on arrival.
Resuming the generator
Section titled “Resuming the generator”A seeded request must not notice that it was split. Its tokens are drawn from stream(seed, sample) (see spec/pcg32.md). P drew the first token with one uniform_f64 (0 draws when greedy) and reports rng_draws_consumed. D seeds the same stream and advances it by that many uniforms before its first draw, so a seeded disaggregated request emits exactly the tokens a unified engine would, given the same logits.
Freeing on every path
Section titled “Freeing on every path”The KV pool is the engine’s scarcest resource, and every path that takes a block must give it back. The table lists each way a transfer can end and who frees what.
| Path | Who frees |
|---|---|
| push succeeds | P drops its references (full blocks stay cached on P); D holds them under the handle until the resume claims them |
| D refuses a chunk | D releases every block taken for this push before answering |
| the stream breaks (peer gone, cancel) | D’s stream read fails; same as a refusal |
| the push fails on P’s side | P drops its references, then answers the error |
| the client aborts after Prefill | the gateway calls Release(handle) on D |
The heartbeat
Section titled “The heartbeat”The last piece is liveness. Every 2 s each engine sends a WorkerStatus: its id, three addresses, role, model, KV format, queue depth, running sequences, free and total blocks, and whether it is draining. The gateway evicts a worker after 3 missed beats.
Two rules follow from that. A beat must be bounded by a timeout, because a hung registry must not hang the engine. And failures must not stop the loop, because the registry restarting is not the engine’s problem. Only a decode engine advertises kv_address, since only a decode engine receives pushes. An ack with drain = true is remembered until the engine has drained.
Working it by hand
Section titled “Working it by hand”With the rules in place, you can work one envelope, one transfer, and one hand-off with pencil and paper.
One block. This is the example in kv-block.md: , one layer, one head, , and the full block of tokens [1, 2] with K = [[1, 2], [3, 4]] and V = [[0.5, -1], [0, 0.25]].
- Hash: the bytes are
00x8 (parent 0),01 00 00 00,02 00 00 00; FNV-1a 64 gives0xA91AB0C1027B9366. - , so bytes.
- f16: 1.0 is
0x3C00(exponent 15, which is the bias, mantissa 0), stored00 3c; 0.5 is0x3800; -1.0 is0xBC00; 0.25 is0x3400. - The CRC-32C of the first 56 bytes is
0x4F0B541C, appended little-endian:1c 54 0b 4f.
One transfer. Take small shapes: , , , , so and a one-block envelope is bytes. A 9-token prompt has full blocks and a tail of 1 token (). D already caches block 0 (). Each block becomes one chunk:
| Block | Hash | Present on D | Chunk |
|---|---|---|---|
| 0 | yes | empty payload, hash : D takes a reference | |
| 1 | no | 172-byte envelope | |
| 2 (tail, 1 token) | 0 | never asked | 172-byte envelope, fill 1, zeros after |
Bytes moved: . The ack says blocks_received = 2, blocks_deduped = 1.
The hand-off. Seed 77 at temperature 0.9: P draws for the first token and reports rng_draws_consumed = 1. D’s generator starts at stream(77, sample) advanced by one uniform_f64, so its first draw is , the draw a unified engine would use for token 2.
Designing the interface
Section titled “Designing the interface”The interface spans three files. kv_transfer.rs holds the bytes and both sides of the transfer, heartbeat.rs the liveness client, and control.rs the gRPC service the gateway calls.
pub use {tl_proto, tokio, tonic}; // one version of each for the engine and the testspub type SharedKv = Arc<Mutex<KvPool>>;pub fn fnv1a64(data: &[u8]) -> u64;pub fn block_hash(parent: u64, tokens: &[u32]) -> u64; // 0 becomes 1pub fn prompt_hashes(tokens: &[u32], block_tokens: usize) -> Vec<u64>; // full blocks onlypub fn crc32c(data: &[u8]) -> u32;pub struct EnvHeader { pub version: u16, pub dtype: u16, pub n_blocks: u32, pub block_tokens: u32, pub n_layers: u32, pub n_kv_heads: u32, pub head_dim: u32 }pub struct BlockRecord { pub hash: u64, pub n_tokens: u32, pub payload: Vec<u8> }pub enum EnvError { Format(String), Version(String), Shape(String) }pub fn write_envelope(h: &EnvHeader, blocks: &[BlockRecord]) -> Vec<u8>;pub fn read_envelope(buf: &[u8], expect: Option<&KvCfg>) -> Result<(EnvHeader, Vec<BlockRecord>), EnvError>;pub fn resume_rng(seed: u64, draws: u32) -> Pcg32;pub struct KvReceiver { /* pool, handle -> block ids */ }impl KvReceiver { pub fn new(pool: SharedKv) -> KvReceiver; pub fn has_blocks(&self, hashes: &[u64], kv_format: u32) -> Result<Vec<bool>, Status>; pub fn accept_chunk(&self, c: &KvChunk, expect_index: u32, taken: &mut Vec<u32>) -> Result<bool, Status>; pub fn accept_all(&self, chunks: impl IntoIterator<Item = Result<KvChunk, Status>>) -> Result<KvAck, Status>; pub fn claim(&self, handle_id: &str) -> Option<Vec<u32>>; // the resumed request takes the blocks pub fn release(&self, handle_id: &str); pub fn pending(&self) -> usize;}pub struct KvService(pub Arc<KvReceiver>); // impl KvTransferService (has_blocks, push_kv, release)pub fn spawn_router(listener: TcpListener, router: tonic::transport::server::Router) -> io::Result<GrpcServer>;pub fn serve_kv(listener: TcpListener, recv: Arc<KvReceiver>) -> io::Result<GrpcServer>;#[tonic::async_trait] pub trait KvTransport: Send + Sync { async fn has_blocks(&self, target: &str, hashes: &[u64], fmt: u32) -> Result<Vec<bool>, TransferError>; async fn push(&self, target: &str, chunks: Vec<KvChunk>) -> Result<KvAck, TransferError>;}pub struct GrpcTransport { pub timeout: Duration } // impl KvTransportpub fn build_chunks(pool: &SharedKv, handle_id: &str, ids: &[u32], hashes: &[u64], present: &[bool]) -> Result<Vec<KvChunk>, TransferError>;pub async fn transfer(t: &dyn KvTransport, target: &str, pool: &SharedKv, handle_id: &str, ids: &[u32], hashes: &[u64]) -> Result<TransferStats, TransferError>;
// rust/crates/tl-engine/src/heartbeat.rs#[tonic::async_trait] pub trait Registry: Send + Sync { async fn heartbeat(&self, s: WorkerStatus) -> Result<HeartbeatAck, String>; }pub struct GrpcRegistry { pub target: String, pub timeout: Duration }pub fn worker_status(id: &WorkerIdentity, load: &Load) -> WorkerStatus;pub async fn beat_once(reg: &dyn Registry, status: WorkerStatus, timeout: Duration, st: &BeatState) -> bool;impl Heartbeat { pub fn spawn(reg, id, load: Arc<dyn Fn() -> Load + Send + Sync>, interval, timeout) -> io::Result<Heartbeat>; pub fn stop(self); }
// rust/crates/tl-serve/src/control.rs#[tonic::async_trait] pub trait PrefillBackend: Send + Sync + 'static { async fn prefill(&self, job: PrefillJob) -> Result<PrefillOutcome, Status>; // first token, block ids, hashes, draws fn pool(&self) -> SharedKv; fn info(&self) -> InfoResponse; async fn cancel(&self, request_id: &str) -> bool; async fn drain(&self, deadline_ms: i64) -> i32;}pub struct ControlService<B: PrefillBackend> { pub backend: Arc<B>, pub transport: Arc<dyn KvTransport>, pub roles: Vec<String> }pub fn sampling_from_proto(p: Option<&pb::SamplingParams>) -> Result<(SamplingParams, u64, usize), Status>;pub fn serve_control<B: PrefillBackend>(listener: TcpListener, svc: ControlService<B>) -> io::Result<GrpcServer>;The serve loop implements PrefillBackend as EngineBackend in server.rs: it prefills the prompt through the block manager, samples the first token, and hands back the block table. On a decode engine it resumes a request from claim(handle) with its generator advanced as resume_rng(seed, draws) would leave it (see the RNG hand-off below).
The wiring is small. The solution’s tl-engine depends on tl-proto (the generated code in contracts/rust/tl-proto), tokio (full), tonic = "0.14", and prost = "0.14", all listed in allowed-deps.toml. It declares pub mod kv_transfer; pub mod heartbeat; in tl-engine/src/lib.rs and pub mod control; in tl-serve/src/lib.rs. The server starts kv_transfer::serve_kv on [engine].kv_listen for a decode engine, control::serve_control on [engine].grpc_listen for every engine, and Heartbeat::spawn toward [engine].gateway_registry.
Building it step by step
Section titled “Building it step by step”Reasoning from first principles
Section titled “Reasoning from first principles”Before reading code, it is worth seeing that the design is almost forced by a chain of observations.
- Two engines must agree on what a block is without comparing contents. Each full block needs a short name that depends only on its tokens and everything before them, since a block’s K and V depend on the whole prefix. That forces the chained hash .
- A partial block cannot be named. Its contents change as tokens are appended, so it has hash 0, is never deduplicated, and is always sent. That gives the envelopes of the byte formula.
- Bytes from the network are untrusted. The reader must check length, magic, CRC, version, shape, and fills before allocating anything, and must classify the failure: corruption (DATA_LOSS, retry elsewhere) versus a format this worker will never read (FAILED_PRECONDITION).
- A push is a transaction. D takes a reference per chunk as chunks arrive; if anything fails, the push must leave D exactly as before. So every taken block id goes into one
takenvector, and the error path releases all of it. Only a complete push is stored under the handle. - Asking must be free.
HasBlocksuses the pool’slookup, which takes a reference; the answer must release it at once, or every routing question pins blocks. - Between asking and pushing, D can evict. A deduped chunk for a block that has since been evicted gets NOT_FOUND, and the only safe answer is to resend every payload once.
- P owns the prompt’s blocks until the push ends, either way. After success, D has its own copies; after failure, nobody needs them. So P releases its references unconditionally, after
transferreturns and before looking at its result. - Seeded sampling must not notice the split. Both engines use
stream(seed, sample). P usedrng_draws_consumeduniforms for the first token, so D’s generator must stand that many draws in. - Liveness reporting must not depend on the registry being alive. Each beat is wrapped in a timeout, failures are counted and never end the loop, and the heartbeat runs on its own thread and runtime, so a hung registry cannot touch the engine.
The rest of this section turns each observation into code.
Hashes and checksums
Section titled “Hashes and checksums”Hashing is the foundation, so it comes first. block_hash writes the parent before the tokens, and prompt_hashes walks the prompt’s full blocks only.
/// The chained hash of one full block: fnv1a64(le_u64(parent) || le_u32(tokens)...), 0 replaced by 1.pub fn block_hash(parent: u64, tokens: &[u32]) -> u64 { let mut buf = Vec::with_capacity(8 + 4 * tokens.len()); buf.extend_from_slice(&parent.to_le_bytes()); // the parent makes h_i name the whole prefix for t in tokens { buf.extend_from_slice(&t.to_le_bytes()); // little-endian: the same bytes on every engine } match fnv1a64(&buf) { 0 => 1, // 0 is reserved for "no hash" (a partial or unregistered block) h => h, }}
pub fn prompt_hashes(tokens: &[u32], block_tokens: usize) -> Vec<u64> { let mut out = Vec::with_capacity(tokens.len() / block_tokens); let mut parent = 0; for chunk in tokens.chunks_exact(block_tokens) { // chunks_exact drops the partial tail parent = block_hash(parent, chunk); out.push(parent); } out}crc32c is the bitwise reflected CRC with polynomial 0x82F63B78, init and final xor all ones: eight shift-and-xor steps per byte. It is slow next to a table or the SSE4.2 instruction, but a 172-byte block is nothing next to the forward pass that produced it, and the bit loop is easy to check against the check value in kv-block.md.
The envelope reader
Section titled “The envelope reader”With checksums available, the reader can validate an envelope. Its checks are ordered so that each one can trust what the previous ones established.
pub fn read_envelope(buf: &[u8], expect: Option<&KvCfg>) -> Result<(EnvHeader, Vec<BlockRecord>), EnvError> { if buf.len() < HEADER_BYTES + 4 { /* Format */ } // enough bytes to read a header at all if &buf[..4] != b"TLKV" { /* Format */ } let h = EnvHeader { /* version, dtype, n_blocks, block_tokens, n_layers, n_kv_heads, head_dim */ }; // u128: a hostile n_blocks cannot overflow the expected length let want_len = (h.n_blocks as u128) * (12 + h.payload_bytes() as u128) + HEADER_BYTES as u128 + 4; if buf.len() as u128 != want_len { /* Format */ } let body = &buf[..buf.len() - 4]; if crc32c(body) != u32_at(buf, buf.len() - 4) { return Err(EnvError::Format("CRC mismatch".into())); // -> DATA_LOSS } // only after the CRC: a version field we trust was really sent if h.version != 1 || h.dtype != DTYPE_F16 { return Err(EnvError::Version(/* ... */)); // -> FAILED_PRECONDITION } if let Some(c) = expect { // B, L, Hkv, D must equal the receiving pool's, or the bytes mean something else // ... EnvError::Shape } // ... per block: n_tokens in 1..=B, and a non-zero hash only on a full block}status_of maps EnvError::Version to FAILED_PRECONDITION and everything else to DATA_LOSS. The CRC check comes before the version check deliberately: a flipped bit in the version field should read as corruption, not as “a format I do not read”.
The decode side: accepting one chunk
Section titled “The decode side: accepting one chunk”The decode side applies the reader to each chunk and then either imports the block or takes a reference on a cached copy.
pub fn accept_chunk(&self, c: &KvChunk, expect_index: u32, taken: &mut Vec<u32>) -> Result<bool, Status> { if c.kv_format != KV_FORMAT { return Err(Status::failed_precondition(/* ... */)); } // mixed-version rollout if c.block_index != expect_index { return Err(Status::invalid_argument(/* ... */)); } // order is the block table let mut pool = lock(&self.pool); if c.payload.is_empty() { // a deduped chunk: take a reference on D's cached copy if c.block_hash == 0 { return Err(Status::invalid_argument("an empty payload needs the block's hash")); } let id = pool.lookup(c.block_hash).ok_or_else(|| Status::not_found(/* evicted since HasBlocks */))?; taken.push(id); return Ok(true); } if crc32c(&c.payload) != c.crc32c { return Err(Status::data_loss(/* ... */)); } let cfg = pool.cfg(); let (_, recs) = read_envelope(&c.payload, Some(&cfg)).map_err(|e| status_of(&e))?; if recs.len() != 1 { return Err(Status::data_loss(/* ... */)); } // A full block P never registered travels with hash 0 in its envelope; // the chunk's hash names it. A registered one must agree. if recs[0].hash != 0 && recs[0].hash != c.block_hash { return Err(Status::data_loss(/* ... */)); } if c.block_hash != 0 && recs[0].n_tokens != cfg.block_tokens { return Err(Status::data_loss(/* ... */)); } let ids = pool.import(&c.payload).map_err(/* EFULL/ENOMEM -> RESOURCE_EXHAUSTED, else DATA_LOSS */)?; let id = ids[0]; taken.push(id); // pushed before register: if register fails, the error path frees it if c.block_hash != 0 { pool.register(id, c.block_hash).map_err(|e| Status::internal(e.to_string()))?; // the next prompt can dedup it } Ok(false)}Every refusal happens before import, so a refused chunk allocates nothing; whatever earlier chunks took is already in taken.
The decode side: all or nothing
Section titled “The decode side: all or nothing”One chunk at a time is not enough; the whole push has to be a transaction. The gRPC handler reads the stream and keeps a single taken list.
async fn push_kv(&self, request: Request<Streaming<KvChunk>>) -> Result<Response<KvAck>, Status> { let mut s = request.into_inner(); let mut taken: Vec<u32> = Vec::new(); // ... ack, total, i let res: Result<(), Status> = async { // s.message() fails when the peer goes away mid-transfer: same path as a refusal while let Some(c) = s.message().await? { // ... the first chunk fixes handle_id and n_blocks_total; later chunks must match if self.0.accept_chunk(&c, i, &mut taken)? { ack.blocks_deduped += 1; } else { ack.blocks_received += 1; } i += 1; } if taken.len() as u32 != total || taken.is_empty() { return Err(Status::invalid_argument(/* stream ended early */)); // a clean early end is still incomplete } Ok(()) } .await; match res { Ok(()) => { self.0.store(&ack.handle_id, taken); Ok(Response::new(ack)) } // held until claim or Release Err(st) => { self.0.release_ids(&taken); Err(st) } // D exactly as before }}The async block plus one match is the Rust shape of “try, and on any error roll back”: every ? inside lands in Err(st), so no exit path can skip release_ids. store releases whatever an older handle with the same id held, so a retried push does not leak the first attempt. release is claim followed by release_ids, so it is idempotent and accepts unknown handles.
has_blocks has the opposite obligation: it must release the reference lookup took, because asking should take nothing.
for &h in hashes { match pool.lookup(h) { Some(id) => { pool.release(id).map_err(|e| Status::internal(e.to_string()))?; // asking takes nothing out.push(true); } None => out.push(false), }}The prefill side
Section titled “The prefill side”On P, build_chunks turns the block table into chunks, and transfer asks, pushes, and retries once on eviction.
pub fn build_chunks(pool: &SharedKv, handle_id: &str, ids: &[u32], hashes: &[u64], present: &[bool]) -> Result<Vec<KvChunk>, TransferError> { let pool = lock(pool); let mut out = Vec::with_capacity(ids.len()); for (i, &id) in ids.iter().enumerate() { let hash = hashes.get(i).copied().unwrap_or(0); // past the full blocks: the tail, hash 0 let dedup = hash != 0 && present.get(i).copied().unwrap_or(false); let payload = if dedup { Vec::new() } else { pool.export(&[id]).map_err(/* ... */)? }; // a one-block envelope let crc = if payload.is_empty() { 0 } else { crc32c(&payload) }; out.push(KvChunk { handle_id: handle_id.to_string(), block_hash: hash, block_index: i as u32, n_blocks_total: ids.len() as u32, kv_format: KV_FORMAT, payload, crc32c: crc }); } Ok(out)}
pub async fn transfer(t: &dyn KvTransport, target: &str, pool: &SharedKv, handle_id: &str, ids: &[u32], hashes: &[u64]) -> Result<TransferStats, TransferError> { let present = t.has_blocks(target, hashes, KV_FORMAT).await?; // ... a short answer is an error let chunks = build_chunks(pool, handle_id, ids, hashes, &present)?; match t.push(target, chunks.clone()).await { Ok(ack) => Ok(stats(&chunks, &ack)), Err(e) if e.code == tonic::Code::NotFound => { // a cached block was evicted between the two calls: resend everything once let all = build_chunks(pool, handle_id, ids, hashes, &vec![false; hashes.len()])?; let ack = t.push(target, all.clone()).await?; Ok(stats(&all, &ack)) } Err(e) => Err(e), }}Trace the hand-worked transfer through this code. present = [true, false], so chunk 0 is empty with hash , chunk 1 is a 172-byte envelope, and chunk 2 (the tail, where hashes.get(2) is None) is a 172-byte envelope with hash 0: 344 payload bytes, as computed earlier.
ControlService::run_prefill in control.rs validates before doing any work: the engine must serve prefill, prompt and target must be non-empty, the deadline must be in the future, and sampling ranges are checked by sampling_from_proto. It then runs the backend’s prefill, and afterwards:
let res = kv_transfer::transfer(self.transport.as_ref(), &r.decode_target, &pool, &handle_id, &out.block_ids, &out.block_hashes).await;// P's references go either way: D holds its own copies now, and a// registered full block stays cached here for the next prompt.self.release(&out.block_ids);res.map_err(|e| transfer_status(&e))?; // an unreachable D becomes UNAVAILABLE: the gateway picks another// ... KvHandle { handle_id, n_tokens, block_hashes, kv_format, first_token, prompt_tokens, rng_draws_consumed }Releasing before the ? is the line that keeps a failed push from leaking the prompt’s blocks on P.
The RNG hand-off
Section titled “The RNG hand-off”The generator hand-off is a few lines once the stream is shared.
pub fn resume_rng(seed: u64, draws: u32) -> Pcg32 { let mut r = stream(seed, PURPOSE_SAMPLE); // the same stream P seeded for _ in 0..draws { r.uniform_f64(); // one uniform per sampled token; 0 when greedy } r}The serve loop’s decode side (resume_generate) reaches the same state another way. The resume request does not carry P’s first token, so D claims the handle’s blocks, recomputes the last prompt position (rewriting the same KV), and samples it from a fresh stream(seed, sample). Given the same logits, that draws the same first token P drew, and leaves the generator exactly where resume_rng(seed, rng_draws_consumed) would. Either way, token 2 uses the draw from the hand-worked example.
The heartbeat
Section titled “The heartbeat”Finally, the heartbeat. A single beat is a bounded call whose outcome updates shared counters.
pub async fn beat_once(reg: &dyn Registry, status: WorkerStatus, timeout: Duration, st: &BeatState) -> bool { st.sent.fetch_add(1, Ordering::SeqCst); match tokio::time::timeout(timeout, reg.heartbeat(status)).await { // a hung registry costs at most `timeout` Ok(Ok(ack)) => { st.consecutive_failures.store(0, Ordering::SeqCst); // a success resets the miss count if ack.drain { st.drain.store(true, Ordering::SeqCst); // sticky: never cleared by a later ack } st.route_epoch.store(ack.route_epoch, Ordering::SeqCst); true } _ => { // an error and a timeout count the same st.failed.fetch_add(1, Ordering::SeqCst); st.consecutive_failures.fetch_add(1, Ordering::SeqCst); false } }}Heartbeat::spawn runs a current-thread runtime on its own OS thread and ticks with MissedTickBehavior::Delay, so a slow beat delays the next one instead of causing a burst. It reads load() fresh before each beat and select!s on a oneshot so that stop returns promptly even mid-beat. worker_status advertises kv_address only when the role is decode, since only a decode engine receives pushes.
The full solution is in kv_transfer.rs, heartbeat.rs, control.rs, and the backend in server.rs.
Why this design
Section titled “Why this design”Start with cost. Hashing is in prompt tokens, HasBlocks is lookups, and a transfer moves bytes. For a shared 2,000-token system prompt at , every block after the first request is deduped, and the push carries only the user’s tail.
Why one chunk per block rather than one big envelope? A per-block chunk can be deduped individually, checked individually (a corrupt block names its index), and streamed without holding the whole prompt’s KV in one message, which would hit gRPC’s message size limit for long prompts.
Why a chained hash rather than a hash of the block’s own tokens? Two prompts can share block 3’s tokens and differ before it, and their KV for block 3 differs because attention saw different prefixes. Only the chain makes equal hashes mean equal KV.
Why a separate prefill RPC rather than prefill over HTTP? The gateway needs the KvHandle (hashes, draws, first token) as typed data, and gRPC streams fit the push; HTTP stays the client-facing API.
Two tradeoffs are accepted knowingly. The eviction retry resends every payload rather than only the evicted ones, which is simpler, and evictions between two calls milliseconds apart are rare. And Cancel and Drain on the engine backend are minimal: a prefill runs to completion, and draining is SIGTERM’s job.
What can go wrong
Section titled “What can go wrong”The tests run a fake model that writes a fixed f16 pattern per position into real pools from the model runner, and whose logits hash every cached KV value, so any lost or stale block changes the next token. Prefill and decode engines run the real servers on 127.0.0.1:0. A correct solution has to handle each of these cases:
| Case | Checks | Why it matters downstream |
|---|---|---|
| The hand envelope | the 60-byte worked envelope, the two chained hashes, FNV-1a and CRC-32C check values | the bytes every engine and the KV format v2 migration agree on |
| Reader rules | each reader rule refuses with the right error kind | corrupt or foreign bytes never reach the pool |
| The golden blobs | Rust writer and parity/kv.wire.v1 agree byte for byte; the reader takes them back | parity with the file contract |
| RNG hand-off | resume_rng equals the stream advanced by 0, 1, 2 draws | seeded streams survive the hand-off |
| HasBlocks takes no reference | a hit leaves used and cached counts unchanged; format 2 refused | asking is free |
| Push accepts, dedups, and refuses | import, dedup, and every refusal leaving D exactly as before; an unregistered full block is registered on arrival | no leak on a bad push |
| Release | Release frees, is idempotent, accepts unknown handles; P holds nothing after a push | the gateway’s abort path |
| Disaggregated equals colocated | the same 12 tokens through P and D as on one engine, greedy and two seeds, three prompts | the whole point |
| Bytes moved | sent, deduped, and payload bytes equal the byte formula for 3 cache states | dedup really saves the transfer |
| A reset mid-push | a proxy cuts the push: the RPC fails, both pools return to baseline, both engines keep serving | a decode pod dying mid-transfer |
| An abandoned push | a push abandoned after 5 of 10 chunks leaves D clean | a cancelled stream is not a leak |
| An evicted block | NOT_FOUND on a deduped chunk makes P resend every payload once | a cache eviction between the two calls |
| Prefill validation and Info | role, empty fields, ranges refused before work; Info, Cancel, Drain | the gateway’s routing mistakes are caught |
| Worker status fields | only decode advertises kv_address; format 1; live load | the registry routes KV correctly |
| Beat failures and drain | failures counted and reset, a hung registry bounded by the timeout, drain sticky | the engine outlives a registry outage |
| Heartbeat schedule | beats at once and every interval with fresh load; stop is prompt | the gateway’s view is current |
| gRPC registry round trip | the gRPC client against a real WorkerRegistry server; an unreachable one errors in time | the production path |
Most bugs in this code are quiet: they produce wrong KV or slow leaks rather than crashes. The common ones fall into three groups.
The first group corrupts KV. Hashing a block without its parent lets two prompts that differ early dedup each other’s later blocks, which means wrong KV; block_hash writes le64(parent) before the tokens. Not checking the envelope CRC turns a flipped bit on the wire into a wrong attention value; read_envelope checks the envelope CRC and accept_chunk the chunk CRC, both before importing. A v1 reader that accepts version 2 would read fp8 bytes as f16 during the KV format v1 to v2 migration in Software Engineering; read_envelope refuses any version other than 1 or dtype other than f16 with FAILED_PRECONDITION. Not checking a chunk’s kv_format makes mixed-version rollouts corrupt KV instead of failing cleanly, which is why accept_chunk checks it first. Skipping a deduped block that is gone leaves a handle with a hole, and decode reads an unowned block; a deduped chunk’s lookup miss is NOT_FOUND, and transfer resends every payload once. Advancing the generator one draw too few makes seeded disaggregated streams differ after the first token; resume_rng advances by rng_draws_consumed.
Warning: The second group leaks blocks, and leaks are the bugs that take down a serving fleet slowly. If
HasBlockskeeps its lookup’s reference, blocks are pinned by questions and the pool shrinks with every routing decision. If a refused push keeps what it took, every bad request leaks blocks on D. If P never drops its references, the prefill pool fills after a few hundred requests. If P returns the transfer error before releasing, each failed push leaks the prompt’s blocks on P. The solution guards these withhas_blocksreleasing each hit at once, onetakenlist withrelease_ids(&taken)on every error, andself.release(...)running beforeres.map_err(...)?after every transfer.
The third group wastes work or misleads the gateway. Sending blocks D already holds makes shared system prompts cost a full transfer every time, so the solution asks HasBlocks first and sends empty payloads for present blocks. The writer dropping the block hash means D can never dedup what this engine sends; build_chunks sets block_hash on every full block’s chunk, and accept_chunk registers it. A decode-only engine running Prefill builds KV nobody will read, so run_prefill refuses with FAILED_PRECONDITION unless the roles include prefill. And a success that does not reset the miss count makes the gateway’s eviction logic see phantom misses, which is why beat_once stores 0 in consecutive_failures on every success.
Where this leads
Section titled “Where this leads”This section leans on the model runner’s KvPool (export, import, register, lookup, slabs) and its stream for the hand-off, and on the Rust pool behind both engines from the paged KV block pool: the export envelope, the prefix index, refcounts.
Several later sections build on it. In AI Engineering, worker registry and routing picks P and D, calls Prefill and Release over gRPC, and serves the registry the heartbeat reaches. In Software Engineering, the KV format v1 to v2 migration takes kv_transfer.rs over for format v2 (fp8) and mixed-version negotiation, and the API v1 to v2 migration preserves heartbeat registration, registry-driven draining, and control in the upgraded serve loop.
The production deployment runs these engines as 1 prefill + 2 decode on kind, and the incident drill a decode worker dies mid-stream in Systems Engineering kills a decode pod mid-load. Tracing for the serving path traces kv.transfer as a CLIENT span on P and a SERVER span on D. The next section, serving metrics and tracing, adds the metrics and spans that make all of this observable.
This solution is deliberately minimal next to production systems. Where it uses one gRPC stream per handle, NIXL and the Mooncake transfer engine use RDMA and GPU-direct transfers with no copy through host memory. Where it dedups by chained block hash against one decode target, vLLM’s disaggregated prefill and LMCache keep a shared KV store across many engines. Where it fixes prefill and decode as roles, DistServe and Splitwise tune role ratios to the workload and change roles at run time. And where it sends a 2 s heartbeat with load, KV-aware routers such as llm-d and Dynamo route on each worker’s cached prefixes, not just its load.
Further reading
Section titled “Further reading”- DistServe (free) and Splitwise (free): the papers that made the case for splitting prefill and decode.
- Mooncake (free) and its transfer engine; NIXL.
- vLLM disaggregated prefill and LMCache.
- llm-d and NVIDIA Dynamo: KV-aware routing.
- gRPC core concepts (free).
Key terms
Section titled “Key terms”- Prefill/decode disaggregation: running prompt prefill and token decode on separate engines, so the two phases stop competing for one batch.
- Chained block hash: , a name for a full block that identifies its whole prefix, so equal hashes mean equal KV.
- KV envelope: the
kv-block.mdbyte format: a 28-byteTLKVheader, per-block records (hash, fill, f16 payload), and a trailing CRC-32C. - Deduplicated push: a transfer in which blocks the receiver already caches travel as empty payloads with their hash, so only missing blocks and the tail cost bytes.
- KV handle: the id under which D holds a completed push’s blocks until the resumed request claims them or the gateway releases them.
rng_draws_consumed: the number of uniforms P drew for the first token, which D skips so the seeded stream continues exactly.- Heartbeat: the periodic
WorkerStatusan engine sends to the gateway’s registry; three missed beats evict the worker.
Summary
Section titled “Summary”- A block’s hash names its whole prefix (
H(parent, tokens)), so “D already holds this block” is one table lookup, and only the missing full blocks plus the partial tail cross the network: bytes. - The decode side reads bytes from the network: every reader rule of
kv-block.mdrefuses bad input before anything is allocated, with DATA_LOSS for corruption and FAILED_PRECONDITION for a format it does not read, and the CRC is checked before the version. - Every error path frees what it took: a refused push, a stream cut mid-transfer, an abandoned client, a released handle. Neither engine’s pool may leak.
- Prefill on one engine and decode on another give the same tokens as one engine doing both, greedy and seeded, because the decode side’s generator ends up advanced by exactly the draws the prefill side used.
- The heartbeat never blocks the engine and never stops: each beat is bounded by a timeout, misses are counted, and a drain request is remembered.
Review questions
Section titled “Review questions”-
Why must
HasBlocksrelease the reference thatlookuptakes?Answer
lookupreturns a block with its refcount raised, which is right for a user of the block but wrong for a question. IfHasBlockskept it, every routing decision would pin the prompt’s cached blocks, and the decode pool would shrink with every request the gateway merely considered. The push takes its own reference later, inaccept_chunk. -
A proxy cuts the push after 5 of 10 chunks. Walk through what each side frees.
Answer
On D,
s.message().await?fails, the async block returnsErr, andrelease_ids(&taken)drops the five references; the handle is never stored. On P,transferreturns an error, andrun_prefillcallsself.release(&out.block_ids)before propagating it, so P’s references go too. Both pools return to baseline, and registered full blocks on P stay cached (with no request reference) for the next prompt. -
Why does the envelope reader check the CRC before the version field?
Answer
Error kinds drive routing: FAILED_PRECONDITION means “never send this format here”, DATA_LOSS means “retry, maybe elsewhere”. If the version were read before the CRC, a single flipped bit in the version would be misreported as a format mismatch and the gateway would stop routing to a healthy worker. After the CRC passes, the version is the one the writer meant.
-
Seed 77, temperature 0.9. What breaks if D starts from
stream(77, sample)and samples token 2 directly?Answer
Token 2 would use , the draw P already used for token 1, so every later token is shifted by one draw relative to a unified engine and the seeded stream diverges after the first token. D must stand one draw in:
resume_rng(77, 1), or, as the serve loop does, resample the first token from the fresh stream to reach the same state. -
Why is
drainsticky inBeatState?Answer
The registry asks a worker to drain once; a later ack may not repeat the flag (the registry may restart, or the beat after the request may time out). If one ack without
draincould clear it, the engine would resume taking traffic the gateway has already moved away. Draining is a one-way transition until the process restarts. -
A 9-token prompt at with , where D caches block 0. How many payload bytes move, and what does the ack report?
Answer
, , , and one envelope is bytes, so bytes. Block 0 travels as an empty payload with hash ; block 1 and the one-token tail travel as full envelopes. The ack reports
blocks_received = 2,blocks_deduped = 1.