skip to content

Why does an ASP.NET Core 10 mortgage pre-approval wizard that keeps its steps in session lose answers after scaling to three instances, with two browser tabs overwriting each other?

level: seniorimportance: should knowfreq 36%

answer

  1. where does the record actually live
  2. implicit MemoryDistributedCache per process
  3. cookie key protected by Data Protection
  4. non-locking, whole-record last write wins
  5. LoadAsync before first access

basics

~20 s

An in-memory IDistributedCache is per instance and an unshared Data Protection key ring makes the session cookie unreadable elsewhere, so other instances see an empty session. Session is non-locking and saved whole, so the last request to commit wins.

solid answer

~40 s

Three mechanisms combine. First, the store: `AddDistributedMemoryCache()`, which `AddRazorPages()` and `AddControllersWithViews()` also register implicitly, keeps records in one process, so a request routed to another instance finds no record and continues with an empty session. Use a shared `IDistributedCache` such as Redis. Second, the cookie: the session key is protected with Data Protection, and an instance without the same key ring logs a warning and mints a new session. Third, concurrency: `DistributedSession` loads the whole record, and `CommitAsync` writes the whole record back; there is no lock, so two tabs or parallel requests overwrite each other's steps. Keep the draft in the database keyed by an application id, holding only that id in session or the URL. Also call `await HttpContext.Session.LoadAsync()` first, so the record is not read synchronously.

code

csharp · 17 lines
csharp
builder.Services.AddStackExchangeRedisCache(o =>
    o.Configuration = builder.Configuration.GetConnectionString("redis"));
builder.Services.AddSession();

var app = builder.Build();
app.UseRouting();
app.UseSession();

// Load every session asynchronously before any handler touches it.
app.Use(async (context, next) =>
{
    await context.Session.LoadAsync(context.RequestAborted);
    await next(context);
});

app.MapRazorPages();
app.Run();

go deeper

for a junior

Know that in-memory session data lives on one server, so a second server cannot see it.

for a middle

Name the shared IDistributedCache fix and explain why LoadAsync should run before the first session access.

for a senior

Separate the four causes: per-process store, unshared Data Protection keys, non-locking whole-record commits, and synchronous loads that swallow store failures, and fix each one.

for a principal

Decide which wizard state deserves durable storage with concurrency control, and limit session to disposable state so instance loss and store outages cost little.

## The symptoms A Razor Pages wizard stores each completed step, income, property, deposit, in `HttpContext.Session`. On one instance it works. After scaling out to three instances behind a load balancer, users report answers that disappear between steps, and users with two tabs open find that finishing a step in one tab undoes a step in the other. Under load, request threads also block on session reads. Each symptom has its own mechanism in ASP.NET Core's session implementation. ## Cause 1: the store is per process `DistributedSessionStore` keeps records in whatever `IDistributedCache` is registered. `AddDistributedMemoryCache()` registers `MemoryDistributedCache`, which lives in process memory; `AddRazorPages()` and `AddControllersWithViews()` call it for the cache tag helper, so a Razor Pages app has a per-instance store even if nobody chose one. When the balancer sends step two to a different instance, that instance finds no record for the key, logs *Accessing expired session* and continues with an **empty session**. - **Fix:** register a shared `IDistributedCache`, for example `AddStackExchangeRedisCache(...)`. Choosing and operating that store is the distributed-caching topic. - **Stopgap:** sticky sessions on the load balancer keep a browser on one instance, at the cost of uneven load and lost sessions whenever that instance restarts. ## Cause 2: the cookie cannot be read elsewhere The `.AspNetCore.Session` cookie carries the session key protected by an `IDataProtector`. If each instance generates its own key ring, an instance that did not write the cookie cannot unprotect it. `SessionMiddleware` logs *Error unprotecting the session cookie* at Warning level, generates a new key and, on the first write, a new cookie, so the user's state is orphaned even with a shared store. - **Fix:** persist the key ring to shared storage and give every instance the same application name (`PersistKeysToFileSystem`, `SetApplicationName` and their peers belong to the Data Protection topic). ## Cause 3: no locking, whole-record writes ASP.NET Core session is **non-locking** and **coherent**: 1. Each request loads the entire record once, on first access. 2. Changes are made to that request's in-memory copy. 3. At the end of the request, `CommitAsync` serializes **all** keys and writes them with `SetAsync`. Two overlapping requests from the same browser each start from the same snapshot, and whichever commits last overwrites the other, **even when they changed different keys**. Prefixing keys per tab does not help, because the whole record is written. The durable fix is to stop keeping the wizard's answers in session: - create a draft row when the wizard starts and keep its id in the URL (or one small session value); - save each step to that row, using the ORM's optimistic concurrency token to catch true conflicts; - leave session for disposable UI state. ## Cause 4: synchronous loads and silent failures If a handler touches the session without calling `LoadAsync`, the first access (`GetString`, `SetString`, `IsAvailable`) loads the record **synchronously**, blocking a thread pool thread on a network round trip to the store. Under load that becomes thread-pool starvation. | Path | Store unavailable | Store slow | |---|---|---| | `await Session.LoadAsync()` first | the exception propagates to your code | `OperationCanceledException` after `IOTimeout` (1 minute) | | first access without `LoadAsync` | logged at Error level, `IsAvailable` becomes `false`, `Set` is silently ignored, reads return nothing | the thread waits; `IOTimeout` does not apply | Calling `await HttpContext.Session.LoadAsync()` at the start of every wizard handler, or in a small middleware after `UseSession`, keeps the I/O asynchronous and makes an outage visible instead of quietly dropping the user's answers. A failed commit is caught and logged by the middleware; call `CommitAsync` yourself when the handler must know the write succeeded. ## Putting it together - Shared `IDistributedCache` so every instance sees the same record. - Shared Data Protection key ring so every instance can read the cookie. - `LoadAsync` before first access, with handling for its exceptions. - Wizard answers in the database under an application id; session or TempData only for transient UI hints such as the one-time "saved" message.

  • In ASP.NET Core 10, why do two parallel requests that change different session keys still lose an update?
    `DistributedSession` loads the whole record into a per-request copy and `CommitAsync` writes the whole copy back with `SetAsync`. There is no lock and no per-key merge. Each request started from the same snapshot, so the later commit replaces the earlier one, including keys the later request never touched.
  • What does ASP.NET Core session do if the store is down and the handler never called LoadAsync?
    The synchronous first access catches the exception, logs *Session cache read exception* at Error level, marks the session unavailable and swaps in a no-op store. Reads return nothing and `Set` is silently skipped, so the request completes while the user's input is dropped. `LoadAsync` instead lets the exception reach your code.

  • AddDistributedMemoryCache shares session data across all instances of the app
  • ASP.NET Core locks the session so parallel requests run one at a time
  • Prefixing session keys per tab stops parallel requests overwriting each other
  • A shared Redis store alone is enough; the session cookie needs no shared keys
  • IOTimeout protects the synchronous first session access from a slow store