In this lesson, you will learn how to maintain user session state across application deployments to prevent users from being logged out during rolling updates or scaling events.
The Challenge of In-Memory Sessions
In a standard ASP.NET Core application, if you store session data in the default AddDistributedMemoryCache(), that data lives inside the RAM of your specific web server. When you perform a deployment, your server process restarts, and that memory is wiped clean. This forces every user to re-authenticate, resulting in a poor user experience—especially in a load-balanced environment where requests might hit different server instances.
Externalizing Session State
To persist sessions across deployments, you must move the state out of the application process and into a shared, centralized data store. Redis is the industry standard for this. By using a distributed cache, your session data survives application restarts because it lives in an external database, not the server's memory.
Implementation Concept
Instead of relying on the local process, you configure your Program.cs (or Startup.cs) to use a persistent provider:
// Instead of AddDistributedMemoryCache, use Redis
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "your-redis-connection-string";
options.InstanceName = "IdentitySession_";
});
builder.Services.AddSession(options =>
{
options.Cookie.Name = ".YourApp.Session";
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
When a user logs in, the session token is validated against the identity store, but the session metadata is serialized and stored in Redis. When you deploy a new version of your service, the new instance connects to the same Redis cluster, retrieves the session using the cookie provided by the client, and seamlessly resumes the user's activity.
Why This Matters
By decoupling the session state from the compute instance, you achieve "stateless" application servers. This is critical for modern cloud-native architectures where instances are frequently destroyed and replaced. Whether you are performing a rolling update or autoscaling during peak traffic, the user remains oblivious to the infrastructure changes happening behind the scenes.
Key Takeaway: To ensure continuous sessions during deployments, move session state out of local server memory and into an external, distributed store like Redis.