diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 3f2d16c..f5ed7ed 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -391,6 +391,26 @@ ], "formatNotes": "All three. Point the tool at the repository package, entity package, and the service/controller call sites first. Prefer fixing fetch plans and projections over enabling open-in-view. Copilot: apply path-scoped instructions for `**/*Repository.java` and entity packages.", "body": "Task: Review and harden Spring Data JPA queries and fetch plans for the feature I specify. Eliminate N+1 and pagination traps; prefer DTO projections on read paths; keep @Query parameterized and transactional boundaries clear.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / package root: {{PACKAGE_ROOT}} (e.g. com.example.orders)\n- Primary entities: {{ENTITIES}} (comma-separated)\n- Hot endpoints or use cases: {{USE_CASES}} (e.g. list orders, order detail, admin search)\n- Pagination style required: {{PAGINATION}} (Page | Slice | keyset | none)\n- Max page size: {{MAX_PAGE_SIZE}}\n- Open-in-view policy: {{OPEN_IN_VIEW}} (off | on-legacy | unknown)\n- Soft-delete in play: {{SOFT_DELETE}} (yes | no | unknown)\n- DB dialect: {{DB_DIALECT}} (PostgreSQL | MySQL | SQL Server | other)\n- Query-budget test harness available: {{QUERY_BUDGET}} (datasource-proxy | Hibernate statistics | none)\n\nRequirements:\n\n1. Inventory\n - Repositories under {{PACKAGE_ROOT}} touching {{ENTITIES}}\n - FetchType on associations; existing `@EntityGraph`, `JOIN FETCH`, `@BatchSize`\n - Call sites for {{USE_CASES}} (controller \u2192 service \u2192 repository)\n - Any `Pageable` + collection fetch combinations; `findAll` without bounds\n - Native/`@Query` strings; modifying queries; soft-delete filters if {{SOFT_DELETE}}=yes\n\n2. Design\n - Per {{USE_CASES}}: projection vs entity graph vs fetch join vs batch fetch\n - If {{PAGINATION}} needs collections: two-step ID page then fetch-by-ids (never collection JOIN FETCH + Pageable)\n - Cap page size at {{MAX_PAGE_SIZE}}; whitelist sort properties\n - Respect {{OPEN_IN_VIEW}}: if off/unknown, fetch or project inside `@Transactional(readOnly = true)`\n - Index notes for new WHERE/ORDER BY under {{DB_DIALECT}}\n - If {{QUERY_BUDGET}} \u2260 none: add or outline a statement-count assertion for the hottest list path\n\n3. Author artifacts (prefer concrete diffs)\n - Repository method changes (`@EntityGraph`, `@Query`, projections)\n - Service transaction + DTO mapping adjustments\n - Optional Flyway/Liquibase index stub only if filters changed (do not invent unrelated schema)\n - Test sketches: result correctness + query budget when {{QUERY_BUDGET}} allows\n\n4. Verification\n - Explain why N+1 is gone for {{USE_CASES}}\n - Confirm no HHH90003004-style in-memory pagination\n - Grep: no entity returns on public API for list paths; no string-concat query parameters\n - Soft-delete + uniqueness notes if {{SOFT_DELETE}}=yes\n\nConstraints:\n- Do not invent schema or indexes unrelated to {{USE_CASES}}.\n- Minimal diff; match existing repository style (derived vs `@Query`).\n- No enabling open-in-view as a \u201cfix\u201d for LazyInitializationException.\n- Optimize for GitHub Copilot, Claude Code, and Codex \u2014 concrete Java and checklists.\n\nOutput format:\n1. Plan (fetch strategy per use case)\n2. Code diffs (repository/service/DTO)\n3. Index / migration notes (if any)\n4. Verification checklist + query-budget evidence\n5. Residual risks (cartesian joins, soft-delete, count query cost)\n\nStart from repositories and entities under {{PACKAGE_ROOT}}. Prefer projections and explicit fetch plans over EAGER mappings or open-in-view.\n" + }, + { + "id": "wire-spring-cache-redis", + "title": "Wire Spring Cache With Redis", + "whenToUse": "Scaffold or harden Redis-backed Spring Cache for a named service/module with concrete TTLs, serializers, and eviction.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "spring-boot", + "redis", + "cache", + "performance", + "azure" + ], + "formatNotes": "All three. Point the tool at the cache configuration package and the service methods to annotate. Prefer RedisCacheManagerBuilderCustomizer over an ad-hoc CacheManager bean that disables Boot's spring.cache.redis.* properties. Copilot: apply path-scoped instructions to cache config and @Cache* call sites. Claude Code: skill plus the config class. Codex: AGENTS.md cache section or docs/agents/spring-boot-cache-redis.md, then the diff.", + "body": "Task: Wire or harden Spring Cache backed by Redis for the module I specify. Produce a small diff: explicit Redis cache type, per-cache TTLs, a safe serializer, namespaced keys, targeted eviction, and tests that match the repo.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Module / package: {{MODULE}}\n- Cache names: {{CACHE_NAMES}}\n- TTL per cache name: {{TTLS}} (for example catalog=10m, productById=5m)\n- Serializer: {{SERIALIZER}} (jackson-per-type | generic-jackson-allowlist | keep-existing)\n- Redis target: {{REDIS_TARGET}} (local | Azure Cache for Redis)\n- Fail mode: {{FAIL_MODE}} (fail-open | fail-closed)\n- Test style: {{TEST_STYLE}} (unit-noop | testcontainers | both)\n\nRequirements:\n\n1. Inventory\n - Starters present (`spring-boot-starter-cache`, `spring-boot-starter-data-redis`) and `spring.cache.type`\n - Where `@EnableCaching` lives (application class vs isolated `@Configuration`)\n - Existing `CacheManager`, `RedisCacheConfiguration`, or `RedisCacheManagerBuilderCustomizer` beans\n - `spring.cache.redis.*` and `spring.data.redis.*` (TTL, nulls, prefix, timeout, SSL, pool)\n - `@Cacheable` / `@CacheEvict` / `@CachePut` in {{MODULE}}: keys, `allEntries`, `unless`, `condition`, `sync`\n - How tests get a cache today (sliced context, embedded, shared host, none)\n - If {{REDIS_TARGET}} is Azure Cache for Redis: TLS, auth style already in repo (access key vs Entra), private endpoint or firewall notes. Do not read secret values.\n\n2. Design\n - `spring.cache.type=redis`. Move `@EnableCaching` onto an isolated `@Configuration` if it sits on the application class.\n - Global TTL floor plus per-cache TTL from {{TTLS}} via `RedisCacheManagerBuilderCustomizer`, derived from Boot's `RedisCacheConfiguration`. Do not add a `CacheManager` bean that drops Boot properties.\n - {{SERIALIZER}}: typed Jackson per cache when each name has one value class; generic Jackson only with an allowlisted polymorphic validator. String key serializer. Keep JDK serialization only when {{SERIALIZER}}=keep-existing, and say so.\n - Key prefix: application, environment, schema version. `use-key-prefix` stays true. SpEL keys stable and identical on read and evict. No secrets or PII in keys or values.\n - Evict with the same key. No `allEntries=true` unless the keyspace is tiny and the PR says why. Otherwise version the prefix or a SCAN-based writer.\n - Null policy: `unless` / `condition` or a short null TTL. Disabling null caching requires `unless` so ordinary null returns do not throw.\n - {{FAIL_MODE}}: fail-closed keeps the default error handler (Redis errors fail the call). Fail-open swallows cache-get errors only, logs them, and still runs the method. Do not swallow evict errors for data that must not stay stale.\n - {{REDIS_TARGET}}=Azure Cache for Redis: TLS on, password or Entra token from env / existing Key Vault reference, no public-network shortcut. {{REDIS_TARGET}}=local: localhost or Testcontainers only.\n\n3. Author config, annotations, and tests\n - Property and `RedisCacheManagerBuilderCustomizer` changes for {{CACHE_NAMES}}\n - Annotations on the service methods that own {{CACHE_NAMES}}, matching existing style\n - {{TEST_STYLE}}=unit-noop: `@AutoConfigureCache` or `spring.cache.type=none` on slices; no Redis socket\n - {{TEST_STYLE}}=testcontainers or both: pinned Redis image, hit, miss, and evict for the hottest cache\n - No new dependency unless the module cannot compile without it\n\n4. Verification checklist\n - [ ] `spring.cache.type=redis`; `@EnableCaching` not on the application class\n - [ ] Each name in {{CACHE_NAMES}} has the TTL from {{TTLS}}\n - [ ] Boot `spring.cache.redis.*` still apply (customizer, not a replacement manager)\n - [ ] Serializer matches {{SERIALIZER}}; prefix is namespaced; keys match on read and evict\n - [ ] No `allEntries=true` on a large keyspace; null policy cannot throw on a normal null\n - [ ] {{FAIL_MODE}} is implemented in `CacheErrorHandler` or explicitly left at the default\n - [ ] Tests match {{TEST_STYLE}} and do not point at Azure or a shared server\n - [ ] Diff contains no access keys, connection strings, or invented secret names\n - [ ] Run the module's existing test command and show the result\n\nConstraints:\n- Minimal diff. Match project style (annotations, property files, test base classes).\n- No secrets in the repo. Use placeholders or the app's existing secret mechanism.\n- Do not enable `spring.jpa.open-in-view` or any unrelated feature (security, actuator exposure, schema changes).\n- Do not call `FLUSHDB` / `FLUSHALL`. Do not disable key prefixes.\n- Optimize for GitHub Copilot, Claude Code, and Codex: concrete paths and checklists.\n\nOutput format:\n1. Plan (TTL map, serializer, prefix, fail mode, eviction)\n2. Diff (config, annotations, tests)\n3. Verification checklist with what you actually ran\n4. Residual risks (stampede across pods, transaction-aware gap, Azure memory policy)\n\nStart from {{MODULE}}. Prefer `RedisCacheManagerBuilderCustomizer` over a hand-built `CacheManager`.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index cd1a91b..7ca38a5 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -389,6 +389,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-data-jpa-query.instructions.md` with applyTo for `**/repository/**/*.java`, `**/entity/**/*.java`, `**/*Repository.java`, and persistence YAML. Claude Code: `.claude/skills/spring-data-jpa-query-guardrails/SKILL.md` plus a one-line CLAUDE.md fact on lazy-by-default and no collection fetch+Pageable. Codex: `AGENTS.md` persistence section or linked `docs/agents/spring-data-jpa.md`.", "body": "# Skill: Spring Data JPA Query Guardrails\n\n## Goal\nShip Spring Data JPA access that is correct, lean, and predictable under production data volumes — no accidental N+1, no in-memory pagination traps, no entity leakage at API boundaries, and query plans that match indexes and use cases.\n\n## When to apply\n- New or changed `JpaRepository` / `@Query` / Specifications / Criteria\n- Entity mapping changes (`@OneToMany`, `@ManyToOne`, embeddables, soft-delete filters)\n- List/detail REST or batch jobs that traverse associations\n- Reviews mentioning slow endpoints, high DB CPU, `HHH90003004`, LazyInitializationException, or cartesian explosions\n- Migrations that add columns/indexes used by hot queries (pair with Flyway guardrails when schema changes)\n\n## Baseline rules\n1. **Associations lazy by default.** Map `@ManyToOne` / `@OneToOne` / collections as `FetchType.LAZY`. Override EAGER defaults explicitly. Opt into loading per use case with fetch joins, `@EntityGraph`, or batch fetch — never by leaving EAGER on the mapping.\n2. **Kill N+1 deliberately.** Prefer `@EntityGraph(attributePaths = …)` or JPQL `JOIN FETCH` for associations you always need on that path. For list views with collections, prefer `@BatchSize` / `hibernate.default_batch_fetch_size` or a two-step ID query over silent per-row selects. Assert a query budget in tests (statement count or datasource proxy) for hot paths.\n3. **Never combine collection `JOIN FETCH` with `Pageable`.** Hibernate warns (`HHH90003004`) and paginates in memory. Use: (a) page entity IDs first, then `JOIN FETCH` / entity graph for those IDs; or (b) `@EntityGraph` / batch fetch without collection fetch join on the paged query; or (c) DTO projection that does not inflate rows.\n4. **Projections for reads.** Closed interface or class-based DTO projections (constructor expressions / `@SqlResultSetMapping` when needed) for list and report endpoints. Do not return managed entities (or open SpEL projections that force full entity load) from public APIs.\n5. **`@Query` safety.** Prefer parameterized JPQL/SQL (`:name` / `?1`) — never string-concatenated user input. For modifying queries use `@Modifying(clearAutomatically = true, flushAutomatically = true)` and call from a transactional service. Document native SQL dialect assumptions. Avoid `SELECT *` entity natives that skip the persistence context contract unless reviewed.\n6. **Transactional boundaries.** Read paths: `@Transactional(readOnly = true)` on the service method that owns the session through mapping. Do not touch lazy collections in controllers after the session closes — map to DTOs inside the transaction or use Open-in-view only if the project already standardizes it (prefer off + explicit fetch). Write paths: one clear transactional service method; no repository calls from controllers that start implicit transactions inconsistently.\n7. **Pagination contracts.** Always pass `Pageable` (or keyset/`Slice` when appropriate) for unbounded lists. Cap `size` at the API layer. Prefer `Slice` when total count is expensive and not required. Sort only on whitelisted properties.\n8. **Indexing and explain awareness.** For every new filter/sort/join used in production paths, confirm a supporting index exists or is added in the same change set. Mentally (or via `EXPLAIN`) check selectivity; avoid leading-wildcard `LIKE` and functions on indexed columns in hot queries.\n9. **Soft-delete and filters.** If using `@SQLRestriction` / `@Where` / `@SoftDelete`, ensure count queries, unique constraints, and admin “include deleted” paths are intentional. Soft-delete + unique natural keys need partial unique indexes or equivalent.\n10. **Batching writes.** For bulk inserts/updates, enable JDBC batching (`hibernate.jdbc.batch_size`, order inserts/updates) and avoid flush-per-entity loops. Prefer set-based `@Modifying` queries for mass updates when entity lifecycle listeners are not required.\n11. **One collection fetch at a time.** Fetching two bag collections in one query causes cartesian products. Split queries or use batch fetch for the second collection.\n12. **Equals/hashCode discipline.** Do not use mutable fields or lazy associations in `equals`/`hashCode` for entities; prefer business keys carefully or ID-after-persist patterns already used in-repo.\n\n## Workflow\n1. Inventory repositories, entity graphs, and call sites for the feature (list vs detail vs write).\n2. Decide fetch strategy per use case: projection vs entity graph vs fetch join vs batch size.\n3. Author or adjust repository methods; keep derived query names honest; add `@EntityGraph` / `@Query` only when needed.\n4. Ensure service transaction + DTO mapping; no entity JSON serialization of lazy graphs.\n5. Add/adjust indexes with schema migration if filters changed.\n6. Add characterization or slice tests: correct results + query-count ceiling on the hot path.\n7. PR notes: fetch strategy, pagination approach, index changes, residual N+1 risk.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-data-jpa-query.instructions.md` with `applyTo` for repositories, entities, and persistence config.\n- Always-on: lazy associations; no collection JOIN FETCH + Pageable; DTOs at API boundary.\n- Extend existing repository patterns; do not introduce a second persistence style without cause.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-data-jpa-query-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"JPA associations are LAZY; list endpoints use projections or two-step ID fetch — never collection fetch join with Pageable.\"\n- Before claiming done, show SQL (log or test) and confirm query count for the list path.\n\n### Codex\n- `AGENTS.md` persistence section: N+1 rules, pagination trap, projection preference, `@Query` parameterization.\n- Link to this skill when root AGENTS.md would bloat.\n\n## Anti-patterns\n- `FetchType.EAGER` on `@ManyToOne` “for convenience”\n- Collection `JOIN FETCH` + `Pageable` on the same repository method\n- Returning JPA entities from REST controllers (especially with open-in-view papering over LazyInitializationException)\n- Open SpEL interface projections that load full entities\n- String-concatenated native SQL or JPQL from request parameters\n- `findAll()` without pagination on user-facing APIs\n- Touching lazy collections in `@Async` / event listeners after the session ended\n- Dual bag `JOIN FETCH` in one query (cartesian blow-up)\n- Relying on `spring.jpa.open-in-view=true` as the fetch strategy\n- Missing indexes for new WHERE/ORDER BY on hot paths\n- Soft-delete filters that break unique constraints or admin undelete without a plan\n\n## Verification checklist\n- [ ] Associations are LAZY unless a documented exception exists\n- [ ] Hot list path has no N+1 (query budget test or logged SQL review)\n- [ ] No collection fetch join combined with Pageable\n- [ ] API responses use DTOs/projections, not raw entities\n- [ ] All `@Query` / native SQL uses bind parameters\n- [ ] Read service methods are `readOnly` transactional where appropriate\n- [ ] Page/Slice size capped; sorts whitelisted\n- [ ] Indexes cover new filter/sort columns (migration linked)\n- [ ] Soft-delete behavior verified for counts and uniqueness\n- [ ] Bulk paths use batching or set-based updates when applicable\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-data-jpa-query-guardrails\ndescription: Use when designing or reviewing Spring Data JPA repositories and entity fetch plans — N+1, entity graphs vs fetch joins, pagination traps, DTO projections, @Query safety, transactions, indexing.\n---\n\nFollow Spring Data JPA Query Guardrails: LAZY associations, deliberate fetch plans, no collection JOIN FETCH with Pageable, DTOs at the API boundary, parameterized queries, verify SQL and query counts on hot paths.\n```\n" + }, + { + "id": "spring-boot-cache-redis-guardrails", + "title": "Spring Boot Cache Redis Guardrails", + "whenToUse": "Designing, reviewing, or hardening Spring Cache with Redis (or Azure Cache for Redis) — TTL, serializers, key prefixes, eviction, stampede, multi-instance correctness.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "spring-boot", + "redis", + "cache", + "performance", + "azure" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-boot-cache-redis.instructions.md` with applyTo for cache `@Configuration`, `application*.{yml,yaml,properties}`, and types that use `@Cacheable`, `@CacheEvict`, or `@CachePut`. Claude Code: `.claude/skills/spring-boot-cache-redis-guardrails/SKILL.md` plus a one-line CLAUDE.md fact that Redis cache entries always have a TTL and `@EnableCaching` stays off the application class. Codex: a cache section in root `AGENTS.md` or linked `docs/agents/spring-boot-cache-redis.md`.", + "body": "# Skill: Spring Boot Cache Redis Guardrails\n\n## Goal\nShip Spring Cache on Redis (including Azure Cache for Redis) that expires on purpose, serializes safely, isolates keys per app and environment, and stays correct when more than one pod is running.\n\n## When to apply\n- Enabling `spring-boot-starter-cache` with Redis, or reviewing an existing `CacheManager`\n- Adding or changing `@Cacheable`, `@CacheEvict`, or `@CachePut`\n- Incidents with stale data, unbounded Redis memory, stampedes, or cross-pod inconsistency\n- Moving a local or container Redis onto Azure Cache for Redis\n- Hardening serializers, key names, or bulk eviction before production\n\n## Baseline rules\n1. **Select Redis explicitly and keep caching off slice tests.** Depend on `spring-boot-starter-cache` and `spring-boot-starter-data-redis` (Lettuce unless the build already chose Jedis). Set `spring.cache.type=redis`. Do not assume \"Redis on the classpath\" picks the right manager when another provider is present. Put `@EnableCaching` on a dedicated `@Configuration` (for example `RedisCacheConfig`), not on `@SpringBootApplication`. `@WebMvcTest` and `@DataJpaTest` load the application class; they do not component-scan an arbitrary `@Configuration`. Leaving `@EnableCaching` on the application class pulls cache advice and a connection into slices that should stay light.\n2. **Every cache has a TTL.** `RedisCacheConfiguration` defaults to `Duration.ZERO`, which means entries never expire. That grows memory without bound and, on a server policy of `noeviction`, turns a full cache into write errors. Set a global floor with `spring.cache.redis.time-to-live`. Prefer per-cache TTL through a `RedisCacheManagerBuilderCustomizer` that calls `withCacheConfiguration` and `entryTtl`. Start from the auto-configured `RedisCacheConfiguration` bean so prefix, null policy, and serializer stay intact. Do not replace `CacheManager` with a hand-built bean, and do not declare your own `RedisCacheConfiguration` `@Bean`, unless you re-apply `CacheProperties` yourself. Both bypasses drop Boot's `spring.cache.redis.*` binding (`@ConditionalOnMissingBean`).\n3. **JSON values, string keys, explicit types.** Boot's default value serializer is JDK serialization: opaque bytes, brittle across class moves, and awkward to inspect. Prefer a typed `Jackson2JsonRedisSerializer` when a cache stores one concrete DTO. Use `GenericJackson2JsonRedisSerializer` only with an `ObjectMapper` whose polymorphic validator allowlists those DTOs. Permissive default typing (`@class` plus a laissez-faire subtype validator) is a deserialization risk if anything besides this app can write the keyspace. Document the allowlist. Serialize keys with a string serializer so prefixes and ids stay readable. Do not cache JPA entities, credentials, or types outside the allowlist.\n4. **Prefix and namespace every key.** Leave `spring.cache.redis.use-key-prefix=true` (the default). Turning it off lets two cache names share one Redis key. Set `spring.cache.redis.key-prefix` to application name, environment, and a schema version (`orders:prod:v3:`). Shared Azure instances must not mix apps or environments. Use stable SpEL (`key = \"#id\"`) that you repeat on evict and put. The default key generator hashes every argument, so `Pageable`, principals, and `toString()` of entities become huge or sensitive keys. Never put secrets, tokens, passwords, emails, national ids, or other raw PII in keys or values. Keys show up in `SCAN`, slow logs, and Azure diagnostics.\n5. **Evict one key. Do not `KEYS` the instance.** Prefer `@CacheEvict` / `@CachePut` with the same key the read path uses. `allEntries = true` and `Cache.clear()` walk the keyspace. `RedisCacheManager.builder(connectionFactory)` uses a non-locking writer whose batch strategy is `KEYS` in current Spring Data Redis. `KEYS` is blocking and is a poor fit for a large Azure keyspace. For a real bulk drop, either configure `RedisCacheWriter` with `BatchStrategies.scan(batchSize)` (still expensive, non-atomic, per node on cluster) or bump the version segment of the key prefix and let TTL reap the old generation. Do not call `FLUSHDB` or `FLUSHALL` from application code.\n6. **Decide nulls, then decide stampede.** Default `spring.cache.redis.cache-null-values=true` stores nulls for the full TTL (forever, if TTL was left at zero). Pick one policy: `unless = \"#result == null\"` and disable null caching, or a dedicated short-TTL cache for negative lookups. `disableCachingNullValues()` without `unless` throws when a method returns null, because the cache still attempts the put. `condition` runs before invocation (skip lookup and store). `unless` runs after (the method always runs; the result might not be stored), so it does not stop a stampede. `@Cacheable(sync = true)` locks inside one JVM only. Boot's writer is non-locking, so it is not cross-pod single-flight. If you add a Redis lock, document the lock key, the lock TTL, and the outcome when the holder dies (callers fall through to the database, or they fail).\n7. **Write the system of record, then the cache.** Keep the default `beforeInvocation = false` so evict/put runs after a successful method. Evicting first lets a concurrent reader reload the pre-write row and pin it until TTL. `transactionAware()` on the manager builder defers put/evict until after commit. Boot does not enable it. Turn it on only when a rolled-back transaction must not change the cache. Same-transaction reads will not see the deferred write, and a crash after commit but before the sync leaves stale data until TTL. Assume every pod shares one Redis. A process-local cache (Caffeine) is not coherent across pods. Do not add a near cache unless invalidation is designed and tested. `sync = true` does not coordinate pods.\n8. **Choose fail-open or fail-closed on purpose.** Set `spring.data.redis.timeout` below the caller's timeout so a stuck command does not pin the worker pool. Lettuce pooling needs `commons-pool2` and `spring.data.redis.lettuce.pool.*` (including `max-wait`); an unbounded wait hides the outage. The default `SimpleCacheErrorHandler` rethrows, so a Redis miss-path error fails the request even when the database could answer. That is fail-closed. For fail-open reads, a `CacheErrorHandler` that logs `handleCacheGetError` and does not rethrow lets the interceptor run the method. Swallowing put/evict errors hides a failed invalidation until TTL. Read-mostly catalogs can fail open. Authorization and idempotency keys should fail closed. When Actuator is on the classpath, Redis health is available; do not publish health details on the public port. Use a remote cache when pods must observe the same eviction. Use a local cache when per-pod staleness is acceptable and a Redis outage must not matter.\n9. **Test without a live Redis, then test the hot path with one.** Unit and slice tests should not open a socket. With `@EnableCaching` isolated, `@WebMvcTest` does not cache. Where a slice needs the abstraction, use `@AutoConfigureCache` or `spring.cache.type=none` and assert outcomes, not Redis bytes. For integration of hit, miss, eviction, and null policy, use Testcontainers with a pinned image (for example `redis:7-alpine`), `@ServiceConnection` on Boot 3.1+, or dynamic host/port properties. Do not point CI at Azure or a shared dev cache. Include a round-trip that fails if values come back as JDK payload when JSON was required.\n10. **Azure Cache for Redis is still Redis, plus network and identity.** Enable TLS (`spring.data.redis.ssl.enabled=true`) and use the instance hostname and TLS port (commonly 6380 when non-TLS is disabled). Prefer Microsoft Entra authentication where that tier and the client stack already in the repo support short-lived data-plane tokens. Otherwise set `spring.data.redis.password` from the environment or the app's existing Key Vault reference. Never commit access keys, connection strings, or primary/secondary secrets, and do not invent secret names or resource ids. Restrict the network with the firewall or a private endpoint and private DNS; laptops use local Redis or an approved tunnel, not the production key on a public endpoint. Application TTLs still matter if the server policy is `noeviction`. Use cluster configuration only when the instance is clustered, and do not assume a multi-key command spans prefixes.\n\n## Tool placement\n- **GitHub Copilot:** path-scoped `.github/instructions/spring-boot-cache-redis.instructions.md` with `applyTo` covering the cache configuration class, `application*.{yml,yaml,properties}`, and files that declare `@Cacheable`, `@CacheEvict`, or `@CachePut`. Keep one always-on line in `.github/copilot-instructions.md`: Redis caches have a TTL, JSON values, a namespaced prefix, and no `allEntries=true` on large keyspaces.\n- **Claude Code:** procedure in `.claude/skills/spring-boot-cache-redis-guardrails/SKILL.md`. One CLAUDE.md fact: \"Spring Cache on Redis always sets a TTL via RedisCacheManagerBuilderCustomizer; @EnableCaching lives on an isolated @Configuration, not the application class.\"\n- **Codex:** a short cache section in root `AGENTS.md`, or `docs/agents/spring-boot-cache-redis.md` linked from it when the root file would grow. State TTL, serializer, prefix, eviction, and fail-open versus fail-closed.\n\n## Anti-patterns\n- `@EnableCaching` on `@SpringBootApplication`, so every slice test opens Redis\n- Leaving TTL unset and treating \"it works on my laptop\" as production-safe\n- A custom `CacheManager` or `RedisCacheConfiguration` bean that silently ignores `spring.cache.redis.*`\n- JDK-serialized values, or JSON with permissive `@class` typing on a shared cache\n- `use-key-prefix=false`, or one prefix shared by dev and prod\n- SpEL built from `toString()`, tokens, or PII\n- `@CacheEvict(allEntries = true)` as a routine invalidation on Azure-sized keyspaces\n- `disableCachingNullValues()` without `unless`, so legitimate null returns throw\n- Believing `sync = true` is a cluster-wide single-flight\n- Evicting before the database write, or assuming transaction-aware cache is on by default\n- A Caffeine near cache with no invalidation story in a multi-pod deployment\n- Fail-open put/evict on data that must not stay stale past the method return\n- CI tests aimed at a shared Redis or at Azure\n- Access keys, connection strings, or firewall exceptions committed \"just for local\"\n\n## Verification\n- [ ] `spring.cache.type=redis` and both starters are present; `@EnableCaching` is not on the application class\n- [ ] Global TTL is set, and each hot cache has an explicit TTL from `RedisCacheManagerBuilderCustomizer` derived from Boot's configuration\n- [ ] No replacement `CacheManager` / `RedisCacheConfiguration` bean drops Boot properties\n- [ ] Values are JSON with a documented type allowlist; keys are strings; prefix includes app, environment, and schema version\n- [ ] Read and evict SpEL keys match; keys and values contain no secrets or PII\n- [ ] Bulk clear is scan-based or version-bumped; `allEntries=true` is absent on large caches\n- [ ] Null policy is explicit (`unless` / `condition` / short null TTL) and does not throw on ordinary nulls\n- [ ] Cross-pod single-flight, if any, documents lock TTL and the failure mode; `sync=true` is not described as cluster-wide\n- [ ] Write-then-evict order is intact; `transactionAware` is set only if the PR explains it\n- [ ] Command timeout, pool wait, and `CacheErrorHandler` match the chosen fail-open or fail-closed mode\n- [ ] Slice tests do not need Redis; hot-path integration uses a pinned Testcontainers image\n- [ ] Azure notes name TLS, auth source (Entra or access key via env/Key Vault), and private network, with no secrets in the diff\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-cache-redis-guardrails\ndescription: Use when designing or reviewing Spring Cache on Redis or Azure Cache for Redis — TTL via RedisCacheManagerBuilderCustomizer, JSON serializers, key prefixes, eviction, stampede, and multi-pod correctness.\n---\n\nFollow Spring Boot Cache Redis Guardrails: explicit redis cache type, @EnableCaching on an isolated configuration, TTL on every cache, JSON values, namespaced prefixes, targeted eviction, and a documented fail-open or fail-closed policy.\n```\n" } ] }