A wrapper for HttpClient that caches to disk. Cached files, over the max specified, are deleted based on the last access times.
A wrapper for HttpClient that caches to disk. Cached files, over the max specified, are deleted based on the last access times.
A wrapper for HttpClient that caches to disk. Cached files, over the max specified, are deleted based on the last access times.
See Milestones for release notes.
Headers/Responses respected in caching decisions:
https://nuget.org/packages/Replicant/
There is a default static instance:
var content = await HttpCache.Default.DownloadAsync("https://httpbin.org/status/200");snippet source | anchor
This caches to {Temp}/Replicant.
An instance of HttpCache should be long running.
var httpCache = new HttpCache(
cacheDirectory,
// omit for default new HttpClient()
new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
},
// omit for the default of 1000
maxEntries: 10000);
// Dispose when finished
await httpCache.DisposeAsync();snippet source | anchor
Add HttpCache as a singleton when using dependency injection.
var services = new ServiceCollection();
services.AddSingleton(_ => new HttpCache(cacheDirectory));
using var provider = services.BuildServiceProvider();
var httpCache = provider.GetRequiredService();
NotNull(httpCache);snippet source | anchor
Using HttpClient with HttpClientFactory.
var services = new ServiceCollection();
services.AddHttpClient();
services.AddSingleton(_ =>
{
var clientFactory = _.GetRequiredService();
return new HttpCache(cacheDirectory, clientFactory.CreateClient);
});
using var provider = services.BuildServiceProvider();
var httpCache = provider.GetRequiredService();
NotNull(httpCache);snippet source | anchor
ReplicantHandler can be used as a DelegatingHandler in the HttpClient pipeline:
var handler = new ReplicantHandler(cacheDirectory)
{
InnerHandler = new HttpClientHandler()
};
using var client = new HttpClient(handler);
var response = await client.GetAsync("https://example.com");snippet source | anchor
ReplicantHandler integrates with HttpClientFactory using AddHttpMessageHandler:
var services = new ServiceCollection();
services.AddHttpClient("CachedClient")
.AddHttpMessageHandler(() => new ReplicantHandler(cacheDirectory));snippet source | anchor
To share a single cache (and purge timer) across multiple named clients, register a ReplicantCache as a singleton:
var services = new ServiceCollection();
services.AddReplicantCache(cacheDirectory);
services.AddHttpClient("CachedClient")
.AddReplicantCaching();snippet source | anchor
ReplicantHandler is a standard DelegatingHandler, so it composes with the Microsoft.Extensions.Http.Resilience package (retry / circuit-breaker / timeout strategies built on Polly).
Do you actually need it? Replicant already ships with built-in retry-with-exponential-backoff via the
maxRetriesparameter on bothHttpCacheandReplicantHandler— see Retry on transient failure. If retries on transient 5xx / 408 / network exceptions are all you need, use that and skip the extra dependency. Reach forMicrosoft.Extensions.Http.Resiliencewhen you also want circuit-breaking, timeouts, hedging, rate limiting, or fine-grained control over which responses are retried.
Always place the cache outside the resilience pipeline:
So the handler chain is: ReplicantHandler → ResilienceHandler → primary HTTP handler.
IHttpClientBuilder invokes message handlers in registration order, so the first registered handler is the outermost. Register AddReplicantCaching first, then the resilience handler:
…snippet source | anchor
A shared singleton ReplicantCache matters here because HttpClientFactory recycles handler instances periodically — without it, a fresh CacheStore would be created against the same directory each rotation and throw.
For code that builds an HttpClient by hand, wrap a resilience pipeline in ResilienceHandler (from Microsoft.Extensions.Http.Resilience) and pass it as the inner handler to ReplicantHandler:
…snippet source | anchor
staleIfError: true pairs naturally with the circuit breaker — when the breaker is open and BrokenCircuitException bubbles up, Replicant can serve the last successful response rather than failing outright.ReplicantHandler has its own maxRetries parameter. Leave it at the default of 0 when retries are delegated to the resilience pipeline, to avoid double-retry.GET and HEAD go through the cache path; other verbs bypass ReplicantHandler and hit the resilience pipeline directly.Replicant can serve as a disk-based L2 cache for HybridCache. Register ReplicantDistributedCache as the IDistributedCache backend, and HybridCache will automatically use it for its L2 layer (with in-memory L1 handled by HybridCache itself):
var services = new ServiceCollection();
services.AddReplicantDistributedCache(cacheDirectory);
services.AddHybridCache();snippet source | anchor
Only one cache instance (HttpCache, ReplicantCache, or ReplicantHandler with its own directory) can exist per cache directory at any time. Creating a second instance for the same directory will throw an InvalidOperationException. This prevents multiple purge timers from running against the same files.
To share a cache across multiple handlers or consumers, use a single ReplicantCache instance (see above).
var content = await httpCache.StringAsync("https://httpbin.org/json");snippet source | anchor
var lines = new List();
await foreach (var line in httpCache.LinesAsync("https://httpbin.org/json"))
{
lines.Add(line);
}snippet source | anchor
var bytes = await httpCache.BytesAsync("https://httpbin.org/json");snippet source | anchor
using var stream = await httpCache.StreamAsync("https://httpbin.org/json");snippet source | anchor
await httpCache.ToFileAsync("https://httpbin.org/json", targetFile);snippet source | anchor
await httpCache.ToStreamAsync("https://httpbin.org/json", targetStream);snippet source | anchor
using var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("the content")
};
await httpCache.AddItemAsync(uri, response);snippet source | anchor
If an error occurs when re-validating a potentially stale item, then the cached item can be used as a fallback.
var content = httpCache.StringAsync(uri, staleIfError: true);snippet source | anchor
By default, 404 responses are not cached and throw an exception. Set cache404: true on the constructor to cache 404 Not Found responses to disk, avoiding repeated requests for resources known to be missing. The original 404 status code is preserved in the cached metadata.
await using var cache = new HttpCache(cacheDirectory, cache404: true);
var content = await cache.StringAsync(uri);snippet source | anchor
Transient HTTP failures and network exceptions are automatically retried with exponential backoff when maxRetries is set. This works with both HttpCache and ReplicantHandler.
Retried status codes:
408 Request Timeout500 Internal Server Error502 Bad Gateway503 Service Unavailable504 Gateway Timeoutusing var httpCache = new HttpCache(cacheDirectory, maxRetries: 3);
var content = await httpCache.StringAsync("https://example.com");snippet source | anchor
var handler = new ReplicantHandler(cacheDirectory, maxRetries: 3)
{
InnerHandler = new HttpClientHandler()
};
using var client = new HttpClient(handler);
var response = await client.GetAsync("https://example.com");snippet source | anchor
Retries use exponential backoff (200ms, 400ms, 800ms, ...). When combined with staleIfError, retries are attempted first; if all retries are exhausted, stale cached content is returned as a fallback.
By default, cached entries are revalidated when the server-provided expiry (from Expires or Cache-Control: max-age) has passed. When no expiry header is present, cached entries are served indefinitely without revalidation.
For servers that set short expiry times on content that rarely or never changes (e.g. symbol servers, package registries), set minFreshness to override the server's expiry and keep cached entries fresh for a minimum duration. This avoids unnecessary conditional GET round-trips for immutable content. This is a client-side form of heuristic freshness — useful when the server doesn't send Cache-Control: immutable or long-lived expiry headers.
await using var cache = new HttpCache(
cacheDirectory,
minFreshness: TimeSpan.FromHours(1));
var content = await cache.StringAsync("https://httpbin.org/json");snippet source | anchor
The HttpRequestMessage used can be customized using a callback.
var content = await httpCache.StringAsync(
uri,
modifyRequest: message =>
{
message.Headers.Add("Key1", "Value1");
message.Headers.Add("Key2", "Value2");
});snippet source | anchor
An instance of the HttpResponseMessage can be created from a cached item:
using var response = await httpCache.ResponseAsync("https://httpbin.org/status/200");snippet source | anchor
…HttpCache is the standalone API that owns an HttpClient. ReplicantHandler is a DelegatingHandler that plugs into an existing HttpClient pipeline. Both delegate to CacheSession which orchestrates the cache protocol using CacheStore for disk I/O. When multiple handlers need to share a cache, a single ReplicantCache is registered as a singleton. ReplicantDistributedCache implements IDistributedCache for use as a disk-based L2 backend with HybridCache.
No open issues yet, or sync has not completed.