From 93da3187e0e4bf2bbb54d07692175e44f2ed0a8d Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Wed, 4 Nov 2026 05:14:54 +0000 Subject: [PATCH 1/2] Add transactional outbox guardrails skill for Spring Boot with Kafka and Service Bus --- skillbook/skills.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/skillbook/skills.json b/skillbook/skills.json index a7fcf2e..8ace47e 100644 --- a/skillbook/skills.json +++ b/skillbook/skills.json @@ -960,6 +960,26 @@ ], "formatNotes": "All three. Copilot: path-scoped `.github/instructions/api-idempotency.instructions.md` with applyTo for `**/*Controller.java`, `**/*Filter.java`, `**/web/**`, `**/db/migration/**`, and `**/openapi*.yaml`, or `.github/skills/api-idempotency-key-guardrails/SKILL.md`; one always-on line in `.github/copilot-instructions.md` (\"POST/PATCH with side effects take an Idempotency-Key: atomic claim, fingerprint check, record committed with the business write\"). Claude Code: `.claude/skills/api-idempotency-key-guardrails/SKILL.md`, plus a CLAUDE.md line naming the idempotency store, retention, and which endpoints require the key. Codex: an \"Idempotency\" section in root `AGENTS.md` (or the same SKILL.md under `.agents/skills/`). Pair with api-rate-limiting-guardrails for filter order and 429s, spring-boot-http-client-guardrails and spring-boot-resilience4j for client retries that reuse the key, spring-kafka-consumer-reliability-guardrails for consumer-side dedup, flyway-migration-guardrails for the table, and spring-boot-openapi-contract-guardrails for documenting the header and errors. This skill owns making unsafe HTTP methods safe to retry.", "body": "# Skill: HTTP Idempotency-Key Guardrails for Spring Boot APIs\n\n## Goal\nA client that times out, loses its connection, or gets a 502 can send the same `POST` or `PATCH` again and the server does the work once: one order, one payment, one ticket. The retry gets the first result back, a reused key with a different body is refused, and two copies racing each other cannot both run.\n\n## When to apply\n- Adding or reviewing a `POST` / `PATCH` endpoint that creates something, moves money, sends a message, or calls a paid or rate-limited provider\n- Callers retry: mobile apps, API Management or ingress retries, Resilience4j or Spring Retry on the client, queue-driven workers, other services in the mesh\n- Duplicate rows, double charges, or \"we sent it twice\" incidents\n- Someone proposes \"just make the client stop retrying\" or a unique constraint on a business field as the only guard\n- Exposing an API to partners who expect the `Idempotency-Key` header (IETF httpapi draft, Stripe-style APIs)\n\n## Decide the contract first\nWrite these down per endpoint before any code:\n\n| Question | Typical answer |\n|---|---|\n| Which operations take a key? | Non-idempotent `POST` and `PATCH` with side effects. Not `GET`, `HEAD`, `OPTIONS`. `PUT` and `DELETE` only when they trigger side effects beyond the state change |\n| Required or optional? | Required for money, orders, and outbound messages (missing key is `400`); optional elsewhere |\n| Key scope | Authenticated client (or tenant) + method + route template + key |\n| Retention | At least the longest client retry window; 24 hours is a common default |\n| Replayed outcomes | Success and final business errors are replayed; validation errors and conflicts are not stored |\n| Store down | Fail closed (`503`) for money-moving routes; fail open only where a duplicate is harmless |\n\n## Baseline rules\n1. **The client owns the key.** It creates one random key per logical operation (UUIDv4 or at least 128 bits of randomness) *before* the first attempt and sends the same key on every retry. Never build keys from emails, account numbers, or other personal data. Validate on the server: allowed characters, a maximum length (for example 255), reject malformed keys with `400`. The draft defines the header as a structured-field string (quoted); accept the quoted form and a bare token, and normalize before storing.\n2. **Scope the key to the caller and the operation.** Store records under client identity from the validated token (`azp` / `appid`, or tenant) + HTTP method + route template + key. A global key space lets one client collide with, or read back, another client's response.\n3. **Fingerprint the request.** Hash a canonical form of what makes the request unique (method, route, path variables, relevant query parameters, and the body bytes or a canonical JSON form) with SHA-256. Same key with a different fingerprint is a client bug: answer `422` with `application/problem+json` and a link to your docs. Leave out volatile headers such as tracing ids and timestamps.\n4. **Claim atomically, before doing the work.** Insert an `IN_PROGRESS` row under a unique constraint (`INSERT ... ON CONFLICT DO NOTHING`, or Redis `SET key value NX PX`) and only proceed if you won the insert. Never read-then-insert. A second request that finds the key in progress gets `409 Conflict` with a short `Retry-After`; it does not wait on a lock and it does not run the handler.\n5. **Commit the record with the business change.** Keep the idempotency table in the same database as the data the endpoint writes, and mark the record `COMPLETED` with the stored response in the same transaction. Then \"work done\" and \"record says done\" cannot disagree. Work that leaves the database (payment provider, email, Kafka) gets the key passed along: the provider's own idempotency key, or an outbox row whose dedup id is derived from the key.\n6. **Choose what gets stored, on purpose.** Store and replay `2xx` and final business errors (for example `402` insufficient funds, `409` domain conflict). Do not store errors that happen before execution starts (malformed body, failed validation, auth): release the claim so a fixed request can reuse the key. For `5xx` and timeouts, release the claim only if the transaction rolled back and nothing left the process; if a side effect may have happened, keep the record and reconcile instead of running it again.\n7. **Lease, do not lock forever.** An `IN_PROGRESS` record carries `locked_until`, set a little longer than the request timeout. After the lease expires a retry may take over with a conditional update, but only on endpoints whose work is transactional; otherwise it gets `409` until someone reconciles. Alert on expired leases: each one is a crash or a hung request.\n8. **Replay faithfully and say so.** Return the stored status, body, and the headers that matter (`Content-Type`, `Location`, `ETag`), and add a marker header such as `Idempotent-Replayed: true`. A replay must not re-run validation against current state, emit events, or count as a new business action.\n9. **Retention is a contract.** Expire records after the documented window with a scheduled cleanup on an indexed `expires_at` (or a Redis TTL). After expiry the same key starts a new request; say so in the API docs. Never expire a record that is still `IN_PROGRESS`.\n10. **Treat stored responses as sensitive data.** Bodies can hold personal data and tokens. Cap stored size, consider storing the created resource id and re-rendering instead of the raw body, encrypt at rest if the API carries regulated data, and never log keys next to bodies (log a hash of the key).\n11. **Place it correctly in Spring.** A servlet filter or a `HandlerInterceptor` plus a body-caching wrapper, ordered after authentication (it needs the client identity) and the rate limiter, and before the transaction and the controller. Read and cache the body once for the fingerprint; capture the response with `ContentCachingResponseWrapper` and call `copyBodyToResponse()`. An annotation such as `@Idempotent(required = true)` on handler methods keeps the per-endpoint contract next to the code. Skip streaming and SSE responses, or store only a resource reference for them.\n12. **Make it observable and documented.** Count claims, replays, `409` in-flight, `422` mismatches, lease takeovers, store errors, and store latency by route (no raw keys as tags). Document the header in OpenAPI per operation: required or optional, format, retention, and the `400` / `409` / `422` problem types. Client SDKs and outbound clients reuse the key on every retry and only retry `POST` when a key is set.\n\n## Copy-ready baseline\nFlyway migration (PostgreSQL):\n```sql\ncreate table idempotency_record (\n scope_key varchar(200) not null, -- client id + method + route template\n idem_key varchar(255) not null,\n fingerprint char(64) not null, -- sha-256 hex of the canonical request\n status varchar(16) not null, -- IN_PROGRESS | COMPLETED\n locked_until timestamptz not null,\n response_status int,\n response_headers jsonb,\n response_body bytea,\n created_at timestamptz not null default now(),\n expires_at timestamptz not null,\n primary key (scope_key, idem_key)\n);\ncreate index idx_idempotency_expires on idempotency_record (expires_at);\n```\n\nClaim, then decide:\n```sql\n-- 1 row inserted: you own the key, run the handler\ninsert into idempotency_record (scope_key, idem_key, fingerprint, status, locked_until, expires_at)\nvalues (:scope, :key, :fp, 'IN_PROGRESS', now() + interval '30 seconds', now() + interval '24 hours')\non conflict (scope_key, idem_key) do nothing;\n\n-- 0 rows: load the existing record and branch\n-- fingerprint differs -> 422 problem+json\n-- COMPLETED -> replay stored response + Idempotent-Replayed: true\n-- IN_PROGRESS and locked_until > now() -> 409 problem+json + Retry-After: 1\n-- IN_PROGRESS and lease expired -> conditional takeover (transactional endpoints only)\nupdate idempotency_record\n set locked_until = now() + interval '30 seconds'\n where scope_key = :scope and idem_key = :key\n and status = 'IN_PROGRESS' and locked_until < now();\n```\n\nProblem response for a reused key:\n```http\nHTTP/1.1 422 Unprocessable Content\nContent-Type: application/problem+json\n\n{\"type\":\"https://api.example.com/problems/idempotency-key-reused\",\n \"title\":\"Idempotency-Key was already used with a different request\",\n \"status\":422}\n```\n\n## Review checklist\n- [ ] Each `POST` / `PATCH` with side effects says whether the key is required, optional, or not supported\n- [ ] Keys are validated (format, length) and scoped to client identity + method + route template\n- [ ] Request fingerprint compared; mismatch returns `422`\n- [ ] Claim is one atomic insert under a unique constraint; concurrent duplicate returns `409` with `Retry-After`\n- [ ] Record completion commits in the same transaction as the business write; outbound side effects carry the key\n- [ ] Stored vs not-stored outcomes written down, including `5xx` and timeouts\n- [ ] Lease on in-progress records; expired leases alerted on\n- [ ] Replays return the original status, body, and key headers, plus a replay marker\n- [ ] Retention documented and enforced by an indexed cleanup or TTL\n- [ ] Stored bodies size-capped and treated as sensitive; keys hashed in logs\n- [ ] Filter order: authentication, rate limiting, idempotency, transaction, controller\n- [ ] Metrics, OpenAPI header and error docs, and client retry code reuse the same key\n- [ ] Tests: replay, mismatch, two concurrent requests, crash mid-request, expiry\n\n## Anti-patterns\n- Check-then-insert (`findById` then `save`) instead of an atomic claim\n- One global key space shared by every client\n- Ignoring the body, so a reused key with a new amount silently returns the old result\n- Storing the record in Redis while the business write goes to PostgreSQL with no plan for the gap\n- Caching validation failures so a corrected request can never use its key\n- Re-running the handler on retry and hoping a unique constraint catches it\n- Generating a fresh key on every retry attempt in the client\n- Keeping in-progress locks with no lease, so a crashed pod blocks the key until cleanup\n- Logging full stored responses for debugging\n\n## Copy-ready SKILL.md stub\n```markdown\n---\nname: api-idempotency-key-guardrails\ndescription: Use when adding or reviewing POST/PATCH endpoints with side effects in Spring Boot APIs, or client retries against them: Idempotency-Key header contract (required or optional, retention), key validation and scoping to client + method + route, request fingerprint with 422 on mismatch, atomic claim with 409 for in-flight duplicates, record committed with the business write, outbound side effects carrying the key, stored vs released outcomes, leases, faithful replay, retention cleanup, sensitive stored bodies, filter order, metrics and OpenAPI docs.\n---\n\nFollow HTTP Idempotency-Key Guardrails: decide per endpoint whether the key is required, optional, or unsupported, and document retention (24 hours unless the retry window is longer). The client creates one random key per operation and reuses it on every retry. Validate the key and scope it to client identity + method + route template. Fingerprint the canonical request; same key with a different fingerprint returns 422 problem+json. Claim with one atomic insert under a unique constraint before doing work; a duplicate in flight gets 409 with Retry-After. Mark the record completed with the stored response in the same transaction as the business write, and pass the key to providers or the outbox. Store success and final business errors; release the claim for pre-execution failures and for rolled-back 5xx; reconcile when a side effect may have happened. Use a lease on in-progress records. Replay status, body, and key headers with Idempotent-Replayed: true. Clean up expired records on an index. Treat stored bodies as sensitive and hash keys in logs. Order filters: auth, rate limit, idempotency, transaction, controller. Add metrics, OpenAPI docs, and tests for replay, mismatch, concurrency, crash, and expiry.\n```\n" + }, + { + "id": "transactional-outbox-guardrails", + "title": "Transactional Outbox Guardrails for Spring Boot (Kafka and Azure Service Bus)", + "whenToUse": "Adding or reviewing code in a Spring Boot service that changes its database and must publish an event to Kafka or Azure Service Bus — an outbox row written in the same transaction as the business change with no broker calls inside it, a relay chosen on purpose (polling with FOR UPDATE SKIP LOCKED, Debezium CDC, or a framework registry), per-aggregate ordering that survives several relay replicas, Kafka keys and idempotent producer vs Service Bus MessageId, sessions and duplicate detection, at-least-once delivery with consumer inbox dedupe, message id and traceparent headers, backoff and parked poison rows, retention cleanup, oldest-pending-age metrics, and Testcontainers failure tests.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "java", + "kafka", + "azure-service-bus", + "messaging", + "reliability" + ], + "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" } ] } From 3c0b1704a5e3e29bde1f5ad236bd903598abfc04 Mon Sep 17 00:00:00 2001 From: Ramkumar Ethiraj <64294490+rmkr-dev@users.noreply.github.com> Date: Wed, 4 Nov 2026 05:14:54 +0000 Subject: [PATCH 2/2] Add prompt for adding a transactional outbox to a Spring Boot service --- promptbook/prompts.json | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/promptbook/prompts.json b/promptbook/prompts.json index 09cd596..5f4d800 100644 --- a/promptbook/prompts.json +++ b/promptbook/prompts.json @@ -962,6 +962,26 @@ ], "formatNotes": "All three. Point the tool at the controllers for the POST/PATCH routes, the security and rate-limit filters, the service layer and transaction boundaries, outbound provider clients or the outbox, `db/migration/`, the OpenAPI document, and `application*.yml`, and paste incident notes or logs showing duplicates if you have them. Copilot: the idempotency path instructions plus those files in agent mode (or save it as `.github/prompts/add-idempotency-keys.prompt.md`). Claude Code: the api-idempotency-key-guardrails skill plus the files. Codex: AGENTS.md idempotency section, then the diff. The prompt ships the header as optional first and proves the concurrent-duplicate test before requiring it.", "body": "Task: Add Idempotency-Key support to this Spring Boot API so a retried POST or PATCH runs its side effects once, the retry gets the original result, a reused key with a different request is refused, and concurrent duplicates cannot both run. Finish with an endpoint contract table, a code and migration diff, tests, and a rollout plan.\n\nContext placeholders (fill from the repo or ask only if missing):\n- Service and endpoints: {{SERVICE}} (e.g. payments-api; list POST/PATCH routes and what each one creates or triggers)\n- Caller identity: {{IDENTITY}} (e.g. JWT azp/appid claim, tenant claim, API key; how the principal is available in a filter)\n- Database: {{DATABASE}} (e.g. Azure Database for PostgreSQL with Flyway; where the business writes go)\n- Other store: {{STORE}} (e.g. Azure Cache for Redis, none)\n- Side effects that leave the process: {{SIDE_EFFECTS}} (e.g. payment provider call, email, Kafka publish via outbox)\n- Retry sources: {{RETRIES}} (e.g. mobile app, API Management retry policy, Resilience4j in calling services, workers)\n- Retention: {{RETENTION}} (e.g. 24 hours; longest client retry window)\n- Current symptoms: {{SYMPTOMS}} (e.g. duplicate orders after gateway timeouts, double charges, none yet)\n\nRequirements:\n\n1. Endpoint contract\n - Table: method + route | side effect | key required/optional/unsupported | fingerprint fields | stored outcomes | store-down behaviour\n - Justify each \"required\" from {{SIDE_EFFECTS}}; mark assumptions\n - Retention from {{RETENTION}}, written into the API docs\n\n2. Key handling\n - Read `Idempotency-Key`; accept the quoted structured-field form and a bare token; validate characters and length; 400 for malformed, and for missing when required\n - Scope: client identity from {{IDENTITY}} + method + route template + key; never a global key space\n - Fingerprint: SHA-256 of a canonical request (method, route, path variables, relevant query, body bytes or canonical JSON); exclude tracing and timestamp headers\n\n3. Store and claim\n - Flyway migration for an `idempotency_record` table in {{DATABASE}} (scope, key, fingerprint, status, locked_until, response status, selected headers, body or resource reference, created_at, expires_at; primary key on scope + key; index on expires_at)\n - Atomic claim with one insert under the unique constraint; no read-then-insert\n - Branches: fingerprint mismatch -> 422 problem+json; completed -> replay with `Idempotent-Replayed: true`; in progress with live lease -> 409 problem+json + `Retry-After`; expired lease -> conditional takeover only for transactional endpoints\n - If {{STORE}} is Redis and the business data is in {{DATABASE}}, explain the consistency gap and prefer the database unless there is a measured reason not to\n\n4. Execution and outcomes\n - Mark the record completed with the response in the same transaction as the business write\n - Pass the key (or a derived id) to each item in {{SIDE_EFFECTS}}: provider idempotency key, outbox dedup id\n - Store 2xx and final business errors; release the claim for validation and auth failures and for rolled-back 5xx; keep and flag the record when a side effect may have happened\n - Replays return stored status, body, `Content-Type`, `Location`, `ETag`; they do not re-run the handler or emit events\n\n5. Spring wiring\n - A filter or `HandlerInterceptor` ordered after authentication and the rate limiter, before the transaction and controller\n - Body cached once for the fingerprint; response captured with `ContentCachingResponseWrapper` and `copyBodyToResponse()`\n - An annotation such as `@Idempotent(required = true)` (or config per route) as the per-endpoint switch; streaming and SSE excluded\n - Scheduled cleanup of expired, completed records; never delete in-progress ones\n - Stored bodies size-capped and treated as sensitive; key hashed in logs\n\n6. Clients and docs\n - OpenAPI: header parameter per operation, required flag, retention, 400/409/422 problem types\n - Callers in {{RETRIES}}: generate the key before the first attempt, reuse it on every retry, only retry POST when a key is set, honor 409 Retry-After\n\n7. Observability\n - Counters by route: claimed, replayed, in-flight 409, mismatch 422, lease takeover, store error; store latency; no raw keys as tags\n - Alerts: lease takeovers or store errors above zero; replay rate jump\n\n8. Tests\n - Unit: fingerprint canonicalization, key validation, branch decisions with a fake clock\n - Integration (Testcontainers PostgreSQL): replay returns identical status and body; mismatch 422; two concurrent requests with one key run the handler once; crash between claim and commit; expiry starts a new request\n - Contract: problem+json shapes and headers match the OpenAPI document\n\n9. Rollout\n - Ship optional first, measure how many callers send keys, then make it required per endpoint with notice\n - Feature switch in config; rollback plan\n\nConstraints:\n- Do not invent retention windows, traffic numbers, or provider idempotency features; use placeholders and list what must be confirmed.\n- Do not rely on a business unique constraint as the only duplicate guard.\n- Do not cache pre-execution validation failures against the key.\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. Endpoint contract table with assumptions marked\n2. Patch: migration, record entity or repository, filter or interceptor, annotation, problem responses, cleanup job, application.yml\n3. Outbound key propagation changes\n4. OpenAPI changes and client retry changes\n5. Metrics, alerts, and log fields\n6. Tests\n7. Rollout plan, risks, and follow-ups\n\nStart with the contract table. Prove the concurrent-duplicate test passes before wiring more endpoints.\n" + }, + { + "id": "add-transactional-outbox", + "title": "Add a Transactional Outbox to a Spring Boot Service", + "whenToUse": "Replace direct Kafka or Azure Service Bus sends in a Spring Boot service with a transactional outbox: inventory every publish point and its rollback and crash behaviour, add a Flyway-managed outbox table written in the same transaction as the business change, pick a polling or CDC relay with per-aggregate ordering across replicas, map message id, key or session, and traceparent to the broker, park poison rows, add inbox dedupe to consumers, alert on the age of the oldest pending row, and prove it with Testcontainers crash and outage tests before migrating every event type.", + "tools": [ + "copilot", + "claude-code", + "codex" + ], + "tags": [ + "spring-boot", + "java", + "kafka", + "azure-service-bus", + "messaging", + "reliability" + ], + "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" } ] }