From b3be82a882213d3ebcec294b666d7afc6275ab39 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Wed, 21 Oct 2026 05:05:03 +0000 Subject: [PATCH 1/2] Add Spring Boot outbound HTTP client guardrails skill --- skillbook/skills.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index 4f03c5f..42c8bd7 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -676,6 +676,27 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/spring-kafka-consumer.instructions.md` with applyTo for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*Kafka*Config*.java`, `**/application*.{yml,yaml,properties}`, and topic manifests (`**/kafkatopic*.yaml`, `**/topics/**`). Optional `.github/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md`. Claude Code: `.claude/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md` plus a CLAUDE.md fact that every record may arrive twice and nothing is acked before the side effect is durable. Codex: a Kafka consumer section in root `AGENTS.md` or nested `src/main/java/**/messaging/AGENTS.md`. Pair with spring-boot-testcontainers for the Kafka test harness, spring-boot-micrometer-prometheus-guardrails for metric conventions, k8s-probes-graceful-shutdown-guardrails for the shutdown timeout chain, aks-hpa-requests-limits-guardrails for KEDA/HPA caps, and azure-key-vault-app-integration for SASL credentials. This skill owns consumer delivery semantics, error handling, and DLTs.", "body": "# Skill: Spring Kafka Consumer Reliability Guardrails\n\n## Goal\nMake Spring for Apache Kafka consumers safe to run in production. Kafka delivers at least once, so every handler has to be idempotent. Offsets are committed only after the work is done. Transient failures retry with bounded backoff, while bad data and poison pills go straight to a dead-letter topic you own. Rebalances and rolling restarts must not lose or double-apply side effects, and lag is visible before users notice it.\n\n## When to apply\n- New `@KafkaListener` consumers, or reviews of an existing `ConcurrentKafkaListenerContainerFactory` / `spring.kafka.consumer.*` / `spring.kafka.listener.*` setup\n- Incidents involving duplicates, lost messages, stuck partitions, rebalance storms, or a consumer that \"looks healthy\" but stopped consuming\n- Adding retries, a DLT, or `@RetryableTopic` non-blocking retries\n- Consumers that write to a database, call HTTP APIs, or produce to other topics (side effects that must not run twice)\n- AKS / Kubernetes deployments where scaling, rolling updates, or KEDA change the number of consumer instances\n\n## Baseline rules\n1. **Design for at-least-once.** Assume every record can arrive more than once: after a rebalance, a crash before commit, a retry, or a DLT replay. Exactly-once is only real for Kafka-to-Kafka read-process-write with transactions (`transactional.id` on the producer, `isolation.level=read_committed` on downstream consumers). A database write or HTTP call is never covered by Kafka transactions.\n2. **Idempotent handlers with a dedupe key.** Pick a stable key per message: a producer-assigned event ID header, or a business key such as order ID plus version. Fall back to `topic-partition-offset` only when the source can't give you one, because a producer retry creates a new offset. Use an **inbox** table with a unique constraint on (consumer group, message key) and write it in the same DB transaction as the side effect. A duplicate then becomes a no-op insert conflict. When the handler also emits events, write them to an **outbox** table in that same transaction instead of calling `KafkaTemplate` inline.\n3. **Commit after work, never before.** Keep `enable.auto.commit=false` (Spring's default). The container default `AckMode.BATCH` commits after the whole poll is processed. `RECORD` commits after each record and costs more broker round trips. Use `MANUAL` / `MANUAL_IMMEDIATE` only when the handler finishes asynchronously, and acknowledge only after the side effect is durable. Never acknowledge, then hand off to another thread and hope.\n4. **One error handler, owned by the container.** Register a single `DefaultErrorHandler` bean (Boot wires it into the auto-configured factory). Give it a bounded `BackOff`, such as `ExponentialBackOffWithMaxRetries` (for example 1s, 2s, 4s, capped at 10s, 4 to 6 retries). Do not wrap the listener body in a Resilience4j / Spring Retry loop as well, because that multiplies attempts and hides the delivery count.\n5. **Classify exceptions explicitly.** Retryable means transient: timeouts, 503s, deadlocks, broker unavailable. Non-retryable means it will never succeed: validation failures, unknown schema version, business rule violations, 4xx from a downstream. Add your own types with `addNotRetryableExceptions(...)`. The framework already treats `DeserializationException`, `MessageConversionException`, `ClassCastException` and similar as fatal. Application exceptions must extend `RuntimeException`: anything extending `Error` bypasses the handler and kills the consumer thread.\n6. **Dead-letter on exhaustion, with a real DLT.** Use `DeadLetterPublishingRecoverer` as the recoverer. The default destination is `-dlt` on the same partition, so the DLT needs **at least as many partitions** as the source (or use a resolver that returns a negative partition). Provision DLTs with IaC, set retention, and name an owner. Alert on DLT publish rate and document a replay path. Exclude the stack-trace header (`excludeHeaders(EX_STACKTRACE)`) when exception messages could carry payload data or PII.\n7. **Blocking vs non-blocking retries are a choice about ordering.** `DefaultErrorHandler` retries in place and keeps per-partition order, but it blocks that partition. `@RetryableTopic` moves the record to `-retry` topics and finally `-dlt` (default suffixes; Spring Kafka 4.1+ reuses one retry topic per interval). That frees the partition but **breaks per-key ordering**, and it is not supported for batch listeners. Use it only when ordering doesn't matter, pre-create the retry topics where broker auto-create is off, and keep non-blocking fatal exceptions aligned with rule 5.\n8. **Poison pills never loop.** Wrap both key and value deserializers in `ErrorHandlingDeserializer` (`spring.deserializer.key.delegate.class` / `spring.deserializer.value.delegate.class`). A record that can't be deserialized then reaches the error handler as a fatal `DeserializationException` and goes to the DLT with its original bytes, instead of failing at `poll()` forever. For JSON, configure explicit type mappings or a narrow trusted-packages list, never `*`. Batch listeners must check for `null` values and throw `BatchListenerFailedException` with the failing record or index.\n9. **Size the poll loop against `max.poll.interval.ms`.** Rough budget: `max.poll.records` × p99 handling time + worst-case blocking backoff, with at least 2x headroom under `max.poll.interval.ms` (default 5 minutes). Lower `max.poll.records` (default 500) for slow handlers instead of raising the interval to hours. When backoff delays approach the poll interval, use `ContainerPausingBackOffHandler` or non-blocking retries. Missing the interval triggers a rebalance and redelivery, which is how duplicates start.\n10. **Concurrency follows partitions.** Each container thread owns whole partitions, so `concurrency` × replicas above the partition count leaves idle consumers. Set `concurrency` ≤ partitions per instance and plan the partition count for peak parallelism. With KEDA or HPA, cap max replicas at partitions ÷ concurrency (see **aks-hpa-requests-limits-guardrails**). Per-key ordering holds only within a partition, so key records by the entity whose order matters.\n11. **Gentle rebalances and graceful shutdown.** Use `CooperativeStickyAssignor` (`partition.assignment.strategy`) so a rebalance moves only the partitions that need to move. If brokers support the newer consumer group protocol (`group.protocol=consumer`, Kafka 4.x), prefer it. Consider static membership (`group.instance.id` from the pod name) so rolling restarts within `session.timeout.ms` don't rebalance at all. On shutdown, let the container finish the in-flight batch and commit: keep the container `shutdownTimeout` and `spring.lifecycle.timeout-per-shutdown-phase` below the pod `terminationGracePeriodSeconds` (see **k8s-probes-graceful-shutdown-guardrails**). Flush pending work in a `ConsumerAwareRebalanceListener` when you hold state per partition.\n12. **Lag and failure metrics through Micrometer.** Boot binds Kafka client metrics to Micrometer, so you get `kafka.consumer.fetch.manager.records.lag.max` and friends, plus `spring.kafka.listener` timers for handler duration and outcome. Add counters for retries (a `RetryListener` on the error handler), DLT publishes, and dedupe hits. Keep tags bounded (listener ID, topic, outcome), never keys or payload fields. Client-side lag disappears when the consumer is down, so also alert on consumer group lag from the broker side (an exporter or your managed Kafka's metrics). Dashboard conventions: **spring-boot-micrometer-prometheus-guardrails**.\n13. **Liveness tells the truth.** A dead listener thread must not report healthy. Watch `ConsumerStoppedEvent` / `ListenerContainerIdleEvent` or use a small health contributor on container state. Keep broker reachability out of **liveness** so a broker blip doesn't restart every pod.\n14. **Security: TLS + SASL, no credentials in code.** Use `security.protocol=SASL_SSL` with SCRAM or OAUTHBEARER (for example Entra ID for Azure Event Hubs' Kafka endpoint). The JAAS config, passwords, and connection strings come from Kubernetes secrets or Key Vault through environment placeholders (see **azure-key-vault-app-integration**). Never put them in `application.yml` in Git, a ConfigMap, or Java code. Mount truststores from secrets. Never log record values or full headers: log topic, partition, offset, key hash, and a correlation ID.\n15. **Test failure paths, not only the happy path.** Use Testcontainers Kafka with `@ServiceConnection` for integration tests (see **spring-boot-testcontainers**), or `@EmbeddedKafka` for fast in-JVM slices. Cover: the same record delivered twice gives one side effect; a transient failure retries and then succeeds; a non-retryable exception goes to the DLT on the first failure; a poison-pill payload reaches the DLT with its original bytes; shutdown or rebalance mid-batch loses no committed work. Use Awaitility for assertions, never fixed sleeps.\n\n## Workflow\n1. Inventory: listeners (record vs batch), container factories, ack mode, current error handler and backoff, deserializers, retry/DLT topics, transaction usage, side effects per handler, and partitions vs concurrency vs replicas.\n2. Delivery semantics: for each handler, write down the dedupe key and where it is enforced (inbox table, upsert, natural idempotency). Add inbox/outbox where a side effect is not idempotent.\n3. Error path: one `DefaultErrorHandler` with bounded backoff, explicit non-retryable exceptions, a `DeadLetterPublishingRecoverer`, and `ErrorHandlingDeserializer` on key and value. Decide blocking vs `@RetryableTopic` per listener based on ordering.\n4. Poll loop and scaling: check the `max.poll.records` / `max.poll.interval.ms` budget, the cooperative-sticky assignor (or the new group protocol), static membership, concurrency ≤ partitions, and replica caps.\n5. Ops: the shutdown timeout chain, lag/retry/DLT metrics and alerts, the liveness signal, and SASL/TLS settings sourced from secrets.\n6. Tests for the rule 15 matrix. PR notes cover the dedupe key per handler, the exception classification table, DLT names and owners, the poll-budget math, and residual risks.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/spring-kafka-consumer.instructions.md` with `applyTo` for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*Kafka*Config*.java`, `**/application*.{yml,yaml,properties}`, and topic manifests (`**/kafkatopic*.yaml`, `**/topics/**`).\n- Always-on line in `.github/copilot-instructions.md`: \"Kafka consumers are at-least-once: handlers are idempotent on a dedupe key, offsets commit after work, one DefaultErrorHandler with bounded backoff routes non-retryable and poison records to the DLT.\"\n- Optional `.github/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/spring-kafka-consumer-reliability-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Every Kafka record may arrive twice. Never ack before the side effect is durable, and never retry around the container's error handler.\"\n- Before claiming done, show the exception classification table, the DLT topic list with partition counts, and the passing duplicate / poison-pill / non-retryable tests.\n\n### Codex\n- Kafka consumer section in root `AGENTS.md`, or nested `src/main/java/**/messaging/AGENTS.md` (or linked `docs/agents/spring-kafka-consumer.md`).\n- State: ack mode policy, dedupe-key convention and inbox table, error handler and backoff defaults, retryable vs non-retryable lists, DLT naming and ownership, poll-budget rule, concurrency ≤ partitions, shutdown timeouts, and banned patterns (auto-commit, ack-before-work, nested retry loops, credentials in config).\n\n## Anti-patterns\n- `enable.auto.commit=true`, or acknowledging as soon as the record arrives \"so we don't block\"\n- Handlers that insert, charge, or email without any dedupe check because \"Kafka is exactly-once\"\n- Wrapping the listener in `@Retryable` or a Resilience4j retry on top of `DefaultErrorHandler`\n- `FixedBackOff` with unlimited attempts, so one bad record blocks a partition forever\n- No `ErrorHandlingDeserializer`, so a malformed payload fails at `poll()` in a tight loop\n- `@RetryableTopic` on a stream where per-key order matters, or on a batch listener\n- A DLT with fewer partitions than the source, auto-created with no retention, owner, or alert\n- Raising `max.poll.interval.ms` to hours instead of shrinking `max.poll.records` or fixing slow handlers\n- `concurrency=20` on a 6-partition topic, or KEDA scaling to more pods than partitions\n- Business exceptions that extend `Error`, or liveness that stays green after the listener thread died\n- SASL passwords in `application.yml`, ConfigMaps, or code; record payloads in logs or metric tags\n\n## Done when\n- [ ] Every handler has a documented dedupe key and an enforced idempotency mechanism (inbox, upsert, or natural)\n- [ ] Auto-commit is off, the ack mode is deliberate, and nothing is acknowledged before the side effect is durable\n- [ ] One `DefaultErrorHandler` with bounded backoff, explicit non-retryable exceptions, and a `DeadLetterPublishingRecoverer`\n- [ ] `ErrorHandlingDeserializer` wraps key and value, and JSON type trust is explicit (no `*`)\n- [ ] DLT (and any retry topics) are provisioned with partitions ≥ source, retention, an owner, alerts, and a replay note\n- [ ] The `max.poll.records` × p99 + backoff budget fits under `max.poll.interval.ms` with headroom\n- [ ] Concurrency × max replicas ≤ partitions; cooperative-sticky (or the new group protocol) and shutdown timeouts fit the pod grace period\n- [ ] Lag, retry, DLT, and dedupe-hit metrics are exported with bounded tags, and broker-side group lag is alerted\n- [ ] SASL_SSL/TLS configured, with credentials from secrets or Key Vault only and no payloads in logs\n- [ ] Tests cover the rule 15 matrix and pass in CI\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: spring-kafka-consumer-reliability-guardrails\ndescription: Use when writing or reviewing Spring for Apache Kafka consumers — at-least-once idempotent handlers, ack modes, DefaultErrorHandler backoff and exception classification, DLT and @RetryableTopic, poison pills, poll sizing, concurrency vs partitions, rebalance/shutdown, lag metrics, tests, and SASL/TLS.\n---\n\nFollow Spring Kafka Consumer Reliability Guardrails: assume at-least-once and make every handler idempotent on a dedupe key (inbox/outbox), commit after work with auto-commit off, one DefaultErrorHandler with bounded backoff and explicit non-retryable exceptions, DeadLetterPublishingRecoverer to an owned DLT with partitions ≥ source, ErrorHandlingDeserializer for poison pills, @RetryableTopic only when ordering doesn't matter, max.poll.records sized under max.poll.interval.ms, concurrency × replicas ≤ partitions, cooperative-sticky rebalances with shutdown inside the pod grace period, Micrometer lag/retry/DLT metrics with bounded tags, failure-path tests on Testcontainers or EmbeddedKafka, and SASL_SSL with credentials only from secrets.\n```\n" + }, + { + "id": "spring-boot-http-client-guardrails", + "title": "Spring Boot Outbound HTTP Client Guardrails", + "whenToUse": "Writing or reviewing outbound HTTP calls in Spring Boot (RestClient, WebClient, RestTemplate, HTTP interface clients) — connect, read, pool-wait and overall timeouts with a deadline budget, connection pool sizing and idle eviction, idempotent-only retries in one layer, circuit breakers, typed errors and body limits, OAuth2 and SSL bundle wiring, redirects, header propagation, URI-template metrics, and failure-path tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "http-client", + "restclient", + "webclient", + "resilience", + "timeouts", + "java" + ], + "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" } ] } From a6d992044c31d8b8a1e679e930518db126e8b2d4 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Wed, 21 Oct 2026 05:05:03 +0000 Subject: [PATCH 2/2] Add harden Spring outbound HTTP clients prompt --- promptbook/prompts.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 215621e..5845f51 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -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 `-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" } ] }