Back to insights

Why I Rebuilt WebSpark.HttpClientUtility for .NET 10

December 3, 202613 min read

Bringing WebSpark.HttpClientUtility up to date for .NET 10 turned into a review against current Microsoft guidance. The decorator design I built it on was hiding five bugs, including retries that never ran. This is why v3 moved the work into the IHttpClientFactory pipeline, what changed for users, and what it means for anyone still on .NET 8 or 9.

A before and after comparison. Before, v2 decorators: retries outside the service, a breaker reset per request, an auth provider never called, one cached object shared by all. After, the v3 pipeline fixes each one.
Development Series — 25 articles
  1. Decorator Design Pattern - Adding Telemetry to HttpClient
  2. NuGet Packages: Benefits and Challenges
  3. Mastering Git Repository Organization
  4. CancellationToken for Async Programming
  5. Git Flow Rethink: When Process Stops Paying Rent
  6. Understanding System Cache: A Comprehensive Guide
  7. Guide to Redis Local Instance Setup
  8. Creating a PHP Website with ChatGPT
  9. TaskListProcessor - Enterprise Async Orchestration for .NET
  10. Harnessing the Power of Caching in ASP.NET
  11. Fire and Forget for Enhanced Performance
  12. Building Resilient .NET Applications with Polly
  13. The Singleton Advantage: Managing Configurations in .NET
  14. Troubleshooting and Rebuilding My JS-Dev-Env Project
  15. Generate Wiki Documentation from Your Code Repository
  16. My Journey as a NuGet Gallery Developer and Educator
  17. Architecting Agentic Services in .NET 9: Semantic Kernel
  18. The Building of React-native-web-start
  19. TailwindSpark: Ignite Your Web Development
  20. Evolving PHP Development
  21. Modernizing Client Libraries in a .NET 4.8 Framework Application
  22. Building Git Spark: My First npm Package Journey
  23. Dave's Top Ten: Git Stats You Should Never Track
  24. Getting to Know Your Repository with git-spark
  25. Why I Rebuilt WebSpark.HttpClientUtility for .NET 10

Filed under Pragmatic architecture and modernization

Topic cluster

Software Development Patterns

.NET development, API integration, implementation patterns, and the trade-offs that show up in working code.

A Version Bump That Found Five Bugs

Version 3 of WebSpark.HttpClientUtility is a breaking release, and it was not planned as one. I set out to move the packages onto the .NET 10 line. What I found was that, with resilience turned on, the library had never retried a single request, and its unit tests said it had.

The library grew out of the idea in Decorator Design Pattern - Adding Telemetry to HttpClient: a request service that returns an HttpRequestResult<T> instead of throwing, with caching, retries, a circuit breaker and telemetry each added as a decorator around it.

text
Telemetry -> Polly (retry + circuit breaker) -> Cache -> HttpRequestResultService -> HttpClient

When I built it, that matched common practice. Polly v7 policies were the usual way to retry. IMemoryCache was the usual cache. JSON was deserialized with reflection, and few library authors thought about trimming. Wrapping a service in decorators was a respectable way to add cross-cutting behavior. The guidance kept moving after that, and my library did not.

How I Found Out

It started as dependency housekeeping. When I updated OpenTelemetry to 1.21.0, the build still passed, but that release had dropped its net8.0 and net9.0 builds. On those targets NuGet quietly falls back to the netstandard2.0 build, which depends on Microsoft.Extensions 11.0. A minor version bump would have pushed .NET 11 packages into every .NET 8 and .NET 9 app that used my library, with no warning to anyone.

I held OpenTelemetry at 1.20.x, moved every package version into one Directory.Packages.props file with central package management, and pinned the SDK in global.json. "What is the latest version?" and "what is the latest version that still supports all my targets?" turned out to be different questions. dotnet list package --outdated answers the first. Only the package's dependency groups answer the second.

If I had missed that in one package, I wanted to know what else I had missed. So I read the current Microsoft guidance for HttpClient, resilience, caching, JSON and networking telemetry, and compared it with my code one area at a time. I expected a list of things that looked dated. I found about ten outdated patterns and five real bugs.

The Guidance That Changed

Very little of this arrived in .NET 10 itself. Most of it shipped across .NET 8 and .NET 9. The .NET 10 move gave me a reason to look, and by now these patterns are the default guidance. These are the ones that mattered most.

AreaWhat I built (the pre-.NET 8 way)Current .NET 10 guidanceWhy it matters
CompositionService decorators wired up by a hand-written DI factoryDelegatingHandlers on the IHttpClientBuilder from IHttpClientFactoryHandlers see every attempt and every real status code, and consumers can add their own
ResiliencePolly v7-style policies with a fixed delay, outside the serviceMicrosoft.Extensions.Http.Resilience (Polly v8), one pipeline per named clientRetries run where failures are visible, and the pipeline lives as long as the app
CachingIMemoryCache decorator plus a key-tracking managerHybridCacheBuilt-in protection against cache stampedes, and an optional distributed second tier
JSONA new JsonSerializerOptions per response, reflection only, read from stringsOne shared options instance, read from the stream, JsonTypeInfo<T> overloadsLess allocation (analyzer rule CA1869), and code that works with trimming and Native AOT
Response readingDefault ResponseContentRead, responses not disposedHttpCompletionOption.ResponseHeadersRead and disposalLarge responses can actually stream
TracingA custom correlation header and a new ActivitySource per scopeA static ActivitySource, plus built-in System.Net.Http metrics (.NET 8+) and activities (.NET 9+)Works with W3C trace context and the platform's own telemetry
OpenTelemetry setupThe library set the app's service.name, with a hard-coded version "1.0.9"The library publishes its source and meter names, and the app names itselfA library should not name the host's service
HeadersA 2017 Chrome User-Agent and a forced Accept-Language: en-USThe library's own User-Agent; the caller chooses the languageHonest identification, and some servers block spoofed agents

Any one of these rows could have been a minor-version change. Together they pointed at one root cause: I had put HTTP concerns in the wrong layer.

Five Bugs the Old Design Was Hiding

Before fixing anything, I wrote a new set of tests. They register the library the way a consumer does, with AddHttpClientUtility, and replace only the network handler at the bottom of the pipeline. Nothing inside the library is mocked. Run against version 2.x, all six failed (the caching bug needed two), each for the reason I had predicted.

Retries that never happened

The Polly decorator retried when the service inside it threw an HttpRequestException or timed out. That inner service caught every exception and returned a result object, because returning results instead of throwing is the point of the library. It also did not treat a 503 as a failure. The retry policy never saw anything to retry, so with EnableResilience = true a 503 went straight back to the caller.

The old tests passed because they mocked the inner service to throw, which the real service never did. In v3, a stub that returns 503 and then 200 sees two calls, and the caller gets the 200 with its data.

A circuit breaker that reset on every web request

The decorator chain was built in a scoped DI factory. Every ASP.NET Core request got a new chain, and with it a new circuit breaker with a failure count of zero. The breaker could never reach its threshold. In v3, four failing calls across four DI scopes open the shared circuit after two, and the other two never reach the network.

Streaming that buffered everything first

The library switched to stream-based deserialization above a size threshold. SendAsync used the default completion option, though, so HttpClient had already read the whole body into memory before that code ran. A configuration bug also made the threshold 0 when it was not set, so every response took that path. In v3, responses are read with ResponseHeadersRead, deserialized from the network stream and disposed, and the threshold falls back to its documented 10 MB.

An authentication provider nobody called

HttpRequestResult<T>.AuthenticationProvider was documented as the way to authenticate a request. The only code that used it was the cache key. Requests went out without credentials, and nothing reported an error. v3 adds an AuthenticationHandler that applies the provider on every attempt, so a refreshed token is used on a retry. The crawler's client had the same bug and gets the same fix.

A cache that shared one object with every caller

The cache stored the result object and returned that same instance to every caller, then edited it on each hit. One caller could change what the next one saw, and every caller got the first caller's correlation ID. Five requests arriving while the cache was empty meant five calls to the backend. Because the cache key did not include the request body, a second POST to the same URL within a minute returned the first POST's response and was never sent.

In v3, each caller gets its own copy with its own correlation ID, five simultaneous misses make one backend call, and only successful GET and HEAD responses are cached.

The Rule That Protected the Bug

This project has a written constitution: the architecture rules that guide my reviews and the AI assistants I work with, the approach described in DevSpark: Constitution-Based Pull Request Reviews. Version 1.x of that constitution required the decorator chain, including the position that made retries impossible. A careful review would have flagged the fix as a violation.

So the first change in v3 was to the rules, not the code. Constitution 2.0.0 replaced the decorator requirement with a principle called Pipeline Composition Architecture. Transport concerns such as retries, circuit breaking and authentication are IHttpClientFactory handlers. Result concerns such as caching and telemetry wrap the service. Registration adds to what is already there and never replaces it, and resilience tests must run through a real HttpClient.

It also added a principle called Genuine Fixes: a test that mocks out the behavior it claims to verify does not count as evidence. That is the lesson of the retry bug, written down where a reviewer will find it.

What v3 Looks Like

text
IHttpRequestResultService
  Telemetry  ->  Cache (HybridCache)  ->  HttpRequestResultService
                                              |
                                              v  HttpClient "WebSparkHttpClient"
                                   Resilience (retry + circuit breaker)
                                     -> Authentication
                                       -> your handlers
                                         -> network

Caching and telemetry still wrap the service, because they work on results and a cache hit should never touch the network. Retries, circuit breaking and authentication now live inside the HttpClient, where they see every attempt and every real status code.

Registration is still one line:

C#
builder.Services.AddHttpClientUtility(options =>
{
    options.EnableCaching = true;
    options.EnableResilience = true;
    options.ResilienceOptions.MaxRetryAttempts = 3;
});

A new overload exposes the client underneath, so an application can add its own handlers to the same pipeline:

C#
builder.Services.AddHttpClientUtility(
    options => options.EnableResilience = true,
    client => client.AddHttpMessageHandler<MyAuditHandler>());

The Testing package changed the same way. Its documented pattern used to be new HttpClient(fakeHandler), which skipped the library's pipeline entirely, the same blind spot that let the retry bug ship. Now services.UseFakeHttpResponseHandler(fake) replaces only the network handler, so a consumer's tests run the real retries, authentication and caching.

The Impact on Users

Most code compiles unchanged. HttpRequestResult<T> is still the main API, and HTTP failures still come back as values. IHttpRequestResultService and AddHttpClientUtility(...) keep their shape, presets included. Every request still carries a correlation ID. RequestContext["RetryCount"] is still set when a retry happens; moving retries into a handler would have dropped it silently, so I kept it deliberately.

Package validation reports exactly two API breaks. HttpRequestResultServicePolly is removed, and the cache decorator's constructor takes HybridCache instead of IMemoryCache. An application that only calls AddHttpClientUtility is affected by neither.

The behavior changes are the part to read before upgrading:

Change in v3What to do
Only successful (2xx) GET and HEAD responses are cachedNothing, unless you relied on cached failures or cached POSTs
CacheDurationMinutes defaults to 0 (was 1)Set a duration on each request you want cached
The circuit breaker counts failures over a 30-second window, minimum threshold 2Check any threshold of 1 or very short break durations
Retries use exponential backoff with jitterNothing; RetryDelay is now the base delay
MaxRetries, CircuitState and FinalCircuitState are gone from RequestContextRead circuit state from resilience telemetry
The default User-Agent is WebSpark.HttpClientUtility/{version}, and Accept-Language is not sentSet either header on the request if an API needs it
AddWebSparkOpenTelemetry() no longer sets service.nameName your service in your own OpenTelemetry setup
If you composed decorators by handReplace that with AddHttpClientUtility

The caching default is the change most likely to surprise someone. In 2.x, turning caching on cached every GET for a minute. In v3, turning it on lets each request opt in. I would rather a developer ask for caching than discover it.

The release numbers: tests went from 268 / 268 / 273 to 283 / 283 / 288 on net8.0 / net9.0 / net10.0, after deleting the four Polly tests that mocked the behavior they claimed to test, and the crawler package adds 43 on each target. In the demo site, a repeat cached request took 3 ms against 155 ms for the first call, and the failing-request demo correctly makes no retries for a 400. The build has zero warnings with warnings treated as errors on all three targets.

The documentation had drifted as well. Rewriting it against the real method signatures turned up samples that had never compiled, even on 2.x: properties that did not exist, constructor arguments in the wrong order, a configuration section the library never read. Two demo pages taught a hand-written DI registration that silently replaced the library's pipeline, and the demo never turned caching on, so its own Caching page never cached anything. In v3, every pipeline claim in the docs names the test that proves it.

If You Are on .NET 8 or .NET 9

v3 still targets net8.0, net9.0 and net10.0. .NET 8 and .NET 9 both reached end of support on November 10, 2026, and the constitution allows dropping a target only in a major release, so 3.0 was the moment I could have dropped them. I kept them. Dropping a target breaks consumers, and the new dependencies, Microsoft.Extensions.Http.Resilience and Microsoft.Extensions.Caching.Hybrid 10.11.1, still support .NET 8.

For a .NET 8 or .NET 9 application, that means the same package, the same API and the same five fixes. Working retries do not require a runtime upgrade. The Microsoft.Extensions dependencies stay on the 10.x line, as they did in 2.5, and holding OpenTelemetry at 1.20.x is what keeps .NET 11 packages out of your dependency graph.

The differences are in what the platform adds. The built-in System.Net.Http metrics exist from .NET 8, but the built-in HTTP activities arrived in .NET 9, so on .NET 8 you get the library's own activity and correlation IDs with less of the platform's detail. The new JsonTypeInfo<T> overloads work on every target, and Native AOT is in much better shape on newer runtimes.

An application on an unsupported runtime no longer gets security patches, and a future major version of this library will drop net8.0 and net9.0. When it does, the CHANGELOG will say so under "Breaking", with the reason. Version 2.x keeps working the way it always did, bugs included. Upgrading to 3.0 on .NET 8 is a better place to wait than staying on 2.x.

Staying Current Without a Crisis

None of the guidance I caught up on was hidden. Most of it shipped years ago. I missed it because the library worked, the tests passed and nothing forced a second look. Checking version numbers kept the dependencies fresh while the design underneath went stale. A periodic read of the current guidance, done for its own sake rather than triggered by a scare, would have found the same problems with much less at stake.

The decorator pattern was never the mistake. Putting retries outside a layer that turns failures into values was. Once each concern moved to the layer where it can see what it needs, several of the bugs disappeared without a fix of their own, which makes me wonder what else in my code is correct in isolation and wrong in its position.

I could have shipped some of this as 2.6 and called the behavior changes fixes. They are fixes, and they also change what an application does at runtime. That is what the major version number is for.

Explore More

References

Working through something similar?

If this maps to something you're working on, I'm glad to compare notes. Start with the system and the constraint that matters most.