Netty Framing Deep Dive: LengthFieldBasedFrameDecoder, TCP Stick/Unpack, and Protocol Pitfalls
This article analyzes three real-world Netty framing failures — half-pack JSON parsing, fixed-length decoder misalignment, and unbounded length-field OOM — then explains TCP's lack of message boundaries, compares three framing strategies, details LengthFieldBasedFrameDecoder's five parameters with diagrams, walks through ByteToMessageDecoder's cumulation and callDecode loop, shows Dubbo/gRPC protocol headers, and lists eight common codec pitfalls with fixes.
Three Incidents That Frame the Problem
Incident 1: Half-pack JSON. A gateway used JsonDecoder directly on the byte stream. Under load, 6 KB order messages triggered Unexpected end of JSON input. Root cause: one RPC message was split across multiple TCP segments; the first segment arrived with only half the message. The reverse case — stick pack — occurs when three small messages are sent back-to-back and the server reads all three concatenated; the parser consumes the first and discards the rest as garbage.
// Sender: two independent messages
write({"id":1,"name":"abc"})
write({"id":2,"name":"def"})
// Receiver may read once (stick pack)
{"id":1,"name":"abc"}{"id":2,"name":
// Or may read only (half-pack)
{"id":1,"naIncident 2: Fixed-length decoder meets variable-length messages. The team chose a fixed 512-byte frame for simplicity. When business fields changed length, short messages wasted bandwidth with zero-padding, long messages were truncated. Worse, a deployment once omitted one frame; afterward every message was parsed at the wrong offset — logs filled with "unknown message type 0x7F". Fixed-length only works when field lengths are absolutely constant.
Incident 3: Unbounded length field = OOM. A custom protocol used a 4-byte length field; the decoder copied the example and set maxFrameLength = Integer.MAX_VALUE. Attackers sent a packet claiming 2 GB; Netty faithfully allocated a cumulative buffer — one connection consumed 2 GB direct memory , triggering OOM Killer. The length field is peer-controllable input ; omitting a cap hands memory allocation to attackers.
Why TCP Has No Message Boundaries
TCP guarantees ordered, lossless, duplicate-free bytes — it never promises "one write equals one read" . Three mechanisms erase boundaries:
Nagle algorithm coalesces small writes into one segment.
Send buffer + MSS splits large messages into multiple segments.
Receive buffer merges multiple segments into one readable event for the application.
All happen at the TCP layer; the application sees only a continuous byte stream. Stick/Unpack is not a bug — it is normal behavior of a stream protocol . UDP preserves message boundaries but sacrifices reliability, MTU limits, and congestion control. RPC needs reliable long-lived connections, so every application protocol (HTTP Content-Length, gRPC 5-byte header) must carry its own length information.
Three Framing Schemes and Their Costs
① Fixed-length FixedLengthFrameDecoder: Every frame N bytes; read full = one frame. Pros: zero implementation cost. Cons: variable length = fatal.
② Delimiter DelimiterBasedFrameDecoder: Split on \n or custom string. Pros: readable (Redis/HTTP). Cons: payload cannot contain delimiter, requires escaping.
③ Length field LengthFieldBasedFrameDecoder: Header declares length; cut by length. Pros: universal, extensible, RPC standard. Cons: many parameters, misconfiguration = broken.
Selection logic: logs/text protocols → delimiter (readability first); binary RPC → length field (generality first); fixed-length only for heartbeats with immutable structure. Real protocols often combine: Dubbo uses 16-byte fixed header + variable body; gRPC uses 5-byte fixed header + variable body — both are essentially "length field + fixed header" .
LengthFieldBasedFrameDecoder's Five Parameters
Typical frame structure:
+--------+----------+----------+
| MAGIC | LEN(4B) | BODY |
| 4B | | LEN bytes|
+--------+----------+----------+
0 4 8 →
lengthFieldOffset = 4 (LEN start)
lengthFieldLength = 4 (LEN occupies 4 bytes)
lengthAdjustment = 0 (LEN value only includes BODY)
initialBytesToStrip = 8 (drop header, keep body)
maxFrameLength = upper bound, mandatorylengthFieldOffset : byte index where length field starts. Skip magic/version bytes before it.
lengthFieldLength : 1/2/3/4/8 bytes; determines whether decoder uses readByte / readShort / readInt.
lengthAdjustment : most error-prone . Answers: "besides itself, how many extra bytes does the length value cover?" If LEN = body length only → 0. If LEN = full frame minus header (includes length field itself) → -(offset + lengthFieldLength). If LEN is followed by another fixed header byte (e.g., serialization type) → 1.
initialBytesToStrip : bytes to discard after a full frame is sliced. 0 → downstream gets full frame with header (for magic/version verification); header length → downstream gets body directly. If protocol has magic/version to verify, must set 0 — otherwise verification logic never sees the header.
maxFrameLength : single-frame ceiling; exceeding throws TooLongFrameException. It is a safety valve, not a performance knob . Must reflect true business max message; never Integer.MAX_VALUE (Incident 3).
Mnemonic:
offset = where to read, length = how many bytes, adjustment = compensate difference, strip = keep or drop header, max = max allowed. When tuning, dump real frame hex and count byte-by-byte against the diagram — ten times faster than trial-and-error.
Codec Family: Who Cuts, Who Converts
ByteToMessageDecoder : inbound foundation, bytes → message , contains cumulation & decode loop (2.5). All inbound decoders extend it.
MessageToByteEncoder : outbound foundation, message → bytes , acceptOutboundMessage decides whether to handle the type; encoder releases original message after encoding.
MessageToMessageCodec : bidirectional codec in one class; suited for structure transformation not byte framing .
Layering principle: a pipeline typically has two codec layers — first LengthField handles framing (byte stream → complete byte frames), second custom decoder handles deserialization (byte frame → POJO). Mixing framing and deserialization in one class is the most common architectural mistake: framing logic becomes non-reusable, protocol upgrades require rewriting everything.
Cumulation: How Half-Packs Are Assembled
ByteToMessageDecodermaintains a cumulation buffer: when a read doesn't contain a full frame, bytes are neither dropped nor errored — they stay in cumulation awaiting the next read ; new data is merged ( cumulate) and decode retries. Two merge strategies:
MERGE_CUMULATOR (default): writes new bytes into old buffer, expands if needed. Good for small frames, high frequency.
COMPOSITE_CUMULATOR : uses CompositeByteBuf for zero-copy chaining, but index translation overhead is higher. Good for large frames, low frequency.
Two protection parameters: discardAfterReads (default 16, compresses cumulation after 16 empty reads to avoid reader-index drift) and singleDecode (default false; when true, only one frame per event — used for backpressure). Rarely changed, but worth checking when investigating "memory not releasing".
Real Protocols: Dubbo & gRPC Framing
Dubbo header (16 bytes) : 2-byte magic 0xdabb, 1-byte flags (request/two-way/event/serialization), 1-byte status, 8-byte requestId, 4-byte length — length value records "body length after header", so lengthAdjustment = 0, initialBytesToStrip left for downstream to skip 16 bytes. gRPC header (5 bytes) : 1-byte compression flag + 4-byte length, also body length only. Common pattern: fixed header declares variable body length — the universal skeleton of binary RPC.
HTTP/1.1 Content-Length and chunked encoding are two variants of the length-field idea: former declares total length once; latter splits message into "chunk-length + chunk-body" sequences. Any structured data over a byte stream must answer "where does this message end" in the protocol — no exceptions.
Core Flow: Decoding a Stick-Pack Read
Client sends three messages; server reads first two and a half in one go. Full journey:
Kernel buffer: [frame1][frame2][frame3-first-half]
↓ ① read: one ByteBuf handed up
↓ ② cumulate: merged into cumulation buffer
↓ ③ callDecode loop:
decode frame1 → out.add → fire
decode frame2 → out.add → fire
frame3 length insufficient → break
↓ ④ remaining half-frame stays in cumulation
↓ ⑤ next read arrives → retry decode
↓ ⑥ connection close → decodeLast fallbackKey point 1: one read may yield any number of messages; callDecode must loop — this is how "stick pack" is solved in code: not by discarding extra bytes, but by decoding them all.
Key point 2: undecodable half-frame must be retained . ByteToMessageDecoder uses readerIndex to preserve unconsumed bytes; never discardReadBytes — the #1 mistake when hand-writing decoders: clearing already-read-but-unconsumed bytes loses the frame forever.
Key point 3: every object in out list is released by downstream (per 04-article responsibility table); if callDecode throws, ByteToMessageDecoder releases out and cumulation in finally — no leak on exception paths.
Key point 4: on channel close, decodeLast is invoked once. Default impl calls decode — if cumulation holds a half-frame, it attempts one more decode (usually fails, then released with cumulation). To track "truncated connections", override decodeLast and check cumulation.isReadable().
Core Source Code: Five Segments to Master the Decode Chain
4.1 ByteToMessageDecoder.channelRead
public void channelRead(ctx, msg) {
if (msg instanceof ByteBuf) {
CodecOutputList out = ...;
try {
// merge into cumulation buffer
cumulation = cumulator.cumulate(
ctx.alloc(),
cumulation, (ByteBuf) msg);
// loop decode, may produce 0~N frames
callDecode(ctx, cumulation, out);
}
finally {
fireChannelRead(ctx, out);
out.recycle();
}
}
else {
ctx.fireChannelRead(msg);
}
}Two notes: out uses CodecOutputList (reusable lightweight list, avoids ArrayList allocation per read); fireChannelRead(ctx, out) overload passes each list element downstream sequentially — equivalent to multiple fires but with fewer stack frames. Another instance of 04-article "pooling mindset" at the codec layer.
4.2 callDecode: Why It Must Loop
protected void callDecode(ctx, in, out) {
while (in.isReadable()) {
int outSize = out.size();
int oldLen = in.readableBytes();
decodeRemovalReentry(ctx,
in, out);
// this round produced no new message
if (outSize == out.size()) {
// also consumed no bytes = half-pack
if (oldLen ==
in.readableBytes()) {
break;
// wait for next data
}
}
}
}The two checks answer different questions: outSize unchanged = "no new message produced" , oldLen unchanged = "not a single byte consumed" . Both true = half-pack → must break or CPU spins in empty loop. Conversely, if bytes were consumed but no message emitted (e.g., silently ate a heartbeat marker), loop continues — that frame is "silently handled".
4.3 LengthFieldBasedFrameDecoder Length Calculation
protected Object decode(ctx, in) {
// 1. enough bytes to read length field?
if (in.readableBytes() <
lengthFieldEndOffset) {
return null;
// half-pack
}
// 2. read length & adjust
int len =
getUnadjusted(in);
len += lengthAdjustment;
int frameLen = len
+ lengthFieldEndOffset;
// 3. safety valve: reject oversize
if (frameLen > maxFrameLength) {
throw new
TooLongFrameException();
}
// 4. not enough for full frame → half-pack
if (in.readableBytes() < frameLen) {
return null;
}
// 5. slice frame, strip header, pass downstream
in.skipBytes(initialBytesToStrip);
return in.
readRetainedSlice(
frameLen - initialBytesToStrip);
}Step 3 is Incident 3's defense: after reading length, before allocating memory, validate legality . This line reclaims "memory allocation authority" from the peer. Step 5 uses readRetainedSlice not readSlice — former increments refCnt, guaranteeing parent buffer stays alive while downstream holds the slice (04-article slice+retain standard pattern).
4.4 MessageToByteEncoder: The Outbound Half
public void write(ctx, msg, promise) {
ByteBuf buf = null;
try {
// type mismatch → pass through
if (
acceptOutboundMessage(msg)) {
buf = ctx.alloc().
buffer();
encode(ctx, msg, buf);
}
else {
ctx.write(msg, promise);
return;
}
}
catch (Throwable e) {
ReferenceCountUtil.
release(buf);
throw e;
}
ctx.write(buf, promise);
}Three details: ① acceptOutboundMessage is a type gate — one pipeline may carry business messages, heartbeats, control commands; encoder handles only its type, others pass through. ② Encode failure must release half-built buf (the catch block — 04-article fork). ③ Original msg release is upstream/framework's job ; encoder only produces new buf, never release msg here (double-release).
4.5 Custom Protocol Decoder: Extend + Secondary Parse
public class ProtocolDecoder
extends
LengthFieldBasedFrameDecoder {
public ProtocolDecoder() {
// max, offset, lengthBytes, adjustment, strip
super(
64 * 1024,
0,
4,
0,
4);
}
protected Object decode(ctx, in) {
Object frame =
super.decode(ctx, in);
if (frame == null) {
return null;
// half-pack
}
try {
return parse((ByteBuf) frame);
}
finally {
((ByteBuf) frame).
release();
}
}
}Recommended pattern: framing delegated to superclass, parse only does "complete frame → POJO" — single responsibility, testable, reusable. Note finally release: superclass returns a retainedSlice (refCnt already +1); after parse, must give it back — missing this line reproduces 04-article Incident 1.
Advanced: Private Protocol Design & Security
5.1 Production-Ready Protocol Header
magic 2B 0xCAFE identify protocol, fast-reject junk connections
version 1B protocol version, path for incompatible upgrades
flags 1B bit0=heartbeat bit1=oneway bit2=compression
type 1B request/response/control
serialize 1B serialization (JSON/Hessian)
requestId 8B key for request-response pairing
length 4B body length (excludes header)
body len serialized business datamagic : not optional. Public ports face scanners/misconnects daily; two-byte magic blocks 99% junk at decode step 1, also avoids "HTTP request hitting binary service" weird exceptions.
version : protocol will evolve. One version byte enables "old ignores new fields" instead of full-cluster simultaneous restart.
serialize : embed serialization in header for canary cutover (new/old instances co-run) — borrowed from Dubbo.
requestId : linchpin of full-duplex multiplexing. Multiple concurrent requests on one connection; response matches future via requestId — without it, RPC degrades to serial request-response, connection utilization collapses.
length : drives framing. Must explicitly document whether this length includes the header itself and freeze it in spec — this is the root of lengthAdjustment disputes. Dubbo's length field records "all bytes after header", so adjustment = 0.
5.2 maxFrameLength: Three Layers of Safety
maxFrameLength itself : set to business max message × 2; oversize throws TooLongFrameException.
Connection-level rate limiting : per-connection cumulative buffer threshold; disconnect if exceeded (stops slowloris stuffing many half-frames into memory).
Idle detection (next article): clean connections that "send half a frame then stall".
All three layers together defeat "declare large length + slow send" combo attacks — maxFrameLength alone cannot stop slow trickle.
5.3 Three Performance Levers
Fewer copies : sliced frames use retainedSlice not copy; serialization writes directly to target ByteBuf (Protobuf writeTo(OutputStream) bridgeable), avoiding "to byte[] then write" double memory.
Fewer allocations : reusing encoder-internal temp buffers needs thread-safety care (encoder non-shared by default); prefer ctx.alloc() for pooled buffers; avoid new large arrays in encode.
Right serialization : JSON readable but 1.5–3× size; Hessian middle; Protobuf most compact (~1/3 JSON) but needs .proto. Cross-language → Protobuf; internal Java + speed → Hessian; dev/debug → JSON.
5.4 Codec Layer Leak Points (Tie-in with Article 04)
Leak 1 : decode uses readSlice not readRetainedSlice — downstream holds asynchronously while parent buffer recycled → dirty reads or refCnt exceptions.
Leak 2 : forget to release incoming frame after successful parse — one leak per frame, classic "decoder leak".
Leak 3 : custom encode allocates intermediate ByteBuf not released on exception path (4.4 catch block is the standard pattern).
Add these three to code-review checklist; combined with 04-article PARANOID detector, codec leaks approach zero. Quick self-check: every return in decode — ask "who releases on this path?" — each return is a responsibility handoff.
5.5 High-Frequency Pitfall Checklist
Pitfall 1 : LengthFieldBasedFrameDecoder placed after business handler — wrong order, business always sees raw bytes (03-article Incident 3).
Pitfall 2 : initialBytesToStrip set to header length but still want to verify magic — verification code never sees header, always fails.
Pitfall 3 : lengthAdjustment omits "length field itself", causing every frame to over/under-read 4 bytes, drifting further out of sync.
Pitfall 4 : decode returns null after skipBytes — bytes consumed but no message emitted, frame permanently lost.
Pitfall 5 : decode reads out of bounds (no readableBytes check before readInt) — throws IndexOutOfBoundsException, connection killed.
Pitfall 6 : encoder releases original msg, upstream releases again — IllegalReferenceCountException.
Pitfall 7 : adding member state to @Sharable codec (e.g., accumulation vars) — multi-connection crosstalk; codecs must be stateless.
Pitfall 8 : only load-test small messages; production hits large packets and discovers maxFrameLength too small — start at business P99 size × 2, plus dedicated oversize-message test.
Learning Path & Interview Prep
6.1 Four-Stage Roadmap
Beginner (2 days) : write line-based echo with LineBasedFrameDecoder; use tcpdump or manual split-write to reproduce half-pack, observe cumulation behavior.
Intermediate (1 week) : implement 5.1 header with LengthFieldBasedFrameDecoder; deliberately change adjustment to 0/-4/4 to see misalignment; write hex-dump helper handler.
Deep (2 weeks) : read ByteToMessageDecoder.callDecode and cumulator impl, understand MERGE vs COMPOSITE; read all boundary checks in LengthFieldBasedFrameDecoder.decode.
Practice (ongoing) : upgrade 01-article mini-RPC with custom protocol (magic + requestId + body); stress-test 4 KB / 64 KB / 1 MB messages, verify framing correctness and memory watermark; use EmbeddedChannel to unit-test every protocol branch, codify "half-pack / stick-pack / oversize frame" as regression cases.
6.2 Answer Framework: Protocol Questions in Four Acts
① Phenomenon (TCP is byte stream, stick/unpack inevitable) → ② Scheme (pick one of fixed/delimiter/length-field, justify) → ③ Implementation (how five params computed, strip vs adjustment trade-offs) → ④ Hardening (maxFrameLength + rate-limit + idle detection three layers). Follow these four steps for any protocol question.
6.3 Twenty Interview Questions (with Answers)
Key Q&A highlights:
Q1: What are stick/unpack? Why TCP? Stick = multiple messages in one read; unpack = one message split across reads. Root: TCP guarantees ordered bytes, not message boundaries. Nagle merges small packets, MSS splits large, send/receive buffers merge or split — boundaries vanish at transport layer; app must frame.
Q2: How to choose among three schemes? Fixed for immutable heartbeats; delimiter for text/log (payload cannot contain delimiter); length-field for binary RPC (universal, extensible). Production usually "fixed header + length-field + variable body".
Q3: LengthFieldBasedFrameDecoder five params? maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip.
Q4: lengthAdjustment calculation with example? Formula: frameTotal = lengthFieldEndOffset + lengthValue + adjustment. If lengthValue = body only → 0. If lengthValue includes length field itself (4B) → -4. If one extra fixed header byte after length field not counted → +1. Mismatch = over/under-read.
Q5: initialBytesToStrip 0 vs header length? 0 → downstream gets full frame with header (can verify magic/version); header length → downstream gets body directly. Must use 0 when protocol verification needed; cost = downstream skips header itself.
Q6: Why not set maxFrameLength huge? Length field is peer-controlled; Integer.MAX_VALUE hands memory allocation to attacker — one forged packet eats GBs direct memory. Set ~2× business max; oversize throws TooLongFrameException and drops connection.
Q7: How ByteToMessageDecoder handles half-pack? Internal cumulation buffer: new data merged, decode loop retries; if decode returns null and no bytes consumed → break, retain remainder for next read. Buffer compressed after 16 empty reads ( discardAfterReads=16).
Q8: Why callDecode must loop? Exit conditions? One read may contain many messages; must decode all. Exit: input not readable, OR no new message AND no bytes consumed (half-pack) — else CPU spins.
Q9: MERGE vs COMPOSITE cumulator selection? MERGE writes into old buffer (may expand/copy), good for small frames high freq; COMPOSITE uses CompositeByteBuf zero-copy but index translation overhead, good for large frames low freq. Default MERGE; switch for big packets.
Q10: Who releases decoded messages? Downstream consumer. Decoder puts into out, framework fires each downstream; business releases per 04-article responsibility table; if decode throws, ByteToMessageDecoder finally releases out and cumulation — no leak.
Q11: Why separate framing and deserialization into two layers? Framing is protocol layer — business-agnostic, reusable, unit-testable; deserialization is serialization layer — changes with protocol fields. Mixing forces rewriting framing when serialization changes, and loses mature LengthField boundary handling.
Q12: MessageToByteEncoder.acceptOutboundMessage purpose? Type gate: handles only known types, others ctx.write pass through. One pipeline carries business, heartbeat, control — this method routes.
Q13: What fields in private protocol header? magic (block junk), version (smooth upgrade), flags (heartbeat/oneway/compression), type (req/resp/control), serialize (canary serialization switch), requestId (pairing), length (framing). Core: identifiable, evolvable, connection-reusable.
Q14: Why requestId mandatory? Enables connection multiplexing & full-duplex: multiple concurrent requests on one connection; response finds future via requestId. Without it, serial request-response only, connection utilization minimal, RPC performance advantage lost.
Q15: Decode throws exception — what happens? Graceful handling? Exception propagates to exceptionCaught, usually closes connection; cumulation and out cleaned in finally — no leak. For tolerance, wrap decoder with handler that catches, logs, actively closes — because frame boundary now untrusted, continuing reads cascades.
Q16: Large half-pack attack defense? Three layers: maxFrameLength caps single frame; connection cumulative buffer threshold caps half-frame memory per connection; IdleStateHandler cleans "send half then stall" connections. First layer alone cannot stop slow trickle — attacker declares legal length but sends slowly.
Q17: Can codec be @Sharable? Yes, but must be fully stateless. ByteToMessageDecoder exception: holds per-connection state (cumulation), so not sharable (framework checks isSharable and invocation order). Custom codecs without member state are shareable.
Q18: Quick locate frame misalignment? Four steps: ① add hex-dump logger after LengthField, compare first byte to magic; ② tcpdump capture, cross-check frame length vs LEN field; ③ verify adjustment & strip match protocol doc; ④ unit-test with fixed-length crafted messages, byte-by-byte verify framing. Misalignment always solvable by "dump + compare".
Q19: How to unit-test codec? Use EmbeddedChannel: writeInbound(ByteBuf) feed handcrafted bytes (including deliberately split fragments), readInbound assert decoded objects; outbound: writeOutbound(object), readOutbound compare bytes. No real ports/threads; precisely reproduces half-pack, stick-pack, oversize — only reliable way to test codec layer.
Q20: Large message spans many TCP segments — will decoder repeatedly OOM? Yes, if MERGE cumulator keeps expanding, each expansion full-copy; 1 MB message may cause dozens of copies and multiple temp buffers. Fix: switch to COMPOSITE_CUMULATOR zero-copy chaining, enforce maxFrameLength at true business ceiling, and for large payloads use streaming (fragmented protocol or FileRegion) — don't design "one message holds entire content".
6.4 One-Page Cheat Sheet
TCP no boundary stick/unpack is norm
Three cuts: fixed / delimiter / length
Five params: offset len adj strip max
Half-pack relies on cumulation
Framing via callDecode loop
Two iron laws:
max must have ceiling
framing and to-object in two layersSummary & Next Article Preview
Summary: Stick/unpack is not exceptional but the norm; the only solution is "create your own boundaries". Length-field is the standard answer for binary protocols; five parameters determine correctness; maxFrameLength is the mandatory safety valve. Get this layer right, and upstream business handlers can focus purely on POJOs. Next article dives into long-lived connection ops: "Heartbeat, Idle Detection & Production Tuning — IdleStateHandler and Million-Connection Parameters" — covering heartbeats, watermarks, TCP knobs, and stress-test tuning in one go.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
