# Partitioning & Reconciliation

> CDC partitioning and reconciliation: choose keys, handle skew, preserve per-key order, and make late arrivals safe with log-position version guards.

Canonical page: <https://sandgraal.github.io/letstalkcdc/partitioning/>

> **Known errata for this page (1)**
>
> - **Corrected: ts_ms is not a tie-break** (updated 2026-10-12)
>
>   The page said to keep `ts_ms` for lag metrics and, at most, as a secondary tie-break. That contradicted the materialization page and the rest of this page, which keep it out of ordering. It now says to keep `ts_ms` for lag metrics only and to use the within-transaction ordinal as the tie-break. The simulator's "Ordering guarantee" readout used to say "Per-key" whatever the settings; when the hot key is split over several shards it now says that per-key order is broken for the hot key. The PostgreSQL example is now stated as run on PGlite, and the BigQuery example as not run. The static line under the readout no longer says "per-key only", which the readout can contradict.
>
> [See all corrections and caveats](https://sandgraal.github.io/letstalkcdc/errata/)

Design Kafka topics that preserve per-entity ordering, tame skew, and make late arrivals safe with log-position version guards.

Respect Ordering Pick Partition Keys

## The Golden Rule of Kafka Ordering

Kafka guarantees the order of messages *within a single partition*. It makes no ordering guarantees *across* different partitions. Therefore, to maintain the correct sequence of changes for any given entity (like a specific customer or a single product), **all changes for that entity must be sent to the same partition.** This is the fundamental purpose of a [partition key](https://sandgraal.github.io/letstalkcdc/glossary/#partition-key).

That ordering is the order in which records were appended to the partition, and delivery is still [at-least-once](https://sandgraal.github.io/letstalkcdc/glossary/#at-least-once): a restart or replay hands the consumer records it has already seen. Partitioning narrows how much reordering a sink must absorb; it does not remove the need for the sink to be idempotent (see Making Sinks Bulletproof).

## Partition sizing (rule-of-thumb)

Start with a target throughput per partition your consumers can sustain (1–5k events/s).

- **Baseline:** `partitions ≈ ceil(total_events_per_s ÷ target_per_partition)`
- **Include skew headroom:** multiply by 1.5–2× if distribution is Zipf-y or you have hot tenants.
- **Changing partitions later:** adding partitions *does not* move existing records, but it changes which partition a key maps to (the default partitioner uses `hash(key) mod partition_count`). New events for a key can land on a different partition than its older ones, so per-key order is no longer guaranteed across that change. Plan the partition count up front, or cut over to a new topic after the old topic is drained (per-key order across the cutover holds only then).

## How to Choose a Good Partition Key

The quality of your partition key directly impacts both the correctness and performance of your system.

### Good Keys (Preserve Order & Distribute Load)

- **`customer_id`, `order_id`, `product_id`:** The primary key of the business entity. This is the most common and effective choice for preserving per-entity order.
- **`tenant_id` + `customer_id`:** In a multi-tenant system, a composite key can help distribute load from a single large tenant (the "noisy neighbor" problem) across multiple partitions.

### Bad Keys (Lead to Incorrect Order or Skew)

- **`event_id` (a UUID):** This distributes load perfectly but completely destroys per-entity ordering, as subsequent updates for the same customer will land on different partitions and can be processed out of order.
- **A low-cardinality field like `country_code`:** All events for a large country would be sent to a single partition, creating a massive hot spot (partition skew) and slowing down processing for that entire partition.

### Mitigations for hot keys (keep per-entity order)

- **Tenant-scoped keys:** `tenant_id || ':' || entity_pk` preserves order per entity and spreads large tenants.
- **Key salting (shards per entity-family):** For *families* like “all events of a giant tenant,” append a bounded salt: `tenant_id || ':' || (hash(entity_pk) % N)`. Order is preserved *within* the salted sub-stream; readers that need global per-tenant order should avoid salting.
- **Topic split by domain:** Put ultra-hot tenants or tables on their own topic to isolate spikes.

## Partitioning Simulator: The Impact of Key Choice

**Controls**

Partitions 6 Distinct keys (entities) 1000 Events / sec (total) 5000 Key distribution Skew stresses single partitions. If “Hot”: % of traffic to 1 key 40% Consumer capacity per partition (events/s) 2000 Shards per hot key (salting) 1

### Max partition rate

—

Events/s on the hottest partition.

### P95 partition rate

—

Load tail—capacity planning.

### Estimated lag

—

Seconds to drain if max > capacity.

### Ordering guarantee

Per-key

Global order is not guaranteed.

**Partition load (events/s)**

Tip: If one bar dominates, you have partition skew. Consider a better key (include a tenant ID or sharding suffix), or move hot tenants to their own topic/cluster.

## Making Sinks Bulletproof: Version Guards & Watermarks

Even with perfect partitioning, delivery is at-least-once: retries, consumer restarts and replays deliver the same event again, and a rewind, a repartition or a re-snapshot can show your sink an older change after a newer one. Correctness comes from an idempotent sink keyed on the primary key and ordered by the source's log position, so your target table needs a primary key and a log-position column:

1. **`id`:** The primary key of the entity.
2. **`source_lsn` (the log position):** The position of the change in the source's transaction log, copied from the event as-is. It increases in commit order for a given key within one source log (row locks serialise writers per key), so it says which change is newer. Pick the field that is unique per change:
   - **PostgreSQL:** `source.lsn`, where the connector provides a per-change position (positions are unique in practice, but verify this for your connector version).
   - **SQL Server:** compare (`commit_lsn`, `change_lsn`, `event_serial_no`) as a tuple. `commit_lsn` alone is shared by every change in a transaction.
   - **Oracle:** `scn`, with `rs_id` and `ssn` to separate changes that share an SCN (verify the ordering semantics for your Debezium version). `commit_scn` is shared by the whole transaction, and `scn` can repeat across changes in it.
   - **MySQL:** binlog file, `pos` and the row index, because several rows can share one binlog row event.

**Uniqueness.** The guard below assumes the position is unique per change for a key, or is paired with a sequence (as the BigQuery example does with `seq`). If an INSERT and an UPDATE of one key in one transaction share a position, a strict `<` skips the UPDATE and the row stays stale. An equal position is always skipped; that is correct only when it is the same change.

**Comparing.** Compare positions numerically or as a typed tuple, never as free text: the text LSNs `0/9` and `0/10` sort the wrong way round, SQL Server LSNs and Oracle SCNs arrive as strings in Debezium, and MySQL needs a (file, pos[, row]) comparison. Fixed-width hex strings (SQL Server) compare correctly as text only if all values are the same width.

**Lineage.** Positions are comparable only within one source log lineage. After a failover that loses the old primary's tail, a point-in-time restore, a move to a different server or cluster, or a binlog reset (not a normal rotation or a new [replication slot](https://sandgraal.github.io/letstalkcdc/glossary/#replication-slot) on the same cluster), positions can restart lower, and the guard skips every change until the new position passes the stored one. Version the lineage, for example a `source_epoch` column that you compare first, then the position. A GTID is not listed above because GTIDs are comparable only within one server UUID, and file plus position is likewise not portable across servers. A primary-key change is a delete plus an insert, so “for a given key” does not span it.

**Not a Kafka offset.** A Kafka offset is a position in the Kafka log, not the source log. A connector restart re-emits earlier changes at new, higher offsets, so an offset guard would accept them as newer. Use offsets for consumer progress only, never as the row version.

**Not a timestamp.** Do *not* use `ts_ms` as the version. Clocks on different hosts disagree (clock skew), and several changes to one row can share the same millisecond, so the comparison ties. The envelope `ts_ms` (when the connector processed the event) is later on every replay, and snapshot rows carry the snapshot time, so a stale value can win. `source.ts_ms` keeps the original commit time on a replayed streaming event, but it is still millisecond-coarse and clock-dependent. Keep `ts_ms` for lag metrics only; use the ordinal as the tie-break.

The consumer then uses a `MERGE` (or `INSERT...ON CONFLICT`) statement with a crucial `WHERE` clause: **only update the target row if the incoming event's log position is greater than the position already stored.** A replay of the same change carries the same position it had the first time, so the strict comparison skips it.

**Deletes.** A physical `DELETE` removes the version column along with the row, so a late, replayed older update would match nothing, hit `WHEN NOT MATCHED` and resurrect the row. Retain a delete marker instead: a `deleted` flag plus the delete's position on the row, or a separate table of deleted keys and their positions. The cost is that delete markers need a retention and cleanup policy, and reads must filter `deleted = false`. This is the “remove or flag” choice described on [Materialization](https://sandgraal.github.io/letstalkcdc/materialization/). Ignore Kafka null-value tombstone records here: they follow a delete event for log compaction and carry no position. How BigQuery, Databricks, Hudi, Iceberg, Delta and Snowflake take the position and keep the delete: [Which Row Wins in Your Target](https://sandgraal.github.io/letstalkcdc/which-row-wins/).

**[Watermark](https://sandgraal.github.io/letstalkcdc/glossary/#watermark) (aggregates only):** event time is the right axis for closing time windows, but never for deciding which version of a row wins. If events can arrive late, advance a per-table watermark (“safe up to T-Δ”) before finalizing aggregates. Late events ≤ Δ update rows; older ones are quarantined or appended to a corrections table.

### Production-Ready Idempotent Sink Pattern (Postgres)

```
-- Assumes target table has a primary key `id`, a `deleted` flag and a column
-- `source_lsn` (BIGINT) holding the log position carried in the event, e.g.
-- Debezium `source.lsn`. It is a log position, not a clock time.
-- Assumes the connector provides a per-change position (unique in practice
-- for Postgres). If several changes to one `id` can share a position, add a
-- `seq` tie-break as in the BigQuery example below.
-- MERGE applies as a single atomic statement, but it is NOT immune to
-- concurrency: under READ COMMITTED a racing INSERT of the same `id` can
-- still raise a unique_violation. For high-contention upserts prefer
-- INSERT ... ON CONFLICT (id) DO UPDATE, or retry the MERGE on conflict.

MERGE INTO target_table T
USING (
  SELECT
    :entity_id::bigint AS id,      -- use your key's type
    :payload::jsonb AS payload,    -- NULL for a delete: column must be nullable
    :op::text AS op,
    :source_lsn::bigint AS lsn
) AS S
ON (T.id = S.id)
WHEN MATCHED AND T.source_lsn  S.lsn THEN
  -- Only update if the incoming event is later in the log;
  -- a replay of the same change (same lsn) matches nothing.
  -- A delete is kept as a delete marker (deleted = true + its lsn), so a
  -- late older update cannot resurrect the row. Reads filter deleted = false.
  UPDATE SET
    payload = S.payload,
    deleted = (S.op = 'd'),
    source_lsn = S.lsn
WHEN NOT MATCHED THEN
  -- If the record doesn't exist, create it (a delete creates a delete marker)
  INSERT (id, payload, deleted, source_lsn)
  VALUES (S.id, S.payload, (S.op = 'd'), S.lsn);
```

Executed on PGlite (PostgreSQL compiled to WebAssembly) by this site’s unit tests, with the `:name` placeholders replaced by literals: insert, replay, late older change and delete marker. It has not been run on a PostgreSQL server.

### Tie-break within one log position (sequence) — BigQuery example

```
-- `lsn` is the source log position. `seq` orders events that share one
-- position, e.g. the event's index within its transaction (Debezium
-- `transaction.total_order`, where the connector provides one; it needs
-- transaction metadata enabled).
-- Not shown: the delete marker (see Deletes above). `@lsn` is INT64, so SQL
-- Server / Oracle string positions need a typed comparison first.
MERGE `dw.target` T
USING (SELECT @id AS id, @lsn AS lsn, @seq AS seq, @payload AS p) S
ON T.id = S.id
WHEN MATCHED AND (T.lsn < S.lsn OR (T.lsn = S.lsn AND T.seq < S.seq)) THEN
  UPDATE SET payload = S.p, lsn = S.lsn, seq = S.seq
WHEN NOT MATCHED THEN
  INSERT (id, lsn, seq, payload) VALUES (S.id, S.lsn, S.seq, S.p);
```

Untested: not run against a live BigQuery project. Check it against your own schema before use.

A primary-key [upsert](https://sandgraal.github.io/letstalkcdc/glossary/#upsert) with a log-position guard makes the sink idempotent for updates: transport stays at-least-once, and duplicates and late arrivals become no-ops (deletes need the retained delete marker described above). That is exactly-once *processing*. End-to-end exactly-once across independent systems is not achievable; see [Exactly-Once Semantics](https://sandgraal.github.io/letstalkcdc/exactly-once/).

## Audit loops (detect & repair)

- **Windowed row-counts:** compare source vs sink counts over event-time windows (for example 5-minute buckets).
- **Windowed checksums:** compute hash aggregates (`SHA1` of concatenated key fields) per window and diff.
- **Automatic rewind:** on mismatch, rewind the consumer to an offset before the affected window and re-process. Kafka rewinds per partition, so unaffected keys are re-read too; the idempotent, log-position-guarded sink makes that safe.
- **Quarantine queue:** route irreconcilable records to a DLQ with enough context to replay or manually fix.

### Partitioning Knowledge Check

Test your understanding of partition key selection and ordering guarantees.

Q1

#### Why is choosing the right partition key critical in CDC?

A It determines which broker stores the data

B It ensures all events for the same entity are routed to the same partition, preserving order

C It controls the compression algorithm

D Partition keys are optional and don't affect functionality

Q2

#### What is partition skew, and why is it a problem?

A When all partitions have exactly the same data

B When some partitions receive disproportionately more data than others, causing hotspots

C When partitions are stored on different disks

D Skew is not a real problem in production systems

Q3

#### What is a 'late-arriving' event in CDC?

A An event that arrives after the topic is deleted

B An event that arrives after a later change to the same row, due to delays, retries or replays

C An event that is always corrupted

D Events can never arrive late in CDC

Q4

#### How can you mitigate partition skew caused by a single hot key?

A Delete the partition with the hot key

B Use a composite key with additional entropy (e.g., append a sub-ID) or implement key salting

C Reduce the number of partitions

D Partition skew cannot be mitigated

Q5

#### What is an audit loop in the context of CDC partitioning?

A A process that manually reviews all events

B A background job that periodically reconciles source and sink to detect missing or out-of-order events

C A performance optimization technique

D Audit loops are only used in batch systems

**0/5** correct

---

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.
