skip to content

In ASP.NET Core's HybridCache, how are values serialized, how do you plug in an IHybridCacheSerializer<T>, and when do callers share one cached instance?

level: middleimportance: nice to knowfreq 18%

answer

  1. string and byte[] built in
  2. System.Text.Json for everything else
  3. AddSerializer<T, TImplementation>() on the builder
  4. sealed plus [ImmutableObject(true)]
  5. MaximumPayloadBytes 1 MiB

basics

~10 s

HybridCache handles string and byte[] itself and serializes other types with System.Text.Json unless you register an IHybridCacheSerializer<T> or a serializer factory. Mutable types are deserialized for every caller; sealed types marked [ImmutableObject(true)] are shared.

solid answer

~40 s

`AddHybridCache()` registers built-in serializers for `string` and `byte[]` and a default `IHybridCacheSerializerFactory` that uses System.Text.Json for other types. `IHybridCacheSerializer<T>` has two methods, `T Deserialize(ReadOnlySequence<byte> source)` and `void Serialize(T value, IBufferWriter<byte> target)`; register one with `AddHybridCache().AddSerializer<ProductCard, ProductCardSerializer>()`, or a factory with `AddSerializerFactory`, where the last-added factory wins. Serialization runs even without a distributed tier, because a mutable type is kept in L1 as bytes and **deserialized for each caller**, so callers can never mutate one another's copy. A sealed class or a value type marked `[ImmutableObject(true)]`, and `string`, is stored as the instance and shared. Values over `MaximumPayloadBytes` (1 MiB) are logged as an error and not written to the distributed tier, and keys longer than `MaximumKeyLength` (1024) bypass the cache.

go deeper

for a junior

Recall that HybridCache serializes values to store them, with System.Text.Json by default and string and byte[] handled directly.

for a middle

Explain IHybridCacheSerializer<T>'s two methods, registering one with AddSerializer on the builder, and the 1 MiB payload and 1024-character key limits.

for a senior

Explain why mutable types are deserialized per hit even without L2, when sealed types with [ImmutableObject(true)] are shared, and how oversized values silently stop reaching the distributed tier.

for a principal

Decide which cached types become immutable contracts, which serialization format and versioning rules apply across services, and who owns compatibility when cached shapes change.

## What gets serialized, and with what `AddHybridCache()` registers three serialization services with `TryAddSingleton`: - an `IHybridCacheSerializer<string>` and an `IHybridCacheSerializer<byte[]>`, built in, with no JSON involved; - an `IHybridCacheSerializerFactory` that creates System.Text.Json serializers for every other type, using `JsonSerializerOptions.Default` (and turning on fields for types that expose only fields). For each `T`, `DefaultHybridCache` first looks for a registered `IHybridCacheSerializer<T>`, then asks the registered factories, newest first. The serializer contract works on buffers rather than arrays. In this example `CatalogueJson` is the app's own source-generated `JsonSerializerContext`: ```csharp public sealed class ProductCardSerializer : IHybridCacheSerializer<ProductCard> { public ProductCard Deserialize(ReadOnlySequence<byte> source) { var reader = new Utf8JsonReader(source); return JsonSerializer.Deserialize(ref reader, CatalogueJson.Default.ProductCard)!; } public void Serialize(ProductCard value, IBufferWriter<byte> target) { using var writer = new Utf8JsonWriter(target); JsonSerializer.Serialize(writer, value, CatalogueJson.Default.ProductCard); } } ``` ## Registering a serializer `AddHybridCache` returns an `IHybridCacheBuilder` with four extension methods: | Method | Registers | |---|---| | `AddSerializer<T>(IHybridCacheSerializer<T> serializer)` | a serializer instance for one type | | `AddSerializer<T, TImplementation>()` | a serializer type for one type | | `AddSerializerFactory(IHybridCacheSerializerFactory factory)` | a factory instance for many types | | `AddSerializerFactory<TImplementation>()` | a factory type for many types | ```csharp builder.Services.AddHybridCache() .AddSerializer<ProductCard, ProductCardSerializer>(); ``` A factory implements `bool TryCreateSerializer<T>(out IHybridCacheSerializer<T>? serializer)` and returns `false` for types it does not handle, letting earlier factories try. Teams use this to plug in a binary format for a whole family of contract types, or source-generated JSON metadata for trimming and Native AOT. ## Why serialization happens even with no Redis Values are serialized whenever they are written anywhere, not only to L2. For a **mutable** type, L1 holds the serialized bytes, and every L1 hit deserializes a fresh object. The design goal is thread safety: two requests that each receive a `ProductCard` can modify their copies without affecting each other or the cached value. The ASP.NET Core docs describe this as the behaviour code using `IDistributedCache` already had. The cost is a deserialization per hit. For read-only data you can opt out. ## Sharing one instance `HybridCache` reuses the cached object itself only when it can trust the type to be immutable: 1. `string`, always; 2. a **sealed class** or a **value type** that carries `[ImmutableObject(true)]` from `System.ComponentModel`. ```csharp [ImmutableObject(true)] public sealed record ProductCard(string Sku, string Name, decimal Price, string ImageUrl); ``` For such a type, L1 stores the instance and every hit returns the same reference with no deserialization. Interfaces and non-sealed classes are never trusted, because a subclass could be mutable. The attribute is a promise you make: if code later mutates a shared `ProductCard`, every request sees the change. ## Size and key limits | Option | Default | When exceeded | |---|---|---| | `HybridCacheOptions.MaximumPayloadBytes` | 1 MiB | an error "Cache MaximumPayloadBytes ... exceeded." is logged and the value is not written to the distributed tier; the caller still receives it | | `HybridCacheOptions.MaximumKeyLength` | 1024 characters | an error is logged and the factory runs without caching | Keys that are empty, whitespace or contain control characters are rejected the same way: the call still returns data, but nothing is cached. A large catalogue response that silently stops being cached is a common surprise; the log entry is the clue. ## Interview summary - Default: built-in for `string` and `byte[]`, System.Text.Json otherwise. - Custom: `IHybridCacheSerializer<T>` or a factory, registered on the builder. - Mutable types: a fresh copy per caller, at a deserialization cost. - Sealed or value types marked `[ImmutableObject(true)]`: one shared instance. - Over 1 MiB: logged and not written to the distributed tier. ## Compatibility across deploys A serialized value outlives the code that wrote it when it sits in Redis. Two instances running different builds during a rolling deploy can read each other's entries, so: - **Additive changes are safe** with System.Text.Json's defaults: a new property is missing in old entries and gets its default value. - **Renames and type changes are not.** The old shape deserializes incompletely or fails, and a failure is logged as "Cache deserialization failure." and can reach the caller as an exception. - **Version the key** (`card:v2:{sku}`) when the shape changes incompatibly, so old and new builds use different entries until the old ones expire. A custom serializer does not remove this concern; it only moves the compatibility rules into your own code.

  • Why is a non-sealed record marked [ImmutableObject(true)] still deserialized for every caller?
    `HybridCache` only trusts sealed classes and value types: a non-sealed type could have a mutable subclass stored under the same key. Reuse requires both conditions, so add `sealed` as well as the attribute.
  • Which serializer wins if a type has both a registered IHybridCacheSerializer<T> and a factory that can handle it?
    The type-specific `IHybridCacheSerializer<T>` registration is used first. Factories are consulted only when no such registration exists, and among factories the most recently added one that returns `true` from `TryCreateSerializer` wins.

  • HybridCache serializes values only when a distributed cache is registered
  • Every type HybridCache caches is shared as one instance between callers
  • Marking any class [ImmutableObject(true)] is enough for HybridCache to reuse it
  • HybridCache throws to the caller when a value exceeds MaximumPayloadBytes
  • HybridCache uses Newtonsoft.Json as its default serializer