An unresponsive service can be worse than a down one. It can tie up your entire system if not handled properly. All network requests should have a timeout.
Here’s how to add timeouts for popular Rust crates. All have been tested. The default is no timeout, unless otherwise specified. Enjoy!
Also available for Ruby, Python, Node, Go, and PHP
Standard library
Crates
let mut stream = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(1))?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
stream.set_write_timeout(Some(Duration::from_secs(1)))?;
Returns std::io::Error
let client = awc::Client::builder()
.timeout(Duration::from_secs(1))
.finish();
Returns awc::error::SendRequestError
let mut easy = curl::easy::Easy::new();
easy.connect_timeout(Duration::from_secs(1))?;
easy.timeout(Duration::from_secs(1))?;
Returns curl::Error
let transport = elasticsearch::http::transport::TransportBuilder::new(conn_pool)
.timeout(Duration::from_secs(1))
.build()?;
Returns elasticsearch::Error
tokio::time::timeout(Duration::from_secs(1), client.get(uri)).await?;
Returns tokio::time::error::Elapsed
let client = postgres::Config::new()
.connect_timeout(Duration::from_secs(1))
.connect(postgres::NoTls)?;
Returns postgres::Error
let mut con = client.get_connection_with_timeout(Duration::from_secs(1))?;
con.set_read_timeout(Some(Duration::from_secs(1)))?;
con.set_write_timeout(Some(Duration::from_secs(1)))?;
Returns redis::RedisError
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(1))
.build()?;
or
let resp = client.get(url)
.timeout(Duration::from_secs(1))
.send()
.await?;
Returns reqwest::Error
let pool = sqlx::postgres::PgPoolOptions::new()
.acquire_timeout(Duration::from_secs(1))
.connect(uri)
.await?;
Returns sqlx::Error
let config = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(1)))
.build();
Returns ureq::Error
Let us know. Even better, create a pull request for it.
git clone https://github.com/ankane/rust-timeouts.git
cd rust-timeouts
To run all tests, use:
cargo test
To run individual tests, use:
cargo test redis