Redis contracts and expiry
Redis contracts and expiry
Redis is a networked data store often used as a shared cache. Expiration is a key lifetime policy, not a guarantee of application-level freshness, durability or ownership.
Redis keys should be scoped by application, environment, tenant and schema version using unambiguous canonical encoding. Redis SET supports expiration options such as EX (seconds) or PX (milliseconds) and conditional NX or XX; replacing a string normally clears its prior expiration unless a new TTL or KEEPTTL is used. TTL returns remaining whole seconds, -1 for an existing key with no expiration and -2 for a missing key on modern Redis. Expiry is distinct from eviction under memory pressure. Redis values may disappear before TTL and keys can be stale during their valid lifetime. IDistributedCache represents values as bytes and supports GetAsync, SetAsync, RefreshAsync and RemoveAsync; string extensions encode text. Absolute expiration is a maximum lifetime; sliding expiration resets the idle window when refreshed, subject to the absolute limit. Do not assume IDistributedCache exposes Redis-native operations or exactly maps each provider's storage format to Redis SET. The StackExchange.Redis client is a separate lower-level API; reuse its multiplexer rather than opening a connection per request. For a real Redis deployment review ACLs, encrypted transport, approved endpoint, memory policy, timeout, failover, backup and serialization versioning. A shared key is not a security boundary and Redis leases are not universal distributed locks; timeouts and failovers can permit overlapping owners, so use fencing and resource-side checks where needed. Never run global flush or broad key scans on shared systems. The optional Redis-backed fixture requires an explicitly approved disposable loopback instance; its package pin is an available 10.0 release, not a verified latest or tested dependency.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models and isolated local integration fixtures are explicitly distinguished.
Model expiration with an explicit clock
A dictionary models key/value expiry at known times. This is not a Redis implementation and deliberately omits eviction, clocks across hosts and replication.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run.
using System;using System.Collections.Generic;var entries = new Dictionary<string, (string Value,int ExpiresAt)>();const string key = "lab:tenant-a:book:1";entries[key] = ("4", 105);string Get(int now) { if (!entries.TryGetValue(key, out var item)) return "MISS"; if (now >= item.ExpiresAt) { entries.Remove(key); return "MISS"; } return item.Value;}Console.WriteLine($"t=104: {Get(104)}");Console.WriteLine($"t=105: {Get(105)}");Console.WriteLine($"t=106: {Get(106)}");Expected result (not executed):
t=104: 4t=105: MISSt=106: MISSThe explicit boundary makes expiration tests repeatable. Actual Redis server clock and expiration mechanics require separate tests.
Use IDistributedCache without a Redis server
Register the local in-memory implementation. Serialize a versioned book record as JSON and remove only its own key.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires the ASP.NET Core 10 shared framework.
using System;using System.Text.Json;using Microsoft.Extensions.Caching.Distributed;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection(); services.AddDistributedMemoryCache();using var provider = services.BuildServiceProvider();var cache = provider.GetRequiredService<IDistributedCache>();const string key = "lab:v1:tenant-a:book:1";await cache.SetStringAsync(key, JsonSerializer.Serialize(new Book(1,4)), new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(2) });var json = await cache.GetStringAsync(key);if (json is null) throw new InvalidOperationException("unexpected miss");Console.WriteLine(JsonSerializer.Deserialize<Book>(json)!.Quantity);await cache.RemoveAsync(key);Console.WriteLine(await cache.GetStringAsync(key) is null ? "MISS" : "HIT");sealed record Book(int Id,int Quantity);Expected result (not executed):
4MISSThe interface can swap providers, but this local implementation does not prove cross-process sharing. Real deserialization should validate schema and bounds and distinguish corrupt data from a miss.
Optional Redis-backed distributed cache contract
Only after an operator provisions an isolated, disposable Redis server bound to 127.0.0.1:16379, verifies its ACL and no sensitive data, and approves package restore: run with argument --approved-local-redis. No remote endpoint or credentials are accepted. Without that exact argument, the fixture exits before making a connection.
Use the archived Fixture.csproj with an approved .NET 10 SDK. Inspect dependency graph, restore only approved dependencies, build and run. Requires the ASP.NET Core 10 shared framework. Requires Microsoft.Extensions.Caching.StackExchangeRedis 10.0.15. Default run skips network access. Only the approved local opt-in mode exercises Redis.
using System;using System.Threading;using Microsoft.Extensions.Caching.Distributed;using Microsoft.Extensions.DependencyInjection;if (args.Length != 1 || args[0] != "--approved-local-redis") { Console.WriteLine("SKIP: isolated Redis approval required"); return; }var services = new ServiceCollection();services.AddStackExchangeRedisCache(o => { o.Configuration = "127.0.0.1:16379,connectTimeout=2000,syncTimeout=2000,asyncTimeout=2000,connectRetry=0,abortConnect=true"; o.InstanceName = "bytemind-v25:"; });using var provider = services.BuildServiceProvider();var cache = provider.GetRequiredService<IDistributedCache>();string key = "lab:tenant-a:" + Guid.NewGuid().ToString("N");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));try { await cache.SetStringAsync(key, "4", new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1) }, deadline.Token); Console.WriteLine(await cache.GetStringAsync(key, deadline.Token) ?? "MISS"); await cache.RemoveAsync(key, deadline.Token); Console.WriteLine(await cache.GetStringAsync(key, deadline.Token) is null ? "MISS" : "HIT");} finally { using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(3)); await cache.RemoveAsync(key, cleanup.Token); }Expected result (not executed):
Without opt-in: SKIP: isolated Redis approval requiredWith opt-in and healthy isolated server:4MISSOnly one random fixture key is written and removed; TTL limits residue if cleanup fails. Cancellation may not interrupt every network operation; stop the disposable process on a hard test deadline. If the server requires credentials, do not disable its protections; skip this fixture and design a separately authorized configuration.
Apply the concept
Design a cache expiry test for a 5-second entry and a two-replica deployment. Include a corrupt payload, eviction and a Redis outage.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Redis contracts and expiry — knowledge check
Apply the lesson concepts to the following scenarios.
What does modern Redis TTL return for a missing key?
Does an unexpired Redis value necessarily match the database?
What is AddDistributedMemoryCache useful for?
What should a fixture remove after a Redis test?
What normally happens to Redis string TTL on successful SET without expiration options?