惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Last Watchdog
The Last Watchdog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
Y
Y Combinator Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
博客园_首页
小众软件
小众软件
I
InfoQ
J
Java Code Geeks
月光博客
月光博客
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Stack Overflow Blog
Stack Overflow Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
T
Threat Research - Cisco Blogs
A
About on SuperTechFans
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Latest news
Latest news
G
GRAHAM CLULEY
IT之家
IT之家
C
Cisco Blogs
Last Week in AI
Last Week in AI
Engineering at Meta
Engineering at Meta
L
LangChain Blog
The Register - Security
The Register - Security
SecWiki News
SecWiki News
M
MIT News - Artificial intelligence
NISL@THU
NISL@THU
T
Tenable Blog
博客园 - Franky
美团技术团队
I
Intezer
U
Unit 42
雷峰网
雷峰网
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Port Exhaustion, Context Switching, and Why "HttpClientFactory" Exists (.NET)
Outdated Dev · 2026-04-23 · via DEV Community

Hello there!👋🧔‍♂️ When .NET apps call other HTTP APIs under load, production often teaches the same lesson in two different voices: cryptic socket errors such as “Only one usage of each socket address is normally permitted,” and slowdowns or instability that feel like “the network” but trace back to threads waiting on I/O the expensive way. The first story is mostly connection lifecycle (ports, pooling, TIME_WAIT). The second is mostly scheduling (blocking async work, thread-pool pressure, context switching).

What follows maps those symptoms onto System.Net.Http.HttpClient, explains why IHttpClientFactory from Microsoft.Extensions.Http (through AddHttpClient in ASP.NET Core and other generic host apps) is usually the right default, shows where Refit and similar libraries still sit on the same plumbing, and ends with dos and don’ts you can use in code review tomorrow.


The two problems in one sentence

Port exhaustion happens when the OS runs out of usable ephemeral ports (or related socket resources) because too many connections are opened, held, or left in TIME_WAIT. Context switching is the CPU cost of the OS pausing one thread and resuming another; under load, blocking threads on network I/O multiplies that cost and can starve the thread pool. Misusing HttpClient in .NET makes both worse.

Scope: TCP and the thread pool are general OS/runtime ideas, but the APIs, defaults, and examples here are .NET-specific (BCL + ASP.NET Core integration). If you use another language or framework, the symptoms may look the same; the fixes will use different types and lifetimes.


1. How HttpClient is tied to sockets and ports

HttpClient is not “a thin wrapper around a single HTTP call.” It owns (via an HttpMessageHandler, typically SocketsHttpHandler) a pool of connections to each host. Connections are reused when possible (Connection: keep-alive). That is good: fewer handshakes, fewer new local ports per request.

Problems appear when every request gets a new HttpClient (or a new handler) so the runtime cannot reuse connections cleanly, or when connections are not returned to the pool promptly.

Ephemeral ports and TIME_WAIT

When a TCP connection closes, the local endpoint can sit in TIME_WAIT for a while (often on the order of minutes, depending on OS tuning). While in that state, that (local IP, local port, remote IP, remote port) tuple cannot be reused for a new connection with the same identity. Under bursty traffic, opening many short-lived connections can exhaust the available ephemeral port range for a given destination, or stress socket tables, even if CPU and memory look fine.

So “port exhaustion” in discussions of HttpClient usually means ephemeral port / socket exhaustion or too many concurrent outbound connections, not literally “we ran out of port 443.”

The classic anti-pattern

// Anti-pattern: new client per call (or per request scope without proper disposal)
public async Task<string> GetAsync(string url)
{
    using var client = new HttpClient(); // new handler/socket setup underneath
    return await client.GetStringAsync(url);
}

Enter fullscreen mode Exit fullscreen mode

Creating a new HttpClient for each call often creates a new handler chain and new connection behavior. Even with using, you pay setup cost every time and defeat connection pooling across calls. Under load, this pattern is a common contributor to socket pressure and DNS staleness (see below).

Static singleton HttpClient:

private static readonly HttpClient Shared = new();

public Task<string> GetAsync(string url) => Shared.GetStringAsync(url);

Enter fullscreen mode Exit fullscreen mode

This reuses connections and avoids the per-call construction problem, but a long-lived default HttpClient can still hold a handler that never refreshes DNS the way you expect for long-running processes, and you lose per-logical-client configuration unless you add it carefully.

That is where IHttpClientFactory comes in.


2. What IHttpClientFactory fixes

IHttpClientFactory is part of Microsoft.Extensions.Http on .NET; you usually register clients from AddHttpClient in ASP.NET Core or another .NET generic host. Register named or typed clients in DI. The factory:

  1. Pools HttpMessageHandler instances and manages their lifetime (default handler lifetime is about two minutes in modern ASP.NET Core setups; long enough to reuse connections, short enough to pick up DNS and cert changes reasonably).
  2. Centralizes configuration (base address, default headers, timeouts, primary HttpClient handler options).
  3. Lets you compose cross-cutting concerns: logging, resilience (for example with Polly), and tests with clear seams.

Example (ASP.NET Core):

// Program.cs
builder.Services.AddHttpClient("GitHub", client =>
{
    client.BaseAddress = new Uri("https://api.github.com/");
    client.DefaultRequestHeaders.UserAgent.ParseAdd("MyApp/1.0");
});

// A consumer
public class GitHubService(IHttpClientFactory httpClientFactory)
{
    public async Task<string> GetZenAsync(CancellationToken ct = default)
    {
        var client = httpClientFactory.CreateClient("GitHub");
        return await client.GetStringAsync("zen", ct);
    }
}

Enter fullscreen mode Exit fullscreen mode

You still use async/await and one logical client per named registration, not a new physical client per operation.

Key idea: The factory is not magic; it coordinates handler lifetime and pooling so you do not accidentally create unbounded distinct handlers (and thus unbounded distinct connection pools) while still allowing multiple logical HTTP APIs in one process.


3. Other libraries and approaches (same plumbing, nicer surface)

On .NET, everything below ultimately rides on HttpClient and the same socket and threading realities. Pick the surface that matches your team’s style and how strongly typed you want the boundary to be.

Typed clients (first-party)

You inject a class that takes HttpClient in its constructor and register it with AddHttpClient<TClient>(). You get one configured client per type, full testability (mock the wrapper or use a test handler), and no stringly typed client names in business code.

Refit

Refit turns a C# interface into an HTTP client: you declare methods with attributes ([Get("/users/{id}")]). Refit generates the implementation and uses HttpClient under the hood. In ASP.NET Core you typically register with AddRefitClient<T>(), which plugs into IHttpClientFactory, so you keep handler pooling and DNS rotation while your code stays declarative. It shines when an API map is stable and you want compile-time checks instead of manual HttpRequestMessage assembly.

Small example (add the Refit.HttpClientFactory NuGet package):

using Refit;

// Contract
public interface IGitHubZenApi
{
    [Get("/zen")]
    Task<string> GetZenAsync(CancellationToken cancellationToken = default);
}

// Program.cs: Refit wires this client through the same HttpClientFactory pipeline
builder.Services.AddRefitClient<IGitHubZenApi>()
    .ConfigureHttpClient(c =>
    {
        c.BaseAddress = new Uri("https://api.github.com/");
        c.DefaultRequestHeaders.UserAgent.ParseAdd("MyApp/1.0");
    });

// Any service: inject the interface, not HttpClient
public class DemoService(IGitHubZenApi gitHub)
{
    public Task<string> FetchZenAsync(CancellationToken ct = default) =>
        gitHub.GetZenAsync(ct);
}

Enter fullscreen mode Exit fullscreen mode

Flurl

Flurl is a fluent URL builder and HTTP wrapper built on HttpClient. People like it for readable one-off calls and chaining; you still want a single long-lived client strategy (often via FlurlHttp.Configure with a shared client or integration with your DI setup) so you do not recreate clients per call.

RestSharp

RestSharp (from 107+) uses HttpClient internally. The API is different from Refit (builder-style rather than interface-driven). Same rule applies: one client per logical API and no per-request client construction if you care about scale.

Polly and resilience

Polly (or Microsoft.Extensions.Http.Resilience in newer stacks) adds retries, circuit breakers, and timeouts as delegating handlers. AddHttpClient has first-class hooks to add those handlers so retries do not accidentally multiply new sockets; they wrap the same pooled HttpClient pipeline.

When HTTP is the wrong tool

If you control both ends and need streaming, strong contracts, and efficient multiplexing, gRPC (Grpc.Net.Client) is not “instead of HttpClient” in spirit, it still uses HTTP/2, but it changes design and tooling. This post stays on REST-ish HttpClient usage; just remember port and thread pressure also appear if you open too many parallel channels without backpressure.


4. Context switching: what it has to do with HTTP calls

OS thread context switches

When a thread is runnable, the scheduler may preempt it to run another thread on the same CPU. Each switch has a small but non-zero cost (saving registers, cache effects). Under heavy load, too many runnable threads can mean measurable CPU time spent just switching.

Blocking async code

If server code blocks on asynchronous work (.Result, .Wait(), GetAwaiter().GetResult()), you block thread-pool threads while I/O could have freed them:

// Bad in ASP.NET Core request path: blocks a thread
var json = httpClient.GetStringAsync(url).Result;

Enter fullscreen mode Exit fullscreen mode

That can:

  • Reduce the pool’s ability to accept new requests.
  • Increase queueing and latency.
  • Increase context switching as the OS juggles more blocked and runnable threads than necessary.

The fix is to use await all the way and propagate CancellationToken so threads return to the pool while I/O is in flight.

Async I/O is not “free,” but it scales better

await on true async I/O does not mean zero CPU work; there is still scheduling and continuation work. But it avoids holding a thread for every concurrent outbound call, which is exactly what you want when each HttpClient call may wait on the network.

So: proper HttpClient reuse addresses connection/socket pressure; proper async addresses thread-pool and context-switch pressure.


5. HttpClient dos and don’ts (best practices)

Do

  • Use IHttpClientFactory (named, typed, or Refit-generated clients) in ASP.NET Core services so handlers rotate and connections pool predictably.
  • Set timeouts: HttpClient.Timeout and/or per-operation CancellationTokenSource with a bounded delay for user-facing SLAs.
  • Pass CancellationToken from the request (or work item) into every outbound call so work cancels when the caller disconnects.
  • Stay async end-to-end; avoid sync-over-async in request paths.
  • Configure the primary handler when you need it: for example SocketsHttpHandler.PooledConnectionLifetime (and related settings) so long-lived processes refresh connections and DNS sensibly; Microsoft’s HttpClient guidelines spell out recommended values for server scenarios.
  • Treat one logical outbound API as one client registration (one name, one typed client, or one Refit interface), with base address and default headers in one place.
  • Log correlation IDs on outbound calls (via a delegating handler or HttpClient message handler) so distributed traces line up.
  • Test with HttpMessageHandler mocks or WebApplicationFactory for integration tests; avoid hitting real networks in unit tests.

Don’t

  • Don’t do new HttpClient() per request (or per arbitrary using scope) in hot paths; the classic socket exhaustion and DNS foot-guns.
  • Don’t block on Task from HttpClient (.Result, .Wait(), GetResult()) on ASP.NET Core thread-pool threads; it wastes threads and worsens context switching under load.
  • Don’t dispose HttpClient instances returned by IHttpClientFactory.CreateClient(...); the factory owns the lifetime; disposing can break pooling (see official docs).
  • Don’t share mutable per-request state on a static HttpClient (for example default headers that change per user), prefer per-request headers on HttpRequestMessage or separate client registrations.
  • Don’t send unbounded parallel requests without throttling (semaphore, batching, or queue), you can still exhaust remote limits, local ports, or memory even with a correct singleton client.
  • Don’t disable TLS validation or ignore certificate errors in production; that is a security failure, not a performance tweak.

6. Practical checklist

Concern What to do
Too many connections / ports / TIME_WAIT Prefer IHttpClientFactory (or a carefully managed singleton with correct handler lifetime). Avoid new HttpClient() per call.
Stale DNS in long-running apps Factory-managed handler rotation helps; verify SocketsHttpHandler / PooledConnectionLifetime style settings for your version.
Thread pool starvation / high context switching Never block on Task-based APIs; use await and ConfigureAwait(false) only where appropriate (libraries; ASP.NET Core apps usually omit it on the server).
Many distinct outbound bases Use named or typed clients (or Refit interfaces) so each logical API gets one stable configuration, not one new client type per request.

7. Closing thought

Port exhaustion and context switching are different mechanisms, but both show up when a .NET service makes lots of outbound HTTP calls under load. Misusing HttpClient amplifies socket and DNS issues; blocking on async amplifies thread-pool and scheduling issues. IHttpClientFactory is the supported way in ASP.NET Core (and the generic host) to keep handlers and connection pools healthy while you keep your code fully asynchronous, so your CPUs spend time on work, not on fighting the network stack and the scheduler. Libraries like Refit or typed clients sit on top of that .NET foundation; they do not remove the need to get the lifecycle right.


Further reading (official docs)