[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74GEMWFPWDV6WZ4TQMP0HD9":3,"skill-same:01M74GEMWFPWDV6WZ4TQMP0HD9":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M74GEMWFPWDV6WZ4TQMP0HD9","design-cache-layer",null,"Design a Redis cache layer — key schema, TTLs, eviction policy, stampede + thundering-herd protection, hot-key + big-key avoidance. Use after caching-tradeoffs picks where; not Redis server config.","MohammadBafkar\u002Fpolymath","MohammadBafkar","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F34940462?v=4","01M74G540TQFZWK6KVAPKFVGNR","Mohammad Bafkar","01M74G541HG19QP9V5DQCJVKYE",0,"MIT","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-performance\u002Fskills\u002Fdesign-cache-layer\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: design-cache-layer\ndescription: Design a Redis cache layer — key schema, TTLs, eviction policy, stampede + thundering-herd protection, hot-key + big-key avoidance. Use after caching-tradeoffs picks where; not Redis server config.\n---\n\n# design-cache-layer\n\n> Cache design that survives Black Friday, not just the demo. Output: key schema, TTL strategy, write\u002Fread path, failure modes considered.\n\n**Mode:** analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked `[TBD]` or `[VERIFY]`, never filled in.\n\n## When to use\n\n- A read-heavy endpoint needs caching.\n- An existing cache is causing incidents (stampedes, hot keys, memory pressure).\n- A PRD says \"use Redis\" with no further detail.\n\n## Inputs\n\n- The cache shape decided by `polymath-performance:caching-tradeoffs` (what, where, invalidation, staleness) — required; without it, run that first.\n- Traffic: request rate, key cardinality, value sizes, hot-key candidates (measured or `[TBD]`).\n- The Redis deployment (optional): managed vs self-hosted, cluster vs single primary, memory limit.\n\n## Related skills\n\n- [`polymath-performance:caching-tradeoffs`](..\u002Fcaching-tradeoffs\u002FSKILL.md)\n  — vendor-agnostic decision: *what* to cache, *where* to cache,\n  staleness tolerance, failure modes. Run that first to decide the\n  shape; use this skill to ship the Redis layer.\n- [`polymath-performance:audit-redis-config`](..\u002Faudit-redis-config\u002FSKILL.md)\n  — once the cache layer is running, review `maxmemory`, eviction,\n  persistence, replication.\n\n## Procedure\n\n1. **Identify the value.** Caching is for *expensive-to-compute, frequently-read, eventually-consistent* values. If the data is cheap to compute or strongly consistent, do not cache.\n2. **Key schema.** Structured + versioned:\n   ```\n   \u003Cdomain>:\u003Centity>:\u003Cid>:v\u003Cversion>      e.g. refund:profile:42:v3\n   \u003Cdomain>:list:\u003Cfilter-hash>:v\u003Cversion> e.g. refund:list:sha8af2:v3\n   ```\n   The `v\u003Cn>` suffix lets a deploy invalidate everything by bumping it; the alternative (deleting keys) is slow on large keyspaces.\n3. **TTL strategy.**\n   - Per-entry TTL with jitter: `TTL = base ± random(0, base\u002F10)`. Prevents synchronized expiry storms.\n   - Sliding TTL only when reads are bursty around a record (re-set on hit).\n   - Negative caching: also cache \"not found\" for a shorter TTL to absorb 404 floods.\n4. **Eviction.** `maxmemory-policy = allkeys-lru` for pure caches; `volatile-lru` if you also store non-cache data with no TTL.\n5. **Read path with stampede protection.**\n   ```\n   value = GET key\n   if value:\n       return value\n   # cache miss\n   token = random_uuid()\n   if SET nx:lock:key token NX EX=5:\n       try:\n           value = expensive_compute()\n           SET key value EX=jittered_ttl\n           return value\n       finally:\n           # release only OUR lock — compare-and-delete in one Lua call\n           EVAL \"if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) end return 0\" 1 nx:lock:key token\n   for attempt in 1..3:                      # someone else is computing\n       sleep(50ms × attempt)\n       value = GET key\n       if value: return value\n   return serve_stale_or_compute_without_caching()   # bounded wait, never spin forever\n   ```\n   Single-flight by lock; concurrent misses don't all hammer the origin. A plain `DEL` would delete another worker's lock if compute outlived the 5 s expiry.\n6. **Write path.** Update-then-invalidate (`SET origin = new; DEL key`) is simpler than write-through. Know its race: a reader that fetched the old value before the write can re-populate the cache after the `DEL`. Bound it with the TTL, a version in the key\u002Fvalue, or a delayed second `DEL`, depending on how much staleness the data tolerates.\n7. **Hot keys.** A key with > 1% of total RPS is a hot key. Strategies:\n   - Shard the value into multiple keys (`refund:profile:42:shard:{0..9}` round-robin).\n   - Use a local in-process cache in front (Caffeine \u002F lru-cache) for sub-second TTL.\n8. **Big keys.** A single key > 100KB or a single LIST\u002FHASH with > 10k items is a big key. Cluster mode bites on slot rebalances; split.\n9. **Failure modes.**\n   - Cache down → origin slammed. Add a circuit breaker that fails open (skip cache) for a short window.\n   - Origin slow + cache miss → request hangs. Set a *cache-fill timeout* and serve stale.\n10. **Observability.** Hit ratio, miss latency, eviction rate, slow-log entries. Without these, you don't know if the cache is helping or hurting.\n\n## Output\n\n```text\ndesign-cache-layer\n\nEndpoint:   GET \u002Frefund\u002Fprofile\u002F:id\nValue:      RefundProfile (~5KB JSON, computed from 4 SQL queries)\n\nKey schema\n  refund:profile:\u003Cid>:v3                                   primary\n  nx:lock:refund:profile:\u003Cid>:v3   EX=5s, NX               stampede guard\n\nTTL:        300s ± 30s (jitter)\nNegative:   10s for not-found\n\nEviction:   allkeys-lru, maxmemory ~ 8GB.\n\nRead path:\n  GET → on miss, NX-lock → compute → SET EX=jittered → DEL lock.\n\nWrite path:\n  Update SQL → DEL refund:profile:\u003Cid>:v3.\n\nFailure modes covered:\n  ✓ stampede via NX lock\n  ✓ thundering herd via TTL jitter\n  ✓ origin slowness via cache-fill timeout + stale-serve\n  ⚠ hot key: monitor; shard if a single id exceeds 1% RPS\n\nObservability: hit ratio, miss latency p99, eviction rate, slow-log.\n```\n\n## Quality bar\n\n- Key schema versioned for cheap global invalidation.\n- TTL has jitter.\n- Stampede protection in the read path: token-owned lock, compare-and-delete release, bounded waiting.\n- Failure modes named, not assumed.\n\n## Anti-patterns to avoid\n\n- TTL without jitter on a hot key. Synchronized expiry → origin stampede.\n- Write-through caching for everything. Couples writes to cache latency.\n- Forgetting negative caching. 404 floods are real.\n- Using Redis as a primary store without persistence understanding. RDB + AOF have different durability stories.\n","# design-cache-layer\n\n> Cache design that survives Black Friday, not just the demo. Output: key schema, TTL strategy, write\u002Fread path, failure modes considered.\n\n**Mode:** analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked `[TBD]` or `[VERIFY]`, never filled in.\n\n## When to use\n\n- A read-heavy endpoint needs caching.\n- An existing cache is causing incidents (stampedes, hot keys, memory pressure).\n- A PRD says \"use Redis\" with no further detail.\n\n## Inputs\n\n- The cache shape decided by `polymath-performance:caching-tradeoffs` (what, where, invalidation, staleness) — required; without it, run that first.\n- Traffic: request rate, key cardinality, value sizes, hot-key candidates (measured or `[TBD]`).\n- The Redis deployment (optional): managed vs self-hosted, cluster vs single primary, memory limit.\n\n## Related skills\n\n- [`polymath-performance:caching-tradeoffs`](..\u002Fcaching-tradeoffs\u002FSKILL.md)\n  — vendor-agnostic decision: *what* to cache, *where* to cache,\n  staleness tolerance, failure modes. Run that first to decide the\n  shape; use this skill to ship the Redis layer.\n- [`polymath-performance:audit-redis-config`](..\u002Faudit-redis-config\u002FSKILL.md)\n  — once the cache layer is running, review `maxmemory`, eviction,\n  persistence, replication.\n\n## Procedure\n\n1. **Identify the value.** Caching is for *expensive-to-compute, frequently-read, eventually-consistent* values. If the data is cheap to compute or strongly consistent, do not cache.\n2. **Key schema.** Structured + versioned:\n   ```\n   \u003Cdomain>:\u003Centity>:\u003Cid>:v\u003Cversion>      e.g. refund:profile:42:v3\n   \u003Cdomain>:list:\u003Cfilter-hash>:v\u003Cversion> e.g. refund:list:sha8af2:v3\n   ```\n   The `v\u003Cn>` suffix lets a deploy invalidate everything by bumping it; the alternative (deleting keys) is slow on large keyspaces.\n3. **TTL strategy.**\n   - Per-entry TTL with jitter: `TTL = base ± random(0, base\u002F10)`. Prevents synchronized expiry storms.\n   - Sliding TTL only when reads are bursty around a record (re-set on hit).\n   - Negative caching: also cache \"not found\" for a shorter TTL to absorb 404 floods.\n4. **Eviction.** `maxmemory-policy = allkeys-lru` for pure caches; `volatile-lru` if you also store non-cache data with no TTL.\n5. **Read path with stampede protection.**\n   ```\n   value = GET key\n   if value:\n       return value\n   # cache miss\n   token = random_uuid()\n   if SET nx:lock:key token NX EX=5:\n       try:\n           value = expensive_compute()\n           SET key value EX=jittered_ttl\n           return value\n       finally:\n           # release only OUR lock — compare-and-delete in one Lua call\n           EVAL \"if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) end return 0\" 1 nx:lock:key token\n   for attempt in 1..3:                      # someone else is computing\n       sleep(50ms × attempt)\n       value = GET key\n       if value: return value\n   return serve_stale_or_compute_without_caching()   # bounded wait, never spin forever\n   ```\n   Single-flight by lock; concurrent misses don't all hammer the origin. A plain `DEL` would delete another worker's lock if compute outlived the 5 s expiry.\n6. **Write path.** Update-then-invalidate (`SET origin = new; DEL key`) is simpler than write-through. Know its race: a reader that fetched the old value before the write can re-populate the cache after the `DEL`. Bound it with the TTL, a version in the key\u002Fvalue, or a delayed second `DEL`, depending on how much staleness the data tolerates.\n7. **Hot keys.** A key with > 1% of total RPS is a hot key. Strategies:\n   - Shard the value into multiple keys (`refund:profile:42:shard:{0..9}` round-robin).\n   - Use a local in-process cache in front (Caffeine \u002F lru-cache) for sub-second TTL.\n8. **Big keys.** A single key > 100KB or a single LIST\u002FHASH with > 10k items is a big key. Cluster mode bites on slot rebalances; split.\n9. **Failure modes.**\n   - Cache down → origin slammed. Add a circuit breaker that fails open (skip cache) for a short window.\n   - Origin slow + cache miss → request hangs. Set a *cache-fill timeout* and serve stale.\n10. **Observability.** Hit ratio, miss latency, eviction rate, slow-log entries. Without these, you don't know if the cache is helping or hurting.\n\n## Output\n\n```text\ndesign-cache-layer\n\nEndpoint:   GET \u002Frefund\u002Fprofile\u002F:id\nValue:      RefundProfile (~5KB JSON, computed from 4 SQL queries)\n\nKey schema\n  refund:profile:\u003Cid>:v3                                   primary\n  nx:lock:refund:profile:\u003Cid>:v3   EX=5s, NX               stampede guard\n\nTTL:        300s ± 30s (jitter)\nNegative:   10s for not-found\n\nEviction:   allkeys-lru, maxmemory ~ 8GB.\n\nRead path:\n  GET → on miss, NX-lock → compute → SET EX=jittered → DEL lock.\n\nWrite path:\n  Update SQL → DEL refund:profile:\u003Cid>:v3.\n\nFailure modes covered:\n  ✓ stampede via NX lock\n  ✓ thundering herd via TTL jitter\n  ✓ origin slowness via cache-fill timeout + stale-serve\n  ⚠ hot key: monitor; shard if a single id exceeds 1% RPS\n\nObservability: hit ratio, miss latency p99, eviction rate, slow-log.\n```\n\n## Quality bar\n\n- Key schema versioned for cheap global invalidation.\n- TTL has jitter.\n- Stampede protection in the read path: token-owned lock, compare-and-delete release, bounded waiting.\n- Failure modes named, not assumed.\n\n## Anti-patterns to avoid\n\n- TTL without jitter on a hot key. Synchronized expiry → origin stampede.\n- Write-through caching for everything. Couples writes to cache latency.\n- Forgetting negative caching. 404 floods are real.\n- Using Redis as a primary store without persistence understanding. RDB + AOF have different durability stories.\n",{"name":5,"description":7},"main","23f6e21841a39580c9da2b5ec941f39dda17cd86","plugins\u002Fpolymath-performance\u002Fskills\u002Fdesign-cache-layer","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath","https:\u002F\u002Fgithub.com\u002FMohammadBafkar","2026-10-29 18:34:59",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add MohammadBafkar\u002Fpolymath --skill design-cache-layer",{"tool":36,"command":37},"bunx","bunx skills add MohammadBafkar\u002Fpolymath --skill design-cache-layer",{"tool":39,"command":40},"pnpm","pnpm dlx skills add MohammadBafkar\u002Fpolymath --skill design-cache-layer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-performance\u002Fskills\u002Fdesign-cache-layer\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M74GN87EBRHM9N87M7AP1HDD","runbook","Write or refresh an operational runbook for an alert\u002Fsymptom; structured as TL;DR + Pre-checks + Steps + Verification + Rollback + Escalation.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Frunbook\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M74GN5GPKEC1JEKP2DFQNEQJ","rfc","Draft a lightweight design RFC to docs\u002Frfcs\u002F\u003Cslug>.md; Summary, Motivation, Detailed design, Drawbacks, Alternatives, Unresolved questions. A proposal to debate, not a recorded decision (adr).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Frfc\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M74GN2F4CWPMV4X09TG4E304","editorial-pass","Review and tighten prose in a Markdown artifact for a target tone (terse, formal, friendly) without dropping information; preserve quotations and load-bearing constraints.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Feditorial-pass\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M74GMZWGYMZ37C4DYGT6P23G","architecture-review-facilitation","Run an architecture review as a process — entry criteria, reviewer checklist, decision log, and follow-up actions — pairing the design artifact with a red-team pass.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Farchitecture-review-facilitation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M74GMXVX0YX3ETDXS527XDGM","architecture-doc","Write a C4-style architecture document; System Context + Containers (+ Components when interesting) with mermaid diagrams. Describes structure, not a decision (adr) or proposal (rfc).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Farchitecture-doc\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M74GMVG1WSMCK066S3KE6V5K","adr","Write an Architecture Decision Record (Michael Nygard format) to docs\u002Fadrs\u002FNNNN-\u003Cslug>.md; frontmatter validated by the ADR artifact schema. Records a made decision, not a proposal to debate (rfc).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Fadr\u002FSKILL.md",[],[]]