Lesson 8 of 9 · 24m
API Design, Features, and Async Without Dependency Sprawl
Design crates around caller control: optional dependencies, explicit runtime assumptions, feature flags with meaning, and no hidden global behavior.
A systems library is used inside someone else's process, under someone else's runtime, operational constraints, and security posture. That means your crate does not own the world. It must not secretly spawn threads, choose a global allocator, install signal handlers, or require a runtime unless the contract says so. Caller control is the design principle.
Features should describe capability, not implementation accidents
Cargo features are compile-time capability selection:
[features]
default = []
tls = ["dep:rustls"]
compression = ["dep:miniz_oxide"]
tokio-runtime = ["dep:tokio"]
[dependencies]
rustls = { version = "0.23", optional = true }
miniz_oxide = { version = "0.8", optional = true }
tokio = { version = "1", optional = true, features = ["rt", "net"] }A feature named fast-path that secretly changes behavior is a maintenance trap. A feature named tls or compression is understandable and testable. Add CI jobs that build important combinations; feature matrices rot quickly otherwise.
Async is an infection boundary
If your core logic is a state machine, it often does not need async at all:
pub enum Input {
TimerExpired,
BytesReceived(Vec<u8>),
}
pub enum Output {
Send(Vec<u8>),
Close,
ScheduleTimer(std::time::Duration),
}The caller drives the state machine using Tokio, async-std, embassy, or a custom reactor. This pattern is more work up front, but it preserves runtime independence and makes deterministic tests easy. If the crate truly is a Tokio networking convenience layer, say so loudly and do not pretend it is runtime-neutral.
Avoid hidden threads and callbacks
A constructor that spawns a thread creates questions: Who joins it? What panic happens there? Which runtime is active? What happens during shutdown? Prefer explicit handles:
pub struct Worker {
shutdown: std::sync::mpsc::Sender<()>,
join: Option<std::thread::JoinHandle<()>>,
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = self.shutdown.send(());
if let Some(join) = self.join.take() {
let _ = join.join();
}
}
}Even here, document blocking behavior. If shutdown can hang indefinitely, provide shutdown_timeout or expose cancellation semantics. Operators care less about conceptual purity than whether your library wedges process restart.
Configuration belongs in plain data
A builder is useful when construction has ordering or validation complexity. Do not use it to hide plain configuration that could be a struct:
pub struct ClientConfig {
pub connect_timeout: std::time::Duration,
pub max_retries: u32,
pub tls_required: bool,
}Validate once at construction, then store normalized values. Runtime behavior should not depend on mutable global variables unless process-wide state is genuinely the domain.
Field notes
- Every optional dependency increases compile time and supply-chain surface; make it earn the feature flag.
- Runtime-specific types in public APIs are commitments. Do not leak Tokio types into a supposedly generic interface.
- A crate that logs directly chooses policy for the application; emit events or use
tracingdeliberately. - Feature unification means one consumer's enabled feature can affect another consumer in the same build. Avoid features that change semantics rather than add capability.
Was this lesson helpful?