---
name: streaming-cdc-contract
description: "Use when writing or reviewing a consumer of a change-data-capture (CDC) stream — Debezium / Kafka / binlog / logical-replication change events landing in a sink or warehouse table. Branch on the operation type (insert vs update vs delete) instead of appending every event, recognize null-value tombstones, apply a key's events in offset/LSN order with the highest position winning, upsert idempotently because delivery is at-least-once, and honor the sink's soft- vs hard-delete policy for delete events. Do NOT use for batch/ETL rerun-safety (that is pipeline-idempotency), general Kafka throughput/partition tuning, or one-off ad-hoc queries."
metadata:
  decimalai-skill-id: "72752b67-d7a6-4653-8eba-f0fdd3098ac3"
  decimalai-version-id: "7e4f47cd-930d-4e82-b9d6-e5e17654ffde"
  decimalai-version: "1"
  decimalai-body-sha256: "ad58b7c816d1b2448001d2b4c4025039e2edd1ac7387ddc3dd7d87c8d9c4b8c8"
  decimalai-name: "streaming-cdc-contract"
  decimalai-format: "1"
  decimalai-invocation: "model"
  decimalai-category: "data"
  decimalai-source: "https://app.decimal.ai/s/streaming-cdc-contract@1/SKILL.md"
---
# Consuming a change-data-capture stream

A CDC stream is **not** a log of things to append. Each event describes what happened to *one row in a source table* — it was created, changed, or deleted — and your job is to make the sink reflect the source's *current state*, not to accumulate one row per event. The base default is to deserialize each event and `INSERT` it. That is wrong: one row's create → update → update becomes three sink rows, deleted rows never disappear, a redelivered event double-counts, and a null-value record crashes the parser. Apply all five rules below.

A typical event (Debezium envelope shown; binlog and logical-replication payloads carry the same fields under other names):

```json
{
  "op": "u",                     // c=create/insert, u=update, d=delete, r=snapshot read
  "before": { "id": 7, "email": "a@x" },
  "after":  { "id": 7, "email": "b@x" },
  "source": { "lsn": 402096, "ts_ms": 1710000000123 }
}
```

## 1. Branch on the operation type — don't append

Read the op field and take a different action per type; never treat the whole stream as inserts.

- **c / insert** → upsert the `after` image (insert-or-replace on the key).
- **u / update** → apply the **`after`** image to the existing key (the new state; `before` is only the prior value, for diffing). An update is an upsert, not a second row.
- **d / delete** → remove or soft-delete the key (see rule 5). The row's state lives in `before`; `after` is null.
- **r / read** (snapshot backfill at connector start) → upsert the `after` image, same keyed apply as an insert. Snapshot reads represent rows that already exist; upserting makes them idempotent with the live events that follow.

If you `INSERT` every event regardless of op, updates fan out into duplicate rows and deletes are silently ignored. The sink drifts from the source and nothing errors.

## 2. Recognize tombstones (null-value records)

On a log-compacted topic, a delete is often followed by a **tombstone**: a record with the key populated and the **value/payload null**. It is not a row and not an insert — it is a marker that the key is gone, emitted so compaction can garbage-collect that key's history. A consumer that blindly deserializes `value.after` will throw a null-pointer error or write a blank/garbage row.

Detect the null-value record before parsing. What to do with it depends on the source config:

- If the connector also emits an explicit `d` event, the tombstone is redundant — **skip it**; the `d` already carried the delete.
- If deletes are represented **only** by tombstones (no separate `d`), the null-value record **is** the delete signal — act on it and remove/soft-delete the key.

Either way, a tombstone is never data.

## 3. Apply in offset / LSN order — latest position wins per key

Correctness depends on applying a key's events in **commit order**, and each event carries a monotonic position: Postgres LSN, MySQL binlog file+position, a Kafka partition offset, or a source sequence / `ts_ms`. CDC connectors key each event by the row's primary key, so one row's events land on one partition **in order** — within a partition, offset order *is* commit order.

Do not order by wall-clock arrival time, and do not trust global ordering across partitions or across a replay. After a rebalance, restart, or replay you can see a key's events re-delivered or interleaved. Guard every apply with a **version check**: store the last-applied position on the row and apply an event only if its position is **greater** than the stored one. That way a stale, re-delivered, or out-of-order event can never clobber newer state — e.g. an old update arriving after a newer delete is dropped, not applied.

## 4. Apply idempotently — delivery is at-least-once

CDC transports (Kafka, Kinesis, Debezium) guarantee **at-least-once**, not exactly-once. Any event may be redelivered after a consumer restart or an offset-commit gap. So the apply must be a no-op on redelivery:

- **Upsert on the source primary key** — `INSERT ... ON CONFLICT (pk) DO UPDATE` / `MERGE`, never a blind `INSERT`. The conflict key must be the **source PK carried in the event**, not an auto-increment surrogate the sink assigns — a surrogate never matches on replay and still duplicates.
- **Gate by the stored position** (rule 3) so replaying an already-applied event changes nothing.
- **Commit the source offset only after the sink write succeeds** (or write sink + offset atomically). Committing the offset first turns a crash into *lost* events, because at-least-once has silently become at-most-once.

## 5. Honor soft- vs hard-delete

A `d` event means the row was deleted **at the source**. What the sink does about it is a **policy set by the sink's contract**, and you must follow it rather than guess:

- **Hard-delete** — physically `DELETE` the key from the sink. Use when the sink only tracks current state.
- **Soft-delete** — keep the row and set `is_deleted = true` / `deleted_at = <event ts>`. Use when downstream needs deletion history, slowly-changing dimensions, or an audit trail. The row stays for history but must be **excluded from "current" reads** (filter `WHERE NOT is_deleted`).

The one thing you must never do is **ignore `d` events**. Dropping deletes leaves ghost rows in the sink that no longer exist upstream — the most common CDC correctness bug after treating everything as an append.

## Quick checklist

1. Switch on `op` (c/u/d/r) — each type does something different; nothing is a blind append.
2. Null-value record = tombstone; skip it or treat it as the delete, per source config — never parse it as data.
3. Order each key by LSN/offset; apply only if the event's position beats the stored one.
4. Upsert on the source PK and gate by position — at-least-once means events repeat.
5. Deletes are honored per the sink's soft/hard policy; never silently dropped.
