Skip to Content
Skip to content
Set ReadHeaderTimeout and Keep-Alive Timeouts on http.Server
Intermediate
Tutorials

Set ReadHeaderTimeout and Keep-Alive Timeouts on http.Server

Replace http.ListenAndServe with an explicit http.Server configured with ReadHeaderTimeout, ReadTimeout, WriteTimeout, and IdleTimeout. After this, slow or idle clients cannot exhaust server sockets.

Updated 3 min read GoSecurity

One of the easiest ways to take down a Go API server requires zero traffic spike and zero CPU: open 2,000 TCP connections, send GET / HTTP/1.1\r\n, and stop sending. If your service starts with http.ListenAndServe(":8080", mux), Go's default http.Server has no timeouts at all—so all 2,000 connections stay open forever, holding goroutines and file descriptors until the server rejects legitimate users.

That is a classic slow-loris attack—and even without attackers, flaky mobile clients on bad Wi-Fi trigger the exact same socket exhaustion. Setting explicit http.Server timeouts fixes it cleanly without breaking legitimate slow uploads.

Skip ahead

Want the recommended production struct? Jump to the configured http.Server or what each timeout actually measures.

Why ReadHeaderTimeout is safer than a short ReadTimeout

It helps to know the exact timeline of an HTTP request inside net/http:

  1. Client connects over TCP (plus TLS handshake if HTTPS).
  2. Client sends the request line and HTTP headers (usually < 8 KB).
  3. Your handler runs, reads r.Body (which might be a 50 MB file upload), and writes the response.

If you set a tiny ReadTimeout: 2 * time.Second, you accidentally kill legitimate users uploading a 20 MB file over a slow cellular connection—because ReadTimeout covers the entire body read! Setting ReadHeaderTimeout: 5 * time.Second closes slow-loris connections that stall before sending headers, while giving valid uploads room to finish.

Production http.Server configuration

package main

import (
	"log"
	"net/http"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	})

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      15 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	log.Fatal(srv.ListenAndServe())
}

What each timeout protects (and its trade-offs)

Field Timer starts → stops When to adjust
ReadHeaderTimeout Accept/TLS → end of HTTP headers Always set (5s); gosec flags servers missing this
ReadTimeout Accept → end of request body Raise (or omit and use MaxBytesReader + per-route deadline) for large file uploads
WriteTimeout End of request headers → end of response write Disable or use http.NewResponseController(w).SetWriteDeadline on SSE/long-polling routes
IdleTimeout After response sent → next request on keep-alive TCP socket Set explicitly (60s) so idle keep-alive sockets recycle cleanly

💡 Tip

Why keep IdleTimeout around 60 seconds? Reverse proxies like Nginx and AWS ALB have their own idle timeouts (often 60s). Matching or slightly exceeding your load balancer's idle timeout avoids race-condition 502 errors where Go closes a socket at the exact millisecond Nginx sends a new request on it.

Common mistakes

  • Using http.ListenAndServe(":8080", mux) in production: Leaves all four timeouts at 0 (infinite).
  • Setting WriteTimeout: 5 * time.Second on a Server-Sent Events (SSE) stream: After 5 seconds, Go kills the open stream from underneath your handler.
  • Forgetting http.MaxBytesReader on JSON/upload endpoints: Timeouts bound time, not bytes—a fast client can still send 500 MB in 2 seconds unless you cap body size too.

⚠ Warning

WriteTimeout starts counting as soon as request headers are read—which means slow database queries inside your handler eat into your WriteTimeout budget too, not just network write time.

What happens if you skip this

A handful of stalled TCP connections or slow clients tie up goroutines and file descriptors indefinitely until your server hits ulimit -n and stops accepting healthy traffic.

Related course: Go Intermediate.

About

Replace http.ListenAndServe with an explicit http.Server configured with ReadHeaderTimeout, ReadTimeout, WriteTimeout, and IdleTimeout. After this, slow or idle clients cannot exhaust server sockets.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
3 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.