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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions promptbook/prompts.json
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,26 @@
],
"formatNotes": "All three. Point the tool at the services with `@Transactional` methods that publish, the KafkaTemplate or Service Bus sender config, `@TransactionalEventListener` classes, the consumers you own, `db/migration/`, `application*.yml`, and the Bicep or CLI that creates Service Bus entities, and paste incident notes about lost or phantom events if you have them. Copilot: the transactional outbox path instructions plus those files in agent mode (or save it as `.github/prompts/add-transactional-outbox.prompt.md`). Claude Code: the transactional-outbox-guardrails skill plus the files. Codex: AGENTS.md outbox and events section, then the diff. The prompt makes consumers dedupe before the relay goes live and migrates one event type at a time.",
"body": "Task: Add a transactional outbox to this Spring Boot service so every business change that must be announced produces exactly one committed outbox row in the same transaction, a relay delivers it to Kafka or Azure Service Bus at least once and in order per aggregate, and consumers drop duplicates. Finish with a publish-point inventory, a code and migration diff, tests, dashboards, 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, JPA or JDBC, where `@Transactional` boundaries are)\n- Database: {{DATABASE}} (e.g. Azure Database for PostgreSQL flexible server with Flyway)\n- Broker: {{BROKER}} (Kafka with spring-kafka, Azure Service Bus with Spring Cloud Azure or the azure-messaging-servicebus client, or both; tier for Service Bus)\n- Events: {{EVENTS}} (event types, topics or queues, current payload classes, who consumes them)\n- Ordering needs: {{ORDERING}} (e.g. per order id; none)\n- Volume and SLO: {{VOLUME}} (e.g. 50 events/s peak, deliver within 30 s)\n- Relay preference: {{RELAY}} (polling, Debezium CDC already running, Spring Modulith, undecided)\n- Replicas: {{REPLICAS}} (pod count and HPA range; whether a scheduler or leader lock such as ShedLock exists)\n- Consumers we own: {{CONSUMERS}} (services and whether they dedupe today)\n- Symptoms: {{SYMPTOMS}} (e.g. events lost during broker maintenance, phantom events after rollback, none yet)\n\nRequirements:\n\n1. Inventory every publish point\n - Table: class.method | transaction boundary | broker call | event type | key or session | what happens on rollback | what happens on crash after commit\n - Flag sends inside `@Transactional`, `@TransactionalEventListener(AFTER_COMMIT)` publishers, chained transaction managers, and fire-and-forget sends\n\n2. Outbox table and write path\n - Flyway migration for `outbox_event` (UUID id, aggregate type, aggregate id, aggregate version, event type, jsonb payload, jsonb headers, status, attempts, next_attempt_at, last_error, created_at, published_at) with a partial index on pending rows and an index on aggregate id + version\n - Write the row with the same `DataSource` and transaction as the business change; remove the broker call from that transaction\n - Payload is a versioned event DTO, not the JPA entity; no secrets or unneeded personal data\n - Capture `traceparent` and `tracestate` from the current span into headers at write time; add correlation id and schema version\n - If the change comes from an Idempotency-Key request, derive the outbox id from the key so a replay cannot add a second row\n\n3. Relay\n - Recommend polling, CDC, or a framework registry from {{RELAY}}, {{VOLUME}}, and {{BROKER}}; justify it and mark assumptions\n - Polling: `@Scheduled(fixedDelay)` claim of 50-200 rows with `FOR UPDATE SKIP LOCKED` in a short transaction, publish, wait for the ack with a timeout, mark published; dedicated scheduler thread pool; config switch to turn the relay off\n - CDC: Debezium outbox event router config (key from aggregate id, route by aggregate type), `wal_level=logical`, replication slot ownership and lag alert, optional delete after insert\n - Ordering from {{ORDERING}} and {{REPLICAS}}: single active relay, hash-range ownership, or a head-of-line claim that skips aggregates with an older pending or failed row; explain the trade-off\n\n4. Broker mapping\n - Kafka: key = aggregate id, headers `message-id`, `event-type`, `traceparent`; `acks=all`, `enable.idempotence=true`, `max.in.flight.requests.per.connection` <= 5, delivery and request timeouts that fit the claim transaction\n - Service Bus: `MessageId` = outbox id, `SessionId` = aggregate id on session-enabled entities when {{ORDERING}} needs it (`PartitionKey` equal to it if partitioned), `traceparent` as an application property; duplicate detection enabled at queue or topic creation with a stated window (needs Standard or Premium; provide the Bicep or CLI change and note that existing entities must be recreated to enable it)\n - State plainly that neither feature makes delivery exactly-once end to end\n\n5. Failures\n - Exponential backoff with jitter and a cap via `next_attempt_at`; max attempts or max age, then `FAILED`\n - Permanent errors (too large, unknown destination, authorization) go straight to `FAILED`\n - Operator commands to replay or skip a failed row, with an audit log entry; note how a failed row blocks later rows for its aggregate\n\n6. Consumers in {{CONSUMERS}}\n - Inbox table keyed by consumer + message id, inserted in the same transaction as the side effect; skip on conflict\n - Ignore events with an aggregate version older than the last applied one\n - Kafka: commit offsets after the transaction; Service Bus: complete the message after the transaction, abandon or dead-letter deliberately\n\n7. Retention and operations\n - Batched cleanup of published rows older than a documented window; failed rows kept; daily partitions if {{VOLUME}} is high\n - Inbox cleanup longer than the longest redelivery window\n\n8. Observability\n - Gauges: pending count, age of oldest pending row, failed count; counters: published, failed by reason; publish latency timer; relay leader status\n - Alerts: oldest pending age above the {{VOLUME}} SLO for 5 minutes, any failed row, CDC slot lag if used\n - Log message id, aggregate id, event type; no payloads\n\n9. Tests (Testcontainers)\n - PostgreSQL + Kafka container, or the Azure Service Bus emulator container\n - Rollback writes no row; broker down then up delivers; relay killed between send and mark produces a duplicate that the consumer drops; two relay instances keep per-aggregate order; poison row parks after max attempts; cleanup never deletes pending rows\n - Contract test that published messages carry key, message id, and `traceparent`\n\n10. Rollout\n - Consumers dedupe first; then write outbox rows with the relay off and compare against direct sends; then turn the relay on and remove direct sends per event type behind a config switch\n - Rollback plan and a backlog drain estimate for a relay outage at {{VOLUME}}\n\nConstraints:\n- Do not invent volumes, SLOs, broker tiers, or retention windows; use placeholders and list what must be confirmed.\n- Do not keep any broker call inside the business transaction, and do not introduce XA or chained transaction managers.\n- Do not claim exactly-once delivery.\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. Publish-point inventory table with risks\n2. Relay and ordering decision with assumptions marked\n3. Patch: migration, outbox entity or repository, write path changes, relay, broker config, application.yml, infra change for Service Bus if used\n4. Consumer dedupe changes\n5. Metrics, alerts, and log fields\n6. Tests\n7. Rollout plan, risks, and follow-ups\n\nStart with the inventory. Prove the crash-between-send-and-mark test passes before migrating more event types.\n"
},
{
"id": "make-scheduled-jobs-replica-safe",
"title": "Make Spring Boot Scheduled Jobs Safe Across Replicas",
"whenToUse": "Audit and fix the recurring jobs in a Spring Boot service that runs several replicas on AKS or Kubernetes: inventory every `@Scheduled` method and CronJob with its runtime, side effects and duplicate risk, decide in-app ShedLock vs CronJob vs leader election per job, add DB-time ShedLock locks with sized `lockAtMostFor`, make jobs idempotent with watermarks and bounded chunks, harden CronJob manifests and exit codes, add last-success alerts, and prove with Testcontainers that two instances run one tick once before scaling out.",
"tools": [
"copilot",
"claude-code",
"codex"
],
"tags": [
"spring-boot",
"java",
"kubernetes",
"aks",
"scheduling",
"reliability"
],
"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"
}
]
}
Loading
Loading