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 Node packages. All have been tested. The default is no timeout, unless otherwise specified. Enjoy!
Also available for Ruby, Python, Go, PHP, and Rust
Standard library
NPM
- axios
- cassandra-driver
- got
- mongodb
- mysql
- pg
- redis
- @elastic/elasticsearch
- @opensearch-project/opensearch
exec(cmd, {timeout: 1000});
new dns.Resolver({timeout: 1000});
http.request(url, {timeout: 1000});
const socket = new net.Socket();
socket.setTimeout(1000);
axios.get(url, {timeout: 1000});
// or
const instance = axios.create();
instance.defaults.timeout = 1000;
const client = new cassandra.Client({
socketOptions: {
connectTimeout: 1000,
readTimeout: 1000
}
});
await got(url, {timeout: 1000});
const client = new MongoClient(uri, {
connectTimeoutMS: 1000,
socketTimeoutMS: 1000,
serverSelectionTimeoutMS: 1000
});
const connection = mysql.createConnection({
connectTimeout: 1000
});
Default: 10s connect timeout
new Client({connectionTimeoutMillis: 1000});
redis.createClient({connect_timeout: 1000});
new Client({requestTimeout: 1000});
Default: 30s
new Client({requestTimeout: 1000});
Default: 30s
Let us know. Even better, create a pull request for it.
git clone https://github.com/ankane/node-timeouts.git
cd node-timeouts
npm install
To run all tests, use:
npm test
To run individual tests, use:
npm test test/http.test.js