Beyond Migration: Other Uses of Change Events
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A migration pipeline turns every committed change in the legacy Bookshop database into an event on a Kafka topic, and later does the same for the new PostgreSQL database. Those topics are useful for more than copying rows. The official Debezium use cases list cache invalidation, search and derived indexes, data exchange between microservices, CQRS read models, audit logs, streaming analytics, lakehouse ingestion, and AI retrieval. Several of them solve problems that a migration creates anyway: caches that go stale when the JDBC sink writes behind the application’s back, an audit trail that has to prove what changed during the overlap, and read models or search indexes that must follow both systems.
This page is short on purpose. It shows how each use fits the Bookshop pipeline, gives the configuration that the official pages document, and links to the pages that cover the pattern in depth. The outbox pattern, the other big use case, has its own page: Outbox Event Router.
Checked on 2026-11-09 against Debezium 3.7.1.Final (built against Quarkus 3.33.2), with Spring Boot 4.1 and Spring for Apache Kafka 4.1 for the Spring example. The configuration on this page is derived from the official documentation; it was not run.
The same events, more consumers
Every consumer on this page reads topics that the migration already produces. Nothing changes in the legacy database and nothing changes in the source connectors, except where noted.
| Use | What it does with the change events | Where it is covered |
|---|---|---|
Cache invalidation |
Evicts cache entries for rows that changed, whoever changed them |
|
Audit log |
Keeps the ordered history of committed changes with before and after images, enriched with who and why |
|
CQRS read models and search indexes |
Builds denormalised views and search documents from the write model’s changes |
|
Microservices data exchange |
Publishes domain events from an outbox table in the same transaction as the business data |
|
AI retrieval |
Computes embeddings of changed text and keeps a vector store in step with the database |
|
Streaming analytics and lakehouse ingestion |
Feeds stream processors, warehouses or table formats such as Iceberg with changes instead of full copies |
Each new consumer is a new consumer group, or a new sink connector, on existing topics. It does not add load to the legacy database. Two rules from the migration still apply: consumers must be idempotent, because delivery is at least once (see Offsets, Restarts & Exactly-Once), and the topic retention decides how far back a new consumer can start (see Features & Delivery Guarantees).
Cache invalidation
The problem a migration creates
The new bookshop application reads books often and changes them rarely, so it is a natural candidate for a cache:
the Hibernate second-level cache, or a Spring cache in front of the repository. During the overlap, however, the
application is not the only writer. The JDBC sink and the anti-corruption layer write rows that came from Oracle,
and later the cut-over tooling may correct data directly in SQL. None of these writes go through the application, so
none of them evict the cache. The application keeps serving the old price of a book that the legacy system has
already changed.
The fix is to invalidate from the database’s change stream instead of from the code that writes. Every change to the
book table, whatever its origin, becomes an event, and the event evicts the cached entry. The Debezium use cases page
describes this as the cache-invalidation use case, and the Hibernate cache invalidation extension implements it for
Quarkus applications.
The Debezium Hibernate cache invalidation extension (incubating)
The extension is a Quarkus extension that starts an embedded Debezium engine inside the application, captures changes
on the tables of entities that are cached, and evicts the matching second-level cache regions when an UPDATE or
DELETE arrives. The official page marks it as incubating: its semantics and configuration options may change. It
needs JDK 21 or later, a Quarkus application with Hibernate ORM and a second-level cache provider such as
hibernate-jcache, and a Debezium Quarkus connector extension for the database.
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jcache</artifactId>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-quarkus-hibernate-cache</artifactId>
<version>3.7.1.Final</version>
</dependency>
<dependency>
<groupId>io.debezium.quarkus</groupId>
<artifactId>debezium-quarkus-postgres</artifactId>
<version>3.7.1.Final</version>
</dependency>
</dependencies>
The extension configures most Debezium settings itself (topic prefix and connector name invalidation, snapshot mode
no_data, in-memory offsets and schema history). You provide the datasource and turn on the second-level cache:
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=bookshop_app
quarkus.datasource.password=${BOOKSHOP_DB_PASSWORD}
quarkus.datasource.jdbc.url=jdbc:postgresql://postgres:5432/bookshop
quarkus.hibernate-orm.second-level-caching-enabled=true
quarkus.hibernate-orm.cache.region.factory.class=org.hibernate.cache.jcache.JCacheRegionFactory
quarkus.hibernate-orm.cache.default-cache-concurrency-strategy=read-write
quarkus.hibernate-orm.cache.use-query-cache=true
Only entities annotated with @Cacheable are tracked; the extension supports the ENABLE_SELECTIVE shared cache mode
only.
package com.example.bookshop.catalog;
import jakarta.persistence.Cacheable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity
@Table(name = "book")
@Cacheable
public class Book {
@Id
private long id;
private String isbn;
private String title;
@Column(precision = 12, scale = 2)
private BigDecimal price;
private String currency;
private boolean active;
// getters and setters
}
When the JDBC sink or the anti-corruption layer updates a book row, the extension receives the change and evicts the
whole Book region by default. Region eviction is deliberate: an entity cached through a fetch graph or a JOIN FETCH
can have a different "shape" than one loaded by id, so evicting one entry is not always safe. A custom
DebeziumEvictionStrategy CDI bean can evict a single entry instead, and a DebeziumFilterStrategy bean can change
which event types trigger eviction (by default only updates and deletes do: inserts, snapshot reads, truncates and
logical decoding messages are skipped).
Limitations listed on the official page that matter in a migration:
-
No debouncing. A change made by the application itself through Hibernate also comes back through CDC and evicts the region again. That costs extra reads, not correctness.
-
In-memory offsets and schema history by default. The engine starts with
no_data, so it only needs changes made while the application runs. Override the defaults withquarkus.debezium.*properties or aDebeziumConfigurationEnhancerbean if startup on a large schema is slow. -
One replication slot per application replica. With PostgreSQL, each replica generates its own slot name. Make sure
max_replication_slotshas room for every replica, and that slots of replicas that are gone are dropped. -
No query cache invalidation in the current release.
The Quarkus side of the second-level cache is covered on Quarkus — Hibernate ORM and JPA.
The same idea in a Spring Boot application
The Bookshop application in this section is Spring Boot, and the extension above is Quarkus-only. The Spring version
of the idea needs no new capture, but neither existing topic sees every change to book on its own:
-
modern.public.bookcomes from the reverse-replication connectorbookshop-pg-source, which only exists from the write cut-over. It also drops the writes of the forward translators:slot.stream.params=origin=noneand thedropLegacySyncFilter skip every change stampedchanged_by = 'legacy-sync'(see Creating the reverse connector stopped). It carries the application’s own writes after the write cut-over, and nothing else. -
legacy.BOOKSHOP.BOOKcomes frombookshop-oracle-sourceand carries the legacy changes that the forward translators copy into PostgreSQL, before and after the write cut-over.
A listener on both topics in each application instance can evict the cache. Each instance must receive every event, so the listener uses a group id that is unique per instance:
package com.example.bookshop.migration;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class BookCacheInvalidator {
private final CacheManager cacheManager;
public BookCacheInvalidator(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
// One group per instance: every instance must see every change
// Legacy changes copied forward, and the application's own writes after the write cut-over
@KafkaListener(topics = {"legacy.BOOKSHOP.BOOK", "modern.public.book"},
groupId = "bookshop-cache-#{T(java.util.UUID).randomUUID().toString()}",
properties = "auto.offset.reset=latest")
public void onBookChange(ConsumerRecord<?, ?> record) {
Cache books = cacheManager.getCache("books");
if (books != null) {
// Region-style eviction, like the Debezium extension's default strategy
books.clear();
}
}
}
The listener ignores the payload, so it works with whatever key and value deserializers the application uses for
the two topics. A legacy.BOOKSHOP.BOOK event can arrive before the forward translator has written the change to
PostgreSQL, so a read between the eviction and that write can put the old row back in the cache. A short time to live on
the cache entries bounds that window. auto.offset.reset=latest is right here: a new instance starts with an empty cache, so old
changes are irrelevant. Clearing the whole cache keeps the code independent of the key format; evicting by primary key works too if the
listener parses the record key. Spring Boot’s Kafka setup is explained in
Spring Boot: Apache Kafka, and near and far caches in
Near-Far Caches.
Audit logs
What a change stream already contains
A Debezium change event is close to an audit record already: it has the row before and after the change, the operation,
the commit timestamp in the source block and the transaction identifier. Kept on a topic with long retention, the
stream of a table is an ordered history of every committed change, including changes made by batch jobs and by hand in
SQL, which an application-level audit log misses. For a migration that is useful twice:
-
during the overlap, it proves what the legacy system and the new system each changed, which reconciliation and incident analysis need (see Verification & Reconciliation);
-
after decommissioning, the
legacy.*topics (or an export of them) are the record of what the legacy database did in its last months.
What the change event does not contain is who made the change and why. The database transaction log has no business user, only the database user, and in Bookshop every legacy change is made by the same application account.
Transaction metadata and enrichment
With provide.transaction.metadata=true the connector publishes BEGIN and END markers to a transaction topic and
adds a transaction block (id, total order and per-collection order) to each change event, so consumers can group
the events of one transaction. The Bookshop source bookshop-oracle-source already sets it, because the
anti-corruption layer uses the transaction id in its idempotency key, so the audit use needs no change to the
connector:
{
"provide.transaction.metadata": "true"
}
The Debezium blog post on audit logs adds the missing context with a small extra table. The application writes one
row per transaction, keyed by the transaction id, with the business user and the use case. Debezium captures that table
too, and a Kafka Streams application joins each change event with the metadata row of its transaction, buffering
events whose metadata has not arrived yet, and writes the enriched events to an audit topic. The post relies on
exactly-once processing and read_committed consumers so that the audit topic has no duplicates. Kafka Streams and
exactly-once are covered in Kafka Streams and
Kafka Reliability and Exactly-Once Semantics.
For the legacy Oracle system, adding a metadata table means changing the legacy application, which a migration usually
tries to avoid. The new application can do it from the start, so the modern.* stream can carry business context
from the first day of the cut-over.
Keeping the history
Change event topics use the delete cleanup policy by default, with the broker’s retention. An audit trail needs a
retention that matches the legal or business requirement, or an archive sink that copies the stream to object storage.
Do not use log compaction on an audit topic: compaction keeps only the latest event per key, which is the opposite of a
history.
kafka-configs.sh --bootstrap-server localhost:9092 --alter \
--entity-type topics --entity-name legacy.BOOKSHOP.ORDERS \
--add-config retention.ms=-1
Change events also contain personal data (the CUSTOMER table has names and e-mail addresses). An audit trail that
keeps them forever must be designed with data protection in mind; see
Security & Data Protection.
CQRS read models and search indexes
One write model, several read models
Command Query Responsibility Segregation keeps the write model normalised and builds separate, denormalised models for reading. The hard part is keeping the read side up to date, and log-based CDC is the usual answer, as Choosing the Right Database — Keeping Several Databases Consistent explains. The Debezium blog post on CQRS walks through a write model on PostgreSQL feeding read models in MySQL (with the Debezium JDBC sink) and QuestDB, and points out the cost: the read side is eventually consistent, so a user may not see their own write immediately.
A database migration is itself a CQRS-like arrangement: during the read cut-over, the new PostgreSQL database is a read model of the legacy Oracle write model. The same pipeline can therefore feed more read models at no extra cost to the source, as described in Migration Patterns with CDC — CDC feeding CQRS read models. The pattern itself is on CQRS.
Search indexes
A search index such as Elasticsearch or OpenSearch is a read model with a different query language. The guidance from Choosing the Right Database — Full-Text Search Engines applies: the relational database stays the system of record, and the index is fed from its changes. With Debezium the recipe is:
-
Flatten the change event to the row state with
ExtractNewRecordState(Event Flattening) and keep deletes as tombstones, so that the index sink can delete documents. -
Use the table’s primary key as the document id. The change event key is the primary key, so updates overwrite the same document and replays are idempotent.
-
Build documents that span tables (a book with its authors) in a stream processor or in the indexing consumer, not in the source connector. The Debezium blog post on DDD aggregates shows the Kafka Streams approach.
-
When the mapping changes, rebuild the index by replaying the topic from the beginning, or by an incremental snapshot of the source tables (see Incremental & Blocking Snapshots).
The sink for the search engine is a Kafka Connect connector from the search engine’s vendor or a small consumer; Debezium itself does not ship an Elasticsearch sink in 3.7. An Elasticsearch sink is part of the upcoming 3.8 release (announced in 3.8.0.Alpha1).
Debezium AI: embeddings, documents and Python
Retrieval-augmented generation (RAG) needs a vector index that follows the source data: a book that is withdrawn from sale must stop appearing in answers. The freshness problem and the general CDC approach are explained on Ingestion Pipelines & Freshness — Change data capture with Debezium and Kafka. Debezium offers three building blocks for this on top of the change stream.
Embeddings transformation
io.debezium.ai.embeddings.FieldToEmbedding is an SMT that sends the text of one string field to an embedding model
and adds the resulting vector to the record as a io.debezium.data.FloatVector field. It uses LangChain4j and needs
Java 21 or later. Model providers are separate JARs that must be on the connector’s class path: Hugging Face, Ollama,
ONNX MiniLM (the all-minilm-l6-v2 model runs in-process and needs no external service), OpenAI and Voyage AI.
{
"transforms": "embeddings",
"transforms.embeddings.type": "io.debezium.ai.embeddings.FieldToEmbedding",
"transforms.embeddings.field.source": "after.title",
"transforms.embeddings.field.embedding": "after.title_embedding",
"transforms.embeddings.ollama.url": "http://ollama:11434",
"transforms.embeddings.ollama.model.name": "all-minilm"
}
The options table on the official page prints the names with an embeddings. prefix (embeddings.field.source,
embeddings.ollama.url). In the 3.7.1 source those prefixed names are deprecated aliases; the current names are
field.source, field.embedding, ollama.url and so on, as used in the official configuration examples and above.
Put the SMT on a dedicated connector or on the sink that writes to the vector store, not on the migration’s source connector: it calls the model for every event and adds a large field to records that the JDBC sink and the anti-corruption layer do not need. With the source connector unchanged, Debezium Server with its Qdrant or Milvus sink can read the new PostgreSQL database and keep a vector collection in step:
debezium.sink.type=qdrant
debezium.sink.qdrant.host=qdrant
debezium.sink.qdrant.port=6333
debezium.source.connector.class=io.debezium.connector.postgresql.PostgresConnector
debezium.source.offset.storage.file.filename=/debezium/data/offsets.dat
debezium.source.offset.flush.interval.ms=10000
debezium.source.database.hostname=postgres
debezium.source.database.port=5432
debezium.source.database.user=bookshop_cdc
debezium.source.database.password=${BOOKSHOP_CDC_PASSWORD}
debezium.source.database.dbname=bookshop
debezium.source.topic.prefix=catalog-ai
debezium.source.plugin.name=pgoutput
debezium.source.slot.name=bookshop_catalog_ai
debezium.source.publication.name=bookshop_catalog_ai_pub
debezium.source.publication.autocreate.mode=filtered
debezium.source.table.include.list=public.book
debezium.transforms=embeddings
debezium.transforms.embeddings.type=io.debezium.ai.embeddings.FieldToEmbedding
debezium.transforms.embeddings.field.source=after.title
debezium.transforms.embeddings.field.embedding=after.title_embedding
Reference: Debezium Server — Qdrant sink
The Qdrant sink upserts the after part of each event into a collection named after the table and deletes the point
when a delete arrives. It uses the primary key as the point id (only 64-bit integers and UUIDs are supported, so
book.id bigint works), maps FloatVector fields to vectors and the other fields to the payload. The MiniLM provider
needs no settings beyond the general ones, but its JAR (and the debezium-ai-embeddings JAR) must be on the Debezium
Server class path. This pipeline has its own slot and publication, so it never interferes with bookshop_reverse.
Docling transformation
io.debezium.ai.docling.FieldToDocling sends a document stored in a field (or a URL in a field) to a Docling Serve
instance and adds the parsed document (HTML, Markdown or plain text) to the record. It also needs Java 21. It suits
legacy databases that keep PDFs or office documents in BLOB columns or keep links to them: during the migration the
documents can be converted to text once, as they change, instead of in a separate batch job.
{
"transforms": "docling",
"transforms.docling.type": "io.debezium.ai.docling.FieldToDocling",
"transforms.docling.field.source": "after.document_url",
"transforms.docling.field.docling": "after.document_markdown",
"transforms.docling.serve.url": "http://docling:5001",
"transforms.docling.input.source": "link",
"transforms.docling.input.format": "pdf",
"transforms.docling.output.format": "markdown",
"transforms.docling.include.images": "false"
}
input.source=text expects the document content in the field itself; link expects an HTTP or HTTPS URL (other URL
schemes and file paths are rejected). The Docling and Embeddings transformations can be chained in one transforms
list, Docling first, so that the embedding is computed from the parsed text. Document parsing in general, including
Docling on its own, is covered on Document Parsing.
PyDebeziumAI
pydebeziumai is an official Python package that runs the Debezium embedded engine inside a Python process through
JVM bindings, maps change events to LangChain Document objects and upserts or deletes them in a vector store. It
supports PostgreSQL (15, 16 and 17) and MySQL (8.0 and 8.4) sources and Chroma, PGVector and Milvus stores, uses
primary-key-based document ids so that updates and deletes find the right vectors, and compacts bursts of changes to
the same key before flushing.
from pydebeziumai import LiveContext
rag = LiveContext(
debezium_config={
"name": "bookshop-catalog-rag",
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "bookshop_cdc",
"database.password": "change-me",
"database.dbname": "bookshop",
"topic.prefix": "catalog-rag",
"plugin.name": "pgoutput",
"slot.name": "bookshop_catalog_rag",
"table.include.list": "public.book",
},
vector_store="chroma",
embedding_model="local",
id_strategy="table_pk",
)
rag.start()
retriever = rag.as_retriever(search_kwargs={"k": 5})
docs = retriever.invoke("books about database migration")
Reference: Debezium — PyDebeziumAI: example usage
Install it with pip install "pydebeziumai[chroma,debezium]". The supported source versions on the official page stop
at PostgreSQL 17, while the Bookshop target is PostgreSQL 18; check the package documentation before relying on it for
PostgreSQL 18. PyDebeziumAI suits a single Python service that owns its index. When several consumers need the same
events, keep Kafka in the middle and use the SMT or a Kafka consumer instead.
Streaming analytics and lakehouse ingestion
The remaining official use cases need little Debezium-specific configuration. Stream processors such as Kafka Streams, Flink or Spark read the change topics like any other topic (see Kafka Streams). For warehouses and lakehouse table formats, Debezium Server has an Apache Iceberg sink, and Kafka Connect sinks from the warehouse vendors read the flattened events. In both cases the questions are the same as for the JDBC sink: what the key is, how deletes are represented, and how schema changes reach the target (see Handling Schema Changes).
What goes wrong
| Symptom | Cause | Fix |
|---|---|---|
Cache still serves old data after a sink write |
The cache is evicted only by the application’s own writes |
Invalidate from the change stream (extension or listener); make sure the listener group is unique per instance |
Replication slots accumulate on PostgreSQL after redeployments |
The Hibernate cache extension creates a slot per replica, and old replicas' slots are not dropped |
Monitor |
Audit topic lost history |
The topic used compaction or the default retention |
|
Audit events lack the business user |
The transaction log only knows the database user |
Add a transaction metadata table and enrich with a stream processor, as in the audit-log blog post |
Deleted rows still appear in the search index or vector store |
Tombstones were dropped by |
Keep tombstones ( |
Every event in the migration pipeline is slow and large |
The embeddings SMT was added to the migration’s source connector |
Move it to a dedicated connector or Debezium Server instance with its own slot |
Embedding SMT fails at startup with a class not found error |
The provider JAR (for example |
Add the provider JAR next to the connector; run on Java 21 or later |
References
-
Debezium — PostgreSQL connector: provide.transaction.metadata
-
debezium/debezium — FieldToEmbedding source at v3.7.1.Final (configuration names)
-
Debezium blog — Building audit logs with change data capture and stream processing
-
Debezium blog — Creating DDD aggregates with Debezium and Kafka Streams
-
Apache Kafka 4.3 — Topic configs (retention.ms, cleanup.policy)