curl Timeout Configuration

Configure connection and transfer timeouts in curl. Prevent hanging requests with --connect-timeout, --max-time, retry logic, and speed-based limits.

General

Detailed Explanation

Configuring Timeouts in curl

Timeouts are critical for building robust HTTP clients. Without proper timeouts, requests can hang indefinitely, blocking scripts and consuming resources. curl provides several timeout mechanisms.

Connection Timeout

The --connect-timeout flag sets the maximum time in seconds curl waits to establish a TCP connection:

curl --connect-timeout 5 https://api.example.com/data

If the server does not respond within 5 seconds, curl aborts with exit code 28.

Total Request Timeout

The --max-time (or -m) flag sets the maximum time for the entire operation, including DNS resolution, connection, transfer, and response:

curl --max-time 30 https://api.example.com/large-download

Combining Timeouts

Best practice is to set both timeouts:

curl --connect-timeout 5 --max-time 30 https://api.example.com/data

This gives 5 seconds to connect and 30 seconds total for the entire request-response cycle.

DNS Timeout

Slow DNS resolution can be a bottleneck. Use --dns-servers to specify faster DNS servers, or --resolve to skip DNS entirely:

curl --resolve api.example.com:443:93.184.216.34 \
  https://api.example.com/data

Speed-Based Timeout

Kill slow transfers with --speed-limit and --speed-time:

curl --speed-limit 1000 --speed-time 15 https://example.com/file.zip

This aborts if the transfer speed drops below 1000 bytes per second for 15 consecutive seconds.

Retry with Timeout

Combine timeouts with retry logic for resilient requests:

curl --connect-timeout 5 --max-time 30 \
  --retry 3 --retry-delay 2 --retry-max-time 120 \
  https://api.example.com/data

This retries up to 3 times with a 2-second delay between attempts, with a total retry window of 120 seconds.

Timeout in Scripts

In shell scripts, always set timeouts to prevent zombie processes:

if ! curl -sf --connect-timeout 5 --max-time 30 https://api.example.com/health; then
  echo "Health check failed" >&2
  exit 1
fi

Exit Codes

  • 28: Operation timed out
  • 7: Failed to connect to host
  • 6: Could not resolve host

Proper timeout configuration is essential for production scripts, CI/CD pipelines, and monitoring systems where unresponsive endpoints must be detected quickly.

Use Case

A DevOps engineer writing health check scripts needs to ensure requests fail fast when services are unresponsive, triggering alerts within acceptable latency windows.

Try It — Curl to Code Converter

Open full tool