ASP.NET Core provides a feature called Session State to store such information. But what happens when your application runs on two or more servers?
Can Server 2 access the session information stored by Server 1? Not necessarily.
This is where Shared Distributed Cache comes into the picture.
In this tutorial, I'll explain what distributed caching is, why we need it, and how to implement shared distributed caching in ASP.NET Core using both Redis and SQL Server.
What is a cache?
Before understanding distributed caching, let's understand caching.
A cache is a temporary storage location used to store data so that it can be accessed quickly when needed. We all clear the browser cache to remove stored temporary data and help the browser work properly.
For example, suppose a user visits your website and enters their name. You can store that name in the application's memory like this.
string userName = "Arun Banik";
Your application can access this value without querying a database. This is an example of storing data in memory.
Please remember, application memory belongs to a particular application process. If the application restarts, the data stored in memory is lost.
This is one of the limitations of in-memory storage.
Now, understand the problem with multiple servers
Let's imagine that your ASP.NET Core application runs on two servers. Server1 and Server2. Both servers run the same application, but they have separate memory.
Here's a scenario.
- A user visits your website.
- The load balancer sends the request to Server 1.
- Server 1 stores the user's session information in its memory.
- The user makes another request.
- This time, the load balancer sends the request to Server 2.
- Server 2 tries to access the user's session information.
But unfortunately, Server 2 cannot find the session data stored in Server 1's memory.
Why?
Because Server 1 and Server 2 maintain separate memory spaces.
Let's understand this scenario with a diagram.
As you can see, Server 1 has the user's session information, but Server 2 does not. This is a problem when your application is deployed across multiple servers.
What is a shared distributed cache?
A shared distributed cache is a separate storage system that multiple application servers can access. So, instead of storing session information in each server's individual memory, we store it in a common storage system.
Instead of storing session information in each server's individual memory, we store it in a common storage system.
For example, we can use Redis. Redis is an in-memory data store that can be used as a distributed cache.
Now, let's see how the same application works with Redis.
Architecture using a shared distributed cache
Now both servers can access the same session information.
The process works like this.
- The user sends a request to the website.
- The load balancer forwards the request to Server 1.
- Server 1 stores the session information in Redis.
- The next request goes to Server 2.
- Server 2 retrieves the session information from Redis.
- Server 2 can now access the same session data.
This is the main advantage of a shared distributed cache. Multiple application servers can share the same cached data without maintaining separate copies in their individual memory.
What is Redis?
I have mentioned Redis above while explaining how the process works. So, what is Redis.
Redis is an open-source, in-memory data store. It stores data in its own memory and allows applications to read and write data very quickly.
You can learn more about Redis here.
In a multi-server ASP.NET Core application, Redis can act as a central storage system for session data.
For example, suppose you have three application servers.
Server 1
Server 2
Server 3
All three servers can connect to the same Redis instance. If Server 1 stores the following information.
UserName = Mike
City = New York
Server 2 and Server 3 can also retrieve this information from Redis.
How to Implementing Redis distributed cache in ASP.NET Core
Let me show you how to implement Redis in an ASP.NET Core application. Just follow these steps.
Step 1: Install the Redis NuGet package
Open the terminal in your ASP.NET Core project and execute this,
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
This package provides Redis integration for ASP.NET Core's distributed cache abstraction.
Step 2: Configure Redis in Program.cs
Add the following code to your Program.cs file.
var builder = WebApplication.CreateBuilder(args); // Register Redis as the distributed cache. builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; options.InstanceName = "MyApp_"; }); builder.Services.AddSession(); // Register session services. var app = builder.Build(); app.UseSession(); // Enable session middleware. app.MapGet("/", () => "Welcome to ASP.NET Core."); app.Run();
Code for VB.NET
Imports Microsoft.AspNetCore.Builder Imports Microsoft.Extensions.DependencyInjection Dim builder = WebApplication.CreateBuilder(args) ' Register Redis as the distributed cache. builder.Services.AddStackExchangeRedisCache( Sub(options) options.Configuration = "localhost:6379" options.InstanceName = "MyApp_" End Sub) builder.Services.AddSession() ' Register session services. Dim app = builder.Build() ' Enable session middleware. app.UseSession() app.MapGet("/", Function() "Welcome to ASP.NET Core.") app.Run()
Let me explain the important methods.
AddStackExchangeRedisCache(): This method registers Redis as the distributed cache provider. The application uses Redis to store and retrieve cached data.- Configuration:
options.Configuration = "localhost:6379";This specifies the Redis server address and port. Here, localhost is the server address, and 6379 is the default Redis port. - InstanceName:
options.InstanceName = "MyApp_";This specifies a prefix for cache keys created by this application. AddSession(): This registers the services required for ASP.NET Core session management.UseSession(): This enables session middleware so that the application can read and write session information during HTTP requests.
Step 3: Store session information
Now let's store some information in the session.
Create a controller named HomeController.cs.
using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { HttpContext.Session.SetString( "UserName", "Mike" ); return Content("Session value saved!"); } public IActionResult GetUser() { string? userName = HttpContext.Session.GetString("UserName"); return Content( "User Name: " + userName ); } }
When you access the Index action, the application stores the username in the session.
When you access the GetUser action, it retrieves the username.
See that you are using,
HttpContext.Session.SetString();and
HttpContext.Session.GetString();We don't need to write any Redis-specific code inside the controller.
ASP.NET Core automatically uses the configured session store.
Step 4: Run the application
Make sure your Redis server is running.
Finally, run your ASP.NET Core application.
Open the browser and you will see this https://localhost:7001/Home/Index in the address bar.
The application stores the username in the session.
Next, visit this... https://localhost:7001/Home/GetUser.
You should get,
User Name: Mike
👉 You can also deploy the same application on multiple servers and configure each application instance to connect to the same Redis server. The session data will then be accessible across those instances.
Note: The example assumes a locally running Redis instance without authentication. For production, configure secure Redis connectivity, authentication, and appropriate network access. The HTTPS port may differ in your project.
What is the difference between AddDistributedMemoryCache() and AddStackExchangeRedisCache()?
ASP.NET Core provides different implementations of the distributed cache abstraction. Two commonly used methods are,
1) AddDistributedMemoryCache()
builder.Services.AddDistributedMemoryCache();This method stores cached data in the memory of the current application process. Although it implements the IDistributedCache interface, it does not actually share data across multiple application servers.
2. AddStackExchangeRedisCache()
I have used this method in the above example. (See Step 2).
This stores cached data in Redis.
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});Multiple application servers can connect to the same Redis instance and access the shared data. It is also important to understand that AddDistributedMemoryCache() implements the IDistributedCache interface, but its storage is still local to the application process.
The word Distributed in the interface name does not mean that the in-memory implementation automatically shares data across servers.
Can we use SQL Server instead of Redis?
I asked myself this very question when I first started working with Shared Distributed Caching in ASP.NET Core. At first, it seemed quite obvious to me, especially since I had already used SQL Server for both temporary (cache) storage and permanent data storage.
The answer is, Yes.
Redis is not the only option for distributed caching. ASP.NET Core supports SQL Server as a distributed cache provider through Microsoft.Extensions.Caching.SqlServer.
Remember: In this case, you're not using SQL Server to store traditional business data. Instead, you're using it as a distributed cache store, where data is stored temporarily and managed through cache expiration policies.
You can install the following NuGet package.
dotnet add package Microsoft.Extensions.Caching.SqlServer
Then configure it like this.
builder.Services.AddDistributedSqlServerCache(options => { options.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection"); // DefaultConnection is your SQL Server database connection string. options.SchemaName = "dbo"; options.TableName = "AppCache"; });
You must also create the required cache table using the SQL Server distributed cache table creation script or the appropriate tooling.
There are two ways to create this table.
Method 1. Create dbo.AppCache in SQL Server (Manually)
You can create the dbo.AppCache table directly from SQL Server Management Studio (SSMS).
- Open SQL Server Management Studio.
- Connect to your SQL Server instance.
- Select the database specified in your DefaultConnection.
- Click New Query.
- Execute the following SQL script.
CREATE TABLE [dbo].[AppCache] ( [Id] NVARCHAR(449) NOT NULL, [Value] VARBINARY(MAX) NOT NULL, [ExpiresAtTime] DATETIMEOFFSET(7) NOT NULL, [SlidingExpirationInSeconds] BIGINT NULL, [AbsoluteExpiration] DATETIMEOFFSET(7) NULL, CONSTRAINT [pk_AppCache_Id] PRIMARY KEY CLUSTERED ([Id] ASC) );
After creating the table verify it by executing this SELECT query.
SELECT *FROM dbo.AppCache
Method 2. Create dbo.AppCache using the dotnet sql-cache command
First, install the SQL Server caching package.
Install-Package Microsoft.Extensions.Caching.SqlServer
You can install Microsoft.Extensions.Caching.SqlServer directly from NuGet using either Visual Studio's NuGet Package Manager or the .NET CLI.
Next, open the terminal in your project directory and execute the following command.
dotnet sql-cache create "Data Source=.;Initial Catalog=your_database_name;
Integrated Security=True;TrustServerCertificate=True;" dbo AppCacheIf everything done properly, you should see this message:
Table and index were created successfully.
👉 One of the biggest advantages of ASP.NET Core's distributed cache abstraction, is that you do not have to change your existing session code.
Suppost your existing application uses,
HttpContext.Session.SetString(
"UserName",
"Arun"
);You can continue using exactly the same code after switching from in-memory distributed cache to Redis. You only need to change the cache provider configuration in Program.cs. ASP.NET Core handles the rest.
Conclusion
A distributed cache allows multiple application servers to share cached data. While in-memory caching works well for single-server applications, multi-server applications need a shared storage solution to maintain consistent session data.
ASP.NET Core supports distributed caching using Redis and SQL Server, making it easy to switch between caching providers without changing your existing session access code.
