From 906784d55608aae58fa16fa757f8327a0ed9d400 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:06:30 +0000 Subject: [PATCH 1/2] Add scheduled job guardrails skill for Spring Boot on AKS with ShedLock and CronJobs --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index 8ace47e..f20250f 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -980,6 +980,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/transactional-outbox.instructions.md` with applyTo for `**/*Service.java`, `**/outbox/**`, `**/messaging/**`, `**/db/migration/**`, and `**/application*.yml`, or `.github/skills/transactional-outbox-guardrails/SKILL.md`; one always-on line in `.github/copilot-instructions.md` (\"never call Kafka or Service Bus inside a database transaction; write an outbox row in the same transaction and let the relay publish\"). Claude Code: `.claude/skills/transactional-outbox-guardrails/SKILL.md`, plus a CLAUDE.md line naming the outbox table, the relay, and which events need per-aggregate order. Codex: an \"Outbox and events\" section in root `AGENTS.md` (or the same SKILL.md under `.agents/skills/`). Pair with api-idempotency-key-guardrails for request-side dedupe and key-derived message ids, spring-kafka-consumer-reliability-guardrails for the consuming side, flyway-migration-guardrails for the tables, spring-boot-testcontainers for the failure tests, hikari-connection-pool-guardrails for relay connections, and spring-boot-micrometer-prometheus-guardrails for lag metrics. This skill owns getting an event out exactly when its change commits.", "body": "# Skill: Transactional Outbox Guardrails for Spring Boot (Kafka and Azure Service Bus)\n\n## Goal\nWhen a service changes its data and must tell other services about it, the event exists if and only if the change committed. No lost events when the broker is down or the pod dies after commit, no phantom events for rolled-back work, events for one aggregate arrive in order, and every consumer can safely see the same event twice.\n\n## When to apply\n- A service writes to its database and then publishes to Kafka or Azure Service Bus in the same request or handler\n- Code calls `kafkaTemplate.send(...)` or a Service Bus sender inside `@Transactional`, or from `@TransactionalEventListener(AFTER_COMMIT)`, and calls that \"reliable\"\n- Incidents like \"the order exists but downstream never heard about it\" or \"we got the event but the row is not there\"\n- Someone proposes a chained or \"best effort 1PC\" transaction manager across the database and the broker, or XA\n- Adding an `Idempotency-Key` endpoint whose side effect is a message (the outbox row carries the key-derived id)\n- Moving an existing direct publisher to an outbox without breaking consumers\n\n## The rule\nThe database transaction that changes business state also inserts the outbox row. Nothing talks to the broker inside that transaction. A separate relay reads committed rows and publishes them, marking them done only after the broker acknowledges. That gives at-least-once delivery, never exactly-once, so every consumer deduplicates.\n\n## Baseline rules\n1. **Same transaction, same database.** Insert the outbox row with the same `DataSource` and transaction as the business write (a repository call inside the existing `@Transactional` service method). If the business data lives in two databases, you have two outboxes, not one.\n2. **Design the row as a message, not as an entity dump.** Columns: `id` (UUID, becomes the message id), `aggregate_type`, `aggregate_id` (becomes the Kafka key or Service Bus `SessionId`), `aggregate_version` or a per-aggregate sequence, `event_type`, `payload` (versioned schema, only what consumers need, no secrets), `headers` (JSON: `traceparent`, `tracestate`, tenant, schema version, causation and correlation ids), `created_at`, and relay state (`status`, `attempts`, `next_attempt_at`, `published_at`, `last_error`). Capture `traceparent` from the current span when the row is written, not when it is relayed.\n3. **Pick the relay on purpose.**\n\n | Relay | Fits when | Costs |\n |---|---|---|\n | Polling publisher (scheduled job, `FOR UPDATE SKIP LOCKED`) | Low to moderate volume, Kafka or Service Bus, no Kafka Connect in the estate | DB polling load, latency of one poll interval, ordering needs care |\n | CDC (Debezium + outbox event router) | High volume on Kafka, Kafka Connect already run by someone | Logical replication (`wal_level=logical`), replication slots that hold WAL if the connector stalls, another system to operate |\n | Framework registry (for example Spring Modulith event publication registry with externalization) | Modular monolith already on Spring Modulith | Its table, its retry semantics; same consumer rules apply |\n\n Polling is the default. Choose CDC only with a named owner for the connector and a replication slot lag alert.\n4. **Claim rows without double-sending or stalling.** Poll in short transactions: select a bounded batch (50-200) of `PENDING` rows with `next_attempt_at <= now()` using `FOR UPDATE SKIP LOCKED`, publish, wait for the broker acknowledgement, then mark them `PUBLISHED`. Use `fixedDelay` scheduling so runs never overlap, a partial index on pending rows, and a send timeout shorter than the lock or transaction timeout. Never hold the claim transaction open across slow retries.\n5. **Ordering is per aggregate, and SKIP LOCKED alone breaks it.** Several relay replicas with `SKIP LOCKED` can publish event 2 of an order before event 1. Pick one: a single active relay (ShedLock or a PostgreSQL advisory lock as leader election), relay workers that own a hash range of `aggregate_id`, or a claim query that only takes the oldest pending row per aggregate. Writes to one aggregate must already be serialized (row lock or optimistic version), and the message carries `aggregate_version` so consumers can drop stale or detect gaps. Do not rely on `created_at` or a global sequence as commit order across aggregates.\n6. **Map identity and order to the broker.**\n - Kafka: key = `aggregate_id` (same partition, ordered), header `message-id` = outbox `id`, plus `traceparent`. Keep `enable.idempotence=true` and `acks=all` (defaults on current clients) and do not raise `max.in.flight.requests.per.connection` above 5. The idempotent producer only removes duplicates from its own retries within one producer session; a relay that crashes after send and before marking the row still re-sends, so consumers still dedupe.\n - Azure Service Bus: `MessageId` = outbox `id`, `SessionId` = `aggregate_id` on session-enabled queues or subscriptions when order matters (on partitioned entities `PartitionKey` must equal `SessionId`), `traceparent` as an application property. Enable duplicate detection when the queue or topic is created (Standard or Premium; it cannot be turned on later) with a window longer than your worst relay outage you want covered (max 7 days). Duplicate detection covers re-sends inside the window only; consumers still dedupe. With JMS clients, set the Service Bus message id property explicitly, the JMS provider may overwrite `JMSMessageID`.\n7. **Retries with backoff; poison rows are parked, not looped.** On a send failure increment `attempts`, set `next_attempt_at` with exponential backoff plus jitter (cap it, for example 10 minutes), store a short `last_error`. After a maximum (for example 10 attempts or 24 hours) set `FAILED` and alert. Separate transient errors (timeouts, throttling, broker unavailable) from permanent ones (message too large, unknown topic, authorization denied): permanent ones go straight to `FAILED`. When ordering matters, a failed row blocks later rows of the same aggregate; say so, alert, and give operators a replay or skip command with an audit trail.\n8. **Consumers are idempotent by design.** Each consumer keeps an inbox or processed-message table keyed by (consumer name, message id) and inserts into it in the same transaction as its own side effect, skipping when the insert conflicts. Use `aggregate_version` to ignore older updates. For HTTP-triggered work, the outbox `id` can be derived from the request's Idempotency-Key so a replayed request does not create a second message (see api-idempotency-key-guardrails).\n9. **Retention keeps the table small.** Delete `PUBLISHED` rows older than a documented window (for example 7 days) in batches from a scheduled job, or partition by day and drop partitions at high volume. Keep `FAILED` rows until someone resolves them. With CDC you may delete the row in the same transaction right after insert; the change stream still sees the insert.\n10. **Measure the lag, not just errors.** Metrics: pending row count, age of the oldest pending row (the key SLO), publish rate, publish latency, failures by reason, rows in `FAILED`, relay leader status; for CDC, connector status and replication slot lag. Alert when the oldest pending row is older than the delivery SLO (for example 60 seconds for 5 minutes) and on any `FAILED` row. Log message id, aggregate id, and event type, never payloads with personal data.\n11. **Schema and contract.** Version `event_type` or a schema version header, make changes backward compatible, and document each event (topic or queue, key, headers, payload schema, ordering and duplicate guarantees) next to the API contract. AsyncAPI works well for this.\n12. **Test the failure cases.** Testcontainers PostgreSQL plus Kafka (or the Azure Service Bus emulator container): business rollback leaves no outbox row; broker down then up still delivers; relay killed between send and mark produces a duplicate that the consumer drops; two relay replicas never reorder one aggregate; poison row parks after max attempts; cleanup never deletes pending rows.\n\n## Copy-ready baseline\nFlyway migration (PostgreSQL):\n```sql\ncreate table outbox_event (\n id uuid primary key,\n aggregate_type varchar(64) not null,\n aggregate_id varchar(128) not null,\n aggregate_version bigint not null,\n event_type varchar(128) not null,\n payload jsonb not null,\n headers jsonb not null default '{}'::jsonb, -- traceparent, schema version, tenant\n status varchar(16) not null default 'PENDING', -- PENDING | PUBLISHED | FAILED\n attempts int not null default 0,\n next_attempt_at timestamptz not null default now(),\n last_error varchar(500),\n created_at timestamptz not null default now(),\n published_at timestamptz\n);\ncreate index idx_outbox_pending on outbox_event (next_attempt_at) where status = 'PENDING';\ncreate index idx_outbox_aggregate on outbox_event (aggregate_id, aggregate_version);\ncreate index idx_outbox_published on outbox_event (published_at) where status = 'PUBLISHED';\n```\n\nWrite path (same transaction as the business change):\n```java\n@Transactional\npublic Order placeOrder(PlaceOrder cmd) {\n Order order = orders.save(Order.from(cmd));\n outbox.save(OutboxEvent.of(\"order\", order.getId(), order.getVersion(),\n \"order.placed.v1\", OrderPlaced.from(order), Tracing.currentTraceHeaders()));\n return order; // no broker call here\n}\n```\n\nRelay claim (oldest pending row per aggregate, safe with several replicas):\n```sql\nselect e.*\n from outbox_event e\n where e.status = 'PENDING'\n and e.next_attempt_at <= now()\n and not exists (select 1 from outbox_event p\n where p.aggregate_id = e.aggregate_id\n and p.status in ('PENDING', 'FAILED')\n and p.aggregate_version < e.aggregate_version)\n order by e.created_at\n limit 100\n for update skip locked;\n```\nPublish each row, wait for the acknowledgement with a timeout, then in the same short transaction set `status = 'PUBLISHED', published_at = now()`; on failure set `attempts = attempts + 1, next_attempt_at = now() + backoff, last_error = left(:err, 500)`.\n\nConsumer dedupe:\n```sql\ncreate table inbox_message (\n consumer varchar(64) not null,\n message_id uuid not null,\n processed_at timestamptz not null default now(),\n primary key (consumer, message_id)\n);\n-- in the consumer's transaction, before the side effect:\ninsert into inbox_message (consumer, message_id) values (:consumer, :id)\non conflict do nothing; -- 0 rows: already processed, ack and skip\n```\n\n## Review checklist\n- [ ] No broker call inside the business transaction; outbox row written with the same transaction and `DataSource`\n- [ ] Row has message id, aggregate id and version, event type, versioned payload, and headers with `traceparent`\n- [ ] Relay choice (polling, CDC, framework) written down with an owner\n- [ ] Claim uses bounded batches, `FOR UPDATE SKIP LOCKED`, short transactions, and a send timeout\n- [ ] Per-aggregate ordering guaranteed by single relay, key ownership, or head-of-line claim\n- [ ] Kafka key = aggregate id with idempotent producer; or Service Bus `MessageId`, `SessionId`, and duplicate detection set at creation\n- [ ] Backoff with jitter, max attempts, permanent vs transient errors, `FAILED` rows parked and alerted\n- [ ] Every consumer has an inbox or dedupe table in its own transaction\n- [ ] Retention job for published rows; failed rows kept until resolved\n- [ ] Metrics and alerts on oldest pending age, pending count, failures, and CDC slot lag\n- [ ] Testcontainers tests for rollback, broker outage, crash between send and mark, ordering, poison rows\n\n## Anti-patterns\n- `@Transactional` method that saves and then calls `kafkaTemplate.send` or a Service Bus sender\n- `@TransactionalEventListener(AFTER_COMMIT)` publishing directly and calling it an outbox (a crash after commit loses the event)\n- Chained or \"best effort\" transaction managers across the database and the broker treated as atomic\n- Marking rows published before the broker acknowledges, or fire-and-forget sends from the relay\n- Several relay replicas with `SKIP LOCKED` and no ordering strategy for one aggregate\n- Treating Kafka idempotent producer or Service Bus duplicate detection as exactly-once end to end\n- Retrying a poison row forever in a tight loop, or silently deleting it\n- An outbox table that is never cleaned up, or a Debezium replication slot nobody watches\n- Whole JPA entities serialized as the payload, including fields consumers should not see\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: transactional-outbox-guardrails\ndescription: Use when a Spring Boot service changes its database and must publish an event to Kafka or Azure Service Bus: outbox row written in the same transaction as the business change, no broker calls inside the transaction, relay choice (polling with FOR UPDATE SKIP LOCKED, Debezium CDC, Spring Modulith registry), per-aggregate ordering with keys and versions, Kafka idempotent producer vs Service Bus MessageId, sessions and duplicate detection, at-least-once delivery with consumer inbox dedupe, traceparent headers, backoff and poison rows, retention, lag metrics, Testcontainers tests.\n---\n\nFollow Transactional Outbox Guardrails: insert the outbox row (UUID id, aggregate type, id and version, event type, versioned payload, headers with traceparent) in the same transaction and DataSource as the business change, and never call the broker inside that transaction. Default to a polling relay that claims bounded batches with FOR UPDATE SKIP LOCKED in short transactions, waits for the broker ack, then marks rows published; use Debezium CDC only with an owner and replication slot alerts. Keep per-aggregate order with a single active relay, key ownership, or a head-of-line claim. Kafka: key = aggregate id, message id header, idempotent producer with acks=all. Service Bus: MessageId = outbox id, SessionId = aggregate id when order matters, duplicate detection set at entity creation. Delivery is at-least-once, so every consumer dedupes with an inbox table in its own transaction and ignores older aggregate versions. Back off with jitter, park poison rows as FAILED and alert. Clean up published rows on a schedule. Alert on age of the oldest pending row. Test rollback, broker outage, crash between send and mark, ordering, and poison rows with Testcontainers.\n```\n" + }, + { + "id": "scheduled-jobs-shedlock-guardrails", + "title": "Scheduled Job Guardrails for Spring Boot on AKS (ShedLock vs Kubernetes CronJob)", + "whenToUse": "Adding or reviewing recurring jobs in a Spring Boot service that runs several replicas on AKS or Kubernetes — choosing in-app `@Scheduled` with ShedLock, a Kubernetes CronJob, or leader election per job, stable lock names with LockAssert and DB-time locks, `lockAtMostFor` and `lockAtLeastFor` sized from measured runtime, idempotent watermark-based work in bounded chunks with a time budget, scheduler pool sizing and graceful shutdown inside the pod grace period, cron zones and DST, CronJob `concurrencyPolicy`, `startingDeadlineSeconds`, `timeZone`, `backoffLimit`, `activeDeadlineSeconds` and exit codes, last-success alerts, and a two-instance single-run test.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "java", + "kubernetes", + "aks", + "scheduling", + "reliability" + ], + "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" } ] } From 858c63b6b17f755fd0c1fd68db0a9cdceaad3784 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:06:30 +0000 Subject: [PATCH 2/2] Add prompt for making Spring Boot scheduled jobs safe across replicas --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 5f4d800..64bea8b 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -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" } ] }