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

Filter by extension

Filter by extension

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