Connection timeout (thiết lập TCP), Read timeout (nhận response) và Write timeout (gửi request) là 3 loại timeout khác nhau — phải set cả 3 để tránh thread/connection leak.
Connection timeout: thời gian tối đa để thiết lập TCP connection (3-way handshake). Thường 3-10 giây. Nếu timeout: server unreachable, firewall block, hoặc server quá tải không accept connections mới.
Read timeout (response timeout): thời gian tối đa để nhận response sau khi request đã gửi. Nếu timeout: server quá chậm, heavy processing, hoặc network issue. Thường 30-60 giây cho API calls, 5-10 giây cho microservices.
Write timeout (send timeout): thời gian tối đa để gửi request (upload) đến server. Thường liên quan đến slow upload.
Connect-and-Read timeout pattern (Axios):
axios.create({
timeout: 5000, // áp dụng cho toàn bộ request
// Hoặc tách biệt:
httpAgent: new http.Agent({ timeout: 3000 }) // connect timeout
})Best practice: luôn set timeout — không có timeout là anti-pattern (thread/connection leak khi downstream service hang).
- Microservices internal: connect 1s, read 5-10s.
- External API calls: connect 3s, read 30s.
- Kết hợp với retry và circuit breaker để handle failures gracefully.
Connection timeout (establishing TCP), Read timeout (receiving response), and Write timeout (sending request) are 3 different timeout types — all 3 must be set to prevent thread/connection leaks.
Connection timeout: the maximum time allowed to establish a TCP connection (3-way handshake). Typically 3–10 seconds. If it times out: the server is unreachable, a firewall is blocking the connection, or the server is too overloaded to accept new connections.
Read timeout (response timeout): the maximum time to receive a response after a request is sent. If it times out: the server is too slow, doing heavy processing, or there is a network issue. Typically 30–60 seconds for external API calls, 5–10 seconds for microservice calls.
Write timeout (send timeout): the maximum time to send a request (upload) to the server — relevant for slow uploads.
Connect-and-Read timeout pattern (Axios):
axios.create({
timeout: 5000, // applies to the entire request
// Or separate:
httpAgent: new http.Agent({ timeout: 3000 }) // connect timeout
})Best practice: always set timeouts — missing timeouts are an anti-pattern (threads/connections leak when a downstream service hangs indefinitely).
- Microservice internal calls: connect 1s, read 5–10s.
- External API calls: connect 3s, read 30s.
- Combine with retry logic and a circuit breaker to handle failures gracefully.