futures-batch
A stream adaptor that chunks up items with timeout support. Items are flushed when:
- The buffer reaches capacity or
- A timeout occurs
Based on the Chunks adaptor from futures-util, with added timeout functionality.
Note: Originally called
tokio-batch, but renamed since it has no dependency on Tokio.
Usage
Add to your Cargo.toml:
[]
= "0.7"
Use as a stream combinator:
use Duration;
use ;
use ChunksTimeoutStreamExt;
async
This creates chunks of up to 5 items with a 10-second timeout.
TryChunksTimeout
For streams that yield Result values, use try_chunks_timeout to batch successful values and immediately propagate errors:
use Duration;
use ;
use TryChunksTimeoutStreamExt;
async
This batches Ok values until the buffer is full or timeout occurs, while immediately propagating any Err values.
Features
sink (optional)
Enable Sink support for bidirectional streams:
[]
= { = "0.7", = ["sink"] }
When enabled, both ChunksTimeout and TryChunksTimeout implement Sink and forward sink operations to the underlying stream.
Performance
futures-batch has minimal overhead and is suitable for high-performance applications:
- Used for batching syscalls in production
- Built on
futures-timerwith microsecond resolution - Zero allocations for chunk creation (reuses capacity)
Benchmarks show consistent ~20ns per operation across different batch sizes.
Credits
Thanks to arielb1, alexcrichton, doyoubi, leshow, spebern, and wngr for their contributions!