Writing

DiceRPC: One Handler Registry, Three Transports

Reading time: 9 minutes

DiceRPC started in October 2025 as a commit called minirpc: a JSON-RPC server over TCP, one JSON object per line, with three demo methods (ping, get_balance, send_tx) and a single integration test. A few days later it had HTTP, batching, auth, shared state and metrics. In September 2026 I came back to it and spent most of my time on the less exciting part: putting limits on everything that touches the network, and adding a WebSocket transport.

The crate is 0.1.0, and the README says plainly that it is for learning, prototypes and internal tools. This post explains how it is put together, why I made the choices I did, and what is still missing.

The core idea

I wanted one place to register methods, and then be able to serve those same methods over HTTP, TCP or WebSocket without changing them. A handler should not know or care which transport the request came in on.

Everything else in the crate grows out of that idea. The transports parse bytes into requests, apply limits and auth, then hand off to the same RpcServer.

The JSON-RPC envelope with serde

JSON-RPC 2.0 is a small spec. A request has jsonrpc, method, optional params and an id. A response echoes the id and carries either result or error, never both. serde’s derive macros handle most of this:

// src/rpc/rpc.rs
pub struct RpcRequest {
    pub jsonrpc: String,
    pub method: String,
    #[serde(default)]
    pub params: Value,
    pub id: Value, // id can be string or number or null
}

pub struct RpcResponse {
    pub jsonrpc: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<RpcErrorObj>,
    pub id: Value,
}

#[serde(default)] means a request without params deserializes as Value::Null instead of failing. skip_serializing_if matters more than it looks. My early version sent "error": null alongside a result. Most clients accept that, but the spec says a response has one or the other. There is now a test, responses_serialize_exactly_one_result_or_error_member, that pins this down.

I kept params and id as plain serde_json::Value. That is the main trade-off in the crate. Handlers get untyped JSON and validate it themselves. It keeps the registry simple, because every handler has the same signature, but it pushes parameter parsing into every method. You can see the cost in the demo handlers in src/server/handlers.rs: a lot of params.get("address").and_then(|v| v.as_str()).ok_or_else(...).

Handlers as trait objects

Every async closure in Rust has its own anonymous type, and so does the future it returns. To store many different handlers in one HashMap, they need a common type. That means a trait object: a pointer to “some type that implements this trait”, where the method to call is looked up at runtime.

// src/rpc/rpc.rs
pub type Handler = dyn Fn(Value) -> HandlerFuture + Send + Sync + 'static;
pub type HandlerFuture =
    std::pin::Pin<Box<dyn std::future::Future<Output = Result<Value, RpcErrorObj>> + Send>>;

pub struct RpcServer {
    handlers: RwLock<HashMap<String, Arc<Handler>>>,
}

There are two layers of type erasure here. dyn Fn hides the closure type. Pin<Box<dyn Future>> hides the future type. The future is boxed because its size isn’t known at compile time, and pinned because an async block can hold references into itself, so it must not move once it has been polled. Send + Sync lets a handler be shared across Tokio worker threads.

register is generic, so callers never write any of that by hand:

pub async fn register<F, Fut>(&self, method: &str, f: F)
where
    F: Fn(Value) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Value, RpcErrorObj>> + Send + 'static,
{
    let handler_arc: Arc<Handler> = Arc::new(move |params: Value| {
        let fut = f(params);
        Box::pin(fut)
    });
    self.handlers.write().await.insert(method.to_string(), handler_arc);
}

The cost is one heap allocation per call for the boxed future, plus a dynamic call. For an RPC layer where each request already involves parsing JSON and a network round trip, I judged that acceptable. I have not measured it, though.

Don’t hold the lock while user code runs

The registry sits behind a Tokio RwLock so methods can be registered after the server is already shared. One change from the hardening pass is worth calling out:

// Clone the handler while holding the registry lock, then release the
// lock before awaiting user code.
let handler = self.handlers.read().await.get(&req.method).cloned();

if let Some(handler) = handler {
    match (handler)(req.params).await { /* ... */ }
}

The handlers are stored as Arc<Handler> so this clone is cheap: it only bumps a reference count. The read guard is dropped at the end of the let statement, so a slow method no longer blocks register for its whole duration. It is a small change, but it’s the kind of bug that only appears under load.

In hindsight, a RwLock is more than this needs. Almost every server registers all its methods at startup. A builder that produces an immutable HashMap would remove the lock entirely, and it would also mean register doesn’t need to be async.

handle_request also checks the envelope before dispatch: jsonrpc must be exactly "2.0", the method must not be blank, and the id must be a string, number or null. If the id is invalid, the error response uses null instead of echoing it back.

Batches with an untagged enum

A JSON-RPC batch is just an array of requests. serde’s untagged representation tries each variant in order, so one type covers both shapes:

// src/util/batch.rs
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum BatchRequest {
    Single(RpcRequest),
    Batch(Vec<RpcRequest>),
}

handle_batch maps each request to a future and awaits them together with futures::future::join_all. An empty array returns -32600 Invalid Request, as the spec requires.

“Concurrent” needs a caveat. join_all polls every future inside the same task. If handlers wait on I/O, they overlap. If a handler does heavy CPU work, the rest of the batch waits behind it. I’d make that clear in the docs, or spawn each entry as its own task when there’s a good reason to.

The downside of untagged is the error messages. When neither variant matches, serde reports that the data matched no variant, without saying which field was wrong. That error text goes straight back to the client.

Shared state with Arc

The demo StateStore in src/state.rs holds accounts and transactions in two Arc<RwLock<HashMap<...>>> fields. The stateful handlers capture an Arc<StateStore> and clone it on each call:

// src/server/handlers.rs
server
    .register("get_balance", move |params| {
        let state = state.clone();
        async move {
            // ...
            let balance = state.get_balance(address).await.unwrap_or(0);

The double clone confuses people new to async Rust. The closure is Fn, so it can be called many times. Each call returns an async move block that needs its own owned handle to the state, because the future may outlive that particular call. So the closure keeps one Arc, and each future gets a fresh clone.

transfer takes the accounts write lock once for the whole operation. It uses checked_add for the receiver’s balance and the sender’s nonce, and treats a transfer to yourself as a nonce bump only. The September pass added those overflow checks. One thing I would change: the transaction record is written under a separate lock after the accounts lock is released. So there is a short window where the balances have moved but the transaction doesn’t exist yet. It’s harmless for a demo, but a real store would need both writes in one transaction.

All of this lives in memory and disappears on restart. The README says so.

Three transports, the same limits

The HTTP transport is an Axum router with POST / and POST /rpc. It takes the raw body as Result<Json<Value>, JsonRejection>, so a parse failure becomes a JSON-RPC -32700 response instead of Axum’s default plain-text rejection. It always returns HTTP 200 and puts errors in the JSON-RPC envelope.

TCP comes in two modes. The original newline-delimited server is still there as “legacy”. It now reads lines through read_bounded_line, which refuses any line over 1 MiB instead of buffering whatever a client sends. The framed mode uses a 4-byte big-endian length prefix:

// src/transport/framing.rs
let len = u32::from_be_bytes(len_bytes) as usize;

// Sanity check: prevent extremely large allocations
if len > max_frame_size {
    return Err(anyhow!("Frame too large: {len} bytes (maximum {max_frame_size})"));
}
let mut payload = vec![0u8; len];

That check runs before the allocation. Without it, a client could send four bytes claiming a 4 GiB frame and make the server allocate it.

WebSocket, behind the websocket feature, serves /ws. Each text or UTF-8 binary message holds one request or batch, and it replies to pings itself. With header auth, the API key is checked during the HTTP upgrade, so an unauthenticated client gets a 401 or 403 and never gets a socket.

Each network-facing transport got the same set of builder methods in the hardening commit, with the same defaults: 1 MiB per body, frame or message, 100 entries per batch, a 30-second timeout, and a semaphore. On HTTP the semaphore caps concurrent requests at 256. On WebSocket and framed TCP it caps connections at 1,024. A connection holds an OwnedSemaphorePermit for its lifetime, so the slot is freed when the task ends, however it ends.

Here are the trade-offs I’d point out in review:

  • HTTP waits up to request_timeout for a permit, then applies a separate request_timeout to the work itself, so the worst case is about twice the configured value.
  • A timeout drops the handler’s future. Tokio cancels it at its next .await, which is safe for pure reads but can leave a multi-step handler half done.
  • WebSocket handles one message at a time per connection. Responses stay in request order, but one slow request blocks the rest on that socket.
  • Framed TCP silently drops connections over the limit. WebSocket at least returns a 503.

Auth and metrics

AuthMiddleware supports three strategies: None, ApiKeyInParams and ApiKeyInHeader (x-api-key). Keys are compared with the subtle crate’s ct_eq, so the comparison takes the same time whether the first byte is wrong or the last one is. It is applied as an extension trait, AuthenticatedServer, rather than inside RpcServer, which keeps the core registry unaware of auth.

Metrics are deliberately basic. Request, success and error counts are AtomicU64 with Relaxed ordering, which is fine for independent counters. The latency figure is called a moving average, but it’s really an exponential one: (avg * 9 + new) / 10. It sits behind an async RwLock that it doesn’t need. Batches are recorded under the method name batch(N), so the per-method map gets a new key for every batch size, and a batch with one failed entry counts as one error in total. All of this is exposed as JSON at GET /metrics, not in Prometheus format.

What’s missing / next

Some of these are already on the README roadmap. Others I found while writing this post.

  • Notifications are not supported. id has no #[serde(default)], so a request without one fails to deserialize and gets an error response. The spec says a notification gets no response at all.
  • The TCP-only build is broken. The README lists cargo build --no-default-features --features tcp, but lib.rs re-exports server::metrics::Metrics unconditionally, and server only compiles with the http feature. cargo check with that feature set fails on missing crate::server. That’s a quick fix, and a CI job per feature set would have caught it. The repo has no CI configuration.
  • The legacy newline TCP server has no auth, batching or connection limit. Only the framed mode got the full hardening.
  • No benchmarks, load tests or fuzzing. I have no numbers on throughput or on what the boxed handlers cost. The framing and batch parsers are good candidates for fuzzing.
  • Tests exist but have gaps. There are around 60 test functions across the tests/ directory and a few inline modules. Most of them cover the state store, TCP and WebSocket. There is no full JSON-RPC compliance suite yet.
  • No per-method authorization, no TLS, no key storage. Keys come from an environment variable, and any valid key can call any method.
  • Typed params. I’d like an optional register_typed::<P, R> that deserializes params into a struct and returns -32602 Invalid params automatically. It would remove most of the boilerplate in the demo handlers.

Takeaways

  • A single Arc<Handler> registry behind several transports worked well. The transports differ only in framing, limits and where the API key comes from.
  • Type erasure with dyn Fn and Pin<Box<dyn Future>> is what lets one map hold all the handlers. The price is a heap allocation per call, which I’ve accepted but not measured.
  • Most of the real work in an RPC server is outside the protocol: bounding sizes before allocating, capping connections, timeouts, and being clear about what a timeout does to work that’s already running.
  • serde handles most of the JSON-RPC envelope for you. The remaining spec details, like notifications and exactly-one-of result/error, need tests, because they’re easy to get slightly wrong.

The code is at github.com/dicethedev/DiceRPC.