A DNS rotation problem occurs when a long-lived HttpClient keeps sending requests to an old service address after a hostname’s DNS record changes. This can leave an application connected to the wrong server. section 33.1
A service address changes
An application uses a singleton HttpClient to call an HTTP API. The client resolves the hostname once, connects to the resulting IP address, and continues using that connection. If DNS later points the hostname to a different server, the singleton does not detect the change and keeps sending requests to the original server. section 33.1
Figure 33.3 HttpClient does a DNS lookup before establishing a connection to determine the IP address associated with a hostname. If the DNS record for a hostname changes, a singleton HttpClient will not detect it and will continue sending requests to the original server it connected to.
Trace the DNS lookup that occurs before connection establishment and see why a singleton HttpClient can miss a changed hostname record. section 33.1
IHttpClientFactory addresses the problem by separating HttpClient lifetime from the underlying HttpClientHandler. It periodically replaces pooled handlers, allowing later connections to perform fresh DNS resolution while avoiding the socket exhaustion caused by disposing handlers too frequently. section 33.2.1
A practical setup uses the factory to manage outbound connections:
- Register the service with builder.Services.AddHttpClient(). section 33.2.1
- Inject IHttpClientFactory and call factory.CreateClient() for requests. section 33.2.1
- Let the factory manage the HttpClientHandler pipeline so connections can be reused and handlers can be periodically replaced. section 33.2.1
