Keeping search in sync: CDC, reindexing and aliases
Feed a search index from the system of record through an outbox or change data capture, protect it from late and replayed events with source versions, state its freshness and consistency honestly, and change a mapping with a backfill and an atomic alias swap.
Contentsand lesson path
On this page
- Why it matters
- From the database to the index
- Late, repeated and deleted events
- Freshness and consistency you can promise
- Reindexing behind an alias
- Check your understanding
- Apply it
- Review prompt
Lessons of Search & Indexing Services
- Inverted indexes, analyzers and scoring Concept · 25 min
- Keeping search in sync: CDC, reindexing and aliases Concept · 20 min
- Shards, replicas and scatter-gather queries Concept · 20 min
- Designing typeahead under 100 ms Worked example · 25 min
- Indexing location: geohash, quadtrees and S2 cells Concept · 20 min
- Search design check Knowledge check · 8 questions
What you will learn
- Design an indexing pipeline from the system of record (for example change data capture into a search index) and state its freshness and consistency guarantees.
01. Why it matters
A search index is a derived copy. The products live in a database, the system of record, and the index holds a reshaped copy that is good at text queries. Every design that adds search must answer three questions. How does a change travel from the database to the index? What can a user see while it travels? And how do you rebuild or reshape the index while it keeps serving traffic?
The tempting answer to the first question is to write to both places from the request handler. That dual write fails quietly: if the process dies or the index call times out after the database commit, the two copies disagree, and nothing in that design notices or repairs the gap. This lesson builds the alternative, a pipeline driven by the database, then covers versions, freshness and reindexing on the OpenSearch node from lesson 01.
02. From the database to the index
Two designs give the indexer a durable, ordered stream of changes that it can replay after a crash:
- A transactional outbox. The service writes the product row and an event row in the same database transaction, and a relay publishes the event rows to a message log such as Kafka. The event exists if and only if the change was committed. See Distributed data patterns.
- Log-based change data capture (CDC). A connector such as Debezium reads the database's own change log and publishes every committed insert, update and delete, without touching application code. The Change Data Capture lessons, including the Debezium lab, cover how it works.
The indexer consumes that stream and writes search documents with the bulk API, in batches of hundreds to a few thousand documents. Partition the stream by product ID, so that all changes to one product arrive in order at one consumer.
A search document is usually denormalised: one product document carries the brand name, the category path, the stock flag and the price, which live in four tables. That has two consequences. First, build each document from the current state of the source rather than patching it with the fields in the event; a rebuilt document is the same however many times you build it. Second, a change to a shared row fans out. When a brand is renamed, the indexer must find every product of that brand and rebuild each of them. A popular brand can mean thousands of rebuilds for one changed row.
03. Late, repeated and deleted events
Pipelines like this usually run with at-least-once delivery: the consumer commits its position in the log only after the write, so after a crash or a rebalance some events arrive again, and a replay from an old position can bring very old events. An old event must not overwrite a newer document, so send a version from the source with every write. With version_type=external, OpenSearch accepts the write only if that version is higher than the stored one.
A row version column fails for fan-out: when a brand rename makes the indexer rebuild a product, the product row has not changed, so the write is refused. A Kafka offset fails too: each partition counts on its own, and brand and product events sit in different partitions. What works is one position for the whole database in commit order. PostgreSQL decodes concurrent transactions in commit order, and a long transaction can hold changes with lower LSNs than one that committed before it. So use a commit LSN, such as the first value of Debezium's source.sequence, which its documentation calls the last committed LSN, rather than source.lsn, the LSN of the change itself.
Save sync_demo.py and run it against the node from lesson 01; it creates and deletes its own indexes. Part 1 writes three events for product 42, one of them late. Part 2 deletes a document and then replays an older update; the numbers stand for commit LSNs.
"""Versioned writes, deletes, refresh and an alias swap in OpenSearch.
Python 3.12, standard library only. Run it against an empty local node."""
import json
import os
import time
import urllib.error
import urllib.request
OS = os.environ.get('OS_URL', 'http://localhost:9200')
def call(method: str, path: str, body=None) -> tuple[int, dict]:
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(OS + path, data=data, method=method,
headers={'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req) as resp:
return resp.status, json.load(resp)
except urllib.error.HTTPError as err:
return err.code, json.load(err)
def put(index: str, doc_id: int, version: int, title: str) -> str:
"""Write one change event. The version stands for the commit LSN of the change."""
path = f'/{index}/_doc/{doc_id}?version={version}&version_type=external'
status, body = call('PUT', path, {'title': title})
return f"{status} {body.get('result') or body['error']['type']}"
def hits(index: str, word: str) -> int:
body = call('POST', f'/{index}/_search', {'query': {'match': {'title': word}}})[1]
return body['hits']['total']['value']
for name in ('products_v1', 'products_v2', 'tombstones'):
call('DELETE', f'/{name}')
one_shard = {'number_of_shards': 1, 'number_of_replicas': 0}
call('PUT', '/products_v1', {'settings': one_shard, 'aliases': {'products': {}},
'mappings': {'properties': {'title': {'type': 'text'}}}})
print('1. versioned writes through the alias')
print(' doc 42 v7 ->', put('products', 42, 7, 'Hiking boots'))
print(' doc 42 v5 (late) ->', put('products', 42, 5, 'Hiking boot'))
print(' doc 42 v9 ->', put('products', 42, 9, 'Waterproof hiking boots'))
put('products', 41, 3, 'Rain boots for kids')
put('products', 43, 2, 'Boot laces')
print('2. a delete, then a replayed older update')
call('PUT', '/tombstones', {'settings': {**one_shard, 'index.gc_deletes': '0s'}})
put('tombstones', 7, 5, 'Trail shoes')
status, body = call('DELETE', '/tombstones/_doc/7?version=10&version_type=external')
print(' delete v10 ->', status, body['result'])
print(' replay v9 at once ->', put('tombstones', 7, 9, 'Trail shoes'))
time.sleep(1.5) # gc_deletes is 0s here; the default is 60s
print(' replay v9 later ->', put('tombstones', 7, 9, 'Trail shoes'))
print('3. refresh decides when a write becomes searchable')
call('PUT', '/products_v1/_settings', {'index': {'refresh_interval': '-1'}})
put('products', 44, 4, 'Trail running shoes')
found = call('GET', '/products/_doc/44')[1]['found']
print(f" get by id found={found}, search hits={hits('products', 'shoes')}")
call('POST', '/products_v1/_refresh')
print(f" after _refresh: search hits={hits('products', 'shoes')}")
call('PUT', '/products_v1/_settings', {'index': {'refresh_interval': None}})
print('4. reindex into a new mapping, then swap the alias')
print(f" products -> {list(call('GET', '/_alias/products')[1])}, "
f"'boot' hits={hits('products', 'boot')}")
call('PUT', '/products_v2', {'settings': one_shard, 'mappings': {'properties': {
'title': {'type': 'text', 'analyzer': 'english'}}}})
status, body = call('POST', '/_reindex?refresh=true', {
'source': {'index': 'products_v1'},
'dest': {'index': 'products_v2', 'version_type': 'external'}})
print(f" reindexed {body['created']} docs into products_v2")
status, body = call('POST', '/_aliases', {'actions': [
{'remove': {'index': 'products_v1', 'alias': 'products'}},
{'add': {'index': 'products_v2', 'alias': 'products'}}]})
print(f" swap acknowledged={body['acknowledged']}")
print(f" products -> {list(call('GET', '/_alias/products')[1])}, "
f"'boot' hits={hits('products', 'boot')}")
print(' doc 42 version in v2:', call('GET', '/products/_doc/42')[1]['_version'])
print(' doc 42 v8 (late) ->', put('products', 42, 8, 'Hiking boot'))1. versioned writes through the alias
doc 42 v7 -> 201 created
doc 42 v5 (late) -> 409 version_conflict_engine_exception
doc 42 v9 -> 200 updated
2. a delete, then a replayed older update
delete v10 -> 200 deleted
replay v9 at once -> 409 version_conflict_engine_exception
replay v9 later -> 201 created
3. refresh decides when a write becomes searchable
get by id found=True, search hits=0
after _refresh: search hits=1
4. reindex into a new mapping, then swap the alias
products -> ['products_v1'], 'boot' hits=1
reindexed 4 docs into products_v2
swap acknowledged=True
products -> ['products_v2'], 'boot' hits=3
doc 42 version in v2: 9
doc 42 v8 (late) -> 409 version_conflict_engine_exceptionIn part 1 the late version 5 is refused with a version conflict, so the consumer can log it and move on. Part 2 shows a trap. OpenSearch remembers the version of a deleted document only for index.gc_deletes, 60 seconds by default; the demo sets it to 0 seconds to make the point quickly. Within that window a replayed update is refused. After it, the same update creates the product again, although it was deleted at version 10.
Two habits avoid this. A soft delete writes a small tombstone document with deleted: true and its version, which every query filters out, and a cleanup job removes tombstones only when no replay can be that old, for example once the log retention has passed. Or the indexer checks the source before every write: if the row no longer exists, it deletes the document instead of writing the event.
04. Freshness and consistency you can promise
A committed change becomes searchable only after several steps: the connector reads it, the message waits in the queue, the indexer batches it, the bulk write lands, and a refresh makes new documents visible to search. OpenSearch refreshes every second by default. If you leave the interval unset, though, a shard that has had no search for 30 seconds skips these background refreshes until the next search arrives. A refresh interval of -1 turns them off, which speeds up bulk loads.
Part 3 of the output shows the difference between reading and searching. With refresh off, a GET by ID finds product 44 at once, because it reads the latest version of the document directly. A search finds nothing until the refresh. Searching is near real-time; reading by ID is not delayed.
So state the guarantees as targets you can measure, not as hopes:
- Freshness: for example, 99% of committed changes are searchable within 5 seconds, and deletes within 60 seconds. Measure it by storing the commit time in each document, and by a probe that writes a test row every minute and polls search until it appears.
- Order: per document, through key partitioning and versions. There is no order across documents.
- Atomicity: none across documents. An order and its lines, or 3,000 products of a renamed brand, become visible one by one.
- Read-your-writes: not by default. A seller who saves a listing and searches for it at once may not find it. Show the saved listing from the database on the confirmation page, or write that one document with
refresh=wait_for, which waits for the next refresh.
05. Reindexing behind an alias
Some changes cannot be made in place. A new analyzer, a different field type, or a new number of primary shards (lesson 03) means building a new index, because terms are produced when documents are written. To switch without downtime, clients should not use a concrete index name: they search and write through an alias such as products, which points to products_v1 today. A rebuild then follows these steps:
- Create
products_v2with the new mapping. For a large backfill, set its refresh interval to-1and its replicas to 0. - Record the current position of the change stream, the consumer offset of every partition, before the backfill starts.
- Backfill from the system of record, or copy from
products_v1with_reindexwhen v1 holds complete documents. Give each backfilled document the LSN of the snapshot it was read from, or keep the v1 versions withversion_type: external. - Replay the change stream into v2 from the recorded position until it catches up. The overlap with the backfill is harmless, because older versions are refused.
- Restore the refresh interval and replicas, then check document counts, sample queries and a set of relevance tests.
- Move the alias in one
_aliasesrequest, which OpenSearch applies atomically. - Keep v1 fed with changes for a rollback window, then delete it.
Part 4 of the output runs the core of this. Through the alias, boot finds one product with the standard analyzer of v1 and three after the swap to the english analyzer of v2. Product 42 keeps version 9 in v2, so a late version 8 is still refused after the switch. Without version_type: external, the copied documents would restart at version 1, and every delayed event would win.
06. Check your understanding
07. Apply it
Write the ingestion section of this skill's practice design, product search at 5,000 queries per second:
- Choose an outbox or CDC, and justify it in two sentences for your primary database.
- Define the search document: fields, the source tables of each field, and which source changes fan out to many documents.
- Name the version you will send with each write, and how deletes are handled.
- State a freshness target for updates and one for deletes, with how you will measure both.
- Write the rebuild runbook: the steps above, with who checks what before the alias swap.
08. Review prompt
Without looking back, explain: why a dual write drifts and what an outbox or CDC changes; why the indexer sends a source version; how a delete can come back after gc_deletes; which steps add up to index lag; which guarantees a search index usually does not give; and the order of steps in a rebuild behind an alias.
References
- Elasticsearch: near real-time search
- OpenSearch: index aliases
- OpenSearch: Index document API (versioning, refresh)
- OpenSearch: Reindex API
- OpenSearch: index settings (refresh_interval, gc_deletes)
- PostgreSQL: logical decoding output plugins (transactions decoded in commit order)
- Debezium: PostgreSQL connector (source.lsn and source.sequence)
- Transactional outbox pattern (microservices.io)
- Debezium: Outbox Event Router
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.