Inferensys

Prompt

Change Data Capture Payload Prompt for Outbox Patterns

A practical prompt playbook for generating Change Data Capture payloads from extraction results, designed for event-driven architects implementing outbox patterns with exactly-once delivery guarantees.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, and constraints for generating CDC-ready outbox payloads from extraction results.

This prompt is designed for event-driven architects and platform engineers who need to turn extraction outputs into change data capture (CDC) events compatible with the outbox pattern. The core job is to take a set of extracted records—often from a document or unstructured source—and produce a strictly typed payload that includes the operation type (INSERT, UPDATE, DELETE), a before state, an after state, and source position metadata. The output must be ready for insertion into an outbox table, where it will be polled by a message relay (such as Debezium or a custom publisher) and emitted to a log like Kafka. The reader is expected to have an existing outbox table schema and a downstream consumer that expects exactly-once semantics.

Use this prompt when your extraction pipeline is the source of truth for a business event and you need to guarantee that every state change produces a single, ordered, replayable event. The prompt is most effective when you can supply the current extracted state alongside the previously known state, allowing the model to compute the delta and assign the correct operation type. It is not a replacement for a database transaction log; it is a bridge between unstructured data extraction and a structured event stream. Do not use this prompt for high-frequency, low-latency CDC directly from a database—native log-based CDC tools are the right choice there. This prompt is for cases where the source of change is an AI extraction result, not a database row mutation.

The prompt requires several inputs to function correctly: the current extracted payload, the previous known state (if any), the target outbox table schema, and a source position identifier (such as a document version, extraction timestamp, or log sequence number). Without the previous state, the model cannot reliably determine whether the operation is an INSERT or an UPDATE. The output must include an aggregate_id for partitioning, an aggregate_type for routing, and a monotonically increasing source_position for ordering guarantees. The model is instructed to detect no-op changes—where the before and after states are semantically identical—and suppress those events to avoid polluting the outbox with empty deltas.

Before deploying this prompt into a production pipeline, you must implement a validation harness that checks the output against the outbox table schema, verifies that the source_position is strictly greater than the last published position, and confirms that the operation field is one of the allowed enum values. For high-risk domains such as financial or compliance systems, add a human review step for DELETE operations and for any event where the model's confidence in the delta is flagged as low. The prompt template includes a [RISK_LEVEL] parameter that adjusts the verbosity of the model's reasoning and the strictness of its no-op detection. Start with standard risk and escalate to high when the outbox feeds into a system of record.

PRACTICAL GUARDRAILS

Use Case Fit

Where the CDC Outbox prompt works, where it breaks, and what you must provide before using it in a production event pipeline.

01

Good Fit: Event-Driven Architectures

Use when: you need to emit a CDC-style event (before/after payload, operation type, source position) from an extraction result into an outbox table for exactly-once delivery. Guardrail: ensure the outbox table schema supports the operation, before, after, and source_position fields this prompt produces.

02

Bad Fit: Bulk Snapshot Exports

Avoid when: you are generating full-table snapshots or batch dumps without a change event. This prompt assumes a single-record change with a before/after diff. Guardrail: for bulk exports, use a batch ingestion prompt instead and skip the CDC envelope.

03

Required Input: Source Position Metadata

Risk: without a source position (log sequence number, timestamp, offset), exactly-once delivery and ordering guarantees collapse. Guardrail: always provide a monotonically increasing source_position input. If unavailable, flag the event as positionless and route to a dead-letter queue.

04

Required Input: Operation Type Classification

Risk: misclassifying an update as an insert or a delete as an update corrupts downstream projections. Guardrail: pre-classify the operation type (create, update, delete, snapshot) before calling this prompt. Do not rely on the model to infer it from the payload alone.

05

Operational Risk: Outbox Ordering Violations

Risk: if multiple events for the same entity are emitted out of order, downstream consumers may apply an older state after a newer one. Guardrail: use the source_position as the outbox sort key and enforce per-entity ordering at the consumer. Never rely on insertion time alone.

06

Operational Risk: Duplicate Event Emission

Risk: retries or reprocessing can emit the same change event twice, breaking idempotency. Guardrail: include a deterministic event_id derived from the entity key and source position. Consumers must deduplicate on this ID. Test with at-least-once delivery scenarios.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template that produces before/after payloads, operation type, and source position metadata for outbox-pattern CDC events.

This template is designed to be dropped into an extraction pipeline where the model has already produced a structured record from source text. Its job is to compare that extracted record against a previous state and emit a change data capture event suitable for an outbox table. The prompt expects you to supply the current extraction, the previous state (or null for inserts), a target schema, and ordering metadata. Every placeholder is enclosed in square brackets so you can substitute values programmatically before sending the prompt to the model.

text
You are a CDC event builder for an outbox pattern. Your output must be a single JSON object conforming to [OUTPUT_SCHEMA].

## Inputs
- Current extracted record: [CURRENT_RECORD]
- Previous state (null if this is an insert): [PREVIOUS_STATE]
- Source document identifier: [SOURCE_ID]
- Extraction timestamp (ISO 8601): [EXTRACTION_TS]
- Outbox sequence hint (monotonically increasing integer): [SEQUENCE_HINT]

## Operation Rules
1. Compare [CURRENT_RECORD] with [PREVIOUS_STATE] field by field.
2. If [PREVIOUS_STATE] is null, set `operation` to `"insert"` and `before` to null.
3. If any field value differs, set `operation` to `"update"`. Include the full `before` and `after` payloads.
4. If no fields differ, set `operation` to `"noop"`. Include `before` and `after` as identical payloads.
5. If [CURRENT_RECORD] is null or empty and [PREVIOUS_STATE] is not null, set `operation` to `"delete"` and `after` to null.
6. Never invent fields. Use only the fields present in [OUTPUT_SCHEMA].
7. Set `source_position` to a string combining [SOURCE_ID] and [EXTRACTION_TS] in the format `"[SOURCE_ID]@[EXTRACTION_TS]"`.
8. Set `sequence` to [SEQUENCE_HINT]. The consumer will use this for ordering, not you.

## Constraints
- Do not include commentary, explanations, or markdown fences.
- Return only the JSON object.
- If you cannot determine the operation with certainty, set `operation` to `"update"` and set `confidence` to `"low"`.
- For regulated or high-risk domains, flag the event with `"requires_review": true` when confidence is low.

Adaptation notes: Replace [OUTPUT_SCHEMA] with your actual JSON Schema definition for the outbox event envelope—this should include fields like event_id, aggregate_id, operation, before, after, source_position, sequence, timestamp, and confidence. If your outbox table uses a different ordering mechanism (e.g., a database-generated sequence), remove [SEQUENCE_HINT] and adjust rule 8. For teams using Avro or Protobuf, add a constraint that field ordering must match the schema exactly. Always validate the model's output against [OUTPUT_SCHEMA] in your application layer before writing to the outbox table—never trust the model to get the schema right on every call.

What to do next: Wire this prompt into a pipeline step that runs after extraction and before outbox insertion. Add a JSON Schema validator in your harness that rejects malformed events and triggers a retry or dead-letter queue. For high-throughput systems, consider batching comparisons and using a cheaper model for the diff step, reserving a more capable model only for ambiguous cases flagged with confidence: "low". Avoid using this prompt for streaming CDC from databases—it is designed for extraction-derived events, not log-based capture.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the CDC payload prompt. Each placeholder must be populated before the prompt is assembled. Validation notes describe how to check the input before it reaches the model.

PlaceholderPurposeExampleValidation Notes

[SOURCE_DOCUMENT_TEXT]

The raw unstructured text from which the change event is extracted

User updated billing address from 123 Main St to 456 Oak Ave effective 2025-06-01

Must be a non-empty string. Check length under model context limit. Reject null or whitespace-only input.

[PREVIOUS_STATE_PAYLOAD]

The last known state of the record before the change, used to construct the before image

{"address_line_1": "123 Main St", "city": "Springfield", "zip": "01101"}

Must be valid JSON or null. If null, operation type must be INSERT. Validate against the target schema before passing to the prompt.

[TARGET_SCHEMA_DEFINITION]

The JSON Schema or table definition that the output payload must conform to

{"type": "object", "properties": {"address_line_1": {"type": "string"}, "city": {"type": "string"}}, "required": ["address_line_1", "city"]}

Must be a valid JSON Schema object. Required fields must be declared. Check for enum constraints and format keywords that the prompt must respect.

[OPERATION_TYPE_HINT]

A hint for the expected CDC operation: INSERT, UPDATE, or DELETE. The prompt uses this to shape the payload

UPDATE

Must be one of INSERT, UPDATE, DELETE. If not provided, the prompt must infer from context. Validate against a strict enum before assembly.

[SOURCE_POSITION_METADATA]

Metadata about the source document's position in a stream or log, used for ordering and exactly-once delivery

{"log_file": "app-events-2025-06-01.log", "offset": 14523, "ingestion_time": "2025-06-01T14:30:00Z"}

Must be a valid JSON object. offset field must be an integer. ingestion_time must be ISO 8601. Reject if offset is missing or negative.

[OUTBOX_TABLE_NAME]

The target outbox table name, used to generate the correct routing key or topic reference

user_address_changes_outbox

Must be a non-empty string matching [a-z_]+ pattern. Validate against a known list of outbox tables if available. Reject names with special characters or SQL injection patterns.

[IDEMPOTENCY_KEY_STRATEGY]

Instructions for how to generate an idempotency key, such as source_offset, hash of before/after, or composite key

Use SHA-256 hash of concatenated source_offset and operation_type

Must be a non-empty string describing a deterministic strategy. If the strategy relies on fields not present in the payload, flag a pre-flight warning.

[EXACTLY_ONCE_SEMANTICS_FLAG]

Boolean flag indicating whether the downstream consumer requires exactly-once delivery guarantees

Must be true or false. If true, the prompt must include deduplication instructions and the idempotency key must be non-null. If false, at-least-once delivery is acceptable.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the CDC outbox prompt into a reliable event publishing pipeline with validation, ordering, and exactly-once delivery.

This prompt is designed to sit between your extraction layer and your outbox table writer. The model receives a source document and a previous state snapshot, then produces a structured CDC payload containing operation, before, after, changed_fields, and source_position. The application layer is responsible for validating this payload, assigning the outbox sequence, and writing it transactionally alongside any business entity changes. Do not let the model generate the outbox ID, transaction ID, or publication timestamp—those must be assigned by the application to preserve ordering and idempotency guarantees.

Validation and retry flow. Before writing to the outbox, validate the model output against a strict schema: operation must be one of insert, update, or delete; before and after must be valid JSON objects or explicit null; changed_fields must be a string array listing only fields present in the after object; source_position must include a non-empty document_id and a span_start integer. If validation fails, retry once with the validation error message appended to the prompt as a correction hint. If the retry also fails, route the record to a dead-letter queue with the original input, both failed outputs, and the validator error trace. For delete operations, require that after is null and changed_fields is empty—this is a common failure mode where models hallucinate residual fields.

Exactly-once delivery and outbox ordering. Use a database transaction to insert the validated CDC payload into your outbox table with an auto-incrementing sequence_id, a deterministic idempotency_key (hash of document_id + operation + source_position.span_start), and a published_at timestamp set to NULL. Your outbox poller or Debezium connector reads unpublished rows in sequence_id order and marks published_at after successful publication. If the same idempotency key appears again, skip insertion. This pattern keeps the model focused on payload structure while the application owns delivery semantics. Log every outbox write with the model version, prompt version, and validation result for auditability. When upgrading the prompt, run a regression suite of known document-and-prior-state pairs to confirm that operation classification and changed_fields detection remain stable across versions.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the CDC outbox payload produced by the prompt. Use this contract to build a downstream validator before inserting into the outbox table or publishing to the event stream.

Field or ElementType or FormatRequiredValidation Rule

operation

enum: INSERT | UPDATE | DELETE

Must be one of the three allowed values. Reject any other string.

before

object | null

Must be null for INSERT. Must be a non-null object for UPDATE and DELETE. Schema must match the target table.

after

object | null

Must be null for DELETE. Must be a non-null object for INSERT and UPDATE. Schema must match the target table.

source_position

string

Must be a valid log sequence number, offset, or timestamp. Format must match the configured source connector type.

transaction_id

string

Must be a non-empty string. Should be a UUID or monotonic identifier from the source transaction log.

table_name

string

Must match a known table in the registered schema catalog. Case-sensitive exact match required.

event_timestamp

ISO 8601 UTC string

Must parse to a valid UTC datetime. Reject if timezone is missing or ambiguous.

payload_signature

string

If present, must be a hex-encoded HMAC-SHA256 of the serialized payload. Validate against shared secret if configured.

PRACTICAL GUARDRAILS

Common Failure Modes

CDC payloads for outbox patterns break in predictable ways. Here are the most common failure modes and how to guard against them before they reach production.

01

Missing or Incorrect Operation Type

What to watch: The model emits operation: "update" when the payload only contains the after state without a before diff, or misclassifies an insert as an upsert. Downstream consumers relying on the operation type will apply wrong semantics. Guardrail: Validate that operation is one of insert, update, or delete and that update payloads always include both before and after objects. Reject or repair payloads that violate this contract before writing to the outbox table.

02

Outbox Ordering Gaps from Missing Sequence Numbers

What to watch: The prompt omits or hallucinates the monotonically increasing sequence number, causing consumers to skip events or replay duplicates. Exactly-once delivery breaks when sequence tracking is unreliable. Guardrail: Never let the model generate the sequence number. Assign it at the application layer using a database sequence or atomic counter. Validate that every outbox row has a strictly increasing, non-null sequence number before commit.

03

Source Position Metadata Drift

What to watch: The model fabricates log positions, offsets, or timestamps that don't match the actual source system state. This makes debugging, replay, and idempotency checks impossible. Guardrail: Extract source position metadata from the actual source system (binlog coordinates, LSN, Kafka offset) and inject it as a pre-filled variable in the prompt. Validate that the output preserves these values exactly—no transformation, no truncation.

04

Schema Mismatch Between Before and After Payloads

What to watch: The before and after objects have different field sets, missing required columns, or inconsistent types. Downstream consumers that diff the two payloads will fail or produce corrupted state. Guardrail: Enforce a strict schema where before and after share the same field definitions. Validate structural equality of keys and types across both objects. Reject payloads where before has fields absent from after or vice versa.

05

Large Payloads Exceeding Outbox Row Limits

What to watch: The model emits full document payloads with large text blobs, base64-encoded content, or deeply nested structures that exceed database row size limits or message broker max message sizes. Guardrail: Set explicit size constraints in the prompt. Truncate or offload large fields to external storage and replace them with references in the CDC payload. Validate payload size before insertion and route oversized records to a dead letter queue.

06

Idempotency Key Collisions from Non-Deterministic Generation

What to watch: The model generates idempotency keys from extracted content that varies across retries, causing duplicate events for the same logical change. Guardrail: Derive idempotency keys from deterministic source fields (primary key + source position) at the application layer. Never let the model invent them. Validate uniqueness constraints on the outbox table and alert on key collisions in production.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the quality of a CDC outbox payload before it is published to the event stream. Use this rubric to automate pass/fail checks in your CI/CD pipeline or pre-production validation harness.

CriterionPass StandardFailure SignalTest Method

Schema Compliance

Payload validates against the target JSON Schema or Avro schema definition.

Schema validation error; missing required fields; incorrect types.

Automated schema validator run against the generated output.

Operation Type Correctness

The operation field is exactly one of the allowed enum values: create, update, delete.

Operation field is missing, null, or contains an invalid string.

Enum check against the allowed set; reject any other value.

Before/After Payload Completeness

For update, both before and after objects are present and non-null. For create, before is null. For delete, after is null.

before or after is missing or incorrectly null for the given operation type.

Conditional null check based on the value of the operation field.

Source Position Metadata

The source object contains a non-null sequence (string or integer) and a valid ISO 8601 timestamp.

source object is missing; sequence is null; timestamp is unparseable.

Parse source.timestamp with a strict ISO 8601 parser; assert source.sequence is not null.

Outbox Ordering Guarantee

The source.sequence value is strictly greater than the sequence of the last successfully processed event for the same aggregate.

Sequence number is equal to or less than the previous event's sequence (duplicate or out-of-order).

Stateful test: maintain last sequence per aggregate ID; assert new sequence > last sequence.

Idempotency Key Presence

The payload contains a deterministic idempotency_key field, typically a hash of the aggregate ID and sequence number.

idempotency_key is missing, null, or changes on re-generation of the same event.

Re-generate the event from the same input; assert the idempotency_key is identical.

Hallucination Check

All values in the after or before payloads are directly traceable to the input extraction data. No invented fields or values.

A field exists in the output that is not present in the input extraction schema or data.

Diff the set of output keys against the set of allowed keys from the input extraction contract.

Null vs. Absent Field Discipline

Fields with unknown or missing values are explicitly set to null. Fields that are not part of the schema are absent.

A missing value is represented by an empty string "" or the field is simply omitted when it should be null.

Schema-aware walk of the output object; assert null for nullable fields with no value; assert absence for non-schema fields.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict output schema, retry logic, and an outbox ordering contract. Include:

  • JSON Schema validation in the prompt with operation enum locked to INSERT, UPDATE, DELETE
  • sequence_number field derived from [OUTBOX_POSITION]
  • transaction_id grouping for multi-row changes
  • Instruction to output null for before on INSERT and null for after on DELETE

Wire the prompt into a pipeline that:

  1. Validates output against the schema
  2. Retries once on validation failure with the error message
  3. Logs the raw payload and validation result

Watch for

  • Silent format drift when the model changes operation casing or field order
  • Missing transaction_id when the diff spans multiple records
  • sequence_number gaps if the model invents rather than using [OUTBOX_POSITION]
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.