Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions promptbook/prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
}
Loading
Loading