# System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it. SocketException: No connection could be made because the target machine actively refused it. (127.0.0.1:443)

- **ID:** `dotnet/httpclient-socket-connection-pool-exhausted`
- **Domain:** dotnet
- **Category:** network_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

## Root Cause

HttpClient instances are not being disposed properly, leading to socket exhaustion and port starvation as each instance holds onto TCP connections for longer than necessary, especially under high concurrency.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| .NET Core 3.1 | active | — | — |
| .NET 5.0 | active | — | — |
| .NET 6.0 | active | — | — |
| .NET 7.0 | active | — | — |
| .NET 8.0 | active | — | — |

## Workarounds

1. **Use IHttpClientFactory to manage HttpClient instances. Register it in DI: services.AddHttpClient(); Then inject IHttpClientFactory and create clients with factory.CreateClient(). This reuses connections and avoids socket exhaustion.** (95% success)
   ```
   Use IHttpClientFactory to manage HttpClient instances. Register it in DI: services.AddHttpClient(); Then inject IHttpClientFactory and create clients with factory.CreateClient(). This reuses connections and avoids socket exhaustion.
   ```
2. **If not using DI, use a static or singleton HttpClient instance and ensure it is not disposed. Example: private static readonly HttpClient _httpClient = new HttpClient();** (90% success)
   ```
   If not using DI, use a static or singleton HttpClient instance and ensure it is not disposed. Example: private static readonly HttpClient _httpClient = new HttpClient();
   ```
3. **Increase the default connection limit per remote endpoint using ServicePointManager: ServicePointManager.DefaultConnectionLimit = 100; Place this in application startup.** (70% success)
   ```
   Increase the default connection limit per remote endpoint using ServicePointManager: ServicePointManager.DefaultConnectionLimit = 100; Place this in application startup.
   ```

## Dead Ends

- **Creating a new HttpClient instance for each request inside a using block.** — Disposing HttpClient too frequently causes socket exhaustion because each instance opens a new TCP connection but does not reuse sockets efficiently. (90% fail)
- **Increasing the connection limit in the app.config or machine.config.** — While this can help, it does not address the root cause of not reusing connections; it only delays exhaustion. (70% fail)
- **Setting ServicePointManager.DefaultConnectionLimit to a high value.** — This is a global setting that affects all HttpClient instances and may not be sufficient if instances are created and disposed frequently. (80% fail)
