Structured Concurrency¶
Structured concurrency means every concurrent task has a clear owner and a bounded lifetime: when the owning scope or struct ends, its child tasks have either been joined to completion or deterministically cancelled.
Unstructured "fire-and-forget" tokio::spawn(...) calls—where the returned JoinHandle is dropped on the floor—make it easy to leak tasks across hot reloads, silently swallow panics, lose backpressure under traffic bursts, and hold references (Arc<Dispatcher>, Arc<Router>, DNS resolvers, sockets) long after a subsystem is supposedly stopped.
Tokio's primary tool for dynamic structured concurrency is tokio::task::JoinSet.
Choosing the Right Concurrency Primitive¶
| Situation | Recommended Primitive | Lifetime Behavior |
|---|---|---|
| Fixed, small set of concurrent futures in one function | tokio::join!, tokio::try_join!, or tokio::select! |
All branches live on the current task's stack and end before the function returns |
| Dynamic number of child tasks owned by a struct or loop (e.g., per-query workers, listener pool) | tokio::task::JoinSet<T> |
Dropping the JoinSet aborts all remaining tasks; allows capping in-flight concurrency |
| Exactly one helper task whose lifetime matches a stream/session handle | tokio_util::task::AbortOnDropHandle<T> |
Dropping the handle aborts the helper task immediately |
| Need to wait for all spawned tasks to finish gracefully (rather than aborting them on drop) | tokio_util::task::TaskTracker + CancellationToken |
Cancel token, close tracker, then tracker.wait().await |
| Independent long-lived connection that intentionally outlives the accept loop | Tracked tokio::spawn (registered in StatisticsManager / connection table) |
Bounded by connection idle/close limits and explicit close APIs |
Patterns in ClashRS¶
1. Bounded Dynamic Workers with JoinSet (DnsHijacker)¶
clash-lib/src/proxy/dns_hijack.rs is the reference pattern in ClashRS for managing dynamic background work with JoinSet. When TUN or TPROXY intercepts DNS packets, resolving them inline would stall the entire packet loop, while unbounded tokio::spawn would let a DNS flood exhaust memory.
DnsHijacker solves both problems with a JoinSet<()> and an explicit concurrency cap:
const MAX_IN_FLIGHT: usize = 256;
pub(crate) struct DnsHijacker {
resolver: ThreadSafeDNSResolver,
tasks: JoinSet<()>,
saturated: bool,
}
impl DnsHijacker {
pub(crate) fn spawn<F, Fut>(&mut self, query: Vec<u8>, reply: F) -> bool
where
F: FnOnce(Vec<u8>) -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send,
{
// 1. Reap completed tasks so the JoinSet never grows unboundedly.
while self.tasks.try_join_next().is_some() {}
// 2. Enforce backpressure / admission control.
if self.tasks.len() >= MAX_IN_FLIGHT {
if !self.saturated {
self.saturated = true;
warn!("{MAX_IN_FLIGHT} hijacked dns queries in flight, dropping new queries");
}
return false;
}
self.saturated = false;
// 3. Spawn under the JoinSet's ownership.
let resolver = self.resolver.clone();
self.tasks.spawn(async move {
match exchange(&resolver, &query).await {
Ok(data) => reply(data).await,
Err(e) => warn!("dropping hijacked dns query: {e}"),
}
});
true
}
}
This single pattern delivers three guarantees:
- Bounded concurrency: At most
MAX_IN_FLIGHTDNS lookups run simultaneously. - Automatic cleanup on drop: When
handle_inbound_datagramexits (e.g., TUN stops or reloads),DnsHijackeris dropped, itsJoinSetaborts all in-flight queries, and every clonedArc<dyn ClashResolver>is released. - Zero orphan tasks: No separate cancellation plumbing is needed for each individual query.
Always Reap Completed Tasks in Long-Lived JoinSets
A JoinSet stores the completion result of every finished task until you drain it with join_next().await or try_join_next(). If a long-lived loop only calls tasks.spawn(...) and never reaps finished entries, tasks.len() and memory usage will grow forever!
- When spawning from an event handler: drain with
while self.tasks.try_join_next().is_some() {}before checkingself.tasks.len(). - When driving a
select!loop: include a guarded branch:
tokio::select! {
Some(res) = tasks.join_next(), if !tasks.is_empty() => {
if let Err(err) = res && err.is_panic() {
error!("worker task panicked: {err}");
}
}
// ... other branches ...
}
The if !tasks.is_empty() guard is critical—without it, join_next() returns None immediately when empty and spins the loop.
2. Single Companion Task Bound to a Handle (AbortOnDropHandle)¶
When a stream or datagram wrapper needs one background driver task (for example, bridging an async protocol engine to AsyncRead/AsyncWrite or Stream/Sink), wrap its JoinHandle in tokio_util::task::AbortOnDropHandle.
Both clash-lib/src/proxy/naive/stream.rs and clash-lib/src/proxy/naive/datagram.rs follow this pattern:
pub(super) struct Datagram {
tx: PollSender<WindPacket>,
rx: mpsc::Receiver<WindPacket>,
local_addr: SocksAddr,
_task: AbortOnDropHandle<()>,
}
As soon as the caller drops Datagram (even during an error unwind or parent task cancellation), _task aborts the background UDP worker automatically. Pair this with a CancellationToken when the worker also needs to stop in response to a shared outbound shutdown signal.
3. Scope-Bound Concurrency via tokio::select!¶
When a subsystem consists of a fixed number of cooperating loops that must live and die together, run them as sibling futures inside a single tokio::select! instead of spawning separate detached tasks.
In clash-lib/src/proxy/tun/runner.rs, stack_to_tun, tun_to_stack, accept_tcp, handle_inbound_datagram, and cancellation_token.cancelled() all live in one select!. If any loop fails or shutdown is triggered, all sibling loops are dropped together in the same scope—including the DnsHijacker nested inside handle_inbound_datagram.
Observing Panics & Errors from Child Tasks¶
Dropping a bare JoinHandle hides panics unless they hit the global panic hook. With JoinSet:
join_next()/try_join_next()returnsOption<Result<T, JoinError>>.- Inspect
Err(join_err)whenjoin_err.is_panic()so unexpected panics are logged or propagated during tests, while ignoringjoin_err.is_cancelled()during normal shutdown. - When shutting down a
JoinSetcleanly, prefer cancelling its sharedCancellationToken, then drainingwhile let Some(res) = tasks.join_next().await { ... }(optionally under a timeout, followed bytasks.shutdown().await).
Testing Task Cleanup Deterministically¶
One of the best ways to verify structured concurrency is to assert that dropping a component releases every Arc held by its child tasks. clash-lib/src/proxy/dns_hijack.rs demonstrates this technique:
#[tokio::test]
async fn dropping_hijacker_releases_in_flight_queries() {
let resolver = txt_resolver();
let weak = Arc::downgrade(&resolver);
let mut hijacker = DnsHijacker::new(resolver);
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
assert!(hijacker.spawn(query_bytes, move |_| async move {
let _ = rx.await;
}));
tokio::task::yield_now().await;
drop(hijacker);
// Aborted tasks drop their futures when the runtime next polls them.
for _ in 0..16 {
if weak.upgrade().is_none() {
break;
}
tokio::task::yield_now().await;
}
assert!(weak.upgrade().is_none());
assert!(tx.is_closed());
}
Review Checklist¶
- [ ] No new bare
tokio::spawndrops itsJoinHandleunless the task is explicitly tracked (e.g., an independent dispatched connection) and bounded in lifetime. - [ ] Every long-lived
JoinSetreaps completed tasks viatry_join_next()or a guardedjoin_next()branch. - [ ] Dynamic task spawning enforces an upper bound or backpressure mechanism so traffic bursts cannot cause unbounded memory growth.
- [ ] Helper tasks owned by stream/datagram types use
AbortOnDropHandle(or explicitJoinSet/CancellationTokenteardown) so dropping the owner cannot leak background tasks. - [ ] Unit tests verify that dropping or shutting down the owning component releases in-flight child tasks.