Advanced

Partitioning & Reconciliation

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

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.

That ordering is the order in which records were appended to the partition, and delivery is still 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).

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)

Bad Keys (Lead to Incorrect Order or Skew)

Mitigations for hot keys (keep per-entity order)

Partitioning Simulator: The Impact of Key Choice

Controls
6 1000 5000 Skew stresses single partitions. 40% 2000 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 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. 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.

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 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.

Audit loops (detect & repair)

Partitioning Knowledge Check

Test your understanding of partition key selection and ordering guarantees.

Q1

Why is choosing the right partition key critical in CDC?

Q2

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

Q3

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

Q4

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

Q5

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

0/5 correct
Progress 0% No progress yet
Progress is stored locally in this browser.