Fine-Tuning Caching in ASP.NET Core

Ibrahim Jaber
3 min readOct 19, 2023

Setting the Stage with a Fun Problem

Imagine you’re the genius behind an online pizza delivery service called “PizzaExpress.” Your customers crave piping hot pizzas delivered to their doorsteps within 30 minutes. However, each order requires multiple database queries, and your app must serve these requests at lightning speed to meet that 30-minute deadline. How can you fine-tune your app to deliver on this promise?

The Power of Caching

Caching is your secret sauce! It’s like having a super-speedy pizza-making machine that can instantly recreate any pizza your customers order. Instead of making the same pizza from scratch every time someone orders it, you make it once, save it, and then serve it faster than you can say “extra cheese.”

Now, let’s fine-tune this pizza-making machine, ahem, I mean caching in ASP.NET Core.

Step 1: Understand the Cache

Before you can fine-tune caching, you need to understand how it works. In ASP.NET Core, you have different cache implementations to choose from: in-memory caching, distributed caching, or custom caches. For simplicity, let’s stick to in-memory caching.

Here’s how you can set it up:

public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
// Other service configurations...
}

Step 2: Cache at the Right Spot

In your “PizzaExpress” app, you can cache pizza menus, ingredients, and order history. It’s tempting to cache everything, but remember that caching consumes memory. You need to be smart about what you cache. For instance, you might cache the pizza menu, which doesn’t change often, but not the current order status.

Step 3: Set Cache Expiration

Caches can go stale, just like yesterday’s pizza. You must set an expiration time for cached data to ensure it stays fresh. For example, the pizza menu might not change for a day, so you can cache it for 24 hours:

_cache.Set("pizza_menu", menu, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24)
});

Step 4: Monitor Cache Performance

--

--

Ibrahim Jaber

Software developer | Programming and Blockchain enthusiast | If you'd like to buy me coffee: https://ko-fi.com/ibrahimjaber