diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 64bea8b..5fbfea3 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -1002,6 +1002,26 @@ ], "formatNotes": "All three. Point the tool at every class with `@Scheduled` or `@EnableScheduling`, the scheduling and task config, `application*.yml`, `db/migration/`, the Deployment, HPA and any CronJob manifests or Kustomize overlays, and paste logs or metrics with job runtimes and any duplicate-run or missed-run incidents. Copilot: the scheduled jobs path instructions plus those files in agent mode (or save it as `.github/prompts/make-scheduled-jobs-replica-safe.prompt.md`). Claude Code: the scheduled-jobs-shedlock-guardrails skill plus the files. Codex: AGENTS.md scheduled jobs section, then the diff. The prompt adds locks and idempotency before any scale-out and moves long jobs to CronJobs one at a time.", "body": "Task: Make every recurring job in this Spring Boot service safe to run with several replicas on AKS or Kubernetes: each job runs once per intended interval, survives deploys and pod loss without losing or doubling work, stops inside its time box, and alerts when it stops succeeding. Finish with a job inventory, a placement decision per job, a code and manifest diff, tests, alerts, and a rollout plan.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service: {{SERVICE}} (e.g. orders-api; Spring Boot version, virtual threads on or off)\n- Database: {{DATABASE}} (e.g. Azure Database for PostgreSQL flexible server with Flyway)\n- Replicas: {{REPLICAS}} (pod count, HPA range, rollout strategy, terminationGracePeriodSeconds, preStop sleep)\n- Jobs: {{JOBS}} (each `@Scheduled` method, CronJob, or external trigger with its purpose)\n- Runtimes: {{RUNTIMES}} (typical and slowest run per job from logs or metrics, or \"unknown\")\n- Locking today: {{LOCKING}} (none, ShedLock, replicas: 1, hostname check, custom table)\n- Schedule zone: {{ZONE}} (e.g. UTC; business zone if a job must run at local wall-clock time)\n- Observability: {{OBSERVABILITY}} (e.g. Micrometer to Datadog or Prometheus, log shipping, kube-state-metrics)\n- Symptoms: {{SYMPTOMS}} (e.g. duplicate emails, overlapping runs, cleanup silently stopped, none yet)\n\nRequirements:\n\n1. Inventory every job\n - Table: class.method or CronJob name | trigger (cron, fixedRate, fixedDelay) and zone | typical and slowest runtime | side effects (DB writes, emails, external calls, files) | idempotent? | what happens if it runs twice | what happens if a tick is skipped | current lock\n - Flag unlocked `@Scheduled` methods on multi-replica services, `replicas: 1` or hostname workarounds, five-field cron in `@Scheduled` or six-field cron in a CronJob, implicit zones, and jobs that work on \"the last N minutes\"\n\n2. Placement per job\n - In-app `@Scheduled` + ShedLock for short, frequent jobs; Kubernetes `CronJob` for long, heavy, or nightly work; leader election only for continuous single-active workers; queue-driven when one run fans out to many items\n - Justify each choice from {{RUNTIMES}} and {{REPLICAS}}; mark assumptions\n\n3. In-app scheduling\n - Add ShedLock (`shedlock-spring`, `shedlock-provider-jdbc-template`) with a Flyway migration for the `shedlock` table (name as primary key) and `JdbcTemplateLockProvider` using `.usingDbTime()`\n - `@EnableSchedulerLock(defaultLockAtMostFor = ...)`; per job `@SchedulerLock` with a stable name, `lockAtMostFor` 3-5x the slowest run, `lockAtLeastFor` just under the interval for very short jobs, and `LockAssert.assertLocked()` as the first line\n - Scheduling config guarded by `app.scheduling.enabled`; cron and intervals moved to config with an explicit `zone`; `fixedDelay` where \"after finishing\" is meant\n - `spring.task.scheduling.pool.size`, `thread-name-prefix`, and `shutdown.await-termination` with a period that fits inside terminationGracePeriodSeconds minus preStop from {{REPLICAS}}; note what changes if virtual threads are on\n\n4. Make the work idempotent\n - Replace \"this tick\" windows with a durable watermark or pending-row state\n - Bounded chunks in short transactions, `FOR UPDATE SKIP LOCKED` where several workers may claim rows, a time budget check between chunks that ends the run before `lockAtMostFor`\n - Dedupe external side effects (emails, webhooks, files) with a run key or sent-marker; never rely on the lock alone\n\n5. CronJobs\n - Manifest (Kustomize or plain YAML matching the repo) with `concurrencyPolicy: Forbid`, `startingDeadlineSeconds`, `timeZone`, history limits, `backoffLimit`, `activeDeadlineSeconds`, `ttlSecondsAfterFinished`, `restartPolicy: Never`, and a `podFailurePolicy` for non-retryable exit codes\n - Same image with a job profile: no web server, scheduling off, an `ApplicationRunner` for the task, exit through `SpringApplication.exit` with an `ExitCodeGenerator`\n - Own service account and workload identity, requests and memory limit, and sidecar handling so the pod completes\n - Use the `batch.kubernetes.io/cronjob-scheduled-timestamp` annotation as logical run time where the cluster supports it\n\n6. Observability\n - Structured log line per run: job, run id, logical time, items processed, duration, outcome, error class\n - Metrics: run duration and outcome (`tasks.scheduled.execution` or custom timers), lock acquired vs skipped, items processed, last-success timestamp gauge per job\n - Alerts from {{OBSERVABILITY}}: no success within 2-3 intervals, failure count, run duration near `lockAtMostFor` or `activeDeadlineSeconds`, failed CronJob Jobs\n\n7. Tests\n - Testcontainers database with two application contexts (or two lock providers) firing the same job: exactly one run per tick\n - A run that crashes mid-way is resumed by the next run without duplicate side effects\n - A skipped tick is caught up by the following run\n - Graceful shutdown waits for an in-flight chunk; CronJob entry point returns non-zero on failure\n - Scheduling disabled in the default test profile\n\n8. Rollout\n - Deploy ShedLock table and locks before scaling out or removing `replicas: 1` and hostname checks\n - Mixed-version window during the rolling update: same lock names for compatible jobs, new names plus a flag for changed ones\n - Move long jobs to CronJobs one at a time with the in-app trigger disabled by config, and a rollback plan\n\nConstraints:\n- Do not invent runtimes, intervals, or SLOs; use placeholders and list what must be measured.\n- Do not present ShedLock or `concurrencyPolicy: Forbid` as exactly-once; every job must tolerate a duplicate run.\n- Do not fix duplicates with `replicas: 1`, pod-0 checks, or disabling the HPA.\n- Minimal diff; no unrelated refactors.\n- Optimize for GitHub Copilot, Claude Code, and Codex: give concrete files and a checklist.\n\nOutput format:\n1. Job inventory table with risks\n2. Placement decision per job with assumptions marked\n3. Patch: dependencies, Flyway migration, scheduling config, job changes, application.yml, CronJob manifests\n4. Idempotency and watermark changes\n5. Metrics, alerts, and log fields\n6. Tests\n7. Rollout plan, risks, and follow-ups\n\nStart with the inventory. Prove the two-instance single-run test passes before scaling the deployment out.\n" + }, + { + "id": "harden-azure-service-bus-consumer", + "title": "Harden an Azure Service Bus Consumer (Spring Boot)", + "whenToUse": "Make a Spring Boot Azure Service Bus consumer production-safe (PeekLock, settle only after a durable side effect, abandon versus dead-letter, an owned DLQ, idempotent handlers, lock renewal versus processing time, prefetch and concurrency, sessions or competing consumers, graceful shutdown, DLQ and lock-lost metrics) and produce a minimal diff with failure-path tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "java", + "azure-service-bus", + "messaging", + "reliability", + "idempotency" + ], + "formatNotes": "All three. Point the tool at `application.yml`/`application.properties` (`spring.cloud.azure.servicebus.*` or `spring.cloud.stream.servicebus.*`), the processor or listener classes, settlement code, any inbox migration, and the Bicep or ARM that creates the queue or subscription (lock duration, max delivery count, sessions, duplicate detection). Keep test harness conventions aligned with spring-boot-testcontainers. Copilot: azure-service-bus-consumer path instructions plus those files in agent mode. Claude Code: the azure-service-bus-consumer-reliability-guardrails skill plus the listener, config, and entity files. Codex: AGENTS.md Service Bus consumer section, then the diff.", + "body": "Task: Harden the Azure Service Bus consumer(s) I specify so they are safe in production. Use PeekLock, make each handler idempotent under at-least-once delivery, and complete only after the side effect is durable. Abandon recoverable failures, dead-letter poison messages with a reason, and keep an owner on the dead-letter queue. Size locks, prefetch, and concurrency to real processing time, and make shutdown stop receiving without completing after a lost lock. Finish with a minimal diff I can open as a PR, plus tests for redelivery, dead-letter, and lock-lost.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service root / module: {{APP_PATH}}\n- Spring Boot / Spring Cloud Azure (or Stream binder) version: {{BOOT_VERSION}} (e.g. Boot 3.4 / Spring Cloud Azure 5.18 | unknown)\n- Listeners in scope: {{LISTENERS}} (bean or binding name → queue or topic, processor | manual receiver | JMS)\n- Entity: {{ENTITY}} (queue name, or topic + subscription; sessions on or off; partitioned or not)\n- Lock duration and renewal: {{LOCK_DURATION}} (entity lock, max-auto-lock-renew-duration, or \"unknown\")\n- Max delivery count: {{MAX_DELIVERY}} (entity setting, default 10 if unset)\n- Prefetch and concurrency: {{SIZING}} (prefetch-count, max-concurrent-calls, max-concurrent-sessions, replica / HPA range)\n- Side effects per handler: {{SIDE_EFFECTS}} (db-write | http-call | publish | email | none)\n- Dedupe key available: {{DEDUPE_KEY}} (MessageId | application property | business key | none | unknown)\n- Ordering requirement: {{ORDERING}} (per-key FIFO required | order irrelevant)\n- Client stack: {{CLIENT}} (Spring Cloud Azure processor | Spring Cloud Stream Service Bus binder | azure-messaging-servicebus processor | manual receiver)\n- Broker extras: {{BROKER}} (duplicate detection window | dead-letter on expiration | none | unknown)\n- Pain points: {{PAIN}} (duplicates | lost-messages | dlq-growth | lock-lost | stuck-active | none)\n\nRequirements:\n\n1. Inventory\n - Read {{APP_PATH}} build file, `application*.yml|properties` (`spring.cloud.azure.servicebus.*` and `spring.cloud.stream.servicebus.*`), every processor, `@ServiceBusListener` or binder consumer, and any hand-rolled `ServiceBusReceiverClient` loop\n - Record per listener: receive mode, auto-complete, who calls complete / abandon / deadLetter, prefetch, max concurrent calls, sessions, lock renewal, and what each side effect does\n - Find catch-all handlers that log and return, completes that run before the database commit, and any `ReceiveAndDelete`\n - Note IaC for {{ENTITY}}: lock duration, max delivery count, sessions required, duplicate detection, dead-letter on expiration. Note metrics, alerts, and where the namespace credential or connection string comes from\n\n2. Findings (rank by risk: non-idempotent side effects > ReceiveAndDelete or complete-before-commit or catch-and-complete > poison messages with no reason > unowned DLQ or blind replay > lock budget or prefetch > sessions versus ordering > shutdown > observability and tests > secrets in config)\n - Side effects with no dedupe key or inbox, so a redelivery double-charges, double-inserts, or double-sends\n - `RECEIVE_AND_DELETE` on work that cannot be lost, or complete (including auto-complete) before the side effect is durable\n - `catch (Exception)` that completes or returns normally, so a failure is settled as success\n - Manual `complete` while `auto-complete` is still true\n - No handler dead-letter for poison input, so messages sit until `MaxDeliveryCountExceeded` with no useful reason\n - No reader, owner, or alert on the `$deadletterqueue` sub-queue, or a replay that resends the same `MessageId` inside {{BROKER}} duplicate detection\n - `max-auto-lock-renew-duration` and {{LOCK_DURATION}} shorter than p99, or prefetch large enough that messages expire in the client buffer\n - Sessions missing where {{ORDERING}} is per-key FIFO, or sessions enabled while publishers omit `SessionId`\n - `replicas: 1` (or a hostname check) used as the duplicate fix\n - Shutdown timeout longer than the pod grace period, or a complete attempted after `MessageLockLost`\n - Connection strings in Git, ConfigMaps, or code; message bodies in logs or metric tags\n\n3. Fix — settlement\n - Set receive mode to PeekLock on every listener in {{LISTENERS}} that has a side effect. Leave receive-and-delete only where the team has written down that loss is acceptable\n - For {{CLIENT}}, turn `auto-complete` off if the handler settles itself (`processor.auto-complete=false`, binding `consumer.auto-complete=false` plus the `Checkpointer`, or `disableAutoComplete()`). If auto-complete stays on, the method must commit before it returns and must not swallow exceptions\n - Complete only after the side-effect transaction commits. Abandon on recoverable failures. Dead-letter poison failures with `DeadLetterReason` and a short `DeadLetterErrorDescription` (a code, not the payload)\n - On `MESSAGE_LOCK_LOST` or `SESSION_LOCK_LOST`, return without complete, abandon, or dead-letter\n\n4. Fix — idempotency\n - For each handler in {{SIDE_EFFECTS}}, use {{DEDUPE_KEY}} (or propose one). Add an inbox table with a unique `(consumer, message_id)` constraint, written in the same database transaction as the side effect, or an upsert on the business key\n - A conflict means the work is already durable: complete and skip\n - Route outbound events through an outbox in that same transaction. Do not treat broker duplicate detection as the consumer lock; it only collapses duplicate sends\n\n5. Fix — retry and DLQ\n - Keep {{MAX_DELIVERY}} as the backstop for abandons and expired locks. Dead-letter classified poison on the first attempt so the reason is yours, not only `MaxDeliveryCountExceeded`\n - Add a DLQ reader (processor `sub-queue` = dead-letter sub-queue, SDK `SubQueue.DEAD_LETTER_QUEUE`) that records reason, message id, and delivery count. It alerts; it does not auto-replay\n - Document replay: read `DeadLetterReason` first. If {{BROKER}} has duplicate detection, resend under a new `MessageId` and keep the original id in an application property the inbox already uses\n\n6. Fix — sizing\n - From {{LOCK_DURATION}} and measured p99, set the entity lock above a normal attempt (it cannot exceed five minutes) and `max-auto-lock-renew-duration` above p99 plus downstream waits. Do not park the lock at five minutes to avoid renewal\n - Set `prefetch-count` to 0 for slow handlers, or a small multiple of `max-concurrent-calls` once lock-lost stays flat\n - Set `max-concurrent-calls` so {{SIZING}} replicas times in-flight handlers fit CPU and the connection pool. With sessions, that limit is per session; set `max-concurrent-sessions` and a `session-idle-timeout` above a normal handler\n - Enable sessions only when {{ORDERING}} is per-key FIFO. Otherwise competing consumers on {{ENTITY}}. Remove any `replicas: 1` workaround\n\n7. Fix — shutdown, metrics, credentials\n - Stop the processor before waiting for in-flight callbacks. Keep `spring.lifecycle.timeout-per-shutdown-phase` and the client close timeout under `terminationGracePeriodSeconds` minus preStop. Do not complete after the lock is lost\n - Export handler latency and counters for complete, abandon, dead-letter, lock-lost, and dedupe hits, with tags limited to entity, subscription, and outcome. Note the Azure Monitor alerts to add: dead-letter count rising, active count high while complete rate is flat\n - Namespace plus workload-identity or another `TokenCredential`. Any remaining connection string comes from Key Vault or a secret, referenced by placeholder. Log message id, delivery count, and outcome, never the body\n\n8. Tests\n - Unit tests with a fake settlement context: same message twice → one side effect and a second complete; poison → `deadLetter` with the expected reason and no complete; lock-lost mid-handler → no settlement; a commit followed by lock-lost → the next delivery is an inbox no-op\n - One integration test on the Service Bus emulator via Testcontainers (or the emulator container) for peek-lock complete, abandon then redelivery, and a message on the dead-letter sub-queue. No shared namespace. Awaitility, no fixed sleeps\n - Call out emulator gaps (sessions, duplicate detection, partitioning) instead of pretending the emulator is Premium\n\n9. Verification and the PR diff\n - Settlement table: exception or outcome → complete / abandon / dead-letter / stop\n - Entity table: {{ENTITY}} lock duration, max delivery count, sessions, duplicate detection, DLQ owner\n - Lock budget: p99, entity lock, renewal duration, prefetch, concurrency times replicas\n - Metrics and alerts list, and confirmation that no connection string or body appears in config, logs, or tags\n - The diff stays minimal: extend the existing processor or binding, the inbox migration, and the tests. No second client stack and no new messaging framework\n\nConstraints:\n- Minimal diff. Do not replace a working processor with a hand-rolled receive loop, or a receive loop with a new framework, unless the current loop cannot settle safely.\n- Do not invent namespace names, entity names, lock durations, or delivery counts. Use placeholders when {{LOCK_DURATION}} or {{MAX_DELIVERY}} is unknown, and list what to measure.\n- Do not claim exactly-once. Duplicate detection and an inbox are different tools; the handler still has to be idempotent.\n- Do not fix duplicates with `replicas: 1`.\n- Optimize for GitHub Copilot, Claude Code, and Codex: concrete diffs and a checklist.\n- Leave entity changes and alert rules as follow-up notes unless the repo already manages that IaC.\n\nOutput format:\n1. Findings table: severity | location | issue | fix\n2. Patch (receive mode and auto-complete, settlement changes, inbox migration, DLQ reader or runbook note, sizing, shutdown, metrics)\n3. Tests added and their results\n4. Settlement table, entity table, lock-budget math, and follow-ups (alerts, replay runbook, emulator gaps)\n\nStart from {{APP_PATH}}. Fix non-idempotent side effects and complete-before-commit before tuning prefetch or metrics." } ] } diff --git a/skillbook/skills.json b/skillbook/skills.json index f20250f..27acea6 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -1000,6 +1000,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/scheduled-jobs.instructions.md` with applyTo for `**/*Job.java`, `**/scheduling/**`, `**/*Scheduler*.java`, `**/cronjob*.{yml,yaml}`, `**/db/migration/**`, and `**/application*.yml`, or `.github/skills/scheduled-jobs-shedlock-guardrails/SKILL.md`; one always-on line in `.github/copilot-instructions.md` (\"every @Scheduled method on this multi-replica service needs @SchedulerLock and must be idempotent; never fix duplicates with replicas: 1\"). Claude Code: `.claude/skills/scheduled-jobs-shedlock-guardrails/SKILL.md`, plus a CLAUDE.md line naming the lock table, the scheduling on/off property, and which jobs run as CronJobs. Codex: a \"Scheduled jobs\" section in root `AGENTS.md` (or the same SKILL.md under `.agents/skills/`). Pair with k8s-probes-graceful-shutdown-guardrails for grace periods, transactional-outbox-guardrails for relay leadership, hikari-connection-pool-guardrails for job connection demand, flyway-migration-guardrails for the lock table, java-virtual-threads-spring-guardrails if virtual threads are on, and spring-boot-testcontainers for the multi-instance test. This skill owns when and where recurring work runs and proving it runs once.", "body": "# Skill: Scheduled Job Guardrails for Spring Boot on AKS (ShedLock vs Kubernetes CronJob)\n\n## Goal\nEvery recurring job runs once per intended interval across all replicas, survives deploys, pod evictions and scale events without losing or doubling work, finishes or stops cleanly inside its time box, and pages someone when it silently stops running.\n\n## When to apply\n- A Spring Boot service has `@EnableScheduling` and `@Scheduled` methods and runs with more than one replica, an HPA, or blue/green or canary rollouts\n- Someone proposes \"set replicas to 1\" or \"only run on pod 0\" to stop duplicate runs\n- Adding a nightly report, cleanup, reconciliation, token refresh, outbox relay, or export job\n- Deciding between an in-app scheduler with ShedLock and a Kubernetes `CronJob`\n- Incidents like \"the report was emailed three times\", \"cleanup has not run since Tuesday\", or \"the job overlapped itself and deadlocked\"\n\n## The rule\nA scheduler only decides *when* to try. Correctness comes from the job itself: it is idempotent, works from a durable watermark instead of \"this tick\", processes bounded chunks in short transactions, and records its last success. Locks (ShedLock) and `concurrencyPolicy: Forbid` reduce duplicates; they are not fencing and never a substitute for idempotency.\n\n## Choose where the job runs\n\n| Option | Fits when | Watch out for |\n|---|---|---|\n| In-app `@Scheduled` + ShedLock (JDBC lock table) | Short to medium jobs (seconds to a few minutes) that need the service's beans, DB and config; frequent intervals | Runs on every replica unless locked; competes with request traffic for CPU, heap and DB connections; deploys interrupt runs |\n| Kubernetes `CronJob` running the same image in a job profile | Long, heavy, or nightly jobs; needs its own resources, identity, or retries; clear audit of each run | Minimum 1-minute resolution; a run can occasionally be created twice or skipped; cold start per run; sidecars must exit |\n| Leader election (Kubernetes Lease via Spring Cloud Kubernetes or Spring Integration leader) | Continuous single-active workers (pollers, relays) rather than discrete ticks | Split-brain windows during lease handover; the work still has to be idempotent |\n| Queue-driven worker (scheduler only enqueues) | Fan-out work or many items per run | Needs dedupe on the enqueue side |\n\nDefault: in-app + ShedLock for jobs under ~5 minutes that run at least hourly; `CronJob` for anything longer, resource-heavy, or nightly batch.\n\n## Baseline rules (in-app scheduling)\n1. **Every `@Scheduled` method on a multi-replica service has `@SchedulerLock`.** Use a stable, unique `name` (max 64 chars, no version or pod name in it). Call `LockAssert.assertLocked()` as the first line so a missing proxy or annotation fails loudly instead of running everywhere.\n2. **Use DB time.** `JdbcTemplateLockProvider` with `.usingDbTime()` so pod clock skew cannot grant two locks. Create the `shedlock` table through Flyway, with `name` as the primary key, in the service's own database. Never share one lock table across environments.\n3. **Size `lockAtMostFor` from measured p99 runtime, not hope.** Set it well above the slowest run (for example 3-5x p99) and below the interval for interval jobs. It is the crash safety net: if a run outlives it, another replica starts a second run. Set `lockAtLeastFor` to just under the interval for very short jobs so clock jitter between replicas cannot double-run one tick. Set `@EnableSchedulerLock(defaultLockAtMostFor = ...)` as a conservative default.\n4. **Remember ShedLock skips, it does not queue.** A replica that cannot get the lock does nothing for that tick. Design for \"next successful run catches up\": read from a watermark (`last_processed_at`, a high-water id, or pending rows) rather than \"process the last 15 minutes\".\n5. **Give scheduling its own pool and config.** Spring Boot's default scheduler has one thread (`spring.task.scheduling.pool.size=1`), so one slow job delays every other job. Size the pool to the number of jobs that may run at once, name the threads, and set `spring.task.scheduling.shutdown.await-termination=true` with a period shorter than `terminationGracePeriodSeconds` minus the preStop sleep. With `spring.threads.virtual.enabled=true` Boot switches to a virtual-thread scheduler and the pool size no longer applies; check jobs for pinning and connection pool pressure.\n6. **Prefer `fixedDelay` for \"run again after finishing\"; use cron only for wall-clock times.** Spring cron has six fields (seconds first), unlike five-field Kubernetes cron. Set `zone = \"UTC\"` (or an explicit zone) on every cron; avoid 01:00-03:00 local times in zones with DST, which skip or repeat. Put intervals and cron expressions in config (`${jobs.cleanup.cron}`) so ops can change them, and support `-` to disable a cron job.\n7. **Chunk the work.** Process bounded batches (for example 500 rows) in short transactions, claim rows with `FOR UPDATE SKIP LOCKED` when several workers might touch them, and check a time budget between chunks so the run stops before `lockAtMostFor`. Never hold one transaction or DB connection for the whole run; keep the job's pool demand inside HikariCP headroom.\n8. **Fail visibly, not silently.** An exception in a `@Scheduled` method is logged and the schedule continues, so failures vanish. Catch at the job boundary, log a structured line with job name, run id, items processed, duration and outcome, increment a failure counter, and rethrow or record the failure.\n9. **Instrument success, not just errors.** Spring Framework 6.1+ records `tasks.scheduled.execution` observations for `@Scheduled` methods when an `ObservationRegistry` is present; add `shedlock-micrometer` or your own metrics for lock acquired vs skipped. Publish a `job_last_success_timestamp_seconds{job}` gauge (or persist it in a `job_run` table) and alert when it is older than 2-3 intervals: a dead man's switch catches jobs that stopped being scheduled at all.\n10. **Make jobs switchable.** Put `@EnableScheduling` on a config class guarded by a property (`app.scheduling.enabled`) so tests, local dev, one-off admin pods, and incident response can turn it off. Keep the Actuator `scheduledtasks` endpoint internal only.\n11. **Deploys run two versions at once.** During rolling updates and blue/green, old and new pods share the lock table by job name; a job whose logic changed incompatibly needs a new lock name and a migration plan, or a feature flag.\n\n## Baseline rules (Kubernetes CronJob)\n1. `concurrencyPolicy: Forbid` unless overlapping runs are proven safe; `Replace` kills a running job mid-work.\n2. Set `startingDeadlineSeconds` (at least 10, for example 300) so a controller outage does not start a stale run hours late or record `TooManyMissedTimes`.\n3. Set `timeZone: \"Etc/UTC\"` (stable since Kubernetes 1.27) instead of relying on the controller's zone; never put `TZ=` or `CRON_TZ=` in `schedule`.\n4. In `jobTemplate`: `backoffLimit` small and deliberate (default 6 retries is often too many for non-idempotent work), `activeDeadlineSeconds` as the hard time box, `ttlSecondsAfterFinished` for cleanup, `restartPolicy: Never` so retries are new pods with clean logs, and a `podFailurePolicy` that does not retry exit codes meaning \"bad input\".\n5. Run the service image with a job profile: `spring.main.web-application-type=none`, scheduling disabled, run the task from an `ApplicationRunner`, and exit with `System.exit(SpringApplication.exit(ctx))` and an `ExitCodeGenerator` so failures surface as a non-zero exit code. On AKS with a mesh, use native sidecars or make sure the proxy exits, or the Job never completes.\n6. Give it its own resources, service account and workload identity, and keep history small (`successfulJobsHistoryLimit: 3`, `failedJobsHistoryLimit: 3`). Alert on failed Jobs and on no successful Job within the expected window (kube-state-metrics `kube_cronjob_status_last_successful_time` or your own gauge).\n7. Kubernetes may occasionally create two Jobs for one schedule or none, so the job must still be idempotent. On 1.32+ read the `batch.kubernetes.io/cronjob-scheduled-timestamp` annotation (via the downward API) as the run's logical time.\n\n## Copy-ready baseline\n```java\n@Configuration\n@EnableScheduling\n@EnableSchedulerLock(defaultLockAtMostFor = \"PT10M\")\n@ConditionalOnProperty(name = \"app.scheduling.enabled\", havingValue = \"true\", matchIfMissing = true)\nclass SchedulingConfig {\n @Bean\n LockProvider lockProvider(DataSource dataSource) {\n return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder()\n .withJdbcTemplate(new JdbcTemplate(dataSource))\n .usingDbTime()\n .build());\n }\n}\n\n@Component\nclass ExpiredSessionCleanupJob {\n @Scheduled(cron = \"${jobs.session-cleanup.cron:0 */15 * * * *}\", zone = \"UTC\")\n @SchedulerLock(name = \"session-cleanup\", lockAtMostFor = \"PT12M\", lockAtLeastFor = \"PT1M\")\n void run() {\n LockAssert.assertLocked();\n Instant deadline = Instant.now().plus(Duration.ofMinutes(8));\n int deleted;\n do {\n deleted = repository.deleteExpiredBatch(500); // short transaction per chunk\n processed.increment(deleted);\n } while (deleted == 500 && Instant.now().isBefore(deadline));\n lastSuccess.set(Instant.now().getEpochSecond());\n }\n}\n```\n\n```yaml\nspring:\n task:\n scheduling:\n pool.size: 4\n thread-name-prefix: sched-\n shutdown:\n await-termination: true\n await-termination-period: 20s\n```\n\nFlyway (PostgreSQL):\n```sql\ncreate table shedlock (\n name varchar(64) not null primary key,\n lock_until timestamp not null,\n locked_at timestamp not null,\n locked_by varchar(255) not null\n);\n```\n\nKubernetes CronJob:\n```yaml\napiVersion: batch/v1\nkind: CronJob\nmetadata:\n name: orders-nightly-export\nspec:\n schedule: \"30 20 * * *\"\n timeZone: \"Etc/UTC\"\n concurrencyPolicy: Forbid\n startingDeadlineSeconds: 600\n successfulJobsHistoryLimit: 3\n failedJobsHistoryLimit: 3\n jobTemplate:\n spec:\n backoffLimit: 2\n activeDeadlineSeconds: 3600\n ttlSecondsAfterFinished: 86400\n template:\n metadata:\n labels:\n azure.workload.identity/use: \"true\"\n spec:\n serviceAccountName: orders-export\n restartPolicy: Never\n containers:\n - name: export\n image: myacr.azurecr.io/orders-api:1.8.3\n args: [\"--spring.profiles.active=job,export\", \"--spring.main.web-application-type=none\"]\n resources:\n requests: { cpu: \"500m\", memory: \"1Gi\" }\n limits: { memory: \"1Gi\" }\n```\n\n## Review checklist\n- [ ] Each job has a placement decision (in-app + ShedLock, CronJob, leader election, queue) written down\n- [ ] Every `@Scheduled` method on a multi-replica service has `@SchedulerLock` with a stable name and `LockAssert.assertLocked()`\n- [ ] Lock provider uses DB time; lock table created by Flyway with a primary key\n- [ ] `lockAtMostFor` sized from measured runtime; `lockAtLeastFor` set for short jobs\n- [ ] Job is idempotent, works from a watermark, chunks work in short transactions, and stops on a time budget\n- [ ] Scheduler pool sized and named; graceful shutdown fits inside `terminationGracePeriodSeconds`\n- [ ] Cron expressions in config with an explicit zone; no DST-gap times\n- [ ] Failures logged with job name, run id, counts, outcome; failure counter exported\n- [ ] Last-success gauge or table with a \"not run in N intervals\" alert\n- [ ] Scheduling can be disabled by property; tests run with it off\n- [ ] CronJob: `Forbid`, `startingDeadlineSeconds`, `timeZone`, `backoffLimit`, `activeDeadlineSeconds`, `ttlSecondsAfterFinished`, `restartPolicy: Never`, exit codes, own identity\n- [ ] Test proves two app instances against one Testcontainers database run a tick once\n\n## Anti-patterns\n- `replicas: 1` or \"only on pod-0\" hostname checks as the duplicate-run fix\n- `@Scheduled` on a multi-replica service with no lock, or a lock with a pod-specific name\n- `lockAtMostFor` shorter than a slow run, or ShedLock treated as a fencing token for non-idempotent side effects\n- Jobs that process \"the last N minutes\" and lose work whenever a tick is skipped\n- One long transaction or connection held for the whole run\n- Five-field cron pasted into `@Scheduled`, or six-field cron pasted into a CronJob\n- `concurrencyPolicy: Allow` (the default) with non-idempotent jobs, or no `activeDeadlineSeconds`\n- Swallowed exceptions with no metric, and no alert when a job stops running\n- A CronJob pod that never completes because a sidecar keeps running\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: scheduled-jobs-shedlock-guardrails\ndescription: Use when adding or reviewing recurring jobs in a Spring Boot service on AKS or Kubernetes: choosing in-app @Scheduled with ShedLock vs a Kubernetes CronJob vs leader election, lock names and LockAssert, DB-time locks, lockAtMostFor and lockAtLeastFor sizing, idempotent watermark-based chunked work, scheduler pool and graceful shutdown, cron zones and DST, CronJob concurrencyPolicy, startingDeadlineSeconds, timeZone, backoffLimit and activeDeadlineSeconds, last-success alerts, and multi-instance tests.\n---\n\nFollow Scheduled Job Guardrails: decide per job whether it runs in-app with ShedLock (short, frequent), as a Kubernetes CronJob (long, heavy, nightly), or behind leader election (continuous single worker). On multi-replica services every @Scheduled method gets @SchedulerLock with a stable name, LockAssert.assertLocked(), a JdbcTemplateLockProvider using DB time, and lockAtMostFor sized well above measured runtime; ShedLock skips rather than queues and is not fencing, so jobs are idempotent, read from a durable watermark, process bounded chunks in short transactions, and stop on a time budget. Size and name the scheduler pool, wait for tasks on shutdown within the pod grace period, keep cron in config with an explicit zone, and allow scheduling to be disabled by property. CronJobs use concurrencyPolicy Forbid, startingDeadlineSeconds, timeZone Etc/UTC, a small backoffLimit, activeDeadlineSeconds, ttlSecondsAfterFinished, restartPolicy Never, non-web job profile with real exit codes, and their own identity. Log every run with job name, run id, counts and outcome, export a last-success timestamp, and alert when a job has not succeeded in 2-3 intervals. Prove with Testcontainers that two instances run one tick once.\n```\n" + }, + { + "id": "azure-service-bus-consumer-reliability-guardrails", + "title": "Azure Service Bus Consumer Reliability Guardrails (Spring Boot)", + "whenToUse": "Writing or reviewing Spring Boot consumers of Azure Service Bus queues or topic subscriptions — PeekLock settlement, complete only after a durable side effect, abandon vs dead-letter, MaxDeliveryCount and the system DLQ, lock duration and auto-renewal, prefetch and concurrency, idempotent handlers, sessions vs competing consumers, graceful shutdown, DLQ and lock-lost metrics, and tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "java", + "azure-service-bus", + "messaging", + "reliability", + "idempotency" + ], + "formatNotes": "All three. Copilot: path-scoped `.github/instructions/azure-service-bus-consumer.instructions.md` with applyTo for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*ServiceBus*Config*.java`, `**/application*.{yml,yaml,properties}`, and Service Bus IaC (`**/*servicebus*.bicep`, `**/servicebus*.json`). Optional `.github/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md`. Claude Code: `.claude/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md` plus a CLAUDE.md fact that every Service Bus message may arrive twice and nothing is completed before the side effect is durable. Codex: a Service Bus consumer section in root `AGENTS.md` or nested `src/main/java/**/messaging/AGENTS.md`. Pair with transactional-outbox-guardrails for publishing (this skill owns consuming), spring-kafka-consumer-reliability-guardrails as the Kafka contrast (offsets and DLTs vs settlement and the system DLQ), k8s-probes-graceful-shutdown-guardrails for the shutdown timeout chain, azure-key-vault-app-integration for connection strings or certificates, spring-boot-testcontainers for the emulator harness, and hikari-connection-pool-guardrails for concurrency vs pool size. This skill owns consumer delivery semantics, settlement, DLQ, and lock handling — not outbox publishing.", + "body": "# Skill: Azure Service Bus Consumer Reliability Guardrails (Spring Boot)\n\n## Goal\nMake Spring Boot consumers of Azure Service Bus safe to run as several replicas. Under PeekLock the broker delivers at least once: a crash, an abandon, or a lost lock all show up as another delivery. Complete a message only after the side effect is durable, abandon what can succeed on a later try, and dead-letter what never will. Locks, prefetch, and concurrency stay inside what the handler can finish. The dead-letter queue has an owner, and duplicates are stopped in the handler.\n\nThis skill owns consumer delivery, settlement, the dead-letter queue, and lock handling. Publishing, the outbox relay, and broker-side duplicate detection on send stay in **transactional-outbox-guardrails**. Settlement here (complete, abandon, dead-letter) is the Service Bus counterpart of a Kafka offset commit, and the system dead-letter sub-queue is the counterpart of a dead-letter topic, with different mechanics (see **spring-kafka-consumer-reliability-guardrails**).\n\n## When to apply\n- A new queue or subscription listener, or a review of a `ServiceBusProcessorClient`, a Spring Cloud Azure processor, or a Spring Cloud Stream Service Bus binding\n- Incidents: double charges, lost messages, a growing dead-letter queue, `MessageLockLost`, or a consumer that looks healthy while the active count climbs\n- Choosing sessions for per-key order versus competing consumers for throughput\n- AKS rollouts where the pod grace period is shorter than in-flight work\n- Anyone reaching for `ReceiveAndDelete`, `replicas: 1`, or a catch-all that completes\n\n## Baseline rules\n1. **PeekLock for anything with a side effect.** `PEEK_LOCK` locks the message and leaves it on the entity until you settle it. `RECEIVE_AND_DELETE` removes it the moment the client receives it: a crash, a timeout, or a failed commit, and the work is gone. Use receive-and-delete only for data you can drop (a sample, a heartbeat). Spring Cloud Azure: `spring.cloud.azure.servicebus.processor.receive-mode=peek_lock`. The Stream binder default is already `spring.cloud.stream.servicebus.bindings..consumer.receive-mode=peek_lock`; leave it there. On the Java builder, `receiveMode(ServiceBusReceiveMode.PEEK_LOCK)`. If the app still uses the JMS starter, the same rule applies: acknowledge only after commit, and avoid a mode that settles on receive.\n\n2. **Settle only after the side effect is durable.** Complete removes the message. Abandon releases it now and increments the delivery count so another competing consumer can try. Dead-letter moves it to the system DLQ with a short `DeadLetterReason` and `DeadLetterErrorDescription` an operator can act on: a stable code, not the payload and not personal data. The order is: do the work in one transaction, commit, then complete. Completing and then writing loses the message when the write fails. Abandon (or let the exception propagate while auto-complete is on) for recoverable failures: timeouts, deadlocks, 503s, a full pool. Dead-letter on the first attempt when another try cannot help: schema mismatch, validation, a business rule that fails forever. Defer is not a retry mechanism. A deferred message leaves the normal receive path and comes back only if you stored its sequence number.\n\n3. **Auto-complete is a contract.** The processor completes when the callback returns and abandons when it throws. On the Stream binder `auto-complete` defaults to true. That is safe only when the durable write finished before the return and failures are not swallowed. The moment the handler calls `complete`, `abandon`, or `deadLetter` itself, turn auto-complete off: `spring.cloud.azure.servicebus.processor.auto-complete=false`, or `consumer.auto-complete=false` on the binding (the binder then passes a `Checkpointer`), or `disableAutoComplete()` on `ServiceBusProcessorClientBuilder`. Manual complete while auto-complete is still on settles twice. Catching `Exception`, logging, and returning completes a failed message. Let recoverable exceptions propagate, or abandon explicitly.\n\n4. **MaxDeliveryCount and a DLQ you own.** The entity max delivery count (default 10) is the broker's backstop. Abandon, and a lock that expires because the handler was too slow, both count toward it. Past the limit, Service Bus dead-letters the message with reason `MaxDeliveryCountExceeded`. Expired messages land in the DLQ only when the entity dead-letters on message expiration (`TTLExpiredException`); otherwise they disappear. Read `getDeadLetterReason()` and `getDeadLetterErrorDescription()` before any replay. A poison message you can already classify should be dead-lettered by the handler with your own reason, so the queue does not fill with an opaque max-delivery reason. Own the `$deadletterqueue` sub-queue: a separate processor whose `sub-queue` is the dead-letter sub-queue (SDK `SubQueue.DEAD_LETTER_QUEUE`), or an operator tool. It records reason, message id, and delivery count, and it pages someone. It does not auto-replay. Replay is a deliberate resend after the bug is fixed. If the entity has duplicate detection, resending the same `MessageId` inside the detection window is dropped, and completing the DLQ copy then loses the message. Keep the original id in an application property the inbox already keys on, and send the replay under a new `MessageId`.\n\n5. **Lock duration versus processing time.** The queue or subscription lock duration defaults to one minute and cannot exceed five minutes. Each renewal extends the lock by that same duration, and the last successful renewal still holds for one lock duration after the renewal task stops. `maxAutoLockRenewDuration` (property `max-auto-lock-renew-duration`, binder default five minutes) is how long the client keeps renewing. `Duration.ZERO` turns renewal off. Receive-and-delete has no lock to renew. Size the pair from measured p99: the entity lock above a normal attempt, the renewal budget above p99 plus downstream waits, with headroom. A dead pod holds the message until the current lock lapses, so a five-minute lock is not a substitute for renewal. On `ServiceBusFailureReason.MESSAGE_LOCK_LOST` or `SESSION_LOCK_LOST`, stop the handler and do not complete, abandon, or dead-letter. The broker has released the message or will redeliver it. If the database commit happened before the loss, the next delivery has to be a no-op (rule 7). A dropped link or a service update can surface as lock-lost without incrementing the delivery count. An expired lock from a slow handler does increment it. In both cases, stop settling.\n\n6. **Prefetch and concurrency stay inside the lock.** Prefetch (default 0) pulls messages onto the client before a handler wants them, and those messages are locked while they sit in the local buffer. A large prefetch plus a slow handler expires locks, bumps the delivery count, and can dead-letter work that was only waiting locally. Keep prefetch at 0 for database or HTTP handlers. If you raise it, cap it at a small multiple of `max-concurrent-calls`, and only after the lock-lost rate stays flat. `max-concurrent-calls` defaults to 1 on the binder; with sessions it applies per session. Concurrent calls times replicas times connections per call has to fit the Hikari pool (see **hikari-connection-pool-guardrails**). Raising concurrency to hide a slow query holds more locks and more connections. Manual settlement plus a measured prefetch is the safer pair; a fat prefetch with auto-complete races the local buffer.\n\n7. **Handlers are idempotent under redelivery.** Abandon, lock expiry, a crash between commit and complete, and a DLQ replay all deliver again. Broker duplicate detection is a send-side `MessageId` window. It does not suppress consumer redelivery, and it cannot be enabled after the entity exists. Dedupe in the consumer: an inbox row unique on `(consumer, message_id)` inserted in the same transaction as the side effect, an upsert on a natural business key, or an application property the producer set (an event id). Prefer that producer id over the broker sequence number, because a replay is a new sequence. `MessageId` is the right inbox key when the outbox sets it. On conflict, complete and return. When the handler also emits events, write an outbox row in that same transaction instead of calling the sender inline.\n\n```sql\ncreate table inbox_message (\n consumer varchar(64) not null,\n message_id varchar(128) not null,\n processed_at timestamptz not null default now(),\n primary key (consumer, message_id)\n);\n-- same transaction as the side effect:\ninsert into inbox_message (consumer, message_id) values (:consumer, :id)\non conflict do nothing; -- 0 rows: already done, complete and skip\n```\n\n8. **Sessions when order matters; competing consumers otherwise.** Several processor instances on one queue or subscription are competing consumers. There is no Kafka-style partition ownership: more replicas increase throughput until the entity or the database saturates, and they do not remove duplicates. `replicas: 1` is not a correctness fix. Per-key FIFO needs sessions. The queue or subscription is created with sessions required (that flag cannot be flipped later), every message carries a `SessionId` for the entity whose order matters, and only one consumer holds a given session. `max-concurrent-sessions` bounds how many sessions one pod works. Set `session-idle-timeout` above a normal handler so a quiet gap does not drop the session lock while the message lock is still held. On a partitioned entity the partition key and the session id have to match; publishers that follow the outbox skill set both. A missing `SessionId` on a session entity is poison, not a retry.\n\n9. **Prefer the processor over a hand-rolled receive loop.** `ServiceBusProcessorClient` (or a session processor) is the push path: it pumps, renews, and invokes your callback. A `ServiceBusReceiverClient` loop is pull, so you own receive, renewal, settlement, and shutdown, and those bugs show up under load. Use one style per entity. Spring Cloud Azure knobs live under `spring.cloud.azure.servicebus.processor`: `receive-mode`, `auto-complete`, `prefetch-count`, `max-concurrent-calls`, `max-concurrent-sessions`, `max-auto-lock-renew-duration`, `session-enabled`, `subscription-name` for a topic, and `sub-queue` for the DLQ reader. The Stream binder mirrors them at `spring.cloud.stream.servicebus.bindings..consumer.*`. Authenticate with the namespace plus a `TokenCredential` (workload identity on AKS). A connection string, if one still exists, comes from Key Vault or a secret mount (see **azure-key-vault-app-integration**), never from Git or a ConfigMap.\n\n```yaml\nspring:\n cloud:\n azure:\n servicebus:\n namespace: ${SERVICEBUS_NAMESPACE}\n processor:\n receive-mode: peek_lock\n auto-complete: false\n prefetch-count: 0\n max-concurrent-calls: 4\n max-auto-lock-renew-duration: 2m\n```\n\n```java\nvoid onMessage(ServiceBusReceivedMessageContext ctx) {\n var message = ctx.getMessage();\n try {\n // Commits the inbox row and the side effect together. False means already processed.\n if (!inbox.claimAndHandle(message)) {\n ctx.complete();\n return;\n }\n ctx.complete();\n } catch (PoisonMessageException ex) {\n var options = new DeadLetterOptions()\n .setDeadLetterReason(\"validation-failed\")\n .setDeadLetterErrorDescription(ex.getCode());\n ctx.deadLetter(options);\n } catch (ServiceBusException ex) {\n if (ex.getReason() == ServiceBusFailureReason.MESSAGE_LOCK_LOST\n || ex.getReason() == ServiceBusFailureReason.SESSION_LOCK_LOST) {\n return; // lock is gone; do not settle\n }\n throw ex;\n } catch (RuntimeException ex) {\n ctx.abandon(); // transaction rolled back; another delivery may succeed\n }\n}\n```\n\n10. **Shutdown stops receiving, then finishes in-flight work inside the lock.** On context close, stop the processor so it takes no new message, then wait for callbacks that already hold a lock. That wait (`spring.lifecycle.timeout-per-shutdown-phase` and the processor close timeout) has to be shorter than `terminationGracePeriodSeconds` minus the preStop sleep (see **k8s-probes-graceful-shutdown-guardrails**). If the lock drops during the wait, do not complete. Readiness may go false when the processor is stopped. Liveness must not depend on the namespace being reachable, or a broker blip restarts every pod. A manual receiver exits its loop on the shutdown signal and settles only what it still holds a lock for.\n\n11. **Watch the queue, not just the process.** Azure Monitor already exposes active message count, dead-lettered message count, incoming, complete, abandon, and dead-letter counts, plus throttling. Add Micrometer timers for handler latency and counters for settlement outcome, lock-lost, and inbox hits. Tags stay bounded: entity, subscription, outcome. No message id, session id, or payload as a tag. Alert when the dead-letter count is rising, and when the active count stays high while the complete rate is flat (pods up, work not moving). Log message id, delivery count, entity, and outcome. Do not log the body. Tag and dashboard conventions: **spring-boot-micrometer-prometheus-guardrails**.\n\n12. **Test the three paths that fail in production.** The same message delivered twice produces one side effect and a second complete. A poison payload is dead-lettered with your reason and is not completed. A lock-lost error mid-handler does not settle, and a later delivery after a commit is an inbox no-op. Drive those with a fake `ServiceBusReceivedMessageContext` so the test asserts which settlement ran. Add one integration test on the Service Bus emulator (Testcontainers or the emulator container; see **spring-boot-testcontainers**) for peek-lock complete, abandon then redelivery, and a message that lands on the dead-letter sub-queue. Do not point tests at a shared namespace. Use Awaitility, not fixed sleeps. The emulator is not the Premium tier: confirm sessions, duplicate detection, and partitioning on a real namespace before you depend on them.\n\n## Workflow\n1. Inventory: queue versus topic plus subscription, receive mode, auto-complete, who settles, lock duration, max delivery count, prefetch, max concurrent calls, sessions, replicas, side effects, and where the dedupe key lives.\n2. Settlement: PeekLock, complete only after commit, abandon versus dead-letter written down per exception, auto-complete off when the handler settles itself.\n3. Idempotency: inbox or natural key in the same transaction as the side effect. Confirm duplicate detection is not standing in for that inbox.\n4. DLQ: a deliberate max delivery count, a reader for `$deadletterqueue`, and a replay note that reads `DeadLetterReason` and avoids resending the same `MessageId` inside the duplicate-detection window.\n5. Sizing: lock duration, `max-auto-lock-renew-duration`, prefetch, and concurrency against p99 and the connection pool. Sessions only where per-key order is required.\n6. Shutdown and metrics: the grace-period chain, alerts on DLQ growth and stuck active messages, lock-lost and abandon rates.\n7. Tests for the rule 12 matrix. PR notes name the dedupe key, the exception-to-settlement table, the DLQ owner, and the lock budget.\n\n## Tool-specific notes\n### GitHub Copilot\n- Path-scoped `.github/instructions/azure-service-bus-consumer.instructions.md` with `applyTo` for `**/*Listener*.java`, `**/*Consumer*.java`, `**/*ServiceBus*Config*.java`, `**/application*.{yml,yaml,properties}`, and Service Bus IaC (`**/*servicebus*.bicep`, `**/servicebus*.json`).\n- Always-on line in `.github/copilot-instructions.md`: \"Service Bus consumers are at-least-once: PeekLock, idempotent handlers, complete only after the side effect commits, abandon or dead-letter on failure, never ReceiveAndDelete for work you cannot lose.\"\n- Optional `.github/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md` for agent mode.\n\n### Claude Code\n- Procedure in `.claude/skills/azure-service-bus-consumer-reliability-guardrails/SKILL.md`.\n- CLAUDE.md fact: \"Every Service Bus message may arrive twice. Never complete before the side effect is durable, and never settle after MessageLockLost.\"\n- Before claiming done, show the settlement table, the DLQ owner, the lock-budget numbers, and the passing duplicate, dead-letter, and lock-lost tests.\n\n### Codex\n- Service Bus consumer section in root `AGENTS.md`, or nested `src/main/java/**/messaging/AGENTS.md` (or linked `docs/agents/azure-service-bus-consumer.md`).\n- State: PeekLock, the auto-complete policy, the dedupe key and inbox table, abandon versus dead-letter lists, the DLQ path and replay rule, the lock and prefetch budget, sessions versus competing consumers, shutdown timeouts, and banned patterns (ReceiveAndDelete for side effects, complete-then-process, catch-and-complete, unbounded prefetch, `replicas: 1` as a dedupe fix).\n\n## Anti-patterns\n- `RECEIVE_AND_DELETE` for a write, a charge, an email, or anything else you cannot lose\n- Completing, or returning under auto-complete, and then doing the work\n- Catching `Exception`, logging it, and completing or returning normally\n- Auto-complete left on while the handler also calls `complete`\n- Prefetch in the hundreds on a handler that takes seconds, or prefetch raised with no look at the lock-lost rate\n- No reader, owner, or alert on the dead-letter sub-queue, or a job that replays the DLQ in a loop\n- Resending a DLQ message with the same `MessageId` while duplicate detection still covers that id\n- `replicas: 1`, or a single-pod hostname check, as the fix for duplicates\n- Treating broker duplicate detection as consumer idempotency\n- Sessions required on the entity while publishers omit `SessionId`, or sessions turned on when the only goal was throughput\n- Lock duration set to five minutes and renewal left untouched while p99 is longer, or renewal disabled while the handler regularly outlives the lock\n- Message bodies in logs, or message ids on metric tags\n\n## Done when\n- [ ] Receive mode is PeekLock for every handler with a side effect\n- [ ] Complete runs only after the side effect commits; recoverable failures abandon; poison failures dead-letter with a reason and a description\n- [ ] Auto-complete is off if the handler settles itself, and no catch-all completes a failure\n- [ ] Every handler has a dedupe key enforced by an inbox, an upsert, or a natural key in the same transaction\n- [ ] Max delivery count is a choice; the `$deadletterqueue` sub-queue has an owner, an alert, and a replay note that reads `DeadLetterReason` first\n- [ ] Lock duration and `max-auto-lock-renew-duration` cover p99 with headroom; `MessageLockLost` stops the handler without a settlement\n- [ ] Prefetch and `max-concurrent-calls` are sized so locks are not held past processing capacity, and concurrency fits the pool\n- [ ] Sessions are on only where per-key order is required; otherwise competing consumers, not `replicas: 1`\n- [ ] Shutdown stops receive, finishes in-flight work inside the grace period, and does not complete after lock loss\n- [ ] Active count, DLQ depth, lock-lost, abandon, and latency are visible, with alerts on DLQ growth and stuck active messages\n- [ ] Tests cover duplicate delivery, the dead-letter path, and the lock-lost path\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: azure-service-bus-consumer-reliability-guardrails\ndescription: Use when writing or reviewing Spring Boot consumers of Azure Service Bus — PeekLock settlement, complete-after-commit, abandon versus dead-letter, MaxDeliveryCount and the system DLQ, lock renewal, prefetch and concurrency, idempotent handlers, sessions versus competing consumers, shutdown, and DLQ metrics.\n---\n\nFollow Azure Service Bus Consumer Reliability Guardrails: PeekLock for any side effect, complete only after the side effect commits, abandon recoverable failures, and dead-letter poison messages with a reason. Keep an owner on the dead-letter sub-queue who reads DeadLetterReason before replay. Handlers are idempotent (inbox or natural key) because delivery is at-least-once; duplicate detection does not replace that. Size lock duration, max-auto-lock-renew-duration, prefetch, and max-concurrent-calls so locks are not held longer than the work, and stop without settling on MessageLockLost. Use sessions only for per-key order; otherwise competing consumers. Stop receiving on shutdown, finish in-flight work inside the pod grace period, and alert on DLQ growth and stuck active messages.\n```" } ] }