Introduction
Since the HTTP protocol used by web applications is a stateless protocol - which means that their data is not stored anywhere, and for every web request, a new HTTP connection is opened by the browser - the ASP.NET Core provides sessions for storing user data. This data store is maintained by the ASP.NET Core application itself on the same server as the application. Although ASP.NET Core provides an in-memory session provider that stores sessions, sometimes the load needs to be balanced. In such scenarios, session storage strategies like sticky sessions can be used. We need some distributed Cache Mechanism to overcome this issue.
Sticky Sessions
ASP.NET Core application uses the sticky session to tie each session to the specific app instance on an individual server through Application Request Routing module. The sticky sessions can affect the scalability due to improper distribution of load in server. When the requests to the application increase, the server load will increase as well, in such case we need to scale up the server which is very complicated by using sticky session.
The better approach is to use the SQL Server or distributed cache for session storage to overcome the issue in sticky session. However, when it comes to scalable ASP.NET core application, the SQL databases become a performance bottleneck because in SQL the sessions are saved as BLOBs.
On basis of scalability the best approach is using the distributed cache for session storage.
Storing ASP.NET Core Sessions in Distributed Cache
Distributed cache is a cache shared by multiple servers. It is typically maintained as an external service for keeping and accessing data. The distributed cache improves the scalability and performance of an ASP.NET Core Application. Multiple servers can be added to the distributed cache cluster, making it linearly scalable. Users communicate with the ASP.NET Core web farm through a load balancer. The web farm further uses a distributed cache for storing sessions session services provider.
Advantage of using distributed cache
- Doesn’t use local memory
- No single point failure, because of session replication across the servers
- Survives server restart and app deployment.
Distributed cache configuration is implementation specific. In this article I’m going to explain how to configure NCache distributed cache.
What is NCache?
NCache is an Open Source in-memory distributed cache for .NET, Java, and Node.js. NCache is extremely fast and linearly scalable, and caches application data to reduce expensive database trips. Use NCache to remove performance bottlenecks related to your data storage and databases and scale your .NET, Java, and Node.js applications to extreme transaction processing (XTP).
NCache provides a powerful and feature-rich ASP.NET Core Session Service that you can use.
Storage session in distributed cache
Install NCache
Download NCache from NCache Download Center (alachisoft.com). I highly recommend you install the Enterprises edition so that you can explore all its features. Before the installation, make sure .NET 6 has been installed on your machine.
After completing the download and installation process, you can run the NCache Web Manger in the browser from the localhost 8251 port, as shown in the figure below.
We can create clustered and local caches from the NCache web application.
For this demo, I'm using Clustered Cache named as "demoCache", as shown in the below figure.
Click here to see how to create a clustered Cache using NCahce.
Let’s do the stress test to check our cache status. Run the below command in the command prompt to start the stress test:
"test-stress <Cache Name>"
Now that the stress test has been completed, check the count from cache statistics. You can go to cache statistics by selecting our cache from NCache Web application and clicking on the statistics icon.
ASP.NET Core Sessions Storage
With NCache, we can manage ASP.NET Core session storage in two ways:
- The default IDistributedCache Storage
- Using NCache Session provider, which has some advanced features.
Let's see how to use the NCache provider as a IDistributedCache storage for our existing ASP.NET Core web application. We can use NCache as a IDistributedCache Storage provider with a small piece of code changes in our application.
Open your Asp.Net core web application, then download and install the package below from NuGet Package Manager,
“NCache.Microsoft.Extensions.Caching”
Distributed caches, such as NCache, allow you to configure their provider by either configuring all settings in Startup.cs class, or by reading them through the AppSettings.json file of your ASP.NET Core application.
Open appsettings.json and add the object below:
"NCacheSettings": {
"CacheName": "[YourCacheName]",
"SessionAppId": "[YourAppName]",
"EnableSessionLocking": false,
"SessionLockingRetry": -1,
"EnableLogs": false,
"EnableDetailLogs": false,
"ExceptionsEnabled": false,
"OperationRetry": 0,
"operationRetryInterval": 0
}
- CacheName- your Cache Name. In my case it is demoCache.
- SessionAppId – Optional. This specifies an identifier to make sure that the session ID remains unique, in case multiple applications are using the same cache.
- EnableSessionLocking- Optional. If this flag is set, the NCache Session Store Provider exclusively locks the session-store item for which multiple concurrent requests are made. The default is false.
- SessionLockingRetry- Optional. If enableSessionLocking is true and this integer is not less than 0, the NCache Session Store Provider will return the empty session after sessionLockingRetry, which specify the number of retries to acquire a lock. The default is -1.
- EnableLogs- Optional. When this flag is set, the store provider logs all error information. The log files are created in %NCHOME%/log-files/SessionStoreProvider. The default is false.
- EnableDetailLogs- Optional. When this flag is set, the store provider logs all debugging information. The log files are created in %NCHOME%/log-files/SessionStoreProvider. The default is false.
- ExceptionsEnabled- Optional. This specifies whether exceptions from cache API are propagated to the page output. Setting this flag is especially helpful during the development phase of an application, since exceptions provide more information about the specific causes of failure. The default is false.
Open StartUp.cs file and enter the below statement in ConfigureServices function:
services.AddNCacheDistributedCache(Configuration.GetSection("NCacheSettings"));
services.AddSession();
Add below statement in Configure method:
app.UseSession()
That's it. Now you are all set to use the NCache as a provider for ASP.NET Core IDistributedCache.
Summary
We saw how to work with NCache as a provider for ASP.NET Core IDistributed Cache. We will learn more about NCache session provider in my next article.
For reference, you can download the working sample from Github .