Quick revision
The short answer
The method performs a dual write: one write to PostgreSQL and one to Elasticsearch, with nothing that makes them succeed or fail together. The index call can fail after the database commits, or it can index a product whose transaction later rolls back, and two quick updates can reach the index in the wrong order. The simple improvements are to index only after the commit, retry failed index calls, reconcile on a schedule, and use external versions so an older update can never overwrite a newer one; for stronger guarantees we move to an outbox table or change data capture.
What to remember
In this answer, we saw why saving to PostgreSQL and indexing in Elasticsearch in one method drifts: the two writes are not atomic, so an index call can fail after a commit, succeed for a rolled-back transaction, or arrive out of order. We fixed this step by step, by indexing after commit with @TransactionalEventListener, retrying and reconciling by version or updated_at, and sending external versions so older data is rejected. When a periodic safety net is not enough, an outbox table or change data capture removes the dual write altogether.
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.
The method performs a dual write: one write to PostgreSQL and one to Elasticsearch, with nothing that makes them succeed or fail together. The index call can fail after the database commits, or it can index a product whose transaction later rolls back, and two quick updates can reach the index in the wrong order. The simple improvements are to index only after the commit, retry failed index calls, reconcile on a schedule, and use external versions so an older update can never overwrite a newer one; for stronger guarantees we move to an outbox table or change data capture.
Why this question is asked
Almost every product with a search box keeps its real data in a relational database and a copy in a search engine, because the database is good at transactions and the search engine is good at full-text queries. The moment we have two copies, we have the problem of keeping them in step. Interviewers ask this question because the naive code looks perfectly reasonable, and the bugs it causes are intermittent, which makes them hard to trace. In this answer, we will recap what a dual write is, reproduce the ways the naive method goes wrong, and then apply four simple improvements in order: indexing after commit, retries with reconciliation, external versioning, and finally the outbox or change data capture when the simple fixes are not enough.
1A Quick Recap of the Dual Write
Our method saves a product with Spring Data JPA and then indexes it with the Elasticsearch Java client. Writing the same fact to two systems from application code is called a dual write. Each system is reliable on its own, but there is no shared transaction around the pair. PostgreSQL knows nothing about Elasticsearch, and Elasticsearch has no idea whether the database commit happened.
A delay of about one second is normal, because Elasticsearch makes documents searchable at each refresh, every second by default. Products that stay stale or never appear are something else: the two copies have drifted apart.
2Three Ways the Naive Method Goes Wrong
The first failure is the index call failing after the data is safe. If Elasticsearch is restarting or the network times out, the exception may be caught and logged somewhere, or the call may be outside the transaction entirely. Either way the row is committed and the index never hears about it, so the product is missing from search until someone saves it again.
The second failure is the opposite. In the code above, the index call happens inside the transaction, before the commit. If the commit then fails, for example because of a unique constraint checked at flush time or a deadlock, the database rolls back but Elasticsearch already has the document. Search now shows a product, or a price, that does not exist in the database.
The third failure is ordering. Request A commits price 10 and request B commits price 12 a few milliseconds later, but because of thread scheduling or a retry, A's index call arrives last. The index keeps price 10, the stale data the question mentions, and it never fixes itself.
5 messages in order. Play them, or step through them one at a time.
Without versions, whichever index call arrives last wins, even if it carries older data.
3Improvement 1: Index After the Commit
The first fix removes the phantom documents. Instead of calling Elasticsearch inside the transaction, we publish an application event, and a listener annotated with @TransactionalEventListener runs only after the transaction has committed. AFTER_COMMIT is the default phase of this annotation, but writing it out makes the intent clear.
Notice what changed. A rolled-back transaction never fires the listener, so nothing is indexed for data that does not exist. The cost is that the listener runs after the commit, so a failure there can no longer roll the database back. That is fine, because we will handle it with retries in the next step. One catch: if save() is ever called without an active transaction, the event is silently dropped unless we set fallbackExecution = true.
4Improvement 2: Retry, Then Reconcile
Index calls fail for temporary reasons, such as a node restarting or a brief overload that returns HTTP 429. So the indexer retries a few times with a growing delay, for example after 1, 2 and 4 seconds, using Spring Retry or a small loop. Each retry reloads the product by id, so it sends the latest state.
Retries still have a gap: if the application crashes after the commit and before the listener finishes, the event lives only in memory and is gone. That is why we also run a reconciliation job, for example every 10 minutes. It reads rows whose updated_at is newer than the last run, compares each row's version with the version stored in the index, and re-indexes anything that differs. Reconciliation turns 'usually right' into 'right within a known time'.
5Improvement 3: External Versioning Against Out-of-Order Updates
To fix the ordering problem, we let the database decide which update is newer. The entity already has a version column if we use JPA's @Version for optimistic locking, and that number increases on every update. We send it to Elasticsearch with version_type external. Elasticsearch then accepts the write only if the version we send is greater than the version it already holds, and rejects older ones with a version conflict (HTTP 409).
So a conflict here is good news: it means a newer document is already in the index. The indexer should treat a 409 as success and move on, not retry it. With this in place, retries and reconciliation become safe too, because re-sending an old version can never undo a newer one.
6When the Simple Fixes Are Not Enough
These four fixes are good enough for many catalogues, but they still rely on a periodic scan to catch lost events. For a real guarantee, we stop doing the second write from the request thread.
With a transactional outbox, the service inserts a row into an outbox table in the same database transaction as the product change. Because it is one transaction, either both rows commit or neither does. A separate relay reads the outbox and indexes the products, retrying until it succeeds. With change data capture, a tool such as Debezium reads PostgreSQL's write-ahead log, the log of every committed change, and streams those changes to Kafka for an indexer to consume. Both approaches turn the dual write into a single write plus a reliable, replayable feed, at the cost of one more moving part to run.
- Index after commit
@TransactionalEventListener, no phantom documents - Retry failed callsbackoff, reload the row each time
- Send external versionsolder updates are rejected
- Reconcile on a schedulecompare versions by updated_at
- Is a periodic scan an acceptable safety net?YesStop hereNoAdd an outbox table or CDC
5 steps in order. Play them, or step through them one at a time.
Each step closes one of the failure modes; the last one removes the dual write itself.
7Follow-up questions
Why not just put the Elasticsearch call outside @Transactional, after save()?
That removes the phantom document problem only if the method really commits before the call, and it does not handle a crash or an index failure after the commit. It is roughly what @TransactionalEventListener gives us, but less explicit. We still need retries, versions and reconciliation, because the two writes are still separate.
Is the one-second refresh interval part of the problem?
Only for freshness, not for correctness. A document becomes searchable after the next refresh, about one second by default, so a test that searches immediately after saving can miss it. We can pass refresh=wait_for on writes where a user must see their own change, but we should not call refresh on every write, because frequent refreshes create many small segments and slow the cluster down.
8Conclusion
In this answer, we saw why saving to PostgreSQL and indexing in Elasticsearch in one method drifts: the two writes are not atomic, so an index call can fail after a commit, succeed for a rolled-back transaction, or arrive out of order. We fixed this step by step, by indexing after commit with @TransactionalEventListener, retrying and reconciling by version or updated_at, and sending external versions so older data is rejected. When a periodic safety net is not enough, an outbox table or change data capture removes the dual write altogether.
Open with
The root cause is a dual write. Saving to PostgreSQL and indexing in Elasticsearch are two separate operations with no shared transaction, so they can disagree. If the index call fails after the commit, the product is missing from search.
Then, if they want more
If the call happens inside the transaction and the commit then fails, search shows data that was rolled back. And if two updates race, the older one can reach Elasticsearch last and overwrite the newer one, which is the stale data we are seeing.
My first change would be to publish an event and index from a @TransactionalEventListener in the AFTER_COMMIT phase, so we only index committed data. The listener reloads the row and retries with backoff on temporary failures.
Then I would send the entity's version with version_type external, so Elasticsearch rejects any update older than what it has, and I would treat that 409 conflict as success. Because a crash can still lose the in-memory event, I would add a reconciliation job that compares updated_at and versions between the table and the index and re-indexes differences.
If the business needs a stronger guarantee than a periodic scan, I would move to a transactional outbox written in the same transaction, or to change data capture with Debezium reading the write-ahead log, so the index is fed from a reliable, replayable stream instead of a second write in the request.
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 "A Spring Boot service saves a product to PostgreSQL and then calls Elasticsearch to...": https://scrivio-interview-library.netlify.app/databases/search-engines/ea2fff1fdf/