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).
-
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_pkpreserves 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
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
Global order is not guaranteed.
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:
-
id: The primary key of the entity. -
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_lsnalone is shared by every change in a transaction. -
Oracle:
scn, withrs_idandssnto separate changes that share an SCN (verify the ordering semantics for your Debezium version).commit_scnis shared by the whole transaction, andscncan repeat across changes in it. -
MySQL: binlog file,
posand the row index, because several rows can share one binlog row event.
-
PostgreSQL:
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)
- Windowed row-counts: compare source vs sink counts over event-time windows (for example 5-minute buckets).
-
Windowed checksums: compute hash aggregates (
SHA1of 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.
Why is choosing the right partition key critical in CDC?
The partition key determines which partition an event is written to. Since Kafka only guarantees ordering within a partition, using the entity's primary key (e.g., order_id, user_id) as the partition key keeps all changes for that entity in one partition, in order. That removes most reordering, but delivery is still at-least-once, so the sink must also guard on the source's log position.
Review the correct answer and explanation.
What is partition skew, and why is it a problem?
Partition skew occurs when data is unevenly distributed across partitions, often due to poor key selection (e.g., using a tenant ID when one tenant dominates traffic). This creates hotspots—overloading some partitions/brokers while others sit idle—leading to reduced throughput, increased latency, and consumer lag.
Review the correct answer and explanation.
What is a 'late-arriving' event in CDC?
Late-arriving events occur when network delays, retries, multi-partition reads, or replays cause an older event to arrive after a newer one. Without a version guard that compares the source's log position (LSN/SCN/binlog position, not a timestamp), consumers might apply changes out of order, corrupting state (e.g., overwriting new data with old). Watermarks are for closing time windows on aggregates, not for choosing which row version wins.
Review the correct answer and explanation.
How can you mitigate partition skew caused by a single hot key?
If a single entity generates massive traffic (e.g., a celebrity user_id), you can use a composite key that adds entropy (user_id + session_id) or implement key salting (appending a hash suffix). This spreads load across partitions, but per-entity order then holds only within each sub-stream; a streaming consumer cannot recreate the intermediate order without unbounded buffering. The sink's log-position guard keeps the final row correct, not the sequence of changes in between.
Review the correct answer and explanation.
What is an audit loop in the context of CDC partitioning?
An audit loop (or reconciliation job) compares the source database with the downstream sink to detect discrepancies—missing events, late arrivals, or out-of-order updates. This provides a safety net, catching issues that might slip through the streaming pipeline due to partitioning challenges or failures.
Review the correct answer and explanation.