Quick revision
The short answer
We split the problem in two. The initial load bulk-indexes a consistent snapshot of the 30 million rows into a new index with the _bulk API, with refresh turned off and zero replicas, then restores those settings and switches an alias. Ongoing changes flow from a transactional outbox or from Debezium reading PostgreSQL's write-ahead log into Kafka, and an idempotent consumer builds each document and indexes it with an external version such as the LSN, handling deletes from tombstones; lag monitoring and a periodic count and checksum reconciliation prove we stay within 5 seconds.
What to remember
In this answer, we designed sync from PostgreSQL to OpenSearch in two parts. The initial load bulk-indexes a consistent snapshot into a new index with refresh disabled and no replicas, then restores settings and swaps an alias, while a replication slot created first guarantees no change is missed. Ongoing changes come from Debezium or an outbox through Kafka, partitioned by id, into an idempotent consumer that joins related data and indexes with external versions from the LSN, turning tombstones into deletes. Lag metrics prove the 5-second target, and a nightly count and checksum reconciliation proves the copies agree.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We split the problem in two. The initial load bulk-indexes a consistent snapshot of the 30 million rows into a new index with the _bulk API, with refresh turned off and zero replicas, then restores those settings and switches an alias. Ongoing changes flow from a transactional outbox or from Debezium reading PostgreSQL's write-ahead log into Kafka, and an idempotent consumer builds each document and indexes it with an external version such as the LSN, handling deletes from tombstones; lag monitoring and a periodic count and checksum reconciliation prove we stay within 5 seconds.
Why this question is asked
Copying data into a search engine once is easy. Keeping 30 million rows in step with a live database, through restarts, deploys and bugs, without ever having to say 'search is probably right', is a real design problem. Interviewers ask it because it tests how we combine bulk loading, change streams, ordering, deletes and verification into one system. In this answer, we will set out the requirements, design the initial load, connect the load to the change stream without a gap, build the indexing consumer, handle deletes, and finish with the monitoring and reconciliation that let us promise 5 seconds.
1What the Requirements Really Ask For
Eventual consistency within 5 seconds means that after a row commits in PostgreSQL, the matching document in OpenSearch reflects it within 5 seconds, and if nothing else changes, the two copies agree completely. It does not mean every search sees every change instantly. Each stage takes a slice of that budget: capture, Kafka, indexing, and OpenSearch's one-second refresh.
If an average document is 2 KB, 30 million rows make about 60 GB of source data, which fits in two or three primary shards in the commonly recommended 10 to 50 GB range.
2The Initial Load: Bulk Index a Consistent Snapshot
We load into a new index, say products_v1, and point an alias named products at it only when it is ready. Two settings speed up the load: refresh_interval set to -1 stops OpenSearch from creating searchable segments every second, and number_of_replicas set to 0 writes each document once; adding the replica afterwards copies whole segments, which is much cheaper.
Several loader threads read the table in primary key ranges and send _bulk requests of a few thousand documents, roughly 5 to 15 MB, growing the size until throughput stops improving or OpenSearch returns 429 Too Many Requests, and retrying rejected items with backoff. At 20,000 documents per second, 30 million rows take about 25 minutes. When the load finishes, we restore refresh_interval to 1s, set replicas to 1, wait for the cluster health to be green, and swap the alias.
3Joining the Snapshot and the Change Stream Without a Gap
The hard part is the hand-over: the table keeps changing during the load, so we start capturing changes before the load begins and record exactly where the snapshot sits in the change history.
Debezium does this for us if we let it take the initial snapshot: it creates a replication slot, which makes PostgreSQL keep the write-ahead log from that point, reads the table in a consistent snapshot, and then continues streaming from the same position. If we load with our own tool instead, we create the slot first, export its snapshot, read the rows inside that exported snapshot, and then start the consumer from the slot. Either way, the external version saves us from the overlap: every document carries a version from the log, so if a snapshot row and a streamed change for the same id arrive in either order, the newer one wins.
- Create the replication slotPostgreSQL keeps WAL from here
- Read a consistent snapshotsame point as the slot
- Bulk load products_v1refresh -1, replicas 0
- Restore settings, swap aliasrefresh 1s, replicas 1
- Stream changes from the slotDebezium -> Kafka -> indexer
- Newer version wins any overlapexternal version from the log
6 steps in order. Play them, or step through them one at a time.
The slot exists before the snapshot is read, so no change made during the load can be lost.
4Ongoing Changes: Outbox or Change Data Capture
For the live stream we have two good options. With a transactional outbox, the service inserts an event row into an outbox table in the same transaction as the business change, and a relay publishes those rows to Kafka. With change data capture, Debezium reads the write-ahead log, where PostgreSQL records every committed change, through the pgoutput plugin, and publishes one Kafka event per changed row, catching manual fixes and batch jobs too without touching application code. For mirroring a table into search, CDC is usually the better fit; the outbox suits business events that other services also consume.
Kafka topics are partitioned by the product's primary key, so all changes to one product land in one partition and are consumed in commit order. Debezium attaches the log sequence number, or LSN, the position of the change in the write-ahead log, which only ever grows. That is the version we will give OpenSearch.
5The Indexing Consumer
The consumer reads a batch of change events, builds each search document, and sends them in one _bulk request. Building the document often means joining related data: the product row alone has a category id, but the search document needs the category name and the brand. The consumer looks these up, either from the database with one query per batch or from small local caches fed by their own CDC topics.
Each item is indexed with version_type external and the LSN as the version; a version conflict means a newer document is already there. Only after the whole bulk response has been checked do we commit the Kafka offsets. If the consumer crashes before that, the batch is replayed, and the versions make the replay harmless. That is what idempotent means here: processing the same event twice leaves the index exactly as processing it once.
7 messages in order. Play them, or step through them one at a time.
Offsets are committed only after OpenSearch has accepted the batch.
6Handling Deletes
A deleted row produces a delete event, and Debezium follows it with a tombstone, a Kafka record with the key and a null value, so that log compaction can eventually remove the key from the topic. The consumer turns either signal into a delete request with the same external version. OpenSearch remembers deleted versions for a while (index.gc_deletes, 60 seconds by default), so a late, older update for the same id is still rejected in that window.
After that window, a very late older update could bring a deleted document back, so per-key ordering keeps such events rare and the reconciliation job deletes any document whose id no longer exists in the table.
7Proving We Meet the 5 Seconds
We measure lag at each stage: replication slot lag from pg_replication_slots, Debezium's milliseconds-behind-source, Kafka consumer lag, and end-to-end freshness, the time from the event's commit timestamp to indexing, alerting when its 99th percentile passes 4 seconds. A stuck replication slot needs its own alert, because PostgreSQL keeps its write-ahead log and the disk can fill.
Reconciliation proves correctness: a job runs every night, splits the id space into ranges of, say, 100,000 ids, and for each range compares the row count and a checksum, such as the sum of hashes of id and version, between PostgreSQL and OpenSearch. Ranges that match are skipped; ranges that differ are compared id by id and repaired by re-indexing.
8Follow-up questions
Why use the LSN rather than updated_at as the version?
updated_at depends on the clock of whoever wrote the row and can repeat or go backwards, and two updates in the same millisecond look identical. The LSN is a position in the write-ahead log, and because a row is locked while it is being changed, a later change to the same row always has a higher LSN, so it is a reliable ordering per document. A row version column maintained by the application, incremented on every update, also works well and is easier to read in the snapshot phase.
What happens if the indexer is down for an hour?
Kafka keeps the events according to the topic's retention, so the indexer catches up from its committed offsets when it returns. We size retention well above our longest expected outage, for example 7 days. During the outage, search is stale, which our freshness alert reports, but nothing is lost. If the outage outlived retention, we would rebuild from a fresh snapshot.
9Conclusion
In this answer, we designed sync from PostgreSQL to OpenSearch in two parts. The initial load bulk-indexes a consistent snapshot into a new index with refresh disabled and no replicas, then restores settings and swaps an alias, while a replication slot created first guarantees no change is missed. Ongoing changes come from Debezium or an outbox through Kafka, partitioned by id, into an idempotent consumer that joins related data and indexes with external versions from the LSN, turning tombstones into deletes. Lag metrics prove the 5-second target, and a nightly count and checksum reconciliation proves the copies agree.
Open with
I would separate the initial load from ongoing changes. For the load, I create a new index with the final mapping, set refresh_interval to minus one and replicas to zero, and bulk index from a consistent snapshot in primary key ranges, tuning batch size until OpenSearch starts pushing back.
Then, if they want more
Then I restore refresh to one second, add a replica, wait for green, and point an alias at it. To avoid a gap, the change capture starts before the snapshot: Debezium creates a replication slot and snapshots from the same position, so changes during the load are kept in the write-ahead log.
For ongoing changes I would use Debezium reading the WAL into Kafka, keyed by product id so per-product order holds; an outbox is the alternative if the events are business facts for other consumers.
The indexer consumes batches, joins category and brand data, and bulk indexes with version type external using the LSN, so replays and overlaps are harmless and a version conflict just means we already have newer data. Deletes come as delete events and tombstones, which become versioned deletes. Offsets are committed only after the bulk succeeds.
Finally I monitor slot lag, consumer lag and end-to-end freshness against a 4-second alert, and run a nightly reconciliation comparing counts and checksums per id range, re-indexing any range that differs.
About this answer
- Last updated
- 12 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 documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Elasticsearch documentation
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 "Design reliable synchronisation of 30 million rows from PostgreSQL into OpenSearch...": https://scrivio-interview-library.netlify.app/databases/search-engines/78c5412c53/