Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A CDC pipeline applies row changes from Kafka into a PostgreSQL read model. After the topic was resized from 6 to 24 partitions, some rows in the read model show older values than the source, and the errors persist until the row changes again.

Explain how out-of-order changes reached the sink, and write the SQL upsert that makes the sink ignore stale changes.

Kafka keeps order only within a partition. Resizing the topic from 6 to 24 partitions moved many keys to new partitions, so newer changes on a new partition were applied while older changes for the same row still waited in the backlog of the old one, and those older changes then overwrote them. We fix it by carrying the source log position (the PostgreSQL LSN or the MySQL binlog file and position) into the sink and upserting only when the incoming position is newer.

Why this question is asked

Ordering bugs are the hardest kind of pipeline bug, because nothing fails: every message is consumed, every write succeeds, and the data is simply wrong. Interviewers like this one because it tests whether we know what Kafka actually guarantees and whether we can make a sink defend itself instead of trusting delivery order. In this answer, we will recap how a CDC topic keeps order, trace what the resize did to one row, write the guarded upsert, handle deletes, and then repair the damaged rows.

1A Quick Recap of How the Pipeline Keeps Order

Debezium publishes each row change as a Kafka record whose key is the row's primary key. Kafka's default partitioner hashes the key and takes the result modulo the number of partitions, so all changes to customer 42 land on the same partition. Within one partition Kafka keeps records in the order they were written, and one consumer reads a partition in that order. That is the only ordering Kafka promises: there is no order between different partitions.

As long as the partition count never changes, this is enough. Every change to a given row travels through a single, ordered lane, so the sink applies them in commit order even though it has no idea what order means.

2What the Resize Did to One Row

Changing the partition count changes the result of hash modulo count. Customer 42 might have hashed to partition 3 out of 6, and now hashes to partition 17 out of 24. The consumers were lagging when the resize happened, so partition 3 still held unread changes for customer 42 while new changes started arriving on partition 17.

Step throughTwo changes to customer 42 take different lanes
Source DBPartition 3 (old)Partition 17 (new)Sink
status=ACTIVE at LSN 100 (before resize)
status=CLOSED at LSN 250 (after resize)
apply CLOSED: partition 17 has no backlog
apply ACTIVE: backlog finally drained
row now says ACTIVE, source says CLOSED

5 messages in order. Play them, or step through them one at a time.

Kafka kept order inside each partition; the row's changes were simply split across two.

Notice that partition 17 was empty and was read immediately, while partition 3 had a backlog. So the newer change reached the sink first and the older one second. A plain upsert simply writes whatever arrives, so the older value won. The error persists because nothing else is coming for that row; only the next real change to customer 42 overwrites it. The same thing happens without any resize if records are produced without a key, because unkeyed records are spread over partitions with no regard for which row they belong to.

3Carrying the Source Position

The fix is to stop relying on delivery order and let the sink compare versions. Every Debezium event has a source block that says where in the database log the change came from. In PostgreSQL that is the LSN, the log sequence number, a byte position in the WAL that only grows. In MySQL it is the binlog file name and the position in it, which compare as a pair. For one row, each later committed change has a higher position, because a second writer of the same row has to wait for the first to commit, and the log is written in that order.

We store that position in the sink row itself, in a column such as src_lsn. Now the sink knows which version of the row it holds and can refuse anything older.

4Writing the Guarded Upsert

Here is the upsert the sink was running, and what it did with the two changes above.

Java
-- Before: last writer wins
INSERT INTO customer_view (id, name, status) VALUES (42, 'Ana', 'CLOSED')
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, status = EXCLUDED.status; -- 1 row: CLOSED
INSERT INTO customer_view (id, name, status) VALUES (42, 'Ana', 'ACTIVE')
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, status = EXCLUDED.status; -- 1 row: ACTIVE (stale)
-- After: only a newer source position may overwrite
ALTER TABLE customer_view ADD COLUMN src_lsn bigint NOT NULL DEFAULT 0;
INSERT INTO customer_view (id, name, status, src_lsn)
VALUES (:id, :name, :status, :lsn)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, status = EXCLUDED.status, src_lsn = EXCLUDED.src_lsn
WHERE customer_view.src_lsn < EXCLUDED.src_lsn;
-- (42, 'Ana', 'CLOSED', 250) -> INSERT 0 1 row is CLOSED, src_lsn 250
-- (42, 'Ana', 'ACTIVE', 100) -> INSERT 0 0 ignored, 100 < 250 is false
-- (42, 'Ana', 'CLOSED', 250) -> INSERT 0 0 a redelivered duplicate is ignored too

The WHERE clause on DO UPDATE is the whole trick. When it is false, PostgreSQL leaves the existing row untouched and reports zero rows affected, so a stale change becomes a harmless no-op. Because we use strict less-than, a redelivered copy of the same change is also ignored, which makes the sink idempotent. In the consumer we read source.lsn from the Debezium envelope and pass it as :lsn; for MySQL we would store the binlog file and position (or a single number derived from them) and compare the pair.

5Handling Deletes Without Resurrecting Rows

Deletes need the same protection. If we delete the sink row outright, the row and its src_lsn are gone, and a late update for that row arrives to an empty table, inserts itself, and brings a deleted customer back to life. So instead of deleting, we keep a tombstone: the row stays with a deleted flag and the delete's position.

SQL
INSERT INTO customer_view (id, deleted, src_lsn) VALUES (:id, true, :lsn)
ON CONFLICT (id) DO UPDATE SET deleted = true, src_lsn = EXCLUDED.src_lsn
WHERE customer_view.src_lsn < EXCLUDED.src_lsn; -- late updates now lose to the delete
-- nightly: purge tombstones older than any possible lag
DELETE FROM customer_view WHERE deleted AND deleted_at < now() - interval '7 days';

Queries on the read model filter out deleted rows. The purge window must be longer than the worst lag we expect, so that no older change can still be in flight when the tombstone disappears.

6Repairing the Damage and Preventing It

The guard protects us from now on, but rows already overwritten by stale changes stay wrong. We repair them with a targeted re-snapshot of the affected table. Debezium supports incremental snapshots triggered through a signal table, which re-read the current rows while streaming continues; those snapshot events carry current positions, so the guarded upsert applies them over the stale rows. If we know the time window of the resize, we can also compare the sink with the source for rows changed in that window and fix only those.

For prevention, we treat the partition count of a CDC topic as fixed. If it must change, we drain first: pause the connector, let every consumer reach zero lag, resize, and resume, so no old changes are waiting when keys move. An alternative is to create a new topic with the new count and move the connector and consumers over together. The guarded upsert stays in place regardless, because it also protects against replays and any future reordering.

7Follow-up questions

Why is a source timestamp a weaker guard than the log position?

Timestamps have limited resolution, so two changes to the same row within the same millisecond compare as equal and the guard cannot decide. Timestamps can also come from clocks that are adjusted, and the timestamp of a change is not necessarily the order in which changes were committed. The log position is assigned by the database as it writes the log, it is strictly increasing, and for one row it follows commit order, so it gives an exact answer every time.

Would idempotent consumers alone have prevented this?

No. Idempotence means applying the same change twice has the same effect as once, which handles duplicates. Here the problem was two different changes in the wrong order. Only a version comparison, like the source position guard, handles reordering.

Can we avoid the problem by using a single partition?

A single partition keeps total order but limits consumption to one consumer, which caps throughput. The better approach is many partitions keyed by primary key, a partition count that does not change, and a sink that guards with the source position anyway.

8Conclusion

In this answer, we saw that Kafka orders records only within a partition, so resizing a CDC topic moved keys to new partitions while their older changes still waited in old backlogs, and a last-writer-wins sink applied them out of order. We fixed it by storing the source LSN or binlog position in each sink row and using an upsert whose DO UPDATE runs only when the incoming position is newer, kept tombstones so late updates cannot resurrect deleted rows, repaired the damage with a re-snapshot, and agreed never to resize CDC topics without draining them first.

What to say in the interviewAbout 80 seconds aloud

Open with

Kafka only guarantees order within a partition. Debezium keys each change by primary key, so normally all changes for a row go through one partition in order. When the topic went from 6 to 24 partitions, the hash modulo the partition count changed, so many keys moved.

Then, if they want more

The consumers had lag, so older changes for a row were still waiting on the old partition while newer ones arrived on the new, empty partition and were applied first. Then the old ones arrived and our last-writer-wins upsert overwrote the newer data, and the row stays wrong until it changes again.

The fix is to carry a monotonic source position with each change, the PostgreSQL LSN or the MySQL binlog file and position from the Debezium source block, store it in the sink row, and upsert with ON CONFLICT DO UPDATE ... WHERE customer_view.src_lsn < EXCLUDED.src_lsn, so stale or duplicate changes are no-ops.

For deletes I keep a tombstone with its position for a while, otherwise a late update would bring the row back. Then I repair with an incremental re-snapshot of the table and make it a rule that CDC topics are never resized without draining them first.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain how out-of-order changes reached the sink, and write the SQL upsert that makes...": https://scrivio-interview-library.netlify.app/architecture/storage-and-pipelines/ce166f8df9/