Distribute SQL Server Cache Implementation Using .NET Core

Picture of Vivasoft Team
Vivasoft Team
Published on
01.10.2025
Time to Read
2 min
Distributed SQL server cache implementation using dot net core
Table of Contents

A distributed cache is used in an application to enhance performance and scalability by storing data in memory across multiple servers, thereby reducing database load and lowering latency. It provides high availability and fault tolerance by replicating data and distributing the load, which is crucial for high-traffic applications such as e-commerce sites and streaming services.

Today, I will demonstrate a distributed cache using a .NET Core application that allows the distributed cache to use a SQL Server database as its backing store.

Now I will show a step-by-step process to add a distributed cache to the application.

Step 1: Create the SQL Server Cache Table

Create the SQL Server Cache item table in SQL Server. To do so, you have to use the SQL-Cache tool. This tool creates a table with the name and schema that you specify. Install the SQL-Cache tool by running the following command using .NET CLI

				
					dotnet tool install --global dotnet-sql-cache
				
			

Create a table in SQL Server by running the sql-cache create command using .NET CLI.

				
					dotnet sql-cache create "Server=localhost;Database=DB;User Id=sa;Password=****; Encrypt=True;" dbo CacheTable
				
			

Provide the SQL Server instance (Server), database (Database), User Id (Your DB User Id), Password(Your DB Password), schema (for example, dbo), and table name (for example, CacheTable):

A message logged in the console:

				
					Table and index were created successfully
				
			

This creates a table named CacheTable in your database with the following schema.

Distributed SQL server cache

Step 2: Install Required NuGet Package

Now you have to add a package to your application from the NuGet package manager using the following command of .NET CLI.

				
					dotnet add package Microsoft.Extensions.Caching.SqlServer
				
			

Step 3: Configure Distributed Cache in Program.cs

Register to connect the table in the application by adding the following line of code in the Program.cs

				
					builder.Services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    options.SchemaName = "dbo";
    options.TableName = "CacheTable";
});
				
			

Now you can inject IDistributedCache anywhere (service, controller, or class) in your application.

Step 4: Implement Distributed Cache in a Service Class

Inject into a service class to demonstrate its usage

				
					public class ProductService
{
    private readonly IDistributedCache _cache;

    public ProductService(IDistributedCache cache)
    {
        _cache = cache;
    }

    public async Task SetProductAsync(string productId, string productJson)
    {
        var options = new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30), // expire after 30 minutes
            SlidingExpiration = TimeSpan.FromMinutes(10) // refresh expiration if accessed
        };

        await _cache.SetStringAsync(productId, productJson, options);
    }

    public async Task<string?> GetProductAsync(string productId)
    {
        return await _cache.GetStringAsync(productId);
    }
}
				
			

Call the Service class and use it in controller

				
					[ApiController]
[Route("api/[controller]")]
public class ProductsController: ControllerBase
{
    private readonly ProductService _productService;

    public ProductsController(ProductService productService)
    {
        _productService = productService;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> Get(string id)
    {
        var cached = await _productService.GetProductAsync(id);

        if (cached != null)
        {
            return Ok(new { source = "cache", data = cached });
        }

        // Simulate fetching from DB
        var dbData = $"{{ \"id\": \"{id}\", \"name\": \"Sample Product\" }}";

        await _productService.SetProductAsync(id, dbData);

        return Ok(new { source = "db", data = dbData });
    }
}
				
			
50+ companies rely on our top 1% talent to scale their dev teams.
Excellence Our minimum bar.
It has become a prerequisite for companies to develop custom software.
We've stopped counting. Over 50 brands count on us.
Our company specializes in software outsourcing and provides robust, scalable, and efficient solutions to clients around the world.
klikit

Chris Withers

CEO & Founder, Klikit

Klikit-logo
Heartfelt appreciation to Vivasoft Limited for believing in my vision. Their talented developers can take any challenges against all odds and helped to bring Klikit into life.appreciation to Vivasoft Limited for believing in my vision. Their talented developers can take any challenges.
Start with a dedicated squad in 7 days

NDA first, transparent rates, agile delivery from day one.

Where We Build the Future
Scale Engineering Without the Overhead

Elastic offshore teams that integrate with your processes and timezone.

Tech Stack
0 +
Blogs You May Love

Don’t let understaffing hold you back. Maximize your team’s performance and reach your business goals with the best IT Staff Augmentation

let's build our future together

Get to Know Us Better

Explore our expertise, projects, and vision.