diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 5845f51..57afd35 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -699,6 +699,26 @@ ], "formatNotes": "All three. Point the tool at the build file, `application.yml`/`application.properties` (`spring.http.client.*` or `spring.http.clients.*`, `spring.ssl.bundle.*`, `resilience4j.*`), every client configuration class, and the services that call them. Copilot: spring-http-clients path instructions plus those files in agent mode. Claude Code: the spring-boot-http-client-guardrails skill plus the client and config files. Codex: AGENTS.md outbound HTTP clients section, then the diff.", "body": "Task: Harden the outbound HTTP clients in the Spring Boot service I specify. Every call should have bounded timeouts that fit the caller's budget, deliberate connection pools, idempotent-only retries in exactly one layer, a circuit breaker per downstream, typed error handling, and auth/TLS wired through Spring Security and SSL bundles. Finish with a minimal diff I can open as a PR, plus failure-path tests.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- Spring Boot version: {{BOOT_VERSION}} (e.g. 3.4, 3.5, 4.0 | unknown)\n- Client style: {{CLIENT_STYLE}} (RestClient | WebClient | RestTemplate | @HttpExchange interfaces | mixed)\n- Downstreams in scope: {{DOWNSTREAMS}} (name → base URL property, e.g. orders → app.clients.orders.base-url; external | svc.cluster.local)\n- Downstream latency: {{DOWNSTREAM_P99}} (name → p99, or unknown)\n- Caller budget: {{CALLER_TIMEOUT}} (inbound request timeout and ingress/gateway timeout, e.g. 5s / 30s)\n- Expected concurrency: {{CONCURRENCY}} (peak in-flight calls per pod per downstream)\n- Auth per downstream: {{AUTH}} (none | OAuth2 client credentials | Entra workload identity | API key | mTLS)\n- Retry layers today: {{RETRY_TODAY}} (none | Resilience4j | Spring Retry | library | service mesh | several)\n- Virtual threads: {{VIRTUAL_THREADS}} (on | off)\n- Pain points: {{PAIN}} (hung requests | pool exhaustion | retry storm | latency cascade | 5xx during deploys | metric cardinality | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file (which of Apache HttpClient 5, Jetty, Reactor Netty is on the classpath) and `application*.yml|properties` (`spring.http.client.*`, `spring.http.reactiveclient.*`, `spring.http.clients.*`, `spring.ssl.bundle.*`, `resilience4j.*`)\n - Find every outbound client: `RestClient`, `WebClient`, `RestTemplate`, `@HttpExchange` / `@ImportHttpServices`, Feign, raw `HttpClient`. Record per client: built from injected builder or `new`, request factory, connect/read/pool-wait timeouts, pool limits, retry and circuit breaker config, auth mechanism, SSL config, redirect policy, error handling, and base URL source\n - Flag direct `new RestTemplate()`, `RestClient.create()`, `WebClient.create()`, and string-concatenated URIs\n\n2. Findings (rank by risk: missing timeouts or unbounded pool waits > retries on non-idempotent calls or nested retry layers > budget overruns vs {{CALLER_TIMEOUT}} > trust-all TLS, secrets in URLs or logs > undersized or never-evicted pools > missing circuit breakers > error handling and body-size gaps > observability and cardinality > hygiene)\n - Clients with no connect or read timeout, or relying on `SimpleClientHttpRequestFactory` defaults\n - Worst-case (attempts × read timeout + backoff) above {{CALLER_TIMEOUT}}\n - `POST`/`PATCH` retried without an idempotency key; 4xx retried; retries in more than one layer per {{RETRY_TODAY}}\n - Pool per-route limit below {{CONCURRENCY}}, no connection-request timeout, no idle eviction or TTL under the load balancer / Azure SNAT idle timeout\n - Trust-all `TrustManager` or `HostnameVerifier`, tokens in query strings, `Authorization` forwarded across redirects or blindly copied from inbound requests\n - Full bodies or tokens logged; `http.client.requests` tagged with raw URIs\n - Responses not consumed or closed, or unbounded in-memory bodies\n\n3. Fix\n - One configuration per downstream in {{DOWNSTREAMS}} (or an HTTP service client group on Boot 4) built from the injected `RestClient.Builder` / `WebClient.Builder` / `RestTemplateBuilder`, with the base URL from properties\n - Set the factory explicitly for {{BOOT_VERSION}}: `spring.http.client.factory` (3.4/3.5) or `spring.http.clients.imperative.factory` (4.0); never `simple` in production\n - Timeouts per downstream from {{DOWNSTREAM_P99}}: connect 1 to 3s, read = p99 + headroom, pool wait bounded, overall deadline that fits {{CALLER_TIMEOUT}}. Globals via `spring.http.client.*` / `spring.http.clients.*`, overrides via `ClientHttpRequestFactorySettings` / `HttpClientSettings`\n - Pools: Apache HttpClient 5 max total and per route from {{CONCURRENCY}}, idle eviction, TTL; or a named Reactor Netty `ConnectionProvider` with `maxConnections`, `pendingAcquireTimeout`, `maxIdleTime`, `evictInBackground`\n - Retries in one layer only: idempotent methods (or POST with an idempotency key), on connect errors, 502/503/504, and 429 honouring `Retry-After`; exponential backoff with jitter, 2 to 3 attempts; remove the other layers\n - Resilience4j circuit breaker and bulkhead per downstream with explicit, honest fallbacks\n - `.retrieve()` with `onStatus` / `defaultStatusHandler` mapping to typed exceptions carrying downstream name and status; cap body size; release every response\n - Auth per {{AUTH}}: `OAuth2ClientHttpRequestInterceptor` (RestClient) or `ServerOAuth2AuthorizedClientExchangeFilterFunction` (WebClient) for client credentials; workload identity for Azure; API keys from secrets in headers, never URLs\n - TLS via `spring.ssl.bundle.*` referenced from client settings; delete any trust-all code\n - `redirects=dont-follow` unless a downstream needs redirects; allow-list forwarded headers (correlation ID, tenant) and rely on Micrometer Tracing for `traceparent`\n - Metrics: URI templates via `uri(\"/path/{id}\", id)`, client name tag, pool metrics exported; note alerts for p99, error rate, pool pending, open circuit\n - If {{VIRTUAL_THREADS}} = on, keep pool limits and bulkheads and note any `synchronized` I/O sections\n\n4. Tests\n - WireMock (or `MockRestServiceServer` for RestClient/RestTemplate) per downstream:\n - Slow response → read timeout fires within budget\n - Connection refused → fails fast, no long hang\n - 503 then 200 → retried and succeeds; total time within budget\n - 400 → no retry, typed exception\n - 429 with `Retry-After` → waits as instructed, or fails if it exceeds the budget\n - Repeated failures → circuit opens and short-circuits\n - Oversized body → rejected without exhausting memory\n - Use Awaitility or virtual time, no fixed sleeps\n\n5. Verification\n - Budget table: downstream | p99 | connect | read | attempts | backoff | worst case | caller timeout | fits?\n - Pool table: downstream | library | max total | per route | pool wait | idle eviction | TTL\n - Retry ownership table: downstream | layer that retries | methods retried | statuses retried\n - Confirmation that no trust-all TLS, secrets in URLs, raw-URI metric tags, or body logging remain\n\nConstraints:\n- Minimal diff. Keep the existing client style unless it can't meet the rules; don't swap HTTP libraries without saying why.\n- Don't invent base URLs, credentials, latencies, or timeouts. Use placeholders and state assumptions.\n- Don't add a second resilience library or a second retry layer.\n- Optimize for GitHub Copilot, Claude Code, and Codex: give concrete diffs and a checklist.\n- Leave alert rules and mesh retry policy changes as follow-up notes unless the repo already manages them.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (properties + per-downstream client config + pool/factory settings + retry/circuit config + auth/SSL wiring + error mapping)\n3. Tests added and their results\n4. Budget, pool, and retry ownership tables, plus follow-ups (alerts, mesh policy, Boot 4 property migration)\n\nStart from {{APP_PATH}}. Fix missing timeouts and unsafe retries before tuning pools or metrics.\n" + }, + { + "id": "enable-spring-virtual-threads-safely", + "title": "Enable Spring Virtual Threads Safely", + "whenToUse": "Decide whether a Spring Boot service should run on Java virtual threads and, if so, enable them safely: JDK verdict, executor inventory, pool sizes and acquire timeouts from downstream capacity, semaphores or bulkheads per fragile downstream, virtual-thread-per-task executors with CPU work kept on platform threads, context propagation across @Async, pinning fixes only where they matter, and an off-versus-on load-test plan with a minimal diff.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "virtual-threads", + "spring-boot", + "concurrency", + "performance", + "jdk25" + ], + "formatNotes": "All three. Point the tool at the build file, Dockerfile or base image (runtime JDK), `application.yml`/`application.properties` (`spring.threads.virtual.enabled`, `server.tomcat.threads.*`, `spring.datasource.hikari.*`, `spring.task.*`), every executor and async configuration class, and the HTTP client config. Copilot: java-virtual-threads path instructions plus those files in agent mode. Claude Code: the java-virtual-threads-spring-guardrails skill plus the config files. Codex: AGENTS.md concurrency section, then the diff.", + "body": "Task: Decide whether the Spring Boot service I specify should run on Java virtual threads, and if so, enable them safely. Replace the old thread-pool ceiling with explicit limits on every finite resource, keep request context working across async hops, fix only the pinning that matters on our JDK, and finish with a minimal diff plus a load-test plan that compares off and on.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- JDK version (build and runtime image): {{JDK_VERSION}} (21 | 24 | 25 | other)\n- Spring Boot version: {{BOOT_VERSION}} (e.g. 3.4, 3.5, 4.0, 4.1)\n- Web stack: {{STACK}} (Spring MVC servlet | WebFlux | both)\n- Finite resources: {{POOLS}} (e.g. Hikari 10, Apache HttpClient 20 per route, Redis Lettuce, Kafka producer)\n- Downstream limits: {{DOWNSTREAM_LIMITS}} (name → max concurrency or rate limit, or unknown)\n- Custom executors: {{EXECUTORS}} (bean names and purpose, or \"find them\")\n- Context that must propagate: {{CONTEXT}} (SecurityContext | MDC correlation ID | trace | tenant)\n- Current symptom: {{SYMPTOM}} (thread exhaustion | high latency under load | pool pending spikes after enabling | none, evaluating)\n- Load-test tool and target: {{LOAD_TEST}} (Gatling | k6 | JMeter | none yet; target RPS and p99)\n\nRequirements:\n\n1. Inventory\n - Read the build file, Dockerfile or base image (actual runtime JDK), and `application*.yml|properties` (`spring.threads.virtual.enabled`, `server.tomcat.threads.*`, `spring.datasource.hikari.*`, HTTP client pool settings, `spring.task.*`)\n - List every executor: auto-configured (`applicationTaskExecutor`, task scheduler, listener containers) and custom `TaskExecutor` / `ExecutorService` beans, with what runs on each and whether it is I/O or CPU bound\n - List every finite pool with size and acquire timeout, every `ThreadLocal` use, and every `synchronized` block or method that wraps blocking I/O\n - Note whether {{STACK}} is servlet or reactive and whether any reactive code blocks\n\n2. Decision\n - State whether the service is I/O bound and thread-limited, with evidence (thread dumps, Tomcat busy threads, latency vs load). If it is CPU bound or a non-blocking WebFlux app, recommend not enabling and stop after the findings\n - State the JDK verdict: 24+ (no `synchronized` pinning) or 21 to 23 (pinning audit required); recommend JDK 25 if the base image allows\n\n3. Findings (rank by risk: pools with no acquire timeout or sized below expected concurrency > unbounded fan-out or missing downstream limits > missing timeouts on blocking calls > pooled virtual threads or custom executors assumed to move > pinning on hot I/O paths (JDK 21 to 23 only) > ThreadLocal caches and lost context > CPU-bound work on request threads > observability gaps)\n\n4. Fix\n - Enable `spring.threads.virtual.enabled=true` per environment (profile or ConfigMap), keeping the rollback a single property\n - Size each pool in {{POOLS}} from the database or downstream capacity in {{DOWNSTREAM_LIMITS}}; set Hikari `connection-timeout` and HTTP pending-acquire timeouts so waits fail fast\n - Add a `Semaphore` or Resilience4j bulkhead per fragile downstream; no fixed pools of virtual threads\n - Move blocking custom executors to virtual-thread-per-task (`SimpleAsyncTaskExecutor` with virtual threads and an optional concurrency limit); keep CPU-bound executors on a bounded platform pool\n - Propagate {{CONTEXT}} with a `TaskDecorator` or Micrometer context propagation; replace `ThreadLocal` caches with shared immutable objects or explicit parameters\n - On JDK 21 to 23 only: change `synchronized` to `ReentrantLock` (with `unlock()` in `finally`) where the lock is held across blocking I/O on a hot path; on 24+ leave `synchronized` alone\n - Bound any per-request fan-out and pass the remaining deadline to each child; cancel children when the parent fails\n - Keep or add timeouts on every JDBC query, HTTP call, lock wait, and queue poll\n\n5. Tests\n - `@Async` and fan-out test proving SecurityContext, MDC correlation ID, and trace ID survive the hop\n - Concurrency test that fires more requests than the pool size and asserts acquire timeouts fail fast with a clear error instead of hanging\n - Bulkhead or semaphore test showing excess calls are rejected or queued as designed\n - A startup check or test that fails if the runtime JDK is below the stated floor\n\n6. Load-test plan and verification\n - Off-versus-on comparison with {{LOAD_TEST}} at the same pool sizes: throughput, p95, p99, error rate, `hikaricp.connections.pending` and acquire time, HTTP pool pending, heap and GC, and JFR `jdk.VirtualThreadPinned` events (threshold about 20 ms)\n - Resource table: resource | size | acquire timeout | downstream capacity | limiter in front\n - Executor table: executor | before | after | I/O or CPU | concurrency limit\n - Alerts to add: pool pending and acquire time, bulkhead rejections, heap pressure, p99 latency\n\nConstraints:\n- Minimal diff. Don't rewrite working concurrency code that isn't on a hot blocking path.\n- Don't invent pool sizes, downstream limits, or load numbers. Use placeholders and state assumptions.\n- Don't add a reactive stack or a new concurrency library to \"help\" virtual threads.\n- Optimize for GitHub Copilot, Claude Code, and Codex: give concrete diffs and a checklist.\n- Leave JDK base-image upgrades and alert rule changes as follow-up notes unless the repo already manages them.\n\nOutput format:\n1. Decision (enable or not, and why) and JDK verdict\n2. Findings table: severity | location | issue | fix\n3. Patch (properties + pool limits + limiters + executor changes + context propagation + pinning fixes)\n4. Tests added and their results\n5. Resource and executor tables, load-test plan, and follow-ups\n\nStart from {{APP_PATH}}. Bound the pools and downstreams before turning the property on.\n" } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index 42c8bd7..5cd7b05 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -697,6 +697,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-http-clients.instructions.md` with applyTo for `**/*Client*.java`, `**/*HttpConfig*.java`, `**/*WebClient*Config*.java`, and `**/application*.{yml,yaml,properties}`. Optional `.github/skills/spring-boot-http-client-guardrails/SKILL.md`. Claude Code: `.claude/skills/spring-boot-http-client-guardrails/SKILL.md` plus a CLAUDE.md fact that every outbound call has connect, read, and overall timeouts and retries only idempotent requests in one layer. Codex: an \"Outbound HTTP clients\" section in root `AGENTS.md` or a nested `AGENTS.md` beside the client package. Pair with spring-boot-resilience4j for circuit breaker and bulkhead patterns, entra-id-spring-service-auth-guardrails for client-credentials tokens, spring-boot-micrometer-prometheus-guardrails for metric conventions, and k8s-probes-graceful-shutdown-guardrails for the shutdown timeout chain. This skill owns client construction, timeouts, pools, retries, and outbound TLS.", "body": "# Skill: Spring Boot Outbound HTTP Client Guardrails\n\n## Goal\nMake every outbound HTTP call from a Spring Boot service (`RestClient`, `WebClient`, `RestTemplate`, HTTP interface clients) bounded, observable, and safe. Each call has a connect timeout, a read/response timeout, and an overall deadline that fits inside the caller's own budget. Connection pools are sized on purpose. Retries happen only for idempotent requests, with backoff and a cap, and never in two layers at once. TLS, auth headers, and trace context are set once per client, not by hand per call, and no secret or payload leaks into logs or metric tags.\n\n## When to apply\n- New service-to-service calls, or a review of existing `RestClient.Builder`, `WebClient.Builder`, `RestTemplateBuilder`, or `@HttpExchange` / `@ImportHttpServices` setups\n- Incidents with thread or connection pool exhaustion, cascading latency, \"hung\" requests, retry storms, or 5xx bursts during a downstream deploy\n- Calls to external SaaS APIs, Microsoft Graph or Entra token endpoints, or in-cluster `*.svc.cluster.local` services on AKS / Kubernetes\n- Moving from `RestTemplate` to `RestClient`, or picking an HTTP library (JDK, Apache HttpClient 5, Jetty, Reactor Netty)\n- Upgrading Spring Boot 3.4/3.5 to 4.0 (`spring.http.client.*` and `spring.http.reactiveclient.*` become `spring.http.clients.*`)\n\n## Baseline rules\n1. **Inject the builder, never `new` the client.** Use the auto-configured `RestClient.Builder` / `WebClient.Builder` / `RestTemplateBuilder` (or HTTP service client groups in Boot 4) so Micrometer observations, trace propagation, message converters, and SSL bundles apply. Build one client per downstream as a bean. A `RestClient.create()` or `new RestTemplate()` inside a method skips all of that and usually skips timeouts too.\n2. **Pick the request factory on purpose.** Boot picks the first library on the classpath: Apache HttpClient 5, then Jetty, Reactor Netty, the JDK `HttpClient`, and finally `SimpleClientHttpRequestFactory`. Set it explicitly (`spring.http.client.factory` in 3.4/3.5, `spring.http.clients.imperative.factory` in 4.0) so a transitive dependency can't silently change pooling and timeout behaviour. Avoid `simple` in production.\n3. **Three timeouts, every client.** Set a connect timeout (typically 1 to 3s), a read or response timeout sized from the downstream's p99 plus headroom, and an overall deadline for the whole call including retries. Globals go in `spring.http.client.connect-timeout` / `read-timeout` (Boot 3.4/3.5) or `spring.http.clients.*` (4.0). Override per client through `ClientHttpRequestFactorySettings` / `HttpClientSettings`. For pooled clients also bound the **connection-request timeout** (waiting for a pooled connection), because an unbounded pool wait looks exactly like a hung downstream.\n4. **Timeout budget flows downhill.** The sum of (attempts × read timeout) + backoff must be less than the inbound request's own timeout, the gateway or ingress timeout, and any client deadline. If the caller gives up at 5s, a downstream call with a 10s read timeout and three retries is a resource leak. Write the budget down per downstream.\n5. **Size pools to concurrency, per route.** With Apache HttpClient 5, set max total and max per route explicitly (the pooling connection manager defaults are small: 5 per route and 25 total), evict idle and expired connections, and set a time-to-live shorter than any load balancer or Azure SNAT idle timeout (Azure Load Balancer defaults to 4 minutes). With Reactor Netty, use a named `ConnectionProvider` with `maxConnections`, `pendingAcquireTimeout`, `maxIdleTime`, and `evictInBackground`. Pool size should match the concurrency you actually allow, not \"as many as possible\".\n6. **Retry only what is safe to retry.** Retry `GET`, `HEAD`, `PUT`, `DELETE`, and `POST` only with an idempotency key the downstream honours. Retry on connect failures, 502/503/504, and 429 (respect `Retry-After`). Never retry other 4xx, and never retry a read timeout on a non-idempotent call. Use exponential backoff with jitter and a small cap (2 to 3 attempts). Retry in **one layer** only: if Resilience4j, Spring Retry, a service mesh, or the HTTP library already retries, turn the others off.\n7. **Circuit breaker and bulkhead per downstream.** Wrap each downstream (not each method) in a circuit breaker and a concurrency limit so one slow dependency can't take every thread. Fallbacks must be explicit, honest values (cached, empty with a flag, or a clear error), not fake success. Pair with `spring-boot-resilience4j` for the patterns.\n8. **Errors are typed, bodies are bounded.** Use `.retrieve()` with `onStatus(...)` (or `defaultStatusHandler`) to map 4xx/5xx into your own exceptions with the downstream name and status. Cap response body size (`maxInMemorySize` for `WebClient` codecs, a limit for streamed bodies) and always consume or close the response so connections return to the pool. Never log full request or response bodies by default.\n9. **Base URLs and credentials from config only.** Every base URL comes from properties or a ConfigMap (`app.clients..base-url`), never hard-coded. Tokens come from Spring Security's OAuth2 client (`OAuth2ClientHttpRequestInterceptor` for `RestClient`, `ServerOAuth2AuthorizedClientExchangeFilterFunction` for `WebClient`) or workload identity, cached until expiry, and injected by an interceptor or filter. Never put secrets in URLs or query strings.\n10. **TLS through SSL bundles.** Configure trust and client certificates with `spring.ssl.bundle.*` and point clients at them (`spring.http.client.ssl.bundle` or per-client settings). Never ship a trust-all `TrustManager` or `HostnameVerifier`, including \"just for dev\". For mTLS inside the cluster, prefer the mesh; if the app does it, rotate certs without restarts (bundle reload) where supported.\n11. **Redirects are a decision.** All Boot-supported factories follow redirects by default. For APIs, set `redirects=dont-follow` unless a specific downstream needs them, and never forward `Authorization` across a redirect to another host.\n12. **Propagate context, not everything.** Trace context (W3C `traceparent`) is added automatically when you use the injected builders with Micrometer Tracing. Explicitly allow-list any business headers you forward (correlation ID, tenant, locale). Never blindly forward all inbound headers, especially `Authorization`, `Cookie`, or `Host`.\n13. **Observe per downstream with bounded tags.** Keep `http.client.requests` metrics, tagged by client name, method, status, and URI **template** (use `uri(\"/orders/{id}\", id)`, never string concatenation, or tag cardinality explodes). Add pool metrics (active, idle, pending) and alert on p99 latency, error rate, open circuit, and pool pending. Log downstream name, method, template, status, and duration, never tokens or payloads.\n14. **Virtual threads don't remove limits.** With `spring.threads.virtual.enabled=true`, blocking `RestClient` calls are cheap on threads but still use connections, sockets, and downstream capacity. Keep pool limits and bulkheads, and avoid `synchronized` blocks around I/O in older JDKs where they pin carrier threads.\n15. **Test the failure paths.** Use WireMock (or `MockRestServiceServer` for `RestClient` / `RestTemplate`) to prove: slow response trips the read timeout, connect refusal fails fast, 503 retries then succeeds, 400 does not retry, 429 honours `Retry-After`, an open circuit short-circuits, and a large body is rejected. Assert through Awaitility or virtual time, not sleeps.\n\n## Workflow\n1. **Inventory.** List every outbound client: library, builder vs `new`, base URL source, timeouts, pool settings, retry layers (code, Resilience4j, mesh), auth mechanism, SSL config, and redirect policy. Note the inbound timeout and ingress timeout for each calling endpoint.\n2. **Budget.** For each downstream write: p99 latency, chosen read timeout, attempts, backoff, and total worst case, and check it against the caller's timeout.\n3. **Fix the dangerous ones first.** Missing timeouts, unbounded pool waits, retries on non-idempotent calls, nested retry layers, trust-all TLS, and secrets in URLs or logs.\n4. **Centralise.** One `@Configuration` per downstream (or an HTTP service client group) owning base URL, timeouts, pool, auth interceptor, error mapping, and observation name. Business code depends on an interface, not on the HTTP library.\n5. **Observe.** Confirm `http.client.requests` shows URI templates and client names, pool metrics are exported, and alerts exist for latency, errors, pool pending, and circuit state.\n6. **Test.** Add the rule 15 failure-path tests and run them in CI.\n\n## Tool-specific notes\n- **GitHub Copilot:** path-scoped `.github/instructions/spring-http-clients.instructions.md` with `applyTo` for `**/*Client*.java`, `**/*HttpConfig*.java`, `**/*WebClient*Config*.java`, and `**/application*.{yml,yaml,properties}`. Ask agent mode for the inventory table first, then the diff.\n- **Claude Code:** `.claude/skills/spring-boot-http-client-guardrails/SKILL.md`, plus a short `CLAUDE.md` fact: \"Every outbound HTTP call has connect, read, and overall timeouts, and retries only idempotent requests in one layer.\"\n- **Codex:** an \"Outbound HTTP clients\" section in root `AGENTS.md`, or a nested `AGENTS.md` beside the client package, with the budget table format and the test matrix.\n\n## Anti-patterns\n- `new RestTemplate()` or `RestClient.create()` inside a service method, with no timeouts and no observations\n- Relying on library defaults: infinite read timeout on `SimpleClientHttpRequestFactory`, unbounded pool waits, or whatever factory happened to be on the classpath\n- Read timeout × retries longer than the caller's own timeout\n- Retrying `POST` without an idempotency key, retrying 400/401/403/404, or retrying in Resilience4j and the mesh and the library at the same time\n- A single shared pool with a tiny per-route limit, or no idle eviction behind Azure SNAT / load balancer idle timeouts\n- `uri(baseUrl + \"/orders/\" + id)` producing one metric series per ID\n- Trust-all `TrustManager`, or a `HostnameVerifier` that returns `true`, left in prod\n- Forwarding every inbound header downstream, or following redirects with `Authorization` to another host\n- Logging full request and response bodies, tokens, or query strings with secrets\n- Fallbacks that return fake success and hide an outage\n\n## Done when\n- [ ] Every outbound client is a bean built from the injected builder (or an HTTP service client group), with base URL from config\n- [ ] The request factory / connector is set explicitly per environment, never `simple` in production\n- [ ] Connect, read/response, connection-request (for pools), and overall timeouts are set per client, and the budget fits the caller's timeout\n- [ ] Pools have explicit max total, per-route limits, idle eviction, and TTL below the load balancer idle timeout\n- [ ] Retries are idempotent-only, bounded, jittered, honour `Retry-After`, and live in exactly one layer\n- [ ] Each downstream has a circuit breaker and concurrency limit with an explicit fallback\n- [ ] 4xx/5xx map to typed exceptions, response size is capped, and responses are always released\n- [ ] Auth comes from the OAuth2 client or workload identity via interceptor/filter; TLS via SSL bundles; no trust-all code\n- [ ] Redirect policy is explicit; only allow-listed headers are forwarded\n- [ ] `http.client.requests` uses URI templates and client names; pool and circuit metrics are alerted\n- [ ] Failure-path tests (timeout, connect refusal, 503 retry, 400 no-retry, 429, open circuit, large body) pass in CI\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-boot-http-client-guardrails\ndescription: Use when writing or reviewing outbound HTTP calls in Spring Boot (RestClient, WebClient, RestTemplate, HTTP interface clients) — timeouts and deadline budgets, connection pools, idempotent-only retries in one layer, circuit breakers, typed errors, OAuth2/SSL bundle wiring, redirects, header propagation, URI-template metrics, and failure-path tests.\n---\n\nFollow Spring Boot Outbound HTTP Client Guardrails: build every client from the injected builder as a per-downstream bean with base URL from config, set the request factory explicitly, give each client connect, read, pool-wait, and overall timeouts that fit the caller's budget, size pools per route with idle eviction under the LB idle timeout, retry only idempotent requests with jittered bounded backoff in exactly one layer, wrap each downstream in a circuit breaker and bulkhead with honest fallbacks, map 4xx/5xx to typed exceptions and cap body size, get tokens from the OAuth2 client or workload identity and TLS from SSL bundles (never trust-all), make redirects explicit, forward only allow-listed headers, tag metrics by URI template and client name, and prove timeouts, retries, and circuit behaviour with WireMock tests in CI.\n```\n" + }, + { + "id": "java-virtual-threads-spring-guardrails", + "title": "Java Virtual Threads in Spring Boot Guardrails", + "whenToUse": "Enabling or reviewing Java virtual threads in a Spring Boot service (spring.threads.virtual.enabled) — choosing the JDK (pinning before and after JEP 491), knowing which executors move, replacing the old thread cap with explicit pool sizes, acquire timeouts, and per-downstream limits, never pooling virtual threads, ThreadLocal and context propagation, keeping CPU-bound work on platform threads, bounded fan-out, JFR pinning checks, and an off-versus-on load test.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "java", + "virtual-threads", + "spring-boot", + "concurrency", + "performance", + "jdk25" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/java-virtual-threads.instructions.md` with applyTo for `**/*Config*.java`, `**/*Executor*.java`, `**/*Async*.java`, and `**/application*.{yml,yaml,properties}`. Optional `.github/skills/java-virtual-threads-spring-guardrails/SKILL.md`. Claude Code: `.claude/skills/java-virtual-threads-spring-guardrails/SKILL.md` plus a CLAUDE.md fact that every pool and downstream has an explicit limit and timeout once virtual threads are on. Codex: a \"Concurrency and virtual threads\" section in root `AGENTS.md`. Pair with spring-boot-http-client-guardrails for HTTP pool and timeout settings, spring-boot-resilience4j for bulkheads, spring-data-jpa-query-guardrails for query timeouts, and spring-boot-micrometer-prometheus-guardrails for pool-wait metrics. This skill owns the decision to enable, executor choice, concurrency limits, pinning, and context propagation.", + "body": "# Skill: Java Virtual Threads in Spring Boot Guardrails\n\n## Goal\nTurn on virtual threads in a Spring Boot service only when it pays off, and without moving the bottleneck somewhere harder to see. Blocking request handling, `@Async`, scheduled work, and listeners get cheap threads, while every finite resource behind them (JDBC pools, HTTP pools, downstream rate limits, memory) keeps an explicit limit. The JDK level is chosen on purpose, pinning is measured instead of guessed, `ThreadLocal` and MDC usage still works, and a load test proves the switch helped before it reaches production.\n\n## When to apply\n- Deciding whether to set `spring.threads.virtual.enabled=true` on a servlet (Spring MVC) service, or reviewing a PR that does\n- A service that mostly waits on I/O (JDBC, HTTP, Kafka, Redis, Azure SDK calls) and runs out of Tomcat or executor threads under load\n- Latency got worse, or Hikari or HTTP pool \"pending\" metrics spiked, right after enabling virtual threads\n- Upgrading from JDK 21 to 25, or from Spring Boot 3.x to 4.x, on a service that already uses virtual threads\n- Replacing hand-sized `ThreadPoolTaskExecutor` pools used for blocking fan-out calls\n\n## Baseline rules\n1. **Pick the JDK first.** Virtual threads need JDK 21 or later, and Spring Boot's switch has existed since 3.2. On JDK 21 to 23, a virtual thread that blocks inside `synchronized` (or `Object.wait()`) stays pinned to its carrier thread. JDK 24 (JEP 491) removed that, and JDK 25 is the LTS that carries it. Prefer JDK 25 for anything that enables virtual threads; if you must stay on 21, treat rule 6 as mandatory.\n2. **Know what the switch changes.** With `spring.threads.virtual.enabled=true`, Boot runs embedded Tomcat or Jetty request handling, the auto-configured `applicationTaskExecutor` (`@Async`, MVC async), the task scheduler, and supported listener containers (Kafka, RabbitMQ, JMS) on virtual threads. Any executor you define yourself is untouched. List both sets before and after, so nobody assumes a custom pool moved.\n3. **Servlet stacks benefit; reactive stacks don't need it.** Virtual threads help blocking, thread-per-request code. A WebFlux or Reactor app that never blocks gains little. Don't mix the two to \"speed up\" a reactive service; fix the blocking call or isolate it on `boundedElastic` instead.\n4. **The thread limit was your concurrency limit. Replace it.** Tomcat's 200 platform threads used to cap in-flight work. With virtual threads, thousands of requests can pile onto a 10-connection Hikari pool or a 20-connection HTTP pool. Put a deliberate limit in front of every scarce resource: a `Semaphore` or Resilience4j bulkhead around fragile downstreams, a bounded `connection-timeout` on Hikari, and a pending-acquire timeout on HTTP pools. Size pools from what the database or downstream can handle, not from request rate.\n5. **Never pool virtual threads.** Create one per task (`Executors.newVirtualThreadPerTaskExecutor()` or Spring's `SimpleAsyncTaskExecutor` with virtual threads and an optional `concurrencyLimit`). A fixed pool of virtual threads brings back the queueing and sizing problems you were trying to remove.\n6. **Measure pinning instead of rewriting locks.** Record the JFR event `jdk.VirtualThreadPinned` (threshold around 20 ms) during a load test. On JDK 21 to 23, `-Djdk.tracePinnedThreads=short` also helps; it no longer exists on 24+. Only replace `synchronized` with `ReentrantLock` where a lock is held across blocking I/O on a hot path, on a JDK that still pins. On 24+ leave working `synchronized` code alone. Native calls and some class-initialization paths can still pin on every JDK, so watch the JFR event either way.\n7. **Treat `ThreadLocal` as per task, not per worker.** Every virtual thread is new, so caches stored in `ThreadLocal` (formatters, buffers, per-thread connections) are rebuilt on every request and can multiply memory. Make such objects immutable and shared, or pass them explicitly. Keep request context (security context, MDC, trace) flowing through Spring's `TaskDecorator`, Micrometer context propagation, or `ScopedValue` where the JDK and libraries support it, and test that it survives `@Async` hops.\n8. **Keep timeouts, they matter more now.** A blocked virtual thread is cheap, so a missing timeout no longer shows up as thread exhaustion; it shows up as unbounded memory and connection use. Every JDBC query, HTTP call, lock wait, and queue poll still needs a timeout that fits the caller's budget.\n9. **Check the libraries on the hot path.** JDBC drivers, HTTP clients, and SDKs that block inside `synchronized` or native code can pin or serialize under load on older JDKs. Upgrade drivers to versions that document virtual-thread support, and confirm with the JFR pinning event rather than release notes alone.\n10. **CPU-bound work stays on platform threads.** Virtual threads don't add CPU. Keep heavy computation (crypto, compression, large JSON or report generation) on a bounded platform `ThreadPoolTaskExecutor` sized near the core count, and keep it off the request threads.\n11. **Structured fan-out, bounded.** For parallel calls from one request, use a virtual-thread-per-task executor inside try-with-resources (or `StructuredTaskScope` where it's final in your JDK) so children are cancelled with the parent. Cap the fan-out and give every child the remaining deadline, not a fresh one.\n12. **Observe the new bottlenecks.** Alert on `hikaricp.connections.pending` and acquire time, HTTP client pool pending, bulkhead rejections, heap and GC pressure, and request latency percentiles. Thread-count graphs stop being useful; pool wait time is the signal that replaces them.\n13. **Prove it with a load test before production.** Compare the same build with the property off and on, at the same pool sizes: throughput, p95 and p99 latency, error rate, pool wait, heap, and the pinning events. Ship only if the numbers improve or stay level with less tuning, and keep a one-line rollback (the property set to `false`).\n\n## Workflow\n1. **Inventory.** Record JDK version, Boot version, servlet or reactive stack, every executor (auto-configured and custom), every finite pool (Hikari, HTTP clients, Redis, Kafka producer), current Tomcat `threads.max`, and every `ThreadLocal` or MDC use.\n2. **Decide.** Confirm the service is I/O bound and currently thread-limited. If it is CPU bound or already reactive and non-blocking, stop and say so.\n3. **Bound the resources.** Add or check pool sizes, acquire timeouts, and a semaphore or bulkhead per fragile downstream before flipping the switch.\n4. **Enable.** Set `spring.threads.virtual.enabled=true` per environment, move blocking custom executors to virtual threads, keep CPU-bound executors on platform threads.\n5. **Fix context and pinning.** Add context propagation for `@Async` and fan-out; run JFR under load and fix only the pinning sites that matter on your JDK.\n6. **Load test and observe.** Run the off-versus-on comparison, wire the pool-wait alerts, and document the rollback.\n\n## Tool-specific notes\n- **GitHub Copilot:** path-scoped `.github/instructions/java-virtual-threads.instructions.md` with `applyTo` for `**/*Config*.java`, `**/*Executor*.java`, `**/*Async*.java`, and `**/application*.{yml,yaml,properties}`. Ask agent mode for the inventory and decision first, then the diff.\n- **Claude Code:** `.claude/skills/java-virtual-threads-spring-guardrails/SKILL.md`, plus a short `CLAUDE.md` fact: \"Virtual threads are on; every pool and downstream has an explicit limit and timeout, and CPU-bound work uses a bounded platform executor.\"\n- **Codex:** a \"Concurrency and virtual threads\" section in root `AGENTS.md` with the JDK floor, the resource-limit table format, and the load-test comparison it must report.\n\n## Anti-patterns\n- Flipping `spring.threads.virtual.enabled=true` in production without a load test or a rollback plan\n- Leaving Hikari at its default 10 connections with no acquire-time alert after removing the 200-thread cap\n- A `newFixedThreadPool` of virtual threads, or a custom \"virtual thread pool\" class\n- Mass-replacing every `synchronized` with `ReentrantLock` on JDK 24+, or forgetting `unlock()` in `finally` when you do\n- Expensive objects cached in `ThreadLocal`, recreated on every request\n- CPU-heavy work running on virtual request threads\n- Unbounded fan-out (one virtual thread per item in a 50,000-row list) against a downstream with a rate limit\n- Dropping timeouts because \"threads are cheap now\"\n- Assuming a custom `TaskExecutor` bean moved to virtual threads when the property only changes auto-configured ones\n- Adding virtual threads to a WebFlux app instead of fixing the blocking call\n\n## Done when\n- [ ] JDK version is stated, and is 24+ (ideally 25) or the pinning audit is done for 21 to 23\n- [ ] The service is shown to be I/O bound and thread-limited before the switch\n- [ ] Every finite pool has a size from downstream capacity and an acquire timeout; fragile downstreams have a semaphore or bulkhead\n- [ ] Auto-configured and custom executors are listed, with blocking ones on virtual threads and CPU-bound ones on bounded platform threads\n- [ ] No pooled virtual threads; fan-out is bounded and deadline-aware\n- [ ] Security context, MDC, and trace IDs survive `@Async` and fan-out, with a test\n- [ ] JFR `jdk.VirtualThreadPinned` checked under load, and only material pinning sites changed\n- [ ] Off-versus-on load test results recorded; pool-wait, heap, and latency alerts exist; rollback is one property\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: java-virtual-threads-spring-guardrails\ndescription: Use when enabling or reviewing Java virtual threads in Spring Boot (spring.threads.virtual.enabled) — JDK choice and pinning (JEP 491), replacing the thread cap with explicit pool and downstream limits, no pooled virtual threads, ThreadLocal and context propagation, CPU-bound work, bounded fan-out, and an off-versus-on load test.\n---\n\nFollow Java Virtual Threads in Spring Boot Guardrails: enable virtual threads only for I/O-bound servlet services, prefer JDK 25 (audit synchronized-around-I/O pinning on 21 to 23 with JFR jdk.VirtualThreadPinned), list which executors the property moves and which custom ones it doesn't, replace the old thread cap with explicit pool sizes, acquire timeouts, and semaphores or bulkheads per fragile downstream, never pool virtual threads, keep every timeout, keep ThreadLocal caches out and propagate security, MDC, and trace context across async hops, run CPU-bound work on a bounded platform executor, bound fan-out with the parent's deadline, alert on pool wait instead of thread counts, and prove the change with an off-versus-on load test and a one-property rollback.\n```\n" } ] }