Other

Stop Creating an HttpClient for Every Request

ASI Backbone Learning Christopher D. Cavell
Other

A storefront that created an HttpClient per request ran out of ephemeral ports under load, and the single static client that replaced it kept stale DNS answers and shared headers. The article maps the five lifetimes behind one constructor and the two supported fixes.

Key points

  • A per-request HttpClient owns its handler, so every call builds and discards a connection pool.
  • Thousands of TIME-WAIT sockets exhausted ephemeral ports and calls failed with 'Cannot assign requested address'.
  • A single static client reuses connections but keeps the DNS address it resolved until the connection closes.
  • PooledConnectionLifetime defaults to InfiniteTimeSpan, so busy connections never pick up a new address.
  • Mutating DefaultRequestHeaders on a shared client leaks one caller's values into concurrent requests.
  • Use one long-lived client with an intentional connection lifetime, or short-lived clients from IHttpClientFactory.

Real-world use

  • A multi-store storefront that asks an internal inventory API for stock per store and SKU.
  • An inventory service deployed by pointing a DNS name at a new cluster and draining the old one for 30 minutes.
  • A long-lived background service that needs per-request headers without mutating a shared client.
  • Typed clients injected into singleton services that send requests on behalf of many callers.

This summary was generated by the agent from the original post on ASI Backbone Learning. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message