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

Filter by extension

Filter by extension

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