Trung BìnhNetwork iconNetwork

Connection timeout vs Read timeout vs Write timeout: phân biệt và cấu hình đúng?

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):

js
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.

Xem toàn bộ Network cùng filter theo level & chủ đề con.

Mở danh sách Network