
Image source: https://apisero.com/cache-scope-and-object-store-in-mule-4/
Caching refers to the process of storing frequently used data so that those data can be served much faster for any future requests. So we take the most frequently used data and copy it into temporary storage so that it can be accessed much faster in future calls from the client. If we try to explain with a simple example, Let User-1 request some data and it takes 12-15 seconds for the server to fetch the data. While fetching, we will make a copy of our fetched data parallelly to any temporary storage. So now, when User-2 requests the same data, this time we will simply serve his from the cache and it will take only 1-2 seconds for the response as we already stored the response in our cache.
There are two important terms used with cache, cache hit and cache miss. A cache hit occurs when data can be found in a cache and a cache miss occurs when data can't be found in the cache.
Caching significantly improves the performance of an application, reducing the complexity to generate content. It is important to design an application so that it never depends directly on the cached memory. The application should only cache data that don't change frequently and use the cache data only if it is available.
ASP.NET Core has many caching features. But among them the two main types are,
- In-memory caching
- Distributed Caching
In-memory caching
An in-memory cache is stored in the memory of a single server hosting the application. Basically, the data is cached within the application. This is the easiest way to drastically improve application performance.
The main advantage of In-memory caching is it is much quicker than distributed caching because it avoids communicating over a network and it's suitable for small-scale applications. And the main disadvantage is maintaining the consistency of caches while deployed in the cloud.
Implementing In-memory Caching with ASP.NET Core
First create an ASP.NET Core web API application.

Now inside the Startup.cs file just add the following line. This will add a non-distributed in-memory caching implementation to our application.
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
//Rest of the code
}
Now let's create a new controller "EmployeeController". And in this controller we will implement our cache.
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IMemoryCache _memoryCache;
private readonly ApplicationContext _context;
public EmployeeController(IMemoryCache memoryCache, ApplicationContext context)
{
_memoryCache = memoryCache;
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetAllEmployee()
{
var cacheKey = "employeeList";
//checks if cache entries exists
if(!_memoryCache.TryGetValue(cacheKey, out List<Employee> employeeList))
{
//calling the server
employeeList = await _context.Employees.ToListAsync();
//setting up cache options
var cacheExpiryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpiration = DateTime.Now.AddSeconds(50),
Priority = CacheItemPriority.High,
SlidingExpiration = TimeSpan.FromSeconds(20)
};
//setting cache entries
_memoryCache.Set(cacheKey, employeeList, cacheExpiryOptions);
}
return Ok(employeeList);
}
}
This is a pretty simple implementation. We are simply checking if any cached value is available for the specific cache key. If exists it will serve the data from the cache, if not we will call our service and save the data in the cache.
Explanation
Line 9: Injecting ImemoryCache to the constructor
Line 16: Creating a cache key. As we know that data will be saved as key-value pair.
Line 18: Checking if cache value is available for the specific key.
Line 24: Setting the cache. MemoryCacheEntryOptions is used to define crucial properties of cache. some of the properties are:
1. Priority - Priority defines the priority of keeping cache entry in the cache. The default value is set to Normal.
2. Sliding Expiration - A specific timespan within which the cache will expire if it is not used by anyone. As we set the sliding expiration to 20 seconds so it means after cache entry if there is no client request for 20 seconds the cache will be expired.
3. Absolute Expiration - It refers to the actual expiration of the cache entry without considering the sliding expiration. In our code, we set the absolute expiration to 50 seconds. So it means the cache will expire every 50 seconds for sure.
Now let's observe the performance boost of our application after implementing the In-memory caching.
For this run the application and send a get request to the web API using Postman. So the first time we send a request to our API it takes about 2061ms.

So for the first time when we call our API it directly fetches data from the database and parallelly we store the data to the cache.
Now if we request the same endpoint for the same data this time it will only take 20ms.

So this is a pretty amazing improvement. In my case, the dataset is small. If there is a big set of data on that case it will drastically improve our service.
Distributed Caching
Distributed cache is a cache that can be shared by one or more applications and it is maintained as an external service that is accessible to all servers. So distributed cache is external to the application.







Irshad FarasPosted Apr 2, 2023, 3:40 AM
Very easy & to the point explanation. Thanks for article.
walter LopezPosted Dec 28, 2022, 8:21 PM
Hello Bishwanath, thanks for the sample. It's excellent. I believe there's a typo on step 2 (:379) should be (:6379). docker run --name myrediscache -p 5003:6379 -d redis.
Mohammed HassanPosted Sep 20, 2022, 1:07 PM
Thanks a lot for the knowledge sharing.
Sagar LadPosted Oct 1, 2021, 7:51 PM
Nice article
Arnab MukherjeePosted Sep 29, 2021, 5:53 AM
Nice article.
Pranam BhatPosted Sep 14, 2021, 4:54 AM
Good one! Thanks for sharing!!
Filippo QuarantaPosted Sep 3, 2021, 6:20 PM
Valuable article. Thanks.