{"id":194,"date":"2025-09-24T09:20:37","date_gmt":"2025-09-24T07:20:37","guid":{"rendered":"https:\/\/www.insync.co.za\/blog\/?p=194"},"modified":"2025-09-24T09:28:36","modified_gmt":"2025-09-24T07:28:36","slug":"supercharging-performance-with-caching-in-net","status":"publish","type":"post","link":"https:\/\/www.insync.co.za\/blog\/2025\/09\/24\/supercharging-performance-with-caching-in-net\/","title":{"rendered":"Supercharging Performance with Caching in .NET"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Application performance is often constrained not by the business logic itself, but by repetitive database queries and API calls. Caching is one of the most effective techniques to address this problem. By storing frequently accessed data in memory or a fast distributed store, applications can reduce latency, scale more effectively, and lower infrastructure costs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">According to Microsoft, caching can reduce response times by <strong>up to 80%<\/strong> for frequently requested data (<a href=\"https:\/\/learn.microsoft.com\/en-us\/aspnet\/core\/performance\/caching\/\" data-type=\"link\" data-id=\"https:\/\/learn.microsoft.com\/en-us\/aspnet\/core\/performance\/caching\/\">Microsoft Docs<\/a>). Similarly, Redis benchmarks demonstrate the ability to handle <strong>millions of requests per second<\/strong> with sub-millisecond latency (<a href=\"https:\/\/redis.io\/docs\/about\/\" data-type=\"link\" data-id=\"https:\/\/redis.io\/docs\/about\/\">Redis Labs<\/a>).<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What is Caching?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Caching is the process of storing data in a faster medium for repeated access. Instead of querying a database or an external API on every request, the result is stored and reused for a defined period.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The benefits are clear:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reduced response times.<\/li>\n\n\n\n<li>Decreased load on databases and APIs.<\/li>\n\n\n\n<li>Improved scalability under high traffic.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Benchmark: With and Without Cache<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To demonstrate the impact, consider a service call that takes ~200ms:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Without caching:<\/strong> 1,000 requests = ~200 seconds total.<\/li>\n\n\n\n<li><strong>With in-memory caching:<\/strong> 1,000 requests = ~1.5 seconds total.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This represents a <strong>two orders of magnitude improvement<\/strong> with a simple caching layer.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Caching Options in .NET<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. In-Memory Cache<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The simplest option is <code>IMemoryCache<\/code>, which stores data in the application\u2019s memory.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-8fcb4c743e0c3411d7f4771e198e0eb2\"><code>var cache = new MemoryCache(new MemoryCacheOptions());\ncache.Set(\"CurrentTime\", DateTime.Now, TimeSpan.FromMinutes(5));\n\nif (cache.TryGetValue(\"CurrentTime\", out DateTime cachedTime))\n{\n    Console.WriteLine($\"Cached Time: {cachedTime}\");\n}\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Retrieval times are in microseconds.<\/li>\n\n\n\n<li>Best suited for single-server deployments.<\/li>\n\n\n\n<li>Not shared across multiple instances.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">2. Distributed Cache<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For cloud and multi-server applications, .NET provides <code>IDistributedCache<\/code>, with implementations such as Redis, SQL Server, and NCache.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-f173252d5660972cc6bfb1125d49b4ae\"><code>public async Task&lt;string&gt; GetWeatherAsync()\n{\n    var cacheKey = \"weather-today\";\n    var cached = await _cache.GetStringAsync(cacheKey);\n\n    if (cached != null) return cached;\n\n    var weather = \"Sunny\"; \/\/ Simulated API call\n\n    await _cache.SetStringAsync(cacheKey, weather, \n        new DistributedCacheEntryOptions\n        {\n            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30)\n        });\n\n    return weather;\n}\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Data is shared across all application instances.<\/li>\n\n\n\n<li>Redis is a widely adopted choice, proven to deliver sub-millisecond response times even at scale.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">3. Response and Output Caching<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ASP.NET Core includes built-in support for response caching, allowing entire HTTP responses to be cached.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-1e8ba24c35cbd2aef5c542728f54978d\"><code>&#91;ResponseCache(Duration = 60)]\npublic IActionResult Index()\n{\n    return View();\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This approach reduces server load and is effective for content that does not change frequently.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Hybrid Caching<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Hybrid caching is an advanced strategy supported in <strong>ASP.NET Core 9.0+<\/strong> that blends <strong>in-memory caching<\/strong> with a <strong>distributed cache<\/strong> (like Redis).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The main idea:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Your app first checks the <strong>local memory cache<\/strong> for lightning-fast access.<\/li>\n\n\n\n<li>If the data isn\u2019t there, it falls back to the <strong>distributed cache<\/strong> shared across all servers.<\/li>\n\n\n\n<li>If still missing, the data source (database or API) is queried, then stored in both caches for future requests.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This <strong>reduces latency<\/strong> while still keeping data consistent across a multi-server or cloud environment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example:<\/h3>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-50b3e495d209a9aabd8d0fd40b176980\"><code>builder.Services.AddHybridCache(options =&gt;\n{\n    options.DefaultEntryOptions = new HybridCacheEntryOptions\n    {\n        Expiration = TimeSpan.FromMinutes(5)\n    };\n});\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Developers can then inject and use <code>IHybridCache<\/code> to store and retrieve items efficiently:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-5a9fd71f3c2cafbf4364378afd26c960\"><code>public class WeatherService\n{\n    private readonly IHybridCache _cache;\n\n    public WeatherService(IHybridCache cache) =&gt; _cache = cache;\n\n    public async Task&lt;string&gt; GetForecastAsync(string city)\n    {\n        return await _cache.GetOrCreateAsync(\n            key: $\"forecast-{city}\",\n            factory: async cancel =&gt;\n            {\n                \/\/ Fetch from source if not cached\n                await Task.Delay(50, cancel); \n                return $\"Forecast for {city} at {DateTime.Now}\";\n            },\n            options: new HybridCacheEntryOptions\n            {\n                Expiration = TimeSpan.FromMinutes(10)\n            });\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Hybrid Matters<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Performance:<\/strong> Fast in-memory lookups.<\/li>\n\n\n\n<li><strong>Scalability:<\/strong> Shared state across clusters or cloud deployments.<\/li>\n\n\n\n<li><strong>Simplicity:<\/strong> First-class support in .NET 9 with <code>IHybridCache<\/code>.<\/li>\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Reference:<\/strong> <a href=\"https:\/\/learn.microsoft.com\/en-us\/aspnet\/core\/performance\/caching\/hybrid?view=aspnetcore-9.0&amp;utm_source=chatgpt.com\">Microsoft Docs \u2013 Hybrid Caching in ASP.NET Core<\/a><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">At <strong>InSync Software<\/strong>, we often implement <strong>hybrid caching<\/strong> in modern SaaS solutions. It allows us to deliver sub-millisecond response times while ensuring consistency across multiple nodes \u2014 a balance many businesses need when scaling to thousands of users.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">When to Use Caching<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Appropriate scenarios:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Product catalogs or reference data.<\/li>\n\n\n\n<li>Exchange rates and financial market data.<\/li>\n\n\n\n<li>Weather information.<\/li>\n\n\n\n<li>Expensive report generation.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Avoid caching:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Highly volatile data requiring strict consistency (e.g., inventory levels).<\/li>\n\n\n\n<li>Sensitive data such as passwords or tokens.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Caching in .NET offers substantial performance improvements with relatively low implementation effort.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In-memory caching is the fastest option for single-server setups.<\/li>\n\n\n\n<li>Distributed caching, particularly with Redis, enables horizontal scalability.<\/li>\n\n\n\n<li>Response caching in ASP.NET Core reduces backend processing for repeated requests.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">At <strong>InSync Software<\/strong>, we leverage these caching strategies when designing custom solutions for clients. Whether it\u2019s improving responsiveness in high-traffic APIs, scaling multi-tenant SaaS platforms, or reducing cloud costs, caching consistently proves to be one of the highest-impact optimizations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key is to <strong>cache selectively<\/strong>: cache data that is expensive to compute or fetch, and that does not require constant freshness. When applied strategically, caching can improve responsiveness by over 100x while reducing infrastructure costs.e reducing infrastructure costs.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>References<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/learn.microsoft.com\/en-us\/aspnet\/core\/performance\/caching\/\">Microsoft Docs \u2013 Caching in ASP.NET Core<\/a><\/li>\n\n\n\n<li><a>Redis Benchmarks<\/a><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Application performance is often constrained not by the business logic itself, but by repetitive database queries and API calls. Caching is one of the most effective techniques to address this problem. By storing frequently accessed data in memory or a fast distributed store, applications can reduce latency, scale more effectively, and lower infrastructure costs. According [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":197,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[18],"tags":[37,30,20,19],"class_list":["post-194","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-software-development","tag-net","tag-c","tag-coding","tag-software"],"_links":{"self":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts\/194","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/comments?post=194"}],"version-history":[{"count":2,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts\/194\/revisions"}],"predecessor-version":[{"id":199,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/posts\/194\/revisions\/199"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/media\/197"}],"wp:attachment":[{"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/media?parent=194"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/categories?post=194"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.insync.co.za\/blog\/wp-json\/wp\/v2\/tags?post=194"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}