Opening: A Deleted Track Still Shows Up in Search
A teacher deletes a track because of a recording mistake. It disappears from their profile page. But users who type its title into the search box still find it, then get an error when they tap it.
The code looks reasonable: delete from the database, then delete from Elasticsearch. Except that at that moment Elasticsearch was slow, the call timed out, and nothing retried. The database was right, the index fell behind, and nobody knew.
Part 4 closed with one principle: a copy must know its own version. A search index is a copy too. This part covers how to keep Elasticsearch in sync with the database, and how to change its structure without downtime.
Warm-Up Quiz: Do You Still Remember?
Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.
Question 1. The app saves a change to PostgreSQL, then calls Elasticsearch. The second call times out. What is the result?
- A. Nothing, Elasticsearch catches up on its own
- B. The database has committed, the index is behind, and nobody knows until a user finds it
- C. The database rolls back automatically
Show the answer to question 1
B. This is the dual write problem: two systems written without a shared transaction. The test in section 2: with 2% of calls failing, 22 of 1,000 tracks differ between the database and the index.
Question 2. Change events can arrive twice and out of order. How do you stop an old version from overwriting a newer one in Elasticsearch?
- A. Use
version_type=externalwith the version number from the database - B. Add more retries
- C. Make sure Pub/Sub delivers in order
Show the answer to question 2
A. With version_type=external, Elasticsearch only writes if the version sent is greater than the stored version, and answers 409 otherwise. The test in section 4: 389 tracks broken without versions, 0 with versions.
Question 3. You need to change the analyzer of a field in a production index. The zero-downtime way is...
- A. Change the mapping directly on the index in use
- B. Create a new index with the new mapping, fill it, then move the alias in one operation
- C. Delete the index and create it again
Show the answer to question 3
B. The app always reads through an alias. The new index is built next to the old one, then the alias moves atomically. If something is wrong, the alias moves back. Section 6 shows the commands.
Question 4. In this architecture, what is the source of truth?
- A. Elasticsearch, because that is what users search
- B. The main database. Elasticsearch is only a copy for searching
- C. Pub/Sub, because every event goes through it
Show the answer to question 4
B. The database stays the source of truth. The index can always be rebuilt from the database, and that is what makes reconciliation and reindexing possible.
Question 5. An admin script changes 15 tracks directly in the database without writing events. How does the index find out?
- A. It never will
- B. A periodic reconciliation job compares versions in the database and the index, then patches what is behind
- C. Elasticsearch reads the database log
Show the answer to question 5
B. Reconciliation is the safety net for every path that forgets to send events. The test in section 5: 1,000 tracks checked in 15 ms, 15 stale ones patched.
1. The Database Is the Source of Truth, the Index Is a Copy
Elasticsearch exists because relational databases are not designed for typo-tolerant text search, relevance ranking and autocomplete. But Elasticsearch is not where data that must not be lost lives. It is a copy optimized for searching.
That principle has three consequences:
- Every change in the database must reach the index, sooner or later.
- When in doubt, the database is right. The index can be rebuilt at any time.
- Detail pages read from the database, not from search results. Search results may be a few seconds behind, detail pages may not.
The question: how do you guarantee the first consequence when the network, Elasticsearch, or our own code can fail at any time?
2. Test: The Dual Write Problem
The most direct approach is writing to two places in a row:
const { rows } = await pool.query('UPDATE tracks SET title = $2, version = version + 1 WHERE id = $1 RETURNING *', [id, title]);
await search.index(id, rows[0]); // if this fails, the database has already committed
I ran it for 2,000 random changes on 1,000 tracks, with failures injected into 2% of the search calls. The Elasticsearch stand-in for this test is Redis, because my test environment cannot run Elasticsearch. The principle does not depend on the search engine.
2000 perubahan, 44 panggilan search gagal, 22 dari 1000 track berbeda antara database dan index
(2,000 changes, 44 failed search calls, 22 of 1,000 tracks differ between the database and the index.)
Some failures "healed themselves" because the same track was changed again later. The other 22 tracks fell behind with nobody knowing. Adding retries inside the request does not solve it: if the process dies between the two writes, the retry dies with it.
The root cause: two systems are written without a shared transaction. We need a way to record "data changed" and "the index must be updated" atomically.
3. The Outbox Pattern
The idea is simple: the data change and a note saying "there is an event to send" are written in the same database transaction. Sending to Elasticsearch happens later, in another process.
The flow:
- The app updates the track and writes a row to the
outboxtable in one transaction. Both succeed, or both fail. - A relay picks up unsent outbox rows and publishes them to Pub/Sub.
- A worker receives the event and upserts the document into Elasticsearch by track ID, carrying a version number.
- The upsert is idempotent and versioned, so duplicate or out-of-order messages do not corrupt data.
- A reconciliation job periodically compares versions to patch missed events.
The write side:
await client.query('BEGIN');
const { rows } = await client.query(
'UPDATE tracks SET title = $2, version = version + 1 WHERE id = $1 RETURNING id, title, version', [id, title]);
await client.query('INSERT INTO outbox (track_id, version, payload) VALUES ($1, $2, $3)', [id, rows[0].version, rows[0]]);
await client.query('COMMIT');
The relay takes a batch with FOR UPDATE SKIP LOCKED, so several relays can run at once without picking the same rows:
UPDATE outbox SET published_at = now()
WHERE id IN (SELECT id FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 5000 FOR UPDATE SKIP LOCKED)
RETURNING payload;
If the relay dies after publishing but before committing, the same event is published again. That is not a bug, it is the design: at-least-once. Step 4 is what makes it safe.
An alternative to an outbox table is reading the database's change log directly (change data capture), for example with Datastream on GCP. The result is the same, with less application code but more components to operate.
4. Test: Duplicate and Out-of-Order Messages
Pub/Sub guarantees at-least-once delivery, and order is not guaranteed unless you use an ordering key. So I built a test queue that deliberately duplicates 10% of messages, shuffles their order, and fails 2% of processing attempts (failed messages are redelivered). Then two ways of writing to the index:
- Write as is: whoever arrives last wins.
- Mimic
version_type=external: write only if the new version is greater than the stored version, otherwise answer 409. In Redis, I wrote the rule in Lua:
redis.defineCommand('indexExternal', { numberOfKeys: 1, lua: `
local cur = tonumber(redis.call('HGET', KEYS[1], 'version') or '0')
if tonumber(ARGV[1]) <= cur then return 409 end
redis.call('HSET', KEYS[1], 'version', ARGV[1], 'title', ARGV[2])
return 200` });
tulis apa adanya : 2217 pesan (termasuk dobel), 51 kali kirim ulang, 389 dari 1000 track berbeda
version_type=external : 2205 pesan (termasuk dobel), 46 kali kirim ulang, 0 dari 1000 track berbeda
event outbox yang belum terkirim: 0
(tulis apa adanya = write as is, pesan (termasuk dobel) = messages including duplicates, kali kirim ulang = redeliveries, event outbox yang belum terkirim = unsent outbox events.)
Without versions, 389 tracks ended up with old titles, because old events arrived late and overwrote new ones. With versions, all 1,000 tracks match the database exactly, even though messages were duplicated, shuffled, and some had to be redelivered.
In real Elasticsearch, this rule is built into the Index API. The docs explain: with version_type=external, the document is written if the version sent is greater than the stored version, and if it is less or equal, a version conflict occurs with status 409.
PUT tracks/_doc/42?version=8&version_type=external
{ "title": "Tidur Nyenyak", "teacher": "Ayu", "lang": "id", "popularity": 0.93 }
The worker treats 409 as success: it means the index already has the same or a newer version. Do not redeliver it.
Deletes work the same way: DELETE with a version, or mark the document deleted: true with its version, so a late "update" event cannot bring a deleted track back to life. The opening story is exactly this case.
The pattern is the same as idempotency in Part 12 of the Node.js series and the version check in Part 4: every write carries proof of how fresh it is.
5. Test: Reconciliation
The outbox guarantees events are recorded if the code uses the outbox. But there is always a path that forgets: admin scripts, data migrations, manual fixes in a console. Reconciliation is the safety net.
I changed 15 tracks directly with SQL without writing the outbox, then ran a job that compares versions in the database and the index:
const { rows } = await pool.query('SELECT id, title, version FROM tracks WHERE id <= 1000 ORDER BY id');
const pipe = search.redis.pipeline();
rows.forEach((r) => pipe.hget(`idx:${r.id}`, 'version'));
const versions = (await pipe.exec()).map(([, v]) => Number(v));
const stale = rows.filter((r, i) => versions[i] < r.version);
for (const r of stale) await search.indexExternal(r.id, r);
diperiksa 1000 track dalam 15 ms, tertinggal 15, sudah ditambal
dicek ulang: 0 berbeda
(1,000 tracks checked in 15 ms, 15 behind, patched. Checked again: 0 different.)
For a catalog of millions of tracks, run it per ID range or only for rows with an updated_at in the last few hours, and use _mget or an Elasticsearch query that only fetches versions. Run it with Cloud Scheduler, say every hour, and record the number patched as a metric. That number should be zero. If it is often above zero, a write path needs fixing.
6. Changing Mappings Without Downtime: Reindex with an Alias
Most mapping changes in Elasticsearch, such as changing an analyzer or a field type, cannot be done on an existing index. You need a new index. The key: the app never uses an index name directly, it always goes through an alias.
# 1. A new index with the new mapping
PUT tracks_v2
{ "mappings": { "properties": { "title_id": { "type": "text", "analyzer": "indonesian" } } } }
# 2. Fill it (from the database with a job, or from the old index with _reindex)
POST _reindex
{ "source": { "index": "tracks_v1" }, "dest": { "index": "tracks_v2", "version_type": "external" } }
# 3. Move the alias in ONE atomic operation
POST _aliases
{ "actions": [
{ "remove": { "index": "tracks_v1", "alias": "tracks" } },
{ "add": { "index": "tracks_v2", "alias": "tracks" } }
] }
During step 2, the worker should write to both indexes, so changes made mid-process are not lost. version_type: external in _reindex keeps newer documents in tracks_v2 from being overwritten by old copies.
If search results get worse after the switch, run the _aliases command in reverse. Rollback in seconds, the same principle as canary and rollback in Part 4 of the GCP series. Delete tracks_v1 after a few days without problems.
7. Three Search Sync Traps
Trap one: dual writes inside the request. Test: 22 of 1,000 tracks fell behind. Use an outbox or change data capture.
Trap two: writing to the index without versions. Duplicate and out-of-order messages will happen. Test: 389 tracks kept old titles. Use version_type=external, and treat 409 as success.
Trap three: the app using index names directly. Every mapping change becomes a risky operation with downtime. Use an alias from day one.
Summary
- The database is the source of truth, Elasticsearch is a copy for searching. Detail pages read the database.
- Dual writes are not safe: a test with 2% failures left 22 of 1,000 tracks different.
- Outbox: the data change and the event are written in one transaction, a relay with
FOR UPDATE SKIP LOCKEDsends to Pub/Sub, at-least-once. - Versioned upserts:
version_type=external, 409 means something newer is already there. Test with duplicated and shuffled messages: 389 broken without versions, 0 with. Deletes are versioned too. - Periodic reconciliation: 1,000 tracks checked in 15 ms, 15 patched. The number patched is a metric that should be zero.
- Reindex with an alias: build
tracks_v2, write to both during the process, move the alias atomically, roll back with the reverse command.
Closing & What's Next
The track from the opening now disappears from search within seconds, even when Elasticsearch is slow, because its event is recorded in the same transaction and redelivered until it succeeds.
An index in sync is only the baseline. The final part answers the question that usually comes next: are the search results any good? We cover relevance that combines text with business signals, multilingual search, autocomplete, measuring quality with nDCG, and operating Elasticsearch on GCP.
Grab your coffee, see you in the final part!

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

