skip to content

Should a .NET team standardise on immutable collections for shared state like a pricing service's rules snapshot, and what does that standard cost?

level: principalimportance: should knowfreq 30%

answer

  1. readers versus writers
  2. snapshots without locks
  3. who publishes the new version
  4. allocation and lookup cost
  5. frozen for startup data

basics

~20 s

Often yes for read-mostly shared state: readers get lock-free snapshots and writers publish new versions with ImmutableInterlocked.Update. The costs are an allocation per change, slower lookups than Dictionary and new bug patterns, so write-heavy and startup-only state need other choices.

solid answer

~50 s

For **read-mostly** state, standardising on `System.Collections.Immutable` pays: a reader takes one reference and has a snapshot nobody can change under it, with no lock on the hot path, and the snapshot can be handed to background work or logged safely. The standard must also say **how writers publish**: build the new version and swap the field with `ImmutableInterlocked.Update` (a compare-and-swap loop that reruns the transformer when it loses a race), or under a lock when writes are rare; plain reassignment loses updates. The costs are real: every change allocates, tree-based types make lookups O(log n) instead of a `Dictionary`'s O(1), and the team inherits the discarded-result bug, `default(ImmutableArray<T>)` and shallow immutability. So scope it: immutable for shared snapshots with occasional edits, `FrozenDictionary<TKey,TValue>` (.NET 8) for tables built once at startup, and a lock around a `Dictionary` or a concurrent collection for write-heavy state.

code

csharp · 24 lines
csharp
using System.Collections.Immutable;

var store = new RulesStore();
int calls = 0;

Parallel.For(0, 1_000, i =>
    ImmutableInterlocked.Update(ref store.Rules, (current, n) =>
    {
        Interlocked.Increment(ref calls);
        return current.SetItem($"rule-{n}", n);
    }, i));

Console.WriteLine(store.Rules.Count);   // 1000: no edit lost
Console.WriteLine(calls >= 1_000);      // True: a losing transformer runs again

// The bug: read, change, write back with no compare-and-swap.
var racy = new RulesStore();
Parallel.For(0, 1_000, i => racy.Rules = racy.Rules.SetItem($"rule-{i}", i));
Console.WriteLine(racy.Rules.Count);    // often fewer than 1000: lost updates

class RulesStore
{
    public ImmutableDictionary<string, int> Rules = ImmutableDictionary<string, int>.Empty;
}

go deeper

for a junior

Recall that immutable collections let many threads read the same data safely because nobody can change it.

for a middle

Explain that each change allocates a new version and that a shared field still needs a safe way to swap versions.

for a senior

Show the lost-update race on plain reassignment and the ImmutableInterlocked.Update fix, including why its transformer must be pure.

for a principal

Scope the standard by workload, name one publication pattern, carve out write-heavy and startup-only state, and back the choice with measurements.

## The decision A pricing service loads a currency table and feature-flag rules, reads them on every request, and publishes a new rules snapshot when an admin edits them. Several teams own similar services, and a lead is asked whether immutable collections should be the house default for state shared between threads. There is no single right answer; the question is which workloads the default covers and what the team must learn to use it safely. ## What the standard buys - **Lock-free, consistent reads.** A request reads the field once and works with that version for its whole duration. Nobody can add a rule halfway through, so there is no torn state and no lock contention on the hot path. - **Safe hand-off.** A snapshot can be passed to a background job, cached in a response, or logged later without a defensive copy, because it can never change. - **Cheap history.** Keeping the previous version for an audit trail or a rollback needs no copy: it is just the old reference, and `ImmutableList<T>` or `ImmutableDictionary<TKey,TValue>` share most of their structure with the new one, so only the nodes unique to the old version stay alive. - **Simpler reasoning in review.** A field typed `ImmutableDictionary<string, Rule>` documents that readers need not worry about concurrent writers. ## What the standard costs | Cost | Where it shows | |---|---| | An allocation per change | each `Add` or `SetItem` creates new nodes or, for `ImmutableArray<T>`, a whole new array | | Slower lookups | `ImmutableDictionary<TKey,TValue>` lookups are O(log n) per the .NET docs, against O(1) for `Dictionary<TKey,TValue>` | | Slower indexing | `ImmutableList<T>[i]` walks a tree, O(log n) | | Memory per element | tree-based types allocate a node object per element | | New bug patterns | discarded `Add` results, which no built-in analyzer flags; `default(ImmutableArray<T>)` throwing; shallow immutability of mutable element types | None of these matters much for a rules snapshot of a few hundred entries edited a few times a day. All of them matter for a hot dictionary updated thousands of times a second. ## Publishing is part of the standard Immutability protects the **collection**, not the **field** that points to the current version. Two writers that both do `_rules = _rules.SetItem(...)` can each read the same old version, and the second write silently discards the first. In the code example, that pattern typically loses a large share of 1,000 concurrent edits. The standard should name one publication pattern: 1. **`ImmutableInterlocked.Update(ref _rules, transformer)`**: reads the current value, runs the transformer, and swaps with `Interlocked.CompareExchange`; if another writer got there first, it reruns the transformer on the newer value. The transformer must therefore be **pure and cheap**, since it may run more than once. `ImmutableInterlocked` also has `AddOrUpdate`, `GetOrAdd`, `TryAdd`, `TryUpdate` and `TryRemove` for `ImmutableDictionary<TKey,TValue>` fields, and overloads that take `ref ImmutableArray<T>`. 2. **A lock around writers only**, when edits are rare and the transformer is expensive (for example, it calls a database). Readers still read the field without a lock. 3. **Single writer**: one background component owns the field and publishes with a volatile write; everyone else only reads. ## Where the default should not apply - **Built once at startup and never changed**: a `FrozenDictionary<TKey,TValue>` or `FrozenSet<T>` (.NET 8) is typically faster to read than either a `Dictionary` or an immutable dictionary, and needs no publication pattern at all, or a whole-table swap on the rare reload. - **Write-heavy shared maps**: per-key counters or caches with constant inserts allocate a new version per write; a `Dictionary` behind a lock, or a concurrent dictionary (covered with the thread-safe collections), fits better. - **State confined to one thread or one request**: plain `List<T>` and `Dictionary<TKey,TValue>` are cheaper and simpler. - **Hot loops over large data**: prefer `ImmutableArray<T>` over tree-based types, and measure allocations with a benchmark before standardising. ## A workable rule set - Shared, read-mostly state uses immutable or frozen collections, chosen by whether it changes after startup. - Every writer publishes through one named pattern; plain reassignment of a shared field is a review failure. - Bulk construction goes through builders or `ToImmutableArray()`, never `Add` in a loop. - `ImmutableArray<T>` fields are always initialised, and element types of shared snapshots are immutable themselves. - Write-heavy or single-threaded state is exempt, and the exemption is written down so reviewers do not argue it case by case. A standard like this is cheap to adopt incrementally: start with the snapshots that already cause locking pain or torn reads, measure allocation rates before and after, and widen it only where the numbers stay flat.

  • Why must the transformer passed to ImmutableInterlocked.Update have no side effects?
    Because it can run more than once. `Update` reads the current value, calls the transformer, and tries a compare-and-swap; if another thread published in between, it calls the transformer again on the newer value. A transformer that logs, sends a message or increments a counter would do so once per attempt, not once per successful edit.
  • How would you show the team that the standard is affordable for a given service?
    Measure the real workload rather than argue: a BenchmarkDotNet run with the memory diagnoser comparing lookups and edits on the actual sizes, and the service's allocation rate before and after under representative traffic. If reads dominate and edits are rare, the extra allocations disappear in the noise.
  • Does making the rules collection immutable make each Rule object safe to share?
    No. Immutable collections are shallow: they fix which elements the collection holds, not the state of those elements. If `Rule` has settable properties, any reader can change a rule that every other reader sees. The standard has to require immutable element types, such as records with init-only properties.

  • Immutable collections make the field that holds them thread-safe to reassign
  • Immutable collections are always faster because they never need locks
  • ImmutableInterlocked.Update runs the transformer exactly once
  • Every shared collection, including write-heavy counters, should be immutable
  • An immutable list of mutable objects is fully safe to share

Assumes .NET 10; FrozenDictionary<TKey,TValue> and FrozenSet<T>, offered here as the startup-only alternative, were added in .NET 8.