โšก Response Caching

Automatic HTTP response caching with configurable TTL to reduce API calls and improve performance

Cached Request Demo

This request will be cached for 5 minutes. Run it multiple times to see the performance improvement!

Tip: Click the button multiple times to see caching in action. The first request will hit the API, subsequent requests will return instantly from cache!
๐Ÿ”ง How It Works
  1. First Request: When you make a request with caching enabled, it fetches from the API and stores the response in memory
  2. Cache Key: A unique key is generated based on the request URL and method
  3. Subsequent Requests: Future requests with the same key return instantly from cache
  4. TTL Expiration: After the specified duration (e.g., 5 minutes), the cache entry expires
  5. Auto Refresh: Next request after expiration fetches fresh data and updates the cache
๐Ÿ“ Code Example
Configuration in Program.cs
// Add Memory Cache
builder.Services.AddMemoryCache();

// Add caching decorator to the service chain
builder.Services.AddScoped<IHttpRequestResultService>(provider =>
{
    IHttpRequestResultService service = provider.GetRequiredService<HttpRequestResultService>();
    
    // Wrap with caching decorator
    service = new HttpRequestResultServiceCache(
  provider.GetRequiredService<ILogger<HttpRequestResultServiceCache>>(),
        service,
     provider.GetRequiredService<IMemoryCache>()
    );
    
    return service;
});
Usage in Application Code
// Create request with caching enabled
var request = new HttpRequestResult<JokeResponse>
{
    RequestPath = "https://v2.jokeapi.dev/joke/Programming?safe-mode",
    RequestMethod = HttpMethod.Get,
CacheDurationMinutes = 5 // Cache for 5 minutes
};

var result = await _requestResultService.HttpSendRequestResultAsync(request);

// Check if response came from cache
var isCacheHit = result.RequestContext.TryGetValue("CacheHit", out var hit) && (bool)hit;

if (isCacheHit)
{
    Console.WriteLine($"โœ“ Response from cache! (Age: {result.RequestContext["CacheAge"]})");
}
else
{
    Console.WriteLine("โ†ป Fresh response from API, now cached");
}
Benefits of Caching
  • Reduced Latency: Near-instant responses from cache
  • Lower API Costs: Fewer API calls = lower costs
  • Better Performance: Faster page loads and better UX
  • Reduced Load: Less stress on external APIs
  • Rate Limit Protection: Stay within API rate limits
  • Offline Capability: Serve cached data even if API is down
๐Ÿ“Š Expected Performance
Request Type Typical Duration Improvement
First Request (API) 200-500ms Baseline
Cached Request 1-5ms 99% faster! โšก