Reqwest Pool Timeout Configuration
Tune reqwest connection pooling with per-host keepalives, idle timeouts, and layered timeouts for connect, read, and total budgets.
Code
use std::time::Duration;
use reqwest::Client;
fn build_client() -> reqwest::Result<Client> {
Client::builder()
.pool_max_idle_per_host(16)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(3))
.timeout(Duration::from_secs(10))
.redirect(reqwest::redirect::Policy::limited(3))
.user_agent("billing-sync/2.1")
.build()
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::builder()
.pool_max_idle_per_host(16)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(3))
.timeout(Duration::from_secs(10))
.build()?;
let started = std::time::Instant::now();
// 第一次请求建立连接,后续复用同一池内连接
let first = client
.get("https://api.example.com/invoices")
.query(&[("page", "1")])
.send()
.await?
.json::<serde_json::Value>()
.await?;
println!("first took {:?}", started.elapsed());
let second = client
.get("https://api.example.com/invoices")
.query(&[("page", "2")])
.send()
.await?
.json::<serde_json::Value>()
.await?;
println!("second took {:?}", started.elapsed());
println!(
"pages fetched: {} {}",
first.get("page").and_then(|v| v.as_i64()).unwrap_or(0),
second.get("page").and_then(|v| v.as_i64()).unwrap_or(0)
);
let _ = build_client()?;
Ok(())
}What the code does
The working surface is the functions build_client and main — everything else is wiring.
Nothing throws: the failure path is a Result variant the caller must match.
What to watch for
- Plan for an install step:
reqwest::Clientis a real dependency, resolved by the package manager. - No exceptions hide in this snippet — every failure is a
Resultvalue someone must consume.
Using it
The primary signature is fn build_client() -> reqwest::Result<Client>
Running the file prints labeled results such as first took, second took, pages fetched: — each operation’s effect is visible in the output.
The sequence build_client lives in main; running the file triggers it.
Key statements
fn build_client() -> reqwest::Result<Client> {
Client::builder()
.pool_max_idle_per_host(16)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(3))
.timeout(Duration::from_secs(10))
.redirect(reqwest::redirect::Policy::limited(3))
.user_agent("billing-sync/2.1")
.build()
}
let _ = build_client()?;
second.get("page").and_then(|v| v.as_i64()).unwrap_or(0)
);
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- Each fallible operation returns `Result`; nothing is silently discarded.
- Are there third-party dependencies?
- `reqwest::Client` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.