redis
Caching and Redis or Valkey code in .NET with HybridCache and StackExchange.Redis 3. Use when code or a review touches a cache (HybridCache, IDistributedCache, IMemoryCache, GetOrCreateAsync, cache keys, TTLs, invalidation, tags), AddStackExchangeRedisCache, IConnectionMultiplexer, Redis or Valkey keys, a distributed lock, pub/sub, streams, or a cached value that must be fresh on more than one instance. Not for output caching middleware or HTTP cache headers (dev-stack:aspnetcore), EF Core queries without a cache (dev-stack:efcore), or a message broker (dev-stack:rabbitmq, dev-stack:wolverine).
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- redis
- metadata
- { "verified": "2026-10-27", "versions": "Microsoft.Extensions.Caching.Hybrid 10.11.0, Microsoft.Extensions.Caching.StackExchangeRedis 10.0.14, StackExchange.Redis 3.4.20, Valkey 9.1, Redis Open Source 8.10, .NET 10" }
- description
- Caching and Redis or Valkey code in .NET with HybridCache and StackExchange.Redis 3. Use when code or a review touches a cache (HybridCache, IDistributedCache, IMemoryCache, GetOrCreateAsync, cache keys, TTLs, invalidation, tags), AddStackExchangeRedisCache, IConnectionMultiplexer, Redis or Valkey keys, a distributed lock, pub/sub, streams, or a cached value that must be fresh on more than one instance. Not for output caching middleware or HTTP cache headers (dev-stack:aspnetcore), EF Core queries without a cache (dev-stack:efcore), or a message broker (dev-stack:rabbitmq, dev-stack:wolverine).
02 资源文件 12
- 参考文档references/decisions.md8.2 KB
- 参考文档references/hybridcache.md6.7 KB
- 参考文档references/language.md4.7 KB
- 参考文档references/review-checklist.md6.2 KB
- 参考文档references/sources.md6.6 KB
- 参考文档references/stack-rules.md7.6 KB
- 参考文档references/stackexchange-redis.md6.9 KB
- 参考文档references/testing.md3.1 KB
- 参考文档rules.json7.9 KB
- 脚本scripts/convert.py2.9 KB
- 脚本scripts/doccheck.py28.8 KB
- 脚本scripts/stackcheck.py11.9 KB
03 SKILL.md 正文
Redis and caching
Caching in .NET with HybridCache: L1 in the process, Redis or Valkey as L2. Also direct StackExchange.Redis code: the connection, keys, TTLs, locks, pub/sub, and streams. The write path of the data (SaveChangesAsync, then remove the key) starts in dev-stack:efcore. Output caching and HTTP cache headers are in dev-stack:aspnetcore.
First
- Read
references/stack-rules.md. - Find the package versions:
Microsoft.Extensions.Caching.Hybrid,Microsoft.Extensions.Caching.StackExchangeRedis, andStackExchange.Redisin*.csprojorDirectory.Packages.props. Find the image tag of the cache server in the compose files.- StackExchange.Redis 3.x: use this file.
- StackExchange.Redis 2.x, or no direct reference: the cache package alone resolves 2.7.27. Run
dotnet package list --include-transitiveto see it. Add a direct 3.x reference in each change that touches cache code (rule 2), also when the task does not name the client. - No HybridCache, only
IDistributedCacheorIMemoryCache: existing code keeps its style. New cache code uses HybridCache (CACHE-01).
- Count the instances of the app. One instance needs no L2. More than one instance needs L2, and each cached value needs a freshness rule (rule 6).
Done when you can name the package versions, the server (Redis or Valkey), and the number of instances.
Defaults for new code
Ask the human before you apply a default that has no accepted decision (stack rule 4). The full entries are in references/decisions.md.
| Area | Default | ID |
|---|---|---|
| Layer | No cache until a measured need. Then HybridCache. Redis or Valkey as L2 only for more than one instance. | CACHE-01 |
| Server and client | Valkey 9, server-neutral code, StackExchange.Redis 3.x with a direct reference | CACHE-02 |
| Keys | InstanceName = "{service}:", key v{n}:{entity}:{id}[:{variant}] |
CACHE-03 |
| TTL | Expiration 5 min, LocalCacheExpiration 1 min |
CACHE-04 |
| Invalidation | RemoveAsync after the commit, tags for groups, short L1 TTL |
CACHE-05 |
| Serialization | System.Text.Json with a source-generated context, sealed DTO records |
CACHE-06 |
| Fresh on all nodes | No backplane. DisableLocalCache for data that must be fresh |
CACHE-07 |
| Locks | LockTakeAsync and LockReleaseAsync with a token. DistributedLock.Redis for work that can outlive the TTL. |
CACHE-08 |
Existing code
In cache code, the defects of stack rule 3 include these. Each one gives stale or wrong data without an error, and a test with one app instance passes.
| Defect | Rule |
|---|---|
No direct StackExchange.Redis 3.x reference: the app runs on 2.7.27. |
2 |
| A write decision (a price to charge, stock, a permission) reads its value through the cache. | 5a |
No LocalCacheExpiration: L1 lives as long as Expiration on each node. |
6 |
RemoveAsync before SaveChangesAsync. |
7 |
| A key without a version segment for a type that the change gives new fields. | 9a |
New code that copies one of these patterns depends on the defect. So does new code that changes the data behind it. Fix both, and name the fix under "Changes".
Rules
Connection
- Register one
IConnectionMultiplexeras a singleton. Connect withConnectAsyncat startup, setAbortOnConnectFail = falseandClientName, and give the same instance toAddStackExchangeRedisCachethroughConnectionMultiplexerFactory. A multiplexer per call uses up sockets, andabortConnect=truestops the app when the server is down for a moment. - Reference
StackExchange.Redis3.x directly, or add aPackageVersionwhen the repository usesCentralPackageTransitivePinningEnabled.Microsoft.Extensions.Caching.StackExchangeRedis10.0.14 declaresStackExchange.Redis >= 2.7.27, so NuGet takes 2.7.27 from 2023. - Await each Redis call. Set SER305 to SER308 to
errorin.editorconfig. Do not raiseThreadPool.SetMinThreadsto fix timeouts. A thread that blocks on a Redis task starves the pool that must process the reply.
var cacheOptions = ConfigurationOptions.Parse(
builder.Configuration.GetConnectionString("Cache")
?? throw new InvalidOperationException("ConnectionStrings:Cache is not set."));
cacheOptions.AbortOnConnectFail = false; // start, and reconnect, while the server is down
cacheOptions.ClientName = "orders-api";
var cacheConnection = await ConnectionMultiplexer.ConnectAsync(cacheOptions);
builder.Services.AddSingleton<IConnectionMultiplexer>(cacheConnection);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(cacheConnection);
options.InstanceName = "orders:";
});
builder.Services.AddKeyedSingleton<JsonSerializerOptions>(
typeof(IHybridCacheSerializer<>),
new JsonSerializerOptions { TypeInfoResolver = CacheJsonContext.Default });
builder.Services.AddHybridCache(options =>
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5),
LocalCacheExpiration = TimeSpan.FromMinutes(1),
});
Reads with HybridCache
- Read through
HybridCache.GetOrCreateAsync. Pass the state as an argument and use astaticlambda. Do not write cache-aside by hand withIDistributedCacheand a lock. HybridCache does L1, L2, and one factory call per key in one call. - Expect the factory to run one time per process, not one time per cluster. The stampede protection does not cross instances.
5a. Read a value for a write decision from the database, not from the cache. Examples: the price that checkout charges, stock, a permission. Find each write path that reads through a cached read method (for example a
ProductCachein checkout). When the change makes that value change, fix the read. Then say in the report how the write path gets the current value. - L1 has no backplane.
RemoveAsyncandRemoveByTagAsyncon node A clear the L1 of node A and the L2. Node B serves its L1 copy untilLocalCacheExpiration. Give data that must be fresh on all nodesFlags = HybridCacheEntryFlags.DisableLocalCache. For other data, keep L1 shorter than L2: the L1 TTL is the maximum staleness. WithoutLocalCacheExpiration, L1 gets theExpirationof the same options. SoExpiration = 30 minalone keeps a stale L1 copy for 30 minutes.
public static readonly HybridCacheEntryOptions OrderEntry = new()
{
Expiration = TimeSpan.FromMinutes(5),
Flags = HybridCacheEntryFlags.DisableLocalCache, // a cancel must show on each node at once
};
var order = await cache.GetOrCreateAsync(
$"v1:order:{id:N}",
(db, id),
static async (state, token) =>
{
var entity = await state.db.Orders.AsNoTracking().Include(o => o.Lines)
.SingleOrDefaultAsync(o => o.Id == state.id, token);
return entity?.ToResponse(); // a DTO, never the entity
},
OrderEntry,
cancellationToken: ct);
Writes and invalidation
- In the write path, save to the database first, then call
RemoveAsync. Do not write the new value into the cache from the write path. Two writers can store the older value last. - Remove groups with tags (
tags: ["tenant:42"], thenRemoveByTagAsync("tenant:42")). A tag removal is logical. The old values stay in L2 until they expire, and other nodes keep their L1 copies (rule 6).RemoveByTagAsync("*")removes all. A prefix delete andKEYSdo not exist as a cache API.
await db.SaveChangesAsync(ct);
await cache.RemoveAsync($"v1:order:{id:N}", ct); // after the commit, never SetAsync with the new value
Keys, TTLs, and values
- Build keys only from internal IDs or allow-listed values, with a delimiter and a version segment. Raw user input in a key lets a caller fill the cache, and keys without a delimiter collide.
9a. Increase the version segment (
v1:tov2:) when the change adds, removes, or renames a field of a cached type. Add a segment when the existing key has none. During a rolling deploy, the old version writes the old shape under the same key. The new version reads it with default values (0,null) and no error. Give this reason in the report. - Give each direct Redis key a TTL (
StringSetAsync(key, value, expiry)). Add jitter to keys that you write at the same time, so they do not expire at the same time. HybridCache sendsExpirationto L2 itself. - Cache DTOs, never EF entities. An entity with private setters loses data in the JSON round trip, with no error. Mark a DTO
sealedwith[ImmutableObject(true)], so L1 can return the same instance. Plug in the source-generated context with a keyedJsonSerializerOptions(keytypeof(IHybridCacheSerializer<>)), and add a round-trip test for each cached DTO. - Keep each value under
MaximumPayloadBytes(default 1 MB). HybridCache logs a larger value and does not store it.
Locks, pub/sub, and streams
- Use a Redis lock only to prevent duplicate work. Release it with its token (
LockReleaseAsync), never withKeyDeleteAsync. Protect correctness with a database constraint or a concurrency token. Do not use RedLock. A lock that expires during a GC pause or a failover has two holders. - Use pub/sub only for signals that can get lost, with
RedisChannel.Literal. Use a stream with a consumer group andStreamAcknowledgeAsyncfor work. Put cache data and durable data on separate instances, and setmaxmemorywithallkeys-lruon the cache instance.
Detail and examples: references/hybridcache.md and references/stackexchange-redis.md.
Never write
| Wrong | Correct |
|---|---|
using var redis = ConnectionMultiplexer.Connect(cs); in a method or a scoped service |
One singleton from ConnectAsync at startup |
db.StringGetAsync(key).Result |
await db.StringGetAsync(key) |
ThreadPool.SetMinThreads(200, 200) to fix timeouts |
Remove the sync over async (SER307) |
cache.GetOrSetAsync(...), services.AddRedisCache(...), AddHybridCache().AddRedis(...), db.GetAsync<T>(...) |
GetOrCreateAsync, AddStackExchangeRedisCache plus AddHybridCache |
server.Keys(pattern: "orders:*") to clear a prefix |
Tags (RemoveByTagAsync) or a new version segment in the key |
await cache.SetAsync(key, updated) before or after SaveChangesAsync |
SaveChangesAsync, then RemoveAsync(key) |
GetOrCreateAsync(key, ct => db.Orders.Include(o => o.Lines)...) that returns the entity |
Map to a sealed record DTO in the factory |
o.MaximumPayloadBytes = 1024 * 1024; to "make big objects cache" |
Nothing: 1 MB is the default, and HybridCache logs a skip |
AddKeyedSingleton(typeof(IHybridCacheSerializer<>), options) |
AddKeyedSingleton<JsonSerializerOptions>(typeof(IHybridCacheSerializer<>), options) (the other call is ambiguous, CS0121) |
await db.KeyDeleteAsync(lockKey) to release a lock |
await db.LockReleaseAsync(lockKey, token) |
subscriber.PublishAsync("channel", message) |
subscriber.PublishAsync(RedisChannel.Literal("channel"), message) |
services.AddDistributedMemoryCache() as the shared L2 |
A Redis or Valkey IDistributedCache (HybridCache ignores the memory one) |
<PackageVersion Include="StackExchange.Redis" Version="2.13.17" /> as "latest stable 2.x" |
Version="3.4.20": SER305 to SER308 exist only in 3.x, so on 2.x their .editorconfig lines do nothing |
new RedisBuilder().Build() |
new RedisBuilder("valkey/valkey:9.1").Build() |
Check
-
Build with the analyzers as errors. Add this to
.editorconfigfirst:[*.cs] dotnet_diagnostic.SER305.severity = error dotnet_diagnostic.SER306.severity = error dotnet_diagnostic.SER307.severity = error dotnet_diagnostic.SER308.severity = errordotnet build -warnaserrorPass:
Build succeededwith 0 warnings. CS0618 catches a string channel. -
Check the resolved client version:
dotnet package list --include-transitivePass:
StackExchange.Redis3.x in each project. stackcheck cannot see a transitive version, so run this command. -
Run the rules of this skill:
python3 <skill folder>/scripts/stackcheck.py --root <repo>Pass: 0 errors. For each warning, fix it or add
// stackcheck: ignore <RULE-ID> <reason>. -
Run the tests. Data that must be fresh on all nodes needs a test with two app instances on one Valkey container (
references/testing.md). Pass: all tests green.
Review checklist
The full list is in references/review-checklist.md.
- One multiplexer for the process,
ConnectAsync,AbortOnConnectFail = false. tool (RDS-MUX-CONNECT, RDS-ABORT-CONNECT) StackExchange.Redis3.x resolves in each project. tool (dotnet package list --include-transitive, RDS-PKG-SER2)- No sync over async on Redis calls, no
SetMinThreads. tool (SER307, SER308, RDS-MIN-THREADS) - No
KEYSorserver.Keys. tool (RDS-KEYS-SCAN) - Locks release with their token. tool (RDS-KEY-DELETE-LOCK), judge
- Reads use
GetOrCreateAsync, not hand-written cache-aside. judge - Each cached value that must be fresh on all nodes has
DisableLocalCacheor a backplane. judge 7a. No write decision (checkout price, stock, permission) reads through the cache. This includes existing code that the change depends on. Severity: blocking. judge - The write path saves first, then removes the key. No
SetAsyncwith the new value. judge - Cached values are DTOs, not EF entities, with a round-trip test. judge
- Keys have a version segment and come from internal IDs, never raw user input. The version goes up when a cached type gets new fields. judge
- Each direct Redis key has a TTL. L1 is shorter than L2. judge
- Correctness does not depend on a Redis lock. judge
- Work goes through streams with acknowledgement, not pub/sub. tool (CS0618 for string channels), judge
- No old or unsafe packages (
Microsoft.Extensions.Caching.Redis,RedLock.net).dotnet package list --deprecateddoes not flag them. tool (RDS-PKG-OLD, RDS-PKG-REDLOCK)
Report
End with the report of stack rule 8 (references/stack-rules.md): the same headings in the same order on each run. For each cached type, state in one sentence why it is a DTO and not the entity (rule 11). Also give:
- Under "Packages": the
StackExchange.Redisversion that resolved before the change, and the direct 3.x reference (rule 2). - Under "Changes": the key version and its reason (rule 9a), and how each write decision now reads its value (rule 5a).
- Under "Decisions": each CACHE decision that the change uses, at least CACHE-03, CACHE-04, and CACHE-07 when it touches keys, TTLs, or freshness. Mark each one accepted or assumed.
References
references/decisions.md: read before new code needs a CACHE decision. It has the question, the options, and the recommendation.references/hybridcache.md: read when you set up HybridCache, choose entry options or tags, plug in a serializer, or decide how nodes see a change.references/stackexchange-redis.md: read when you write direct Redis code: the connection, keys and TTLs, locks, pub/sub, streams, server settings, or timeouts.references/testing.md: read before you write a test for cached code or for Redis code.references/review-checklist.md: read for a full review.references/sources.md: the primary sources and the credits.references/stack-rules.mdandreferences/language.md: the common rules and the output language.scripts/stackcheck.py: the rule check of this skill.
04 同仓库更多 Skills
web-accessibility
Web accessibility to WCAG 2.2 AA - a checklist for the design, the tool checks (axe-core, the Tab walk, reduced motion), and the manual checks that no tool does (screen reader, zoom, status messages) - with the EAA and EN 301 549 status. Use when a design, mockup, or built feature must be checked for accessibility, when a review must cover keyboard and screen reader use, when the user asks about focus, a focus trap, contrast, or a screen reader on a page, or when the user asks which accessibility rules apply.
ux-states
State inventory for each screen - default, empty, loading, partial, error, success, disabled, overflow, offline, and the business states (no permission, stale data, locked by another user, waiting on an external system, bulk result with failures, read only) - with what the user sees, can do, and how the user recovers. Use when a screen or flow needs its states designed or checked, or when a design shows only the happy path.
ux-setup
Set up a project for UX work - finds the design tools, the design-system source, the brand files, the languages, and the run command, asks the human one round of questions, and writes the "## Design" section of .claude/rules/delivery.md that the ux-design commands and the ux-designer agent read. Moves an older "## Design" section out of CLAUDE.md. Use when /setup, /ux-design, or /ux-review needs the design facts, when the ux-designer agent returns NEEDS_HUMAN because the "## Design" section is missing, or when the user wants to set up or change the design tools of a project.
ux-review
UX review of a built feature against its approved design - Playwright walks each flow and state at 390, 820, and 1440 px, axe-core and the tell checks run on each state, and each heuristic gets a verdict - with findings by owner, severity, and origin, and a verdict in ux-review.md in the work folder of the item. Use when a built feature or screen must be checked against its design, mockups, or prototype, in each state or at each screen size, when built screens need findings by severity, when the build of an item with a UX design is done, or when existing screens need a UX audit.
ux-prototype
Clickable prototype of a designed story in the proto-shell standard, with variants for an A/B test, all states in scope, three sizes, and a test plan with tasks. Use when a design or mockups exist and the team must test the flow or compare variants with users before the build.
ux-practice
The method of the ux-designer agent for the UX design of a story, a feature, or a screen - Double Diamond phases, a design spec with a source for each decision, the UX decision log, evidence tags, severity, and the modes light, full, and new-direction. Preloaded by the ux-designer agent. Use when the ux-designer agent or another UX skill names this method. For the design of an item, a person starts ux-design:ux-design.