Building a Mini RPC Framework: Netty, ZooKeeper, and Lessons from Production Incidents
This article details the construction of a minimal RPC framework using Netty and ZooKeeper, covering protocol design, request correlation, service discovery, load balancing, timeout budgets, retry strategies, and graceful shutdown, illustrated with real production incidents and core code snippets.
Reading font
Three Production Incidents That Shaped the Design
The author begins by recounting three real incidents that expose the core challenges of RPC frameworks:
Response mixing: Under 800 concurrent requests, users saw each other's order details. Root cause: requestId defaulted to 0 and the correlation map used serviceName as key, causing concurrent requests to overwrite each other's futures.
Zombie nodes in ZooKeeper: Persistent nodes were used for registration. After a kill -9, nodes remained in ZK, and consumers cached the list for a week without re-subscribing. New nodes were never discovered, dead nodes never removed.
Retry storm and duplicate orders: Client timeout 800ms, retry 3 times. A downstream slow query (200ms → 1.2s) amplified each request to 4 calls, overloading the service. The non-idempotent order API created 217 duplicate orders. Timeout, retry count, and idempotency form a system of equations — changing one without the others backfires.
These incidents highlight that RPC difficulty lies not in sending requests but in correlating responses, discovering live instances, and handling failures gracefully .
Seven Components of an RPC Framework
Any RPC framework decomposes into seven pieces:
Protocol — framing in byte streams
Serialization — object to bytes
Connection Management — build, reuse, destroy connections
Request Correlation — match responses to requests
Service Discovery — where are service addresses
Load Balancing — pick one address among many
Governance — timeout, retry, circuit breaker, canary
The first four form the communication kernel; the last three are service governance. The article focuses on the two most error-prone: request correlation and service discovery.
Protocol Header: 18 Bytes for Determinism
A custom 18-byte header solves four problems:
Magic (2 bytes, 0xCAFE) — identify own protocol, reject HTTP/scanner traffic
Length (4 bytes) — frame boundary (cf. LengthFieldBasedFrameDecoder)
RequestId (8 bytes, long) — unique call identity for correlation
Type (1 byte) — request/response; Status (1 byte) — success/error; Codec (1 byte) — serialization negotiation; Version (1 byte) — protocol evolution
Design notes: 2-byte magic saves space; long requestId avoids wrap-around (int wraps at 1M QPS in 40 min); length must have a max frame limit to prevent OOM from forged large lengths.
Serialization: Four Options, Three Criteria
Selection depends on:
Cross-language need?
Backward compatibility required?
Willing to maintain IDL (Protobuf)?
Comparison of four formats:
JSON — Readable, debuggable, cross-language; 3-5x size, average performance
Hessian2 — Java-friendly, good compatibility, Dubbo default; Weak cross-language, medium size
Protobuf — Smallest, cross-language, strong contract; Requires IDL, poor dynamism
Kryo — Fastest in Java; Fragile across versions, avoid for long-term storage
The mini framework uses JSON for debuggability. Production: internal high-frequency → Hessian2/Protobuf; external gateway → JSON. Never use Java native serialization — serialVersionUID breaks compatibility and deserialization gadgets pose security risks.
Connection & Correlation: Single Connection Multiplexing
Two models:
Connection pool: one connection per request, simple, natural isolation, but connection count = concurrency limit.
Single connection multiplexing: hundreds of requests on one TCP, routed by requestId. Constant connections, one handshake. Requires manual response correlation and timeout cleanup.
Multiplexing core: ConcurrentHashMap<Long, CompletableFuture>. Two iron rules: future must be removed in finally — otherwise timed-out requests leak memory.
Expose pending map size as a metric — rising pending count signals downstream slowdown or lost responses.
Service Discovery: Ephemeral Nodes + Watch + Full Re-fetch
Path: /rpc/{service}/{ip:port}. Nodes must be EPHEMERAL — process death or session expiry auto-removes node, the only reliable down-detection (no manual hooks). Consumers watch parent path; on event, full re-fetch children and replace local cache. Do not attempt incremental maintenance — events merge, drop, and reconnect compensation is a single bulk event.
Critical principle: Registry outage must not break calls . Keep a local address cache; when ZK unavailable, continue with stale list (brief inconsistency > total unavailability). On recovery, full reconciliation to catch missed changes.
Load Balancing: Four Algorithms, One Hidden Prerequisite
Random: simplest, stateless, naturally even with many instances.
Round-robin: perfectly even but assumes uniform latency; slow nodes accumulate queue.
Consistent hashing: same parameter → same instance, good for local cache; cost is data migration on scale.
Least active: pick instance with fewest in-flight requests, auto-avoids slow nodes; requires client-side in-flight counters, heaviest implementation.
Default: random. Cache services → consistent hashing. Latency-sensitive core paths → least active. Hidden prerequisite: weight and proximity . Heterogeneous clusters need weighted distribution; cross-datacenter deployments should prefer same-DC instances (RT 3ms → 0.3ms, often bigger gain than algorithm change). Round-robin counter bug: AtomicInteger wraps to negative; % size yields negative index. Fix: & 0x7FFFFFFF before modulo.
Timeout Budget: Three-Layer Decreasing, Never Equal
Timeout is a budget: Client 1000ms > Server processing 800ms > Server downstream 500ms . Outer layer gives up first, inner layers release resources early. Equal timeouts cause waste: client times out, server still computing, retry multiplies waste.
Better: propagate remaining budget via deadline in request header. Server computes its remaining time, sets downstream timeout accordingly. Turns cascading timeouts into fast-fail — the switch from passive to active.
Core Flow: Fourteen Steps of One Call
Scenario: Order service calls Inventory deduct(skuId, count). Two machines, client has two addresses from ZK.
① Proxy intercepts deduct call
② Generate requestId (auto-increment + machine bits)
③ Local cache gets instance list (maintained by Watch)
④ Load balance picks one, e.g., 10.0.0.7:20880
⑤ Get connection: reuse or create
⑥ Encode: 18B header + JSON body
⑦ writeAndFlush, request enters EventLoop
⑧ Server decode: frame → deserialize
⑨ Dispatch to business thread pool (don't block IO thread)
⑩ Lookup bean, reflective invoke deduct
⑪ Build response: same requestId, status=0
⑫ Write back to client (via ctx.writeAndFlush, returns to channel's EventLoop)
⑬ Client looks up future by id, completes
⑭ Proxy returns result; on timeout throw exception and clean upKey point 1: Correlation by identity, not order. Step ⑬ is the correctness pivot. Response carries original requestId; client finds unique future and completes — order irrelevant. If matched by sequence, one timeout shifts all subsequent matches (Incident 1).
Key point 2: Business must leave IO thread. Step ⑨ is performance pivot. Reflection may query DB or call downstream; blocking EventLoop stalls all channels on that thread (single-threaded law). Server pipeline only decodes; business goes to separate thread pool; result written back via ctx.writeAndFlush which internally submits to channel's EventLoop — thread-safe.
Key point 3: Late responses after timeout are normal. Step ⑭: timeout throws, but server response may arrive later. Map already removed (finally), handler sees null, silently discards and counts — not an error. This metric reflects true downstream latency distribution.
Key point 4: Connection success ≠ service ready. Step ⑤: after connect, send lightweight handshake (or wait for first successful business call) before marking instance usable; otherwise freshly started, not-yet-initialized instances receive requests and fail. This is why delayed registration exists — write node only after service truly ready.
Core Source Code: Six Sections
4.1 Message Classes: Request and Response
RpcRequestfields: id (long), service (interface FQN), method, types (String[] parameter type names), args (Object[]), deadline (remaining budget). RpcResponse mirrors with status, data, error. Parameter types use String[] not Class[] because Class cannot be expressed in JSON (Hessian can). Deadline propagates timeout budget downstream.
4.2 Client Bootstrap: One Connection + Four Handlers
NioEventLoopGroup(1), Bootstrap, TCP_NODELAY=true, connect timeout 3s. Pipeline (outbound first, inbound before business, heartbeat middle — "read from head, write to head"): RpcEncoder (outbound) RpcDecoder (inbound) IdleStateHandler(0, 20, 0) — write idle 20s triggers heartbeat (cheaper than fixed timer) RpcClientHandler (business inbound)
Three parameter details: TCP_NODELAY mandatory (Nagle adds 40ms latency for small packets); connect timeout 3s vs default 30s; IdleStateHandler only on write idle.
4.3 Initiating Call: Reserve Then Send
long id = SEQ.incrementAndGet();
RpcRequest req = new RpcRequest(id, svc, mtd, ts, as);
CompletableFuture<RpcResponse> f = new CompletableFuture<>();
PENDING.put(id, f); // reserve first
try {
ch.writeAndFlush(req);
return f.get(timeoutMs, MILLIS).getData();
} catch (TimeoutException e) {
throw new RpcTimeoutException(svc + mtd);
} finally {
PENDING.remove(id); // must clean
}Three immutable orders: (1) put before write — response may arrive before put completes on loopback; (2) start timeout timer before waiting; (3) finally remove is the only leak prevention. Exception message includes service+method for instant diagnosis.
4.4 Receiving Response: Lookup, Complete, Clean
CompletableFuture<RpcResponse> f = PENDING.remove(r.getId());
if (f == null) {
LATE.increment(); // late response
return;
}
f.complete(r);Using remove not get gives two guarantees: normal path removes immediately; late responses naturally hit null and are counted/discarded. If written as get + timeout cleanup, two threads race (timeout thread vs handler) requiring null checks — risk of NPE or double complete. Inheriting SimpleChannelInboundHandler auto-releases message reference (reference counting).
4.5 Server: Reflective Invocation & Exception Wrapping
RpcResponse resp = new RpcResponse();
resp.setId(req.getId());
try {
Object bean = BEANS.get(req.getService());
Method m = methodOf(bean, req);
Object r = m.invoke(bean, req.getArgs());
resp.setData(r);
} catch (Throwable t) {
resp.setStatus(500);
resp.setError(t.toString());
}
ctx.writeAndFlush(resp);Three engineering points: (1) Cache Method — getMethod traverses method table each call; at 10k+ QPS it consumes ~5% CPU. Key: service+method+types in ConcurrentHashMap. (2) Unwrap InvocationTargetException — else business NPE wrapped, stack trace distorted. (3) Convert exceptions to status, never drop connection — one bad param validation shouldn't kill TCP; this separates RPC from raw socket programming.
4.6 Registration, Discovery & Dynamic Proxy
Registration: ephemeral node /rpc/{service}/{ip:port} with weight w=100. Node dies with session — only reliable down-detection without manual hooks.
Discovery: watch parent path, on event full re-fetch via getChildren and replace entire cache. Watch is one-time, merged, reconnect compensation is single bulk event — incremental maintenance inevitably loses changes. Full read is cheap: registry read volume ≪ business traffic.
Dynamic proxy: Proxy.newProxyInstance intercepts calls, delegates to LB + client.call. Two costs: (1) exceptions wrapped in InvocationTargetException — must unwrap/rethrow so business catches original type; (2) toString/hashCode/equals enter proxy — must intercept locally or logging triggers phantom RPC.
Advanced Topics: Capacity, Retry, Graceful Shutdown
5.1 Single Connection Capacity
Test env: 4C8G, 300B payload, server 1ms in-memory logic. Single connection: 26k QPS, P99 3.1ms ; 4 connections: 89k QPS, P99 4.7ms ; more connections: QPS +10%, P99 11ms. Bottleneck shifts: EventLoop decode → CPU → GC/context switch. Blindly adding connections worsens tail latency. Criterion: CPU sy > 30% means syscall/copy bottleneck — optimize protocol (fewer small packets) not connections.
5.2 Correct Retry
Three mandatory preconditions: Idempotent (no side effects on retry), Retryable error type (connect refused, connect timeout, write failure, read timeout ONLY if idempotent — NOT business exceptions, validation errors, serialization failures, non-idempotent writes), Budget (total time ≤ caller tolerance). Missing any turns retry into amplifier (Incident 3).
Two implementation details: Must switch instance — retrying same host usually repeats failure; Backoff + jitter — else all clients retry synchronously, second spike kills recovering service (same as connection storm).
5.3 Graceful Shutdown: Five Steps
Deregister first: delete ephemeral node — new calls stop routing here.
Wait propagation: Watch push + local rebuild takes <1s measured, conservatively wait 2s. Skip this → traffic still arrives after node gone.
Quiet period: wait 3-5s for requests already queued in clients to drain.
Wait in-flight: count processing requests, proceed when zero or timeout (e.g., 15s).
Shutdown thread groups: shutdownGracefully(0, 15, SECONDS) and close ZK client.
Missing any step causes micro-outage: no step 1 → requests hit closed port; no step 2 → ~5s errors; no step 3 → batch of "sent but unprocessed"; no step 4 → interrupts mid-DB-write.
5.4 Four Comparative Experiments
Serialization: JSON → Hessian2: size -45%, P99 -18% (larger objects more pronounced)
Connections: 1 → 4: QPS ×3.4, P99 +1.6ms
Business thread pool: IO thread direct → separated: slow downstream P99 900ms → 12ms
TCP_NODELAY: off → on: small packet RT -38ms
Third row most critical: Business thread pool separation is not architectural aesthetics — it's fault isolation . One slow interface (1s) on shared EventLoop drags all connections down (single-threaded law); separated, only its own pool saturates. This is the #1 cause of "one interface kills entire service".
5.5 High-Frequency Pitfalls (Eight)
requestId as int: 1M QPS wraps in 40 min; late old response matches new request → corruption. Use long or snowflake.
Timeout without pending cleanup: futures accumulate, heap slowly rises, dump shows millions of CompletableFuture.
Business logic in Handler: decode → direct DB call in channelRead; one slow query stalls all connections on that EventLoop.
Reflection without Method cache: getMethod each call, +5% CPU at load.
Swallow exception, return null: caller sees null, thinks success; real cause (bad param, NPE) lost forever. Must convert to status+error.
No maxFrameLength: forged length field → OOM; container killed by OOM Killer, no Java exception.
Register container IP: multi-NIC or K8s: InetAddress.getLocalHost() returns 127.0.0.1 or flannel IP; peers cannot connect. Explicitly bind interface or use Pod IP.
Retry without backoff: downstream blip → all clients sync retry → second wave kills recovering service → periodic avalanche.
Six of eight are ordering bugs : put future before write? deregister before close? backoff before retry? Distributed bugs are rarely hard — wrong order = incident.
Learning Path & Interview Framework
6.1 Four-Stage Path
Starter (3 days): wire 6 code sections into Maven module, run "interface call → return". Hardcode address, single node. Goal: one call proxy → reflection → back.
Intermediate (1 week): add ZK register/discover, kill instance watch list shrink; swap JSON→Hessian2 compare size; use EmbeddedChannel for codec unit tests (half-packet, oversize frame).
Deep (2 weeks): add four pieces — deadline propagation, retry (idempotent + switch instance + backoff), connection heartbeat/reconnect, graceful shutdown 5 steps. Done = production-ready.
Practice (ongoing): wrk or custom load test three comparisons (1/4/8 connections, JSON/Hessian, biz pool on/off), record numbers; inject 100ms latency + 1% loss via tc netem, observe timeout/retry behavior. Load test report > any notes.
6.2 RPC Five-Part Answer Framework
Protocol: framing, header fields, anti-mix
Communication: Netty thread model, biz/IO separation, connection reuse
Addressing: ephemeral nodes, watch + full re-fetch, local cache fallback
Governance: timeout budget, retry preconditions, load balancing, canary
Boundaries: failure modes, observability, graceful shutdown
Answer along these five layers — any RPC question lands concretely, not vague "high performance".
6.3 Key Interview Q&A (Condensed)
Q1 Why custom header not raw JSON? JSON lacks framing (TCP no message boundary), no requestId for correlation, no request/response or success/failure distinction. Header: length frames, requestId correlates, status expresses result, magic prevents cross-protocol. JSON only serialization, not protocol.
Q2 Multiplexing vs pool? High-freq short calls → multiplexing: fixed connections, one handshake, fewer context switches; cost: id→future + timeout cleanup. Low-freq/long calls → pool: natural isolation, simple; avoids head-of-line blocking. Dubbo defaults multiplexing for internal high-freq RPC.
Q3 How match response to request? Generate unique requestId (long increment or snowflake), put CompletableFuture in ConcurrentHashMap before send; server echoes same requestId; client handler looks up by id, completes. Never by sequence — one timeout shifts all subsequent (Incident 1).
Q4 Where does late response go? Still arrives, but map entry removed in finally; handler sees null, silently discards and counts. Normal, not error. Late-response counter valuable: reflects true downstream latency distribution, early slowdown signal.
Q5 Why ephemeral nodes? Bound to session; process crash or partition → session expiry → auto delete. Only down-detection not needing manual hooks. Persistent nodes survive kill -9 → traffic to dead addresses (Incident 2). Tradeoff: clean shutdown must delete node, else wait session timeout (tens of seconds).
Q6 Why full re-fetch on Watch? Watch is one-time, merged, reconnect gives single compensation event. Incremental maintenance inevitably loses changes. Full getChildren simple, idempotent, event-content-agnostic. Registry reads ≪ business traffic — cheap.
Q7 Registry down, calls still work? Yes. Client must keep local address cache; registry unavailable → use stale list (brief inconsistency > total unavailability). Nacos chooses AP for this. On recovery, full reconciliation for missed changes. Anti-pattern: query registry per call → registry blip = full outage.
Q8 Why business off IO thread? One EventLoop carries hundreds of connections; any block stalls all. Biz may query DB, call downstream (seconds). Decode only in pipeline; dispatch to separate biz pool; result via ctx.writeAndFlush (internally submits to channel's EventLoop, thread-safe). Benchmark: slow downstream P99 900ms → 12ms.
Q9 Reflection optimization? Three: cache Method (key: service+method+types, avoids getMethod traversal); cache service instance (avoid container lookup); setAccessible(true) disables access checks. Bytecode/MethodHandle possible but cached Method sufficient — saves ~5% CPU at 10k+ QPS.
Q10 Serialization choice? Three questions: cross-language? backward compat? accept IDL cost? Internal Java high-freq → Hessian2/Protobuf; external gateway → JSON (debuggable); strong contract + multi-lang → Protobuf. Never Java native: serialVersionUID breaks compat, deserialization gadget chains = security risk.
Q11 Timeout setting? P99.9 + margin, three-layer decreasing: client > server processing > server downstream. Equal causes outer give up while inner still computes, waste amplified by retry. Better: propagate remaining budget via deadline header; each layer knows its remainder — turns cascade into fast-fail.
Q12 When retry allowed? Three preconditions: idempotent, retryable error (connect/timeout/write failure, NOT business exception/validation/serialization/non-idempotent write), total budget. Implementation: switch instance (same host repeats failure), backoff+jitter (avoid sync retry spike). Non-idempotent writes need server-side dedup key else Incident 3's 217 duplicate orders.
Q13 Load balancing choice? Default random (stateless, naturally even at scale); high latency variance → least active (in-flight count, auto-avoids slow); local cache/sharding → consistent hash; round-robin only for homogeneous stable latency. Weight + same-DC priority usually yields bigger gain than algorithm swap (3ms → 0.3ms RT).
Q14 Why two waits in shutdown? First: Watch propagation (node deleted but consumer list stale, measured <1s, wait 2s). Second: client queue drain (3-5s) + in-flight count to zero. Skip any → errors or interrupted requests. Finally shutdownGracefully + close ZK.
Q15 Detect framework perf issues? Four metrics: pending map size (rising = downstream slow or lost responses), late response count (true RT distribution), biz pool queue depth (full = scale pool or degrade), connection count + EventLoop CPU distribution (uneven = binding imbalance). CPU sy > 30% → syscall/copy bottleneck → optimize protocol not connections.
Q16 Why not int requestId? 2^31 space, 1M QPS wraps in 40 min. Long connection: late old response matches wrapped new request → corruption. Long increment or snowflake (time+machine+seq) practically no collision; also decodes call time from id for debugging.
Q17 Server exception return? Convert to status≠0 + error message in response body. Never drop connection (caller sees ConnectionReset, loses real cause) nor return null (treated as success). Unwrap InvocationTargetException to get original business exception — else stack trace + message distorted.
Q18 Client detect up/down? Watch service parent path; event → full re-fetch children, replace local cache, rebuild connection pool (connect new, close gone). Fallback polling (e.g., 30s) against Watch loss. Registry down → use stale cache.
Q19 Mini vs Dubbo? Gap in governance depth & engineering details: service group/version, multi-protocol/serialization, generic invocation, implicit param pass-through, routing rules & tag canary, circuit breaker/rate limiting, thread pool isolation & rejection, SPI extensions, telnet ops, trace instrumentation. Communication & addressing layers similar — why writing wheel helps read Dubbo fast.
Q20 Top three missing for production? (1) Connection-level fault isolation + reconnect (in-flight requests fast-fail on disconnect, not wait timeout); (2) Thread pool isolation + rejection (per-service pools, prevent one slow interface starving all); (3) Observability (requestId through logs, RT percentiles, pending/late metrics, trace instrumentation). These three close minimum production loop.
6.4 One-Page Cheatsheet
Protocol: 18B header magic/length/requestId
Correlation: id → future, put before write
Cleanup: finally remove, late responses discarded
Connection: single multiplex, NODELAY mandatory
Addressing: ephemeral + watch + full re-fetch
Fallback: registry down → local cache
Balancing: default random, cache → consistent hash
Timeout: three-layer decreasing, deadline propagation
Retry: idempotent + switch instance + backoff+jitter
Shutdown: deregister → wait propagate → quiet → wait in-flight
One iron law: sending is trivial; correlating and cleaning up is the craft
Summary
Three closing points:
RPC skeleton is protocol + correlation + addressing ; the rest (serialization, balancing, governance) are swappable plugins. Get these three right → framework runs; get one wrong → incident.
All correctness reduces to unique identity : requestId unique → no response mix; ephemeral node unique → no duplicate instance; idempotent key unique → no duplicate order on retry.
Framework value half in happy path, half in failure paths : timeout, retry, drain, shutdown — the "ugly" code is the real source of production stability.
Series complete: ten articles walk one full RPC chain. 01: "why these" (IO generations + RPC three elements); 02-06: communication kernel — Reactor, 17 bootstrap steps, ByteBuf memory, framing protocol, heartbeat tuning; 07-09: coordination kernel — ZAB & quorum, watch & reconnect reconciliation, lock & fencing; 10: assembles both into runnable system. Look back: every prior article's "pit" appears here as a design decision: Handler no-block → biz thread pool; refcount → finally remove; one-time watch → full re-fetch; session expiry → graceful shutdown step 1 . Not coincidence — a framework is pits solidified into structure.
Suggested review order: 01 for panorama, 02+03 for thread model intuition, 04+05 for memory/protocol feel, 06 for Netty engineering; 07 twice (ZAB = coordination root), 08+09 together (session, watch, lock = one semantic chain), finally 10 — type the six code sections. Explaining "why this design" beats reciting "how it works" — in interviews, and even more in production debugging.
Three directions to go deeper: read Dubbo source (map to seven layers, focus Cluster & Router); read gRPC HTTP/2 multiplexing (streams/frames = alternative solution); read io_uring + user-space stacks (next-gen communication kernel). Tools evolve, but three questions never change: how to reuse connections, how to frame messages, how to clean up failures.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.