# Design the Event Envelope

Page title: CDC Event Envelope & Delivery

> Break down the structure of CDC change events and learn how at-least-once delivery and exactly-once processing affect consumers.

Canonical page: <https://sandgraal.github.io/letstalkcdc/event-envelope/>

> **Known errata for this page (1)**
>
> - **Corrected: a delete event does not always carry the full row** (updated 2026-10-11)
>
>   The pages said a delete event holds the row as it was (the before image), or that the log holds the before image. That is only true under the right source settings. On PostgreSQL, with the default replica identity on a table that has a primary key, the before image carries only the key columns; `REPLICA IDENTITY FULL` adds the rest of the row, and other replica identity settings differ, so check yours. On MySQL, `binlog_row_image` controls how much of the row is written (FULL, MINIMAL, NOBLOB); the full row needs `binlog_row_image=FULL`. The places that described the before image now state both conditions: the delete page, the event envelope quiz, the use cases page and the security page. A sink that needs the old column values of a deleted row must not assume them.
>
> [See all corrections and caveats](https://sandgraal.github.io/letstalkcdc/errata/)

Learn how CDC tools package change events, why before/after images matter, and how delivery guarantees shape your downstream processing.

See Event Anatomy Lock Schema Contract

## Envelope readiness tracker

Roll up your readiness checklist progress before you dive into the deep-dive sections.

0 of 0 readiness checks complete (0%)

## What lives inside the envelope

Change events are more than a JSON blob. Every field exists to keep data, ordering, and metadata aligned across services. Ground your consumers in the same vocabulary so investigations stay fast.

```json
{
  "op": "u",
  "ts_ms": 1712857612456,
  "source": {
    "db": "app",
    "table": "orders",
    "lsn": 368592330
  },
  "transaction": {
    "id": "4.25.901",
    "total_order": 442,
    "event_count": 2
  },
  "before": { "order_id": 42, "status": "processing" },
  "after": { "order_id": 42, "status": "shipped" },
  "key": { "order_id": 42 }
}
```

| Field | Purpose | Questions it answers |
| --- | --- | --- |
| `op` / action | Signals whether the change was an insert, update, or delete. | Should I [upsert](https://sandgraal.github.io/letstalkcdc/glossary/#upsert) or delete this record? |
| `source.lsn` / log position | The change’s position in the source’s transaction log (LSN, SCN, or binlog file + position). | Was this change applied before or after another event? |
| `ts_ms` / `source.ts_ms` | When the connector processed the event, and when the source committed it. Millisecond-coarse and clock-dependent. | How late is this event? (Lag metrics only, never ordering.) |
| Transaction identifiers | Log sequence numbers, SCNs, or offsets for recovery. | Where do I resume when reprocessing? |
| Primary key | The stable identifier for idempotent upserts. | Which entity does this change belong to? |
| Before/after payloads | Snapshots of column values at either side of the change. | How do I compute diffs or rollbacks? |

## Why before/after images matter

Many downstream jobs need both the new values and the previous state. Audit pipelines, SCD Type 2 tables, and cache invalidation logic all break without the *before* image.

- **[Deduplication](https://sandgraal.github.io/letstalkcdc/glossary/#deduplication).** With the prior primary-key hash you can detect replays without touching the target system.
- **Reversible operations.** Rollbacks and compensation workflows replay the *before* payload to undo a change.
- **Selective projections.** Consumers can skip heavy fields in the after image while still verifying that critical columns changed.

Treat optional images as a contract. If you turn them off for throughput, publish the policy and add guards to your materialization layer.

## Delivery guarantees set your expectations

CDC stacks normally promise **[at-least-once](https://sandgraal.github.io/letstalkcdc/glossary/#at-least-once) (ALO)** delivery. End-to-end exactly-once delivery across independent systems is not achievable; what you layer on top is **exactly-once processing**: at-least-once transport plus an idempotent sink (or a sink that commits offsets with the data).

### At-least-once

- Replays or connector restarts may emit duplicate events.
- Design consumers to be idempotent: upsert by key, avoid increment-only writes.
- Lag metrics and DLQ hygiene keep ALO predictable.

### Exactly-once processing patterns

- Persist offsets in the same transaction as your target writes (see [Is CDC exactly-once? Per hop](https://sandgraal.github.io/letstalkcdc/is-cdc-exactly-once/) for an example).
- Use sink-side dedupe keys (primary-key + log position).
- Recover by rewinding to the last committed offset checkpoint.

## Ordering and compaction

Per-key ordering is preserved within a partition ([Partitioning & Reconciliation](https://sandgraal.github.io/letstalkcdc/partitioning/) covers key choice), but cross-partition sequencing is best-effort. Design your envelope so downstream jobs can stitch history back together.

1. Carry the source log position (LSN, SCN, or binlog position) as the per-key version, not a timestamp.
2. Keep the delete event, which carries a position, and let the connector follow it with a [tombstone](https://sandgraal.github.io/letstalkcdc/glossary/#tombstone) if the topic is [compacted](https://sandgraal.github.io/letstalkcdc/glossary/#compaction). A tombstone is a signal to Kafka’s log cleaner and has no position, so the sink keeps its own delete marker ([three kinds of delete](https://sandgraal.github.io/letstalkcdc/deletes-stay-deleted/#three-deletes)).
3. Make idempotent materialization the default (see the [MERGE cookbook](https://sandgraal.github.io/letstalkcdc/merge-cookbook/)) so out-of-order updates resolve deterministically.

## Transports other than Kafka

Everything above is taught Kafka-first, because that is what most CDC pipelines land on. The envelope travels fine over other transports, but **the ordering and retention guarantees underneath it are not the same** — and those are exactly the properties your sink depends on to dedupe correctly. Port the pipeline without re-reading the guarantees and you inherit a silent correctness bug.

| Transport | Ordering unit | Retention | What changes for the sink |
| --- | --- | --- | --- |
| Kafka | Per partition; key hashing keeps a row’s history together | Time/size based, or compacted by key | The baseline this site assumes. Compaction plus tombstones gives you a replayable latest-state view. |
| Pulsar | Per partition; `Key_Shared` keeps a key on one consumer while still fanning out | Time/size, plus tiered offload; topic compaction available | Closest analogue to Kafka. Confirm the subscription type — `Shared` will happily break per-key order. |
| Kinesis Data Streams | Per shard, by partition key | Fixed window (24h by default, extendable) — **no compaction** | Resharding moves keys between shards, so ordering holds per shard, not per key across a split. There is no compacted view to rebuild state from; keep your own. |
| Google Pub/Sub | **None by default** — only with an ordering key, and only within a region | Ack-based, with a configurable retention window | The riskiest port. Without an ordering key an update can land before the insert it depends on, so ordering must come from the event (log position), never from arrival. |

> **The thesis is transport-independent.** All four are at-least-once. None of them gives you exactly-once into an external sink. The fix is the same everywhere: upsert on the primary key and break ties on **log position (LSN/SCN/GTID), not `ts_ms`**. What the transport changes is how much re-ordering your sink must absorb — not whether it needs to be idempotent.

Practical consequence: on Pub/Sub, and on Kinesis across a reshard, treat arrival order as unordered and rely entirely on the envelope’s source metadata. That is a good habit on Kafka too — it just costs you nothing there. Running Debezium itself without Kafka is covered in [CDC without Kafka](https://sandgraal.github.io/letstalkcdc/non-kafka-cdc/).

## Schema contracts and validation

- Version the payload schema and publish compatibility rules. Schema Registry, EventSchema, or protobuf descriptors make evolution visible.
- Declare nullability explicitly. Optional before-images should use `before: null`, not a missing field, so consumers can detect configuration drift.
- Emit consistent casing and data types. Normalize booleans and numbers so typed sinks (Snowflake, BigQuery) avoid coercion surprises.

Build a contract test that fetches a production envelope, validates it against the schema, and asserts critical fields are non-null. Run it in CI before promoting connector changes. What a consumer may rely on in the envelope, and which DDL breaks it, is on [Data Contracts for Database Events](https://sandgraal.github.io/letstalkcdc/cdc-data-contracts/).

## Connector field crosswalk

| Concept | Debezium | Fivetran | Custom/Kafka Streams |
| --- | --- | --- | --- |
| Operation | `op` (`c`, `u`, `d`, `r`) | `op` (`INSERT`, `UPDATE`, `DELETE`) | Explicit `action` field or topic naming |
| Source position | `source.lsn` (or `source.scn`, or binlog file + position) | `source_lsn` / `source_commit` | High-water mark stored beside offsets |
| Source commit time (metrics only) | `source.ts_ms` | Commit-time column, if the connector exposes one | Commit time kept beside the position, for lag only |
| Transaction envelope | `transaction.id`, `total_order` | `txn_id` (when available) | Custom headers (`x-tx-id`) |
| Before image | `before` | `before` | Previous state cached in state store |
| Metadata | `source.db`, `schema`, `table` | `source_table`, `source_schema` | Headers + payload wrapper object |

Align on vocabulary in your runbooks. Analysts should not have to learn a different event shape per connector.

## Implementation playbooks

Use these checklists when reviewing connector configs or consumer code.

**Connector configuration review**

- Emit both before and after images for update operations.
- Include metadata fields: transaction id, source host, schema.
- Normalize column names and data types in the envelope schema.

**Consumer hardening**

- Guard against duplicate keys and out-of-order events.
- Track the last processed offset per partition.
- Alert on missing tombstones or schema drift.

**Schema migration rollout**

- Backfill new columns in the source before enabling them in CDC.
- Verify downstream code tolerates nullable fields during rollout.
- Advance schema version numbers atomically with deploys.

## Validate envelopes continuously

1. Stream envelopes into a contract test that checks required fields and value ranges.
2. Sample production events hourly and diff them against materialized tables.
3. Alert if optional sections (before image, transaction id) disappear unexpectedly.

These guardrails keep consumers from silently degrading when connector upgrades or config toggles change the envelope shape.

## Event envelope readiness scorecard

Share this checklist before launch so producers, consumers, and platform teams align on envelope expectations and operating guardrails.

0 of 4 ready (0%)

| Capability | Ready when… | If not, do this |
| --- | --- | --- |
| Schema contract | Versioned payload schema is published with required fields called out and nullability documented. | Draft a schema README, add it to source control, and require schema diff reviews for connector merges. |
| Connector config | Before/after images, primary keys, and tombstones are explicitly enabled in configuration. | Review connector settings with platform engineering and add automated config tests in CI. |
| Consumer alignment | Downstream services have idempotent handlers and are storing envelope metadata they depend on. | Host a contract walkthrough, annotate payload fields, and run a replay drill with each critical consumer. |
| Monitoring | Envelope validation job runs on a schedule with alerting for missing fields or unexpected types. | Add schema validation output to observability dashboards and alert on consecutive failures. |

## Monitor drift and data contract guardrails

### Real-time monitors

- Lag freshness checks for each topic partition and consumer group.
- Contract-based anomaly detection on payload nullability and enum values.
- Connector task health alerts tied to restart runbooks.

### Weekly governance loops

- Review schema diff reports for new fields, renamed columns, or deleted metadata.
- Spot check downstream warehouses for late-arrival reconciliation accuracy.
- Capture breaking change proposals in an RFC log with owner sign-off.

Tie monitors back to owners: every alert should have a responder rotation, a playbook link, and a communication channel to pause downstream consumers if contract drift is detected.

### Event Envelope Knowledge Check

Test your understanding of CDC event structure and delivery guarantees.

Q1

#### What is the purpose of the 'before' and 'after' fields in a CDC event envelope?

A They store the timestamp before and after processing

B They capture the row state before the change and the new state after the change

C They indicate the order of events in the stream

D They are used only for delete operations

Q2

#### What does 'at-least-once' (ALO) delivery guarantee mean in CDC?

A Each event is delivered exactly one time, never more

B Events may be delivered multiple times, so consumers must handle duplicates

C Events are delivered in random order

D Only the most recent event is delivered

Q3

#### What is a tombstone event in CDC?

A An event that signals the end of a transaction

B A special event with a null value used to indicate a deleted record for compacted topics

C An error event when CDC fails to capture a change

D The first event in a snapshot

Q4

#### Why is per-key ordering important in CDC streams?

A It ensures events for the same entity are processed in the correct sequence

B It makes the stream faster

C It reduces storage requirements

D It eliminates the need for timestamps

Q5

#### What information does the 'source' metadata in a CDC event typically include?

A The consumer's IP address and client ID

B Database name, table name, and log position (LSN/SCN)

C The CDC tool's version number

D The size of the event in bytes

**0/5** correct

## Further resources

- [Schema evolution](https://sandgraal.github.io/letstalkcdc/schema-evolution/) for versioning and registry workflows.
- [Ops: Offsets & Replays](https://sandgraal.github.io/letstalkcdc/ops-offsets/) for rewind-and-replay recovery drills.
- [Observability basics](https://sandgraal.github.io/letstalkcdc/observability/) to wire the envelope monitors you designed.

---

CDC: The Missing Manual by Christopher Ennis (Let's Talk CDC), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Attribution is required.
