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
21 changes: 21 additions & 0 deletions promptbook/prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,27 @@
],
"formatNotes": "All three. Point the tool at `application.yml`/`application.properties` (`spring.kafka.*`), the `@KafkaListener` classes, container factory and error-handler config, any inbox/outbox migrations, and the topic manifests or IaC for source, retry, and DLT topics. Keep test harness conventions aligned with spring-boot-testcontainers. Copilot: spring-kafka-consumer path instructions plus those files in agent mode. Claude Code: the spring-kafka-consumer-reliability-guardrails skill plus the listener, config, and topic files. Codex: AGENTS.md Kafka consumer section, then the diff.",
"body": "Task: Harden the Spring for Apache Kafka consumer(s) I specify for production. Make handlers idempotent under at-least-once delivery, commit offsets only after work, retry transient failures with bounded backoff, and route non-retryable and poison records to an owned dead-letter topic. Rebalances and shutdowns should not lose or double-apply work. Finish with a minimal diff I can open as a PR, plus tests for the failure paths.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- Spring Boot / Spring Kafka version: {{BOOT_VERSION}} (e.g. 3.5 / 3.3, 4.0 / 4.0 | unknown)\n- Listeners in scope: {{LISTENERS}} (listener id → topic(s), record | batch)\n- Topic partitions and consumer group: {{PARTITIONS}} (e.g. orders.v1: 12 partitions, group orders-svc)\n- Replicas / autoscaling: {{REPLICAS}} (fixed N | HPA min-max | KEDA min-max)\n- Side effects per handler: {{SIDE_EFFECTS}} (db-write | http-call | produce-to-topic | email | none)\n- Dedupe key available: {{DEDUPE_KEY}} (event-id header | business key | none | unknown)\n- Ordering requirement: {{ORDERING}} (per-key order required | order irrelevant)\n- Retry/DLT today: {{RETRY_TODAY}} (none | DefaultErrorHandler defaults | custom | @RetryableTopic)\n- Broker / security: {{BROKER}} (e.g. Confluent Cloud SASL_SSL SCRAM | Azure Event Hubs Kafka OAUTHBEARER | Strimzi mTLS)\n- Pain points: {{PAIN}} (duplicates | lost-messages | stuck-partition | rebalance-storm | lag | poison-pill | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file, `application*.yml|properties` (`spring.kafka.*`), every `@KafkaListener`, container factories, and any `CommonErrorHandler`, `RetryTopicConfiguration`, or `@RetryableTopic` usage\n - Record per listener: ack mode, record vs batch, concurrency, deserializers, transaction use, and what each side effect does\n - Find retry wrappers around listener bodies (`@Retryable`, Resilience4j, hand-written loops), auto-commit settings, and early or async acknowledgements\n - Note topic manifests or IaC for source, retry, and DLT topics; consumer metrics and alerts; SASL/TLS config and where credentials come from\n\n2. Findings (rank by risk: non-idempotent side effects > ack-before-work / auto-commit > poison-pill loops or unbounded retries > missing or unowned DLT > poll-interval / rebalance risks > concurrency vs partitions > observability and test gaps > hygiene)\n - Side effects with no dedupe key or inbox, so duplicates double-charge, double-insert, or double-send\n - `enable.auto.commit=true`, acknowledging before the side effect is durable, or acks from another thread without ordering care\n - Missing `ErrorHandlingDeserializer`, `FixedBackOff` with unlimited attempts, or nested retry loops on top of the container error handler\n - No exception classification: validation and business errors retried like timeouts\n - DLT missing, auto-created, with fewer partitions than the source, or with no owner, alert, or replay path\n - `@RetryableTopic` where {{ORDERING}} = per-key order required, or on a batch listener\n - `max.poll.records` × p99 handling time + backoff near or above `max.poll.interval.ms`\n - Concurrency × max replicas above {{PARTITIONS}}, eager assignor, or shutdown timeouts longer than the pod grace period\n - Credentials in Git, ConfigMaps, or code; record payloads in logs or metric tags\n\n3. Fix\n - Idempotency: for each handler in {{SIDE_EFFECTS}}, use {{DEDUPE_KEY}} (or propose one). Add an inbox table with a unique (consumer group, message key) constraint written in the same DB transaction as the side effect, or an upsert keyed on the business key. Route outbound events through an outbox where the handler also produces\n - Commits: `enable.auto.commit=false`. Keep `AckMode.BATCH` unless the handler completes asynchronously; then `MANUAL_IMMEDIATE` with the ack after the durable write\n - Error handler: one `DefaultErrorHandler` bean with `ExponentialBackOffWithMaxRetries` (start around 1s, ×2, cap 10s, 4 to 6 retries unless the SLO says otherwise), `addNotRetryableExceptions(...)` for validation / business / 4xx types, and a `DeadLetterPublishingRecoverer`. Remove nested retry wrappers. Make sure application exceptions extend `RuntimeException`\n - DLT: name `<topic>-dlt` (or the repo's convention), partitions ≥ source, retention and owner in the topic manifest or IaC, and exclude the stack-trace header if messages can carry PII\n - Non-blocking retries: only if {{ORDERING}} = order irrelevant and the listener is record-based. `@RetryableTopic` with bounded attempts and backoff, retry and DLT topics pre-provisioned, and fatal exceptions matching the blocking classification\n - Poison pills: `ErrorHandlingDeserializer` around key and value delegates, explicit JSON type mapping or narrow trusted packages, and for batch listeners a `null` check that throws `BatchListenerFailedException` with the record or index\n - Poll loop: set `max.poll.records` so `max.poll.records` × p99 + max blocking backoff fits under half of `max.poll.interval.ms`. Use `ContainerPausingBackOffHandler` if backoffs are long\n - Scaling and rebalance: `concurrency` ≤ partitions per instance and max replicas ≤ partitions ÷ concurrency for {{REPLICAS}}; `CooperativeStickyAssignor` (or `group.protocol=consumer` when the broker supports it); optional `group.instance.id` from the pod name; container `shutdownTimeout` and `spring.lifecycle.timeout-per-shutdown-phase` below `terminationGracePeriodSeconds`\n - Observability: keep Boot's Kafka client metrics and `spring.kafka.listener` timers on, and add counters for retries (`RetryListener`), DLT publishes, and dedupe hits with bounded tags. Note the broker-side consumer-group lag alert to add. Log topic/partition/offset/key hash, never payloads\n - Security per {{BROKER}}: `SASL_SSL` (or mTLS) with the JAAS config, passwords, and connection strings from Kubernetes secrets or Key Vault via environment placeholders, and truststores mounted from secrets\n\n4. Tests\n - Integration on Testcontainers Kafka with `@ServiceConnection` (or `@EmbeddedKafka` for a fast slice), with assertions through Awaitility and no fixed sleeps\n - Same record delivered twice → exactly one side effect\n - Transient failure → retries, then succeeds, offset committed once\n - Non-retryable exception → DLT on first failure with original topic/partition/offset headers\n - Malformed payload → DLT with the original bytes, and the partition keeps moving\n - Container stop mid-batch → restart reprocesses only uncommitted records with no duplicate side effects\n\n5. Verification\n - Exception classification table: exception → retryable? → blocking / non-blocking / DLT\n - Topic table: source, retry, and DLT names with partitions, retention, and owner\n - Poll-budget math and the concurrency × replicas ≤ partitions check for {{PARTITIONS}} and {{REPLICAS}}\n - Metrics and alerts list (lag, retry rate, DLT rate, dedupe hits), and confirmation that no credentials or payloads appear in config, logs, or tags\n\nConstraints:\n- Minimal diff. Extend the existing container factory and listeners; don't introduce a second factory or a new messaging framework.\n- Don't invent topic names, broker URLs, credentials, or partition counts. Use placeholders if unknown.\n- Don't claim exactly-once for DB or HTTP side effects. Use Kafka transactions only for Kafka-to-Kafka flows that already need them.\n- Optimize for GitHub Copilot, Claude Code, and Codex: give concrete diffs and a checklist.\n- Leave topic creation and alert rules as follow-up notes unless the repo already manages them.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (config + error handler/recoverer + deserializers + idempotency/inbox migration + listener changes + topic manifests)\n3. Tests added and their results\n4. Classification table, topic table, poll-budget math, and follow-ups (alerts, broker-side lag, DLT replay runbook)\n\nStart from {{APP_PATH}}. Fix non-idempotent side effects and ack-before-work before tuning retries or metrics.\n"
},
{
"id": "harden-spring-outbound-http-clients",
"title": "Harden Spring Outbound HTTP Clients",
"whenToUse": "Make a Spring Boot service's outbound HTTP calls production-safe (explicit request factory, connect/read/pool-wait/overall timeouts that fit the caller's budget, sized pools with idle eviction, idempotent-only retries in exactly one layer, circuit breaker and bulkhead per downstream, typed errors and body caps, OAuth2 and SSL bundle wiring, explicit redirects, allow-listed headers, URI-template metrics) and produce a minimal diff with WireMock failure-path tests.",
"tools": [
"copilot",
"claude-code",
"codex"
],
"tags": [
"spring-boot",
"http-client",
"restclient",
"webclient",
"resilience",
"timeouts",
"java"
],
"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"
}
]
}
Loading
Loading