Debezium Engine (Embedded)
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Most Debezium deployments run connectors in Kafka Connect, and the change events live in Kafka topics where any number of consumers can read them. The Debezium Engine removes both: it is a Java library that runs one connector inside your own process and hands every change event to a method you write. There is no broker to operate, no topic to size and no Connect cluster to monitor. What you give up is everything Kafka provided: durable storage of the events, replay, fan-out to several consumers, and Kafka Connect’s fault tolerance.
For a database migration, that trade-off is attractive in a specific set of cases: a short migration with a single
consumer, a one-off copy of a few legacy tables, a tool that runs next to the legacy database during the overlap and is
thrown away afterwards, or an organisation that cannot run Kafka. This page explains how the engine works and builds a
complete Java 21 program that copies the Bookshop SUPPLIER_CATALOGUE table from Oracle to PostgreSQL with the engine,
storing its offsets and schema history in PostgreSQL. It ends with the Debezium extensions for Quarkus, which wrap the
same engine for Quarkus applications.
Checked on 2026-11-09 against Debezium 3.7.1.Final, with Java 21, the Oracle JDBC driver 23.26.1.0.0, the PostgreSQL JDBC
driver 42.7.14 and Quarkus 3.40.1. The SupplierCatalogueEngine class and the Quarkus PurchaseOrderChangeHandler were
compiled on 2026-11-09 against the released Maven Central artifacts (debezium-embedded, debezium-connector-oracle,
debezium-storage-jdbc and debezium-quarkus-postgres, all 3.7.1.Final), and the engine project was packaged into an
executable jar. Neither was run against a database; the configuration is derived from the official documentation.
When the engine is enough for a migration
| Concern | Kafka Connect | Debezium Server | Debezium Engine |
|---|---|---|---|
Where the connector runs |
Connect workers (a cluster) |
One standalone server process |
Inside your Java application |
Where events go |
Kafka topics |
A sink: Kafka, Kinesis, Pub/Sub, RabbitMQ, a database… |
Your method, in memory |
Consumers of the same events |
Any number, independent |
Whatever the sink system allows |
One: the application |
Replay of past events |
From Kafka retention |
From the sink system, if it keeps them |
None: re-snapshot or restart from an older offset |
Fault tolerance |
Tasks restart on another worker |
Restart the process (Kubernetes, systemd) |
Restart the application |
Code to write |
None for sinks that exist |
None for sinks that exist |
The event handler |
Choose the engine when all of these hold:
-
exactly one system consumes the changes (the new database, written by your code);
-
you can tolerate re-reading changes after a crash (the handler is idempotent), because there is no exactly-once delivery in the engine;
-
nothing else needs the history of the events, for example for auditing or for a second consumer added later;
-
the migration is short, or the engine runs inside an application that is already operated and monitored.
If a second consumer may appear, or if the events must survive the application, use Kafka Connect or Debezium Server with a broker. The comparison is developed in Choosing a Deployment.
The engine implementations
The debezium-api module defines the DebeziumEngine interface and debezium-embedded implements it. Since Debezium
3.2 the only implementation is the asynchronous engine (AsyncEmbeddedEngine); the older EmbeddedEngine, which
ran one task and emitted records sequentially, is gone. DebeziumEngine.create(...) returns the asynchronous engine. It
still runs a single connector, but it can process records in several threads, and it can run several tasks when the
connector supports them (the SQL Server and MongoDB connectors). The Oracle connector always has one task.
Dependencies and packaging
The application needs debezium-api, debezium-embedded, the connector, and the module of each storage backend it uses
that is not built in. The JDBC offset and history stores are in debezium-storage-jdbc. The Oracle connector also needs
the Oracle JDBC driver.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>bookshop-supplier-engine</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.debezium>3.7.1.Final</version.debezium>
</properties>
<dependencyManagement>
<dependencies>
<!-- a transitive dependency asks for a jaxb-api build that is not on Maven Central -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-api</artifactId>
<version>${version.debezium}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-embedded</artifactId>
<version>${version.debezium}</version>
</dependency>
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-connector-oracle</artifactId>
<version>${version.debezium}</version>
</dependency>
<!-- JdbcOffsetBackingStore and JdbcSchemaHistory -->
<dependency>
<groupId>io.debezium</groupId>
<artifactId>debezium-storage-jdbc</artifactId>
<version>${version.debezium}</version>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc11</artifactId>
<version>23.26.1.0.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.14</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<!-- Debezium loads its implementations through META-INF/services -->
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.bookshop.migration.SupplierCatalogueEngine</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Reference: Debezium — Debezium Engine, Dependencies
Two details of this build are easy to get wrong:
-
Merge the
META-INF/servicesfiles. Debezium finds implementations (snapshot locks, storage backends, connector internals) throughServiceLoader. A fat jar built without merging those files keeps only one copy of each, and the engine fails at startup or silently uses a wrong implementation. The Maven Shade plugin needs theServicesResourceTransformer; with the Assembly plugin, use themetaInf-servicescontainer descriptor handler. -
The
jaxb-apipin. Resolvingdebezium-connector-oracle3.7.1.Final from Maven Central pulls a transitivejavax.xml.bind:jaxb-apibuild that is not published there, and Maven stops with "Failed to read artifact descriptor". Managingjaxb-apito 2.3.1, as above, resolves it. It was needed for the build checked on this page.
Output formats
DebeziumEngine.create(...) takes the format in which the handler receives each change event:
| Format class | What the handler receives |
|---|---|
|
The Kafka Connect |
|
|
|
Key and value as JSON encoded in UTF-8 byte arrays |
|
Key and value serialized as Avro (needs a schema registry configuration) |
|
Key and value as CloudEvents messages |
A second argument sets the header format, Json.class or JsonByteArray.class. The converters are configured with
engine properties prefixed converter., for example converter.schemas.enable=false to receive the bare envelope
without the schema, which is what a handler that parses JSON wants.
Json.class is the most convenient for a migration handler that writes SQL, because the event is the same envelope
the other pages of this section show, described in Anatomy of a
Change Event. Connect.class avoids the JSON round trip and gives typed values (a Decimal arrives as a BigDecimal),
which suits large copies where throughput matters.
Storing offsets and schema history
A connector in Kafka Connect gets its offset storage from Connect. In the engine you must configure it. The Oracle
connector, like the MySQL, SQL Server and Db2 connectors, also needs a schema history store: it records the DDL of
the captured tables so that it can decode old redo records after a restart. Without one, the connector refuses to start;
the default, KafkaSchemaHistory, expects a Kafka cluster.
| Backend | Offset store class | Schema history class | Notes |
|---|---|---|---|
Kafka |
|
|
Needs a Kafka cluster; offsets topic must be compacted |
File |
|
|
Single node; the file must survive restarts (a persistent volume) |
Memory |
|
|
Lost on shutdown: tests and one-shot copies only |
JDBC |
|
|
Any relational database with a JDBC driver, including the source or the target |
Redis |
|
|
Single instance or cluster mode |
Amazon S3 |
(none) |
|
Schema history only |
Azure Blob Storage |
(none) |
|
Schema history only |
RocketMQ |
(none) |
|
Schema history only |
The same page also documents Chronicle Queue, which is not a state store but an alternative to the connector’s
in-memory event queue (queue.provider.type): it buffers events in memory-mapped files to reduce heap pressure, and it
does not work on a network file system.
For a migration, the JDBC store is often the best choice when there is no Kafka: the offsets and the history live in a database that is already backed up, and they can be inspected with SQL. Storing them in the target database keeps everything the migration needs in one place.
offset.storage=io.debezium.storage.jdbc.offset.JdbcOffsetBackingStore
offset.storage.jdbc.connection.url=jdbc:postgresql://localhost:5432/bookshop
offset.storage.jdbc.connection.user=bookshop
offset.storage.jdbc.connection.password=${BOOKSHOP_DB_PASSWORD}
offset.storage.jdbc.table.name=debezium_offset_storage
schema.history.internal=io.debezium.storage.jdbc.history.JdbcSchemaHistory
schema.history.internal.jdbc.connection.url=jdbc:postgresql://localhost:5432/bookshop
schema.history.internal.jdbc.connection.user=bookshop
schema.history.internal.jdbc.connection.password=${BOOKSHOP_DB_PASSWORD}
schema.history.internal.jdbc.table.name=debezium_database_history
Reference: Debezium — Storing state, JDBC
The engine reads these as plain strings; the ${...} placeholder is only illustrative and must be resolved by the
application (the class below reads environment variables). The stores create their tables with default DDL
(debezium_offset_storage with id, offset_key, offset_val, record_insert_ts, record_insert_seq, and
debezium_database_history with history_data split into chunks). Override offset.storage.jdbc.table.ddl,
.table.select, .table.insert and .table.delete (and the schema.history.internal.jdbc.table.* equivalents) when a
database dialect rejects the defaults. Before Debezium 3.2 the properties had other names (offset.storage.jdbc.url,
offset.storage.jdbc.user, offset.storage.jdbc.offset.table.name, schema.history.internal.jdbc.url and so on);
examples found online often still use them.
Do not lose the schema history while the offsets survive. A connector restarted with offsets but without history cannot decode the redo log. Keep both in the same store and back them up together. Recovery is covered in Handling Schema Changes.
A complete engine: SupplierCatalogueEngine
The Bookshop supplier feed is a good candidate for the engine. SUPPLIER_CATALOGUE is written by a nightly batch in the
legacy system, the new application only needs a copy of it in legacy_supplier_catalogue, and nothing else consumes
it. The program below captures the table from the FREEPDB1 database of Oracle AI Database 26ai Free (image
gvenzl/oracle-free:23.26.3) and applies every change to
PostgreSQL. In a pipeline that also runs Kafka Connect, this table would be copied by the bookshop-pg-mirror-sink JDBC
sink instead; do not run both on the same table.
package com.example.bookshop.migration;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.debezium.engine.ChangeEvent;
import io.debezium.engine.DebeziumEngine;
import io.debezium.engine.format.Json;
/**
* Copies the legacy Oracle BOOKSHOP.SUPPLIER_CATALOGUE table into the PostgreSQL legacy_supplier_catalogue
* table with an embedded Debezium engine: no Kafka, no Kafka Connect. Offsets and the schema history are
* stored in PostgreSQL, so the copy resumes where it stopped after a restart.
*/
public final class SupplierCatalogueEngine implements DebeziumEngine.ChangeConsumer<ChangeEvent<String, String>> {
private static final String UPSERT = """
INSERT INTO legacy_supplier_catalogue (supplier_id, isbn, supplier_price, feed_ts)
VALUES (?, ?, ?, ?)
ON CONFLICT (supplier_id, isbn) DO UPDATE SET
supplier_price = EXCLUDED.supplier_price,
feed_ts = EXCLUDED.feed_ts
""";
private static final String DELETE = "DELETE FROM legacy_supplier_catalogue WHERE supplier_id = ? AND isbn = ?";
private final Connection target;
private final ObjectMapper mapper = new ObjectMapper();
private SupplierCatalogueEngine(Connection target) {
this.target = target;
}
public static void main(String[] args) throws Exception {
String pgUrl = env("TARGET_JDBC_URL", "jdbc:postgresql://localhost:5432/bookshop");
String pgUser = env("TARGET_USER", "bookshop");
String pgPassword = env("TARGET_PASSWORD", "bookshop");
try (Connection target = DriverManager.getConnection(pgUrl, pgUser, pgPassword)) {
target.setAutoCommit(false);
createTargetTable(target);
CountDownLatch stopped = new CountDownLatch(1);
DebeziumEngine<ChangeEvent<String, String>> engine = DebeziumEngine.create(Json.class)
.using(engineProperties(pgUrl, pgUser, pgPassword))
.using((success, message, error) -> {
System.err.println("Engine stopped (success=" + success + "): " + message);
stopped.countDown();
})
.notifying(new SupplierCatalogueEngine(target))
.build();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(engine);
// close() stops the connector, hands the remaining events to handleBatch and flushes the offsets
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
engine.close();
stopped.await(1, TimeUnit.MINUTES);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}));
stopped.await();
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
}
}
static Properties engineProperties(String pgUrl, String pgUser, String pgPassword) {
Properties props = new Properties();
// Engine
props.setProperty("name", "bookshop-supplier-engine");
props.setProperty("connector.class", "io.debezium.connector.oracle.OracleConnector");
props.setProperty("offset.storage", "io.debezium.storage.jdbc.offset.JdbcOffsetBackingStore");
props.setProperty("offset.storage.jdbc.connection.url", pgUrl);
props.setProperty("offset.storage.jdbc.connection.user", pgUser);
props.setProperty("offset.storage.jdbc.connection.password", pgPassword);
props.setProperty("offset.storage.jdbc.table.name", "debezium_offset_storage");
props.setProperty("offset.flush.interval.ms", "10000");
props.setProperty("converter.schemas.enable", "false");
// Oracle connector
props.setProperty("database.hostname", env("ORACLE_HOST", "localhost"));
props.setProperty("database.port", env("ORACLE_PORT", "1521"));
props.setProperty("database.user", "C##DBZUSER");
props.setProperty("database.password", env("ORACLE_PASSWORD", "dbz"));
props.setProperty("database.dbname", "FREE");
props.setProperty("database.pdb.name", "FREEPDB1");
props.setProperty("topic.prefix", "legacy");
props.setProperty("table.include.list", "BOOKSHOP.SUPPLIER_CATALOGUE");
props.setProperty("decimal.handling.mode", "string");
props.setProperty("snapshot.mode", "initial");
// Schema history, required by the Oracle connector
props.setProperty("schema.history.internal", "io.debezium.storage.jdbc.history.JdbcSchemaHistory");
props.setProperty("schema.history.internal.jdbc.connection.url", pgUrl);
props.setProperty("schema.history.internal.jdbc.connection.user", pgUser);
props.setProperty("schema.history.internal.jdbc.connection.password", pgPassword);
props.setProperty("schema.history.internal.jdbc.table.name", "debezium_database_history");
props.setProperty("schema.history.internal.store.only.captured.tables.ddl", "false");
return props;
}
/**
* Called by the engine with each batch of change events. The batch is written in one PostgreSQL
* transaction; the records are marked processed only after the commit, so the engine never records an
* offset for a change that is not in the target table.
*/
@Override
public void handleBatch(List<ChangeEvent<String, String>> records,
DebeziumEngine.RecordCommitter<ChangeEvent<String, String>> committer) throws InterruptedException {
try (PreparedStatement upsert = target.prepareStatement(UPSERT);
PreparedStatement delete = target.prepareStatement(DELETE)) {
for (ChangeEvent<String, String> record : records) {
if (record.value() == null) {
continue; // tombstone that follows a delete event
}
JsonNode event = mapper.readTree(record.value());
String op = event.path("op").asText();
switch (op) {
case "c", "r", "u" -> addUpsert(upsert, event.get("after"));
case "d" -> addDelete(delete, event.get("before"));
default -> { } // truncate ("t") and messages ("m") are not replicated
}
}
upsert.executeBatch();
delete.executeBatch();
target.commit();
} catch (Exception e) {
rollbackQuietly();
// Throwing stops the engine; on restart it resumes from the last flushed offset
throw new IllegalStateException("Could not apply a batch of " + records.size() + " change events", e);
}
for (ChangeEvent<String, String> record : records) {
committer.markProcessed(record);
}
committer.markBatchFinished();
}
private static void addUpsert(PreparedStatement upsert, JsonNode row) throws SQLException {
// decimal.handling.mode=string: every NUMBER arrives as a JSON string ("3"); asLong() parses it
upsert.setLong(1, row.get("SUPPLIER_ID").asLong());
upsert.setString(2, row.get("ISBN").asText());
JsonNode price = row.get("SUPPLIER_PRICE");
if (price == null || price.isNull()) {
upsert.setNull(3, Types.NUMERIC);
} else {
upsert.setBigDecimal(3, new BigDecimal(price.asText()));
}
JsonNode feedTs = row.get("FEED_TS");
if (feedTs == null || feedTs.isNull()) {
upsert.setNull(4, Types.TIMESTAMP);
} else {
// TIMESTAMP(6) -> io.debezium.time.MicroTimestamp: microseconds since the epoch, no time zone
LocalDateTime value = LocalDateTime.ofInstant(Instant.EPOCH.plus(feedTs.asLong(), ChronoUnit.MICROS),
ZoneOffset.UTC);
upsert.setTimestamp(4, Timestamp.valueOf(value));
}
upsert.addBatch();
}
private static void addDelete(PreparedStatement delete, JsonNode row) throws SQLException {
delete.setLong(1, row.get("SUPPLIER_ID").asLong());
delete.setString(2, row.get("ISBN").asText());
delete.addBatch();
}
private static void createTargetTable(Connection target) throws SQLException {
try (var statement = target.createStatement()) {
statement.execute("""
CREATE TABLE IF NOT EXISTS legacy_supplier_catalogue (
supplier_id bigint NOT NULL,
isbn varchar(13) NOT NULL,
supplier_price numeric(10,2),
feed_ts timestamp,
PRIMARY KEY (supplier_id, isbn)
)
""");
}
target.commit();
}
private void rollbackQuietly() {
try {
target.rollback();
} catch (SQLException ignored) {
// the original exception is more useful
}
}
private static String env(String name, String defaultValue) {
String value = System.getenv(name);
return value == null || value.isBlank() ? defaultValue : value;
}
}
How it works:
-
Configuration. The properties combine engine settings (
name,connector.class, the offset store,offset.flush.interval.ms,converter.schemas.enable), the Oracle connector settings documented in Oracle Connector, and the schema history store. The connector userC##DBZUSERneeds the LogMiner grants of that page.decimal.handling.mode=stringkeepsSUPPLIER_PRICEexact in JSON, and makes everyNUMBERcolumn, including theSUPPLIER_IDkey, a JSON string that the handler parses.schema.history.internal.store.only.captured.tables.ddlstays at its defaultfalse, as onbookshop-oracle-source: the history then records the DDL of every table in the captured schemas, so that a table can be added totable.include.listlater without a new snapshot of the history.converter.schemas.enable=falseis a choice of this engine only: its events go to the handler and to no JDBC sink, so they do not need the embedded schema thatbookshop-oracle-sourcekeeps forbookshop-pg-mirror-sink. -
The
ChangeConsumer.handleBatchreceives a list of events and aRecordCommitter. It writes the whole batch in one PostgreSQL transaction with JDBC batching, commits, and only then callsmarkProcessedfor each record andmarkBatchFinished. The engine flushes an offset only for records marked as processed, so an offset never points past a change that is not in PostgreSQL. -
Idempotent writes.
INSERT ... ON CONFLICT DO UPDATEandDELETEby primary key give the same result when a change is applied twice, which happens after a crash (see Failures and duplicates). -
Tombstones. The engine delivers the tombstone that follows a delete event as a record with a null value; the handler skips it.
-
Errors. An exception thrown from
handleBatchstops the engine. Nothing of the failed batch is marked processed, so the next start re-reads it. Catching and ignoring the exception would lose the batch. -
Shutdown.
engine.close()stops the connector, delivers the remaining events and flushes the offsets. The shutdown hook calls it, and the completion callback releases the main thread. Interrupting the engine thread instead (for example withExecutorService.shutdownNow()) stops it without a clean flush, which means more duplicates on the next start.
The Consumer<ChangeEvent> form of notifying(...) is simpler (one event at a time, offsets committed by the engine),
but the official documentation warns that if that method throws, the engine logs the exception and moves on to the
next record, so that record is lost for the handler. For a migration, ChangeConsumer with explicit commits is the
safer API.
Building and running it
mvn -B package
export ORACLE_HOST=localhost ORACLE_PORT=1521 ORACLE_PASSWORD=dbz
export TARGET_JDBC_URL=jdbc:postgresql://localhost:5432/bookshop TARGET_USER=bookshop TARGET_PASSWORD=bookshop
java -jar target/bookshop-supplier-engine-1.0.0-SNAPSHOT.jar
Reference: Debezium — Debezium Engine, In the Code
On the first start the connector takes an initial snapshot of SUPPLIER_CATALOGUE (its rows arrive with op = r),
then streams the redo log. Stop it with Ctrl+C (the shutdown hook closes the engine cleanly) and start it again: it
resumes from the stored offset without a new snapshot.
-- the copy
SELECT count(*), max(feed_ts) FROM legacy_supplier_catalogue;
-- the engine's position (one row per flush; the newest wins)
SELECT offset_key, offset_val, record_insert_ts
FROM debezium_offset_storage
ORDER BY record_insert_ts DESC, record_insert_seq DESC
LIMIT 1;
-- the schema history recorded for the captured table
SELECT count(*) FROM debezium_database_history;
Compare the count with SELECT COUNT(*) FROM BOOKSHOP.SUPPLIER_CATALOGUE in Oracle, and use the techniques in
Verification & Reconciliation for a full comparison.
Engine properties
The engine has its own properties on top of the connector’s. The ones that matter most in a migration:
| Property | Default | Meaning |
|---|---|---|
|
(required) |
Unique name of the connector instance. It is part of the stored offset key, so changing it starts from scratch |
|
(required) |
The connector class, for example |
|
|
Offset store class (see the table above) |
|
|
How often offsets are flushed. Lower means fewer duplicates after a crash and more writes to the store |
|
|
How long a flush may take before it is cancelled and retried later |
|
|
When to commit offsets, based on time and number of events |
|
|
Retries on connection errors ( |
|
|
First retry delay, doubled on each retry |
|
|
Maximum retry delay |
The asynchronous engine adds:
| Property | Default | Meaning |
|---|---|---|
|
on demand, up to the number of cores |
Threads that run transformations and serialization. |
|
|
|
|
|
Wraps a |
|
|
Time allowed to finish submitted records after a task shutdown |
|
|
Time allowed to start or stop tasks |
Never use UNORDERED for a migration handler that writes rows: two changes of the same row could be applied in the
wrong order. A ChangeConsumer always receives each batch in source order.
Transformations and predicates
The engine applies Kafka Connect single message transformations before it calls the handler, configured exactly as in Kafka Connect but without a prefix. For example, to receive only the new row state instead of the full envelope:
props.setProperty("transforms", "unwrap");
props.setProperty("transforms.unwrap.type", "io.debezium.transforms.ExtractNewRecordState");
props.setProperty("transforms.unwrap.delete.tombstone.handling.mode", "rewrite");
props.setProperty("transforms.unwrap.add.fields", "op,source.scn");
With rewrite, a delete arrives as the last row state with __deleted set to true, and the added fields arrive as
__op and __source_scn. The handler above would then need to read the flattened record instead of before and
after. The options are explained in Event Flattening. Predicates work as
well (predicates, predicates.<name>.type, and transforms.<name>.predicate / .negate) to apply a transformation
only to some records.
Failures and duplicates
The engine delivers each change exactly once while it runs and shuts down cleanly, and at least once after a
crash. The connector records its position in every event, and the engine flushes those positions to the offset store
periodically. After a crash, the engine restarts from the last flushed offset and the handler receives again the changes
that were processed after it. How many depends on offset.flush.interval.ms and on the connector’s batch size
(max.batch.size): up to one batch with a flush interval of 0, and up to several batches with a longer interval.
So the handler must be idempotent, as SupplierCatalogueEngine is. Upserts by primary key and deletes by primary key
are idempotent by nature; writes that are not (an insert with a generated key, a counter, a call to another system) need
an idempotency table like the processed_change table of
Listening to Events in Applications.
The engine has no exactly-once mode. If the migration needs exactly-once delivery into Kafka, use Kafka Connect with exactly-once source support, as described in Offsets, Restarts & Exactly-Once.
Other failure modes to plan for:
-
The application is down for longer than the source keeps its logs. Oracle archive logs, the PostgreSQL WAL held by a replication slot, or the MySQL binlog can be purged or fill the disk. The engine has no buffer of its own; if the position it needs is gone, the connector cannot resume and a new snapshot is needed. Monitor it as you would a connector, with the JMX metrics described in Monitoring, Logging & Tracing.
-
Two instances of the same engine. Nothing prevents two copies of the application from running the same connector with the same offsets. Both would apply the same changes; with PostgreSQL replication slots, the second fails to attach. Run exactly one instance, for example a Kubernetes Deployment with one replica and the
Recreatestrategy. -
Memory. The connector buffers events in an in-memory queue (
max.queue.size,max.batch.size). A slow handler makes the queue fill and the connector wait; it does not lose events.
The Debezium extensions for Quarkus
The Debezium extensions for Quarkus embed the same engine in a Quarkus application and replace the builder code with
configuration and annotations. A method annotated @Capturing receives the change events, optionally filtered by
destination (the topic name the event would have had) or by a filter strategy, and optionally deserialized into a Java
class with a Jackson-based deserializer. CDI events report the connector lifecycle, heartbeats and notifications such as
snapshot progress.
The documented extensions are debezium-quarkus-postgres, debezium-quarkus-mongodb, debezium-quarkus-mysql,
debezium-quarkus-mariadb and debezium-quarkus-sqlserver (group io.debezium.quarkus), and they need Java 21. An
artifact debezium-quarkus-oracle is also published on Maven Central for 3.7.1.Final, but the 3.7 documentation does
not list it as supported, so the Oracle source of the Bookshop migration uses the plain engine above.
A Quarkus use of the extension in the Bookshop migration is the new side: a service that reacts to changes of the new
PostgreSQL purchase_order table in-process, for example to notify the legacy fulfilment system during the overlap.
<dependency>
<groupId>io.debezium.quarkus</groupId>
<artifactId>debezium-quarkus-postgres</artifactId>
<version>3.7.1.Final</version>
</dependency>
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=bookshop_cdc
quarkus.datasource.password=${BOOKSHOP_CDC_PASSWORD}
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/bookshop
quarkus.datasource.jdbc.max-size=4
quarkus.debezium.name=bookshop-order-watcher
quarkus.debezium.topic.prefix=modern
quarkus.debezium.plugin.name=pgoutput
quarkus.debezium.slot.name=bookshop_order_watcher
quarkus.debezium.publication.name=bookshop_order_watcher_pub
quarkus.debezium.table.include.list=public.purchase_order
quarkus.debezium.snapshot.mode=no_data
quarkus.debezium.offset.storage=org.apache.kafka.connect.storage.FileOffsetBackingStore
quarkus.debezium.offset.storage.file.filename=data/bookshop-order-watcher.offsets
Every quarkus.debezium.* property is passed to the engine and the connector without the prefix, and the database
connection comes from the Quarkus datasource. The official example uses MemoryOffsetBackingStore, which forgets the
position on every restart; use a persistent store as above for anything that must resume. The slot and publication
names are separate from the bookshop_reverse slot of the reverse replication, because two connectors must never share
a slot. Here Quarkus resolves ${BOOKSHOP_CDC_PASSWORD} from the environment, unlike the plain engine.
package com.example.bookshop.migration;
import jakarta.enterprise.context.ApplicationScoped;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;
import org.jboss.logging.Logger;
import io.debezium.runtime.Capturing;
import io.debezium.runtime.CapturingEvent;
/**
* Receives the changes of the new PostgreSQL purchase_order table inside the Quarkus application, with no
* Kafka in between.
*/
@ApplicationScoped
public class PurchaseOrderChangeHandler {
private static final Logger LOG = Logger.getLogger(PurchaseOrderChangeHandler.class);
@Capturing(destination = "modern.public.purchase_order")
public void capture(CapturingEvent<SourceRecord, SourceRecord> event) {
Struct value = (Struct) event.record().value();
switch (event) {
case CapturingEvent.Create<SourceRecord, SourceRecord> created ->
LOG.infof("Order created: %s", value.getStruct("after"));
case CapturingEvent.Update<SourceRecord, SourceRecord> updated ->
LOG.infof("Order updated: %s", value.getStruct("after"));
case CapturingEvent.Delete<SourceRecord, SourceRecord> deleted ->
LOG.infof("Order deleted: %s", value.getStruct("before"));
default -> LOG.debugf("Ignored %s on %s", event.getClass().getSimpleName(), event.destination());
}
}
}
The released 3.7.1.Final API declares CapturingEvent<K, V> with two type parameters and the records Create, Update,
Delete, Read, Truncate and Message nested in it; the class above was compiled against it. Some examples of the
3.7 page use a single type parameter (CapturingEvent<SourceRecord>) and will not compile as written.
With a deserializer, the method receives a Java object instead of a SourceRecord: subclass
io.quarkus.debezium.engine.deserializer.ObjectMapperDeserializer<T>, register it with
quarkus.debezium.capturing.<name>.destination and quarkus.debezium.capturing.<name>.deserializer, and declare the
method parameter as the target class (or CapturingEvent of it, to keep the operation type).
Lifecycle observers are useful in a migration tool: ConnectorStartedEvent, ConnectorStoppedEvent,
TasksStartedEvent, TasksStoppedEvent, PollingStartedEvent, PollingStoppedEvent and DebeziumCompletionEvent
(with the success or failure details) for health checks, DebeziumHeartbeat to show that the connector is alive on a
quiet table, and the snapshot notifications (SnapshotStarted, SnapshotTableScanCompleted, SnapshotCompleted,
SnapshotAborted and others) to report the progress of the initial load.
What goes wrong
| Symptom | Cause | Fix |
|---|---|---|
|
|
|
The Oracle connector refuses to start: no schema history |
|
Configure a file, JDBC or Redis schema history |
Every restart takes a new snapshot |
|
A persistent offset store and a stable |
Rows applied twice after a crash |
At-least-once delivery after an unclean stop |
Idempotent handler; lower |
A batch is lost after an error |
The handler caught the exception, or used |
Let |
Changes of one row applied out of order |
|
Keep |
The source disk fills up while the application is down |
Logs or WAL retained for the stopped connector |
Monitor; drop the slot or take a new snapshot if the downtime is permanent |