Redis Cache Implementation in Dot Net Core

Redis Cache Implementation in Dot Net Core

In the world of .NET Core, Redis plays a crucial role in enhancing the performance of an application by reducing the load on the database. In this comprehensive blog post, we will delve deep into the implementation of Redis Cache in Dot Net Core, unraveling its mysteries and exploring its pivotal role in system design.

Caching is a technique that stores frequently accessed data in memory so that it can be retrieved quickly without having to access the underlying database. This can improve the performance and scalability of web applications by reducing the load on the database.

Redis Cache, an open-source, in-memory data structure store, acts as a lightning-fast cache. Implemented seamlessly in Dot Net Core, it revolutionizes how we handle data, ensuring rapid access and retrieval, even for the most complex applications.

Why Redis Cache?

Before we dive into the implementation details, let’s understand why we need Redis Cache. In any application, data retrieval from a database is a time-consuming process. To improve this, we use caching. Caching refers to the process of storing frequently accessed data in a temporary storage area (cache). So, when the same data is requested again, it is retrieved from the cache instead of the database. This significantly improves the performance and speed of data retrieval.

Redis Cache comes into play here. It stores the frequently accessed data in-memory and retrieves it at a much faster rate compared to traditional databases

Redis isn’t just a cache; it’s a versatile data store with various types catering to diverse data needs. From simple strings to intricate sorted sets, grasp the nuances of Redis data types. Understand when to use hashes for efficient storage, or when to opt for sorted sets to handle ranking and scoring seamlessly. Uncover real-world scenarios where each data type shines, empowering you to make informed design decisions in your Dot Net Core projects.

Redis Data Types

Redis supports various types of data structures:

  • Strings: The most basic Redis data type that represents a sequence of bytes.

  • Lists: Lists of strings sorted by insertion order.

  • Sets: Unordered collections of unique strings.

  • Hashes: Collections of field-value pairs.

  • Sorted Sets: Collections of unique strings that maintain order by each string’s associated score.

  • Bitmaps: Allow you to perform bitwise operations on strings.

  • HyperLogLogs: Provide probabilistic estimates of the cardinality (i.e., number of elements) of large sets.

  • Geospatial Indexes: Useful for finding locations within a given geographic radius or bounding box.

  • Streams: Act like an append-only log that helps record events in the order they occur and then syndicate them for processing.

Implementing Redis Cache in Dot Net Core

  1. First, we will install and configure Redis — to do this, grab the Redis image from Docker, as seen below:

command to get the redis image: docker pull redis

once it is done, run the Redis image:

  • d: Run in the background

  • -p-: Set the Port number

  • — name: name of the image

docker -d -p 6279:6279 --name dotnet-redis redis

Once the Redis image setup is done successfully, verify whether the docker image is running or not by using the command: docker ps

2. Next, Create a new .Net core API project and install the Nuget package named: Microsoft.Extensions.Caching.StackExchangeRedis

3. We follow the repository pattern here to go through the Redis implementation.

Assume that we have a repository class called Basket. The function of this Basket class is to retrieve and update the Basket details, such as items that are moved to the Basket and updated there. To expedite this process and avoid repeatedly retrieving the data from the Database, we will store the Basket class operations data in the Redis cache.


using System;
using Basket.API.Entities;

namespace Basket.API.Repositories
    public interface IBasketRepository
        Task<ShoppingCart> GetBasket(string userName);

        Task<ShoppingCart> UpdateBasket(ShoppingCart basket);

        Task DeleteBasket(string userName);

//BasketRepository class

using System;
using Basket.API.Entities;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

namespace Basket.API.Repositories
    public class BasketRepository : IBasketRepository
        private readonly IDistributedCache _redisCache;

        public BasketRepository(IDistributedCache redisCache)
            _redisCache = redisCache ?? throw new ArgumentNullException(nameof(redisCache));

        public async Task<ShoppingCart> GetBasket(string userName)
            var basket = await _redisCache.GetStringAsync(userName);

            if (String.IsNullOrEmpty(basket))
                return null;

            return JsonConvert.DeserializeObject<ShoppingCart>(basket);

        public async Task<ShoppingCart> UpdateBasket(ShoppingCart basket)
            await _redisCache.SetStringAsync(basket.UserName, JsonConvert.SerializeObject(basket));

            return await GetBasket(basket.UserName);

        public async Task DeleteBasket(string userName)
            await _redisCache.RemoveAsync(userName);

The Redis cache is injected into this class and inside the method we are setting and getting the items as per the username.

Configure the Redis server in the appsettings.json file :

 "CacheSettings": {
    "ConnectionString": "localhost:6379"

Setting up the dependency injection for Basket service and Redis cache in program.cs file:

builder.Services.AddScoped<IBasketRepository, BasketRepository>();

builder.Services.AddStackExchangeRedisCache(options =>
    options.Configuration = builder.Configuration.GetValue<string>("CacheSettings:ConnectionString");

The basic implementation of Redis in the dot net core project is seen above; once the Redis consumed methods are completed, these are called from the controller action methods.

Then I installed the RedisInsights client tool which is connected to redis server running on port : 6379 to view the data: you can see we used the Hash datatype to store the data in a key-value format:

Advantages of using Redis Cache in Dot Net Core

Redis Cache isn’t just a tool; it’s a solution. Explore the myriad advantages it offers, from unparalleled speed and scalability to fault tolerance and seamless integration with Dot Net Core technologies. Learn how Redis Cache enhances your project’s resilience, enabling it to handle surges in user traffic effortlessly. Understand its role in enhancing overall user satisfaction, making it a must-have component in your development toolkit.

  • Improved performance: Redis Cache can significantly improve the performance of web applications by reducing the load on the database.

  • Scalability: Redis Cache is a distributed cache, which means that it can be scaled horizontally to meet the needs of even the most demanding applications.

  • Reliability: Redis Cache is a reliable and durable cache, with features such as replication and persistence to prevent data loss.

  • Easy to use: Redis Cache is easy to use and provides a simple API for storing and retrieving data from the cache.

  • Data Structures: Unlike other key-value stores that offer string-to-string mappings, Redis offers numerous data structures.

When and how to use Redis Cache in Dot Net Core

Redis Cache can be used in a variety of scenarios in Dot Net Core applications, including:

  • Caching frequently accessed data: Redis Cache can be used to cache frequently accessed data, such as product data, user data, and configuration data.

  • Output caching: Redis Cache can be used to cache the output of controllers and services, which can improve the performance of dynamic pages.

  • Session caching: Redis Cache can be used to cache session data, which can improve the performance of web applications and reduce the load on the database.

  • Message queuing: Redis Cache can be used as a message queue to implement asynchronous communication between different parts of an application.

Redis Cache can play an important role in system design by improving the performance, scalability, and reliability of web applications.

In this blog post, we’ve unraveled the mysteries of Redis Cache in the Dot Net Core framework and understood its role in system design. We also walked through a step-by-step process of implementing Redis Cache using StackExchange.Redis and configuring it in a .NET Core application. Finally, we highlighted some advantages of using Redis Cache such as high performance, scalability, persistence, and support for various data structures. you’re now equipped with the knowledge to transform your projects. Redis Cache isn’t just a tool; it’s your ticket to creating blazing-fast, reliable, and efficient applications.

Redis Cache in Dot Net Core isn’t merely a technological advancement; it’s a paradigm shift. Embrace it, integrate it, and witness the transformation it brings to your projects. Your users deserve nothing less than exceptional performance, and Redis Cache ensures you deliver exactly that.

Happy Coding!

Did you find this article valuable?

Support Dileep Sreepathi by becoming a sponsor. Any amount is appreciated!