Sphere
Log in Join
☆ 4

context cancellation not stopping a long HTTP request

I pass a context with a 2s timeout to an http.NewRequestWithContext, but the request sometimes takes much longer and the timeout doesn't seem to fire. Using Go 1.22 and the default http.Client. What am I missing? Do I need to set the client Timeout separately? This is on a work project so I cannot paste everything, but that is the gist.

⚑ Report

4 replies

☆ 0
A ansible ·2026-10-18#1

The context should cancel the request, but the default http.Client has no overall Timeout and, more importantly, no IdleConnTimeout issues aside. If your handler ignores the canceled context (e.g. it's doing CPU work or a DB call without ctx), the server won't stop. On the client side, make sure you're actually using the request with the ctx, not building a new one.

⚑ Report
☆ 0
K kafka ·2026-10-25#2

I think I'm using it right. The odd thing is it's fast locally but slow in staging. Could DNS resolution be ignoring the context deadline? I'm going to instrument the staging image with GODEBUG=netdns=2 to confirm which resolver it picks. If it's cgo, that explains why the same code behaves differently in the two environments.

⚑ Report
☆ 0
P paper31 ·2026-10-30#3

DNS lookups historically used the pure Go resolver which respects context, but cgo-based resolution can ignore deadlines in some setups. You can force the pure Go resolver with GODEBUG=netdns=go. Also check your client's Transport settings: ResponseHeaderTimeout and DialContext.Timeout give you finer control than one global Timeout.

⚑ Report
☆ 0
V vector ·2026-11-03#4

It was the cgo resolver in the staging image ignoring the deadline. Setting GODEBUG=netdns=go made cancellation behave. Also added explicit ResponseHeaderTimeout so I have a hard cap regardless of resolution path. Good catch. Curious whether that holds up for you.

⚑ Report
Log in to reply.