skip to content

Your team's Rust service exposes a handler-registration API; should handlers be generic type parameters or boxed `dyn Handler` values, and which default would you set?

level: principalimportance: should knowfreq 40%

answer

  1. who knows the type, and when
  2. one router type versus many
  3. compile time against an indirect call
  4. generic at the door, boxed inside

basics

~20 s

Use generics where the handler type is known at compile time and calls are hot; use Box<dyn Handler + Send + Sync> where the set is open, mixed or chosen at run time. A sound default for a router is the hybrid: accept impl Handler, store it boxed.

solid answer

~50 s

Generic handlers (`Router<H: Handler>`) give direct, inlinable calls and allow generic methods on the trait, but the handler type becomes part of the router's type: one router holds one handler type, mixing types means nesting generics, every holder of the router turns generic too, and each handler type adds monomorphized code and compile time. `Box<dyn Handler + Send + Sync>` gives one concrete `Registry` that holds any number of different handlers chosen at run time, for an allocation per handler and an indirect call per request, and the trait must stay usable as a trait object. In a service whose requests wait on I/O, that indirect call is rarely measurable, so I'd default to the hybrid `register(h: impl Handler + Send + Sync + 'static)` that boxes internally, require generics only where a benchmark shows a per-element hot path, and write the rule into the team's API guidelines.

code

rust · 47 lines
rust
trait Handler {
    fn handle(&self, path: &str) -> String;
}

struct Health;
impl Handler for Health {
    fn handle(&self, _: &str) -> String {
        "ok".to_string()
    }
}

struct Metrics {
    hits: u64,
}
impl Handler for Metrics {
    fn handle(&self, path: &str) -> String {
        format!("{path}: {} hits", self.hits)
    }
}

// Static dispatch: the handler type is part of the router's type.
struct Router<H: Handler> {
    handler: H,
}

// Hybrid: generic at the call site, one boxed type stored inside.
struct Registry {
    routes: Vec<(String, Box<dyn Handler + Send + Sync>)>,
}

impl Registry {
    fn register(&mut self, path: &str, h: impl Handler + Send + Sync + 'static) {
        self.routes.push((path.to_string(), Box::new(h)));
    }
}

fn main() {
    let router: Router<Health> = Router { handler: Health };
    println!("{}", router.handler.handle("/health"));

    let mut reg = Registry { routes: Vec::new() };
    reg.register("/health", Health);
    reg.register("/metrics", Metrics { hits: 42 });
    for (path, h) in &reg.routes {
        println!("{path} -> {}", h.handle(path));
    }
}

go deeper

for a junior

Recall that a generic parameter fixes one handler type per router, while a boxed dyn Handler lets one collection hold different handler types.

for a middle

Explain the costs on each side: monomorphized copies and generic signatures for one, an allocation and an indirect call for the other.

for a senior

Show how you would locate the real hot path, and why the 'static and Send + Sync bounds appear on a boxed handler registry.

for a principal

Own the default and its exceptions: weigh build time, binary size, API ergonomics and trait evolution against measured run-time cost, and record the rule with evidence.

## The decision A team building a Rust service needs one convention for APIs that accept caller-supplied behaviour: request handlers, middleware, event listeners, plugin hooks. There are two shapes, and the choice affects build times, binary size, API ergonomics and what the trait may contain. There is no single right answer; there is a default plus documented exceptions. ## The two shapes - **Static (generic):** `struct Router<H: Handler> { handler: H }`. Each `Router<Health>` or `Router<Metrics>` is a distinct type, and each call to `handle` is monomorphized into a direct call. - **Dynamic (type-erased):** `struct Registry { routes: Vec<(String, Box<dyn Handler + Send + Sync>)> }`. One concrete type holds handlers of any type, and each call goes through the trait object's vtable. - **Hybrid:** `fn register(&mut self, path: &str, h: impl Handler + Send + Sync + 'static)` is generic at the call site and immediately does `Box::new(h)`, so callers pass plain values and the struct stays non-generic. ## What each costs | Concern | Generic `H: Handler` | `Box<dyn Handler + Send + Sync>` | |---|---|---| | Call | direct, inlinable | indirect through a vtable | | Mixed handler types | needs nesting or enums | one `Vec` holds them all | | Chosen at run time (config, feature toggles) | only by branching between separately compiled router types | yes, push any handler into the same `Vec` | | Type signature of holders | every holder becomes generic | concrete | | Compile time and binary size | one copy per handler type | one copy of the routing code | | Trait design | generic methods allowed | trait must stay dyn-compatible | | Allocation | none required | one box per handler | Two of these deserve emphasis. **Signature contagion**: once `Router<H>` is generic, an `App` holding a router must be `App<H>` or name the concrete type, and that spreads through tests and helpers. **Trait limits**: a trait used as `dyn Handler` cannot offer generic methods, or methods returning `Self`, that are callable through the trait object, so choosing dyn constrains how the trait can evolve; the exact rules are covered with trait objects. ## The hybrid, and its fine print The hybrid is a common default for registries because it keeps both sides simple: - callers write `reg.register("/health", Health)`, with no `Box::new` at the call site; - the generic `register` is tiny, so monomorphizing it per handler type costs almost nothing; - the stored type needs `'static`, because a `Box<dyn Handler + Send + Sync>` field defaults to a `'static` trait object; without the bound rustc reports E0310, "the parameter type ... may not live long enough"; - `Send + Sync` must be stated if the registry is shared across worker threads, since a trait object is `Send` or `Sync` only when its type says so, by naming them or through a supertrait. ## Setting the default 1. **Ask who knows the type, and when.** Plugins enabled by configuration, or handler lists assembled at start-up, fit type parameters badly: each combination would need its own router type, spelled out when the code is written. 2. **Locate the hot path.** A handler invoked once per request, beside network and database I/O, will not show an indirect call in a profile. A function called per element in a tight loop, such as a filter over every row or a per-frame update over every game entity, is where generics and inlining pay off. 3. **Price the build.** If dozens of handler types each instantiate a large generic router, compile time and binary size grow with them; erasing at the boundary caps that. 4. **Decide what the trait must express.** If handlers need generic methods, either keep the API generic or move those methods off the object-safe surface. 5. **Write it down with evidence.** Record the default, the exception criteria and a benchmark for the hot-path exception, so reviews cite a rule rather than taste. ## Signals to revisit the default - profiles that show the vtable call or a missed inlining in a hot loop; - builds dominated by instantiations of one generic subsystem; - a trait that needs a generic method the dyn form cannot offer; - a new requirement to register handlers from configuration at run time.

  • Why does the hybrid `register` need `'static` in `impl Handler + Send + Sync + 'static`?
    A `Box<dyn Handler + Send + Sync>` stored in a struct field is a `'static` trait object by default, so a handler that borrows shorter-lived data cannot be stored. Without the bound rustc reports E0310, "the parameter type ... may not live long enough". A registry that truly needs borrowed handlers can name a lifetime on the struct instead.
  • When would you overrule a dyn default and require a generic parameter?
    When the behaviour runs per element in a hot loop, such as a predicate over every row or a per-frame update over thousands of entities, and a benchmark shows the indirect call or lost inlining matters. Also when the trait genuinely needs generic methods that a trait object cannot offer.
  • How would you stop a generic-first API from inflating build times as handler types multiply?
    Keep generic entry points thin and forward to non-generic internals, erase the type at the registration boundary, and measure instantiation counts in the LLVM IR or a symbol-size report before and after. Review new generic public APIs for the copies they create downstream.

  • dyn Trait is always too slow for a production service.
  • Generics are free: they cost nothing in compile time or binary size.
  • A Vec<H> with H: Handler can hold several different handler types at once.
  • Any trait can be used as dyn Trait, so the choice can be deferred freely.
  • The team default should follow taste, without measuring the hot paths.