Signaling and Notifications
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A Debezium connector is mostly configured once and left alone. A migration, though, needs to talk to it while it runs:
"snapshot this table again", "pause the backfill during the legacy batch window", "stop that snapshot, the filter was
wrong". And the migration runbook needs to hear back: "the initial snapshot of BOOKSHOP has finished, you can start the
sinks", "the ORDERS backfill is at chunk 812 of 1200". Signals are the way in, and notifications are the way
out.
This page describes both mechanisms for the Bookshop pipeline: the signal channels and how to set them up on the legacy Oracle database and on Kafka, every signal action with its payload, the notification channels and message formats, and a complete Java program that a runbook uses to wait for the initial snapshot. How the snapshots themselves work is explained on Initial Snapshots and Incremental & Blocking Snapshots.
Checked on 2026-11-09 against Debezium 3.7.1.Final (Oracle AI Database 26ai Free, image gvenzl/oracle-free:23.26.3, PostgreSQL 18, Kafka 4.x in KRaft mode).
The Java program on this page was compiled with Maven against kafka-clients 4.4.0 and Jackson 3.3.0 on Java 21, and its
message handling was exercised with sample notification messages; it was not run against a live connector. The
connector configuration and SQL are derived from the official documentation and were not run.
Signals and notifications at a glance
-
Signals are commands: a type (
execute-snapshot,stop-snapshot,logand so on), an optional JSONdatapayload and, for most channels, an id. They are available for the CockroachDB, Db2, Informix, MariaDB, MongoDB, MySQL, Oracle, PostgreSQL and SQL Server connectors. -
Notifications are status messages: an
aggregate_type(Initial SnapshotorIncremental Snapshot), atype(STARTED,IN_PROGRESS,COMPLETEDand so on), a map ofadditional_dataand a timestamp.
Neither mechanism is acknowledged. Apart from the source channel, signal channels do not retry. The way to know that a signal worked is to watch the notifications (or the log) that it causes.
Reference: Debezium — Signaling overview
Signal channels
signal.enabled.channels lists the channels a connector listens on. The property reference gives source as the
default, and lists source, kafka, file and jmx as the built-in channels; a custom channel adds its own name.
| Channel | How a signal is sent | Use in a migration |
|---|---|---|
|
|
Required for incremental snapshots, because the connector also writes its watermark rows to this table. Signals are ordered with the data changes and survive restarts. |
|
Produce a message to a Kafka topic whose key is the connector’s |
Operators and automation can send signals without credentials for the legacy database. |
|
Call the |
Ad hoc use from JConsole or JDK Mission Control during an incident. |
|
Append a JSON line to a file that the connector reads ( |
Mostly Debezium Server and embedded engines, where there is no Kafka topic and no database write access. |
custom |
Implement |
Integrating with an existing control plane (for example an internal job scheduler). |
The Bookshop signal table
The signal table has exactly three columns named id, type and data, in that order. The id must hold at least 42
characters because the connector writes watermark rows with ids of the form <uuid>-close
(see the snapshot window).
CREATE TABLE BOOKSHOP.DEBEZIUM_SIGNAL (
ID VARCHAR2(42) PRIMARY KEY,
TYPE VARCHAR2(32) NOT NULL,
DATA VARCHAR2(2048) NULL
);
-- the connector reads signals from the redo log, so the table needs the same
-- supplemental logging as every captured table
ALTER TABLE BOOKSHOP.DEBEZIUM_SIGNAL ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS;
-- the connector writes watermark rows (and deletes them with insert_delete);
-- this grant is missing from the official C##DBZUSER list (without it: ORA-41900)
GRANT INSERT, DELETE ON BOOKSHOP.DEBEZIUM_SIGNAL TO C##DBZUSER;
-- the migration operators may send signals, nothing else
CREATE ROLE BOOKSHOP_CDC_OPERATOR;
GRANT INSERT ON BOOKSHOP.DEBEZIUM_SIGNAL TO BOOKSHOP_CDC_OPERATOR;
The INSERT, DELETE grant is not in the official list of grants for the connector user, and nothing fails without
it until the first incremental snapshot. The worked-example run on 2026-11-09 showed the symptom: the execute-snapshot
signal was accepted, and the snapshot then failed with
ORA-41900: missing INSERT privilege on "BOOKSHOP"."DEBEZIUM_SIGNAL", because the connector writes the watermark rows
as C##DBZUSER. SELECT is already covered by SELECT ANY TABLE in the official grants.
The signal table does not have to be in table.include.list; the connector captures it anyway. If the connector uses
column.include.list, though, the three signal columns must be included.
{
"signal.enabled.channels": "source,kafka",
"signal.data.collection": "FREEPDB1.BOOKSHOP.DEBEZIUM_SIGNAL",
"signal.kafka.topic": "legacy.signals",
"signal.kafka.bootstrap.servers": "kafka:9092",
"signal.kafka.groupId": "bookshop-oracle-source-signals",
"signal.kafka.poll.timeout.ms": "100"
}
The first four settings are the canonical ones. signal.kafka.groupId and signal.kafka.poll.timeout.ms are optional
tuning that the canonical connector does not set. Without them the 3.7.1 connector uses the group id kafka-signal and
a poll timeout of 0 ms (KafkaSignalChannel in debezium-connector-common). Set your own group id when more than one
connector reads the same signal topic (see the rules below).
The database part of the Oracle names. The general signaling page gives the Oracle format as
<databaseName>.<schemaName>.<tableName>. For a pluggable database, the signal.data.collection property description
says to use "the name of the root database", while the snapshot.include.collection.list description and the event
examples of the same page use the PDB name. In the 3.7.1 source code, the Oracle connector names every captured table,
the signal table included, with the PDB name when database.pdb.name is set (OracleConnectorConfig.getCatalogName()),
and recognises a signal by an exact table-id match. The Bookshop configuration therefore uses
FREEPDB1.BOOKSHOP.DEBEZIUM_SIGNAL and FREEPDB1.BOOKSHOP.BOOK (the same value as source.db in the change events),
not the CDB name FREE. The worked-example run on 2026-11-09 confirmed it: with FREE.BOOKSHOP.DEBEZIUM_SIGNAL, the
form that the property description suggests, the connector started and streamed normally but silently ignored every
signal, with no error or warning. With FREEPDB1.BOOKSHOP.DEBEZIUM_SIGNAL the log and execute-snapshot signals
worked. Still check a new setup with a log signal (below) before you rely on it: if the connector logs nothing for
the signal, the name does not match.
The same pattern on the new PostgreSQL database, for the reverse-replication connector bookshop-pg-source:
CREATE TABLE public.debezium_signal (
id varchar(42) PRIMARY KEY,
type varchar(32) NOT NULL,
data varchar(2048) NULL
);
-- INSERT and DELETE cover both watermarking strategies (insert_insert, insert_delete); none updates the table
GRANT SELECT, INSERT, DELETE ON public.debezium_signal TO dbz_reverse;
-- if the publication lists its tables explicitly, add the signal table to it
ALTER PUBLICATION bookshop_reverse_pub ADD TABLE public.debezium_signal;
For PostgreSQL the fully-qualified name is <schemaName>.<tableName>, so signal.data.collection=public.debezium_signal.
dbz_reverse is the replication user of the reverse connector, as created on
PostgreSQL Connector.
The name formats per connector:
| Connector | Format of signal.data.collection and of data-collections entries |
|---|---|
Oracle |
|
PostgreSQL |
|
MySQL, MariaDB |
|
SQL Server, CockroachDB, Informix |
|
Db2 |
|
MongoDB |
|
The Kafka signal topic
The Kafka channel starts a consumer inside the connector that reads signal.kafka.topic (default
<topic.prefix>-signal). The topic must have one partition, so that signals stay in order. Create it explicitly:
docker compose exec kafka /kafka/bin/kafka-topics.sh --bootstrap-server kafka:9092 --create \
--topic legacy.signals --partitions 1 --replication-factor 3
docker compose exec kafka /kafka/bin/kafka-topics.sh --bootstrap-server kafka:9092 --create \
--topic legacy.notifications --partitions 1 --replication-factor 3 \
--config retention.ms=2592000000
(Use a replication factor of 1 on a single-broker development cluster.) Rules for the messages:
-
The key is the connector’s
topic.prefix:legacy. A message with another key is ignored, which lets several connectors share one signal topic. -
The value is a JSON object with
typeanddata. There is no id field; the connector generates one. -
signal.kafka.groupId(defaultkafka-signal) is the consumer group of the internal consumer. Give each connector its own group id. -
Properties with the prefix
signal.consumer.are passed to that consumer, for examplesignal.consumer.security.protocol=SSLon a secured cluster (see Kafka Security).
The JMX and file channels
With jmx in signal.enabled.channels and JMX enabled on the Connect worker, the connector registers an MBean named
debezium.<connector-type>.management.signals.<server>, which for the Bookshop source is the Oracle connector with the
server name legacy. Its signal operation takes p0 (the id), p1 (the type, for example execute-snapshot) and p2
(the JSON data).
With file in signal.enabled.channels, the connector reads JSON lines from signal.file:
{"id": "backfill-book-2026-11-09", "type": "execute-snapshot", "data": {"data-collections": ["FREEPDB1.BOOKSHOP.BOOK"], "type": "incremental"}}
Reference: Debezium — Enabling a file signal channel
Reference: Debezium — Enabling a JMX signaling channel
Custom signal channels
A custom channel implements the SignalChannelReader SPI from debezium-connector-common, is declared in
META-INF/services/io.debezium.pipeline.signal.channels.SignalChannelReader, and its JAR is copied into each
connector’s plugin directory. Its name() is the value to put in signal.enabled.channels.
public interface SignalChannelReader {
String name();
void init(CommonConnectorConfig connectorConfig);
List<SignalRecord> read();
void close();
}
Signal actions
The following table lists every action and where it applies. The JSON goes in the DATA column of the signal table, or
in the data field of a Kafka or file signal.
| Type | Connectors | data payload |
|---|---|---|
|
all with signaling |
|
|
all with signaling |
|
|
all with signaling |
|
|
all with signaling |
No data (ignored). Incremental snapshots only. |
|
MySQL, MariaDB |
|
|
Oracle |
|
|
Oracle |
No data. Logs every transaction pending in the LogMiner buffer. |
custom |
any |
Defined by a |
log
The log signal is the simplest way to check that signaling works end to end, and to leave markers in the connector
log at the start and end of each runbook step.
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE, DATA)
VALUES ('runbook-step-3-start', 'log', '{"message": "Runbook step 3 (BOOK backfill) starts at offset {}"}');
COMMIT;
Reference: Debezium — Logging signals
execute-snapshot
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE, DATA)
VALUES ('backfill-book-author-2026-11-09',
'execute-snapshot',
'{"data-collections": ["FREEPDB1.BOOKSHOP.BOOK", "FREEPDB1.BOOKSHOP.AUTHOR"], "type": "incremental"}');
COMMIT;
Reference: Debezium — Ad hoc snapshot signals
{
"type": "execute-snapshot",
"data": {
"data-collections": ["FREEPDB1.BOOKSHOP.ORDERS"],
"type": "INCREMENTAL",
"additional-conditions": [
{
"data-collection": "FREEPDB1.BOOKSHOP.ORDERS",
"filter": "ORDER_DT >= DATE '2024-01-01' AND ORDER_DT < DATE '2025-01-01'"
}
]
}
}
Reference: Debezium — Kafka signal message format
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE, DATA)
VALUES ('blocking-supplier-42',
'execute-snapshot',
'{"type": "blocking", "data-collections": ["FREEPDB1.BOOKSHOP.SUPPLIER_CATALOGUE"], "additional-conditions": [{"data-collection": "FREEPDB1.BOOKSHOP.SUPPLIER_CATALOGUE", "filter": "SELECT * FROM BOOKSHOP.SUPPLIER_CATALOGUE WHERE SUPPLIER_ID = 42"}]}');
COMMIT;
Reference: Debezium — Blocking snapshot signals
When a filter for an incremental snapshot contains a string literal, double every single quote inside the Oracle SQL
literal (DATE ''2024-01-01''); in a Kafka signal no SQL escaping is needed. When a table name contains a dot, a space
or another non-alphanumeric character, quote it inside the JSON string, for example "db1.public.\"My.Table\"".
stop-snapshot
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE, DATA)
VALUES ('stop-order-line-2026-11-09',
'stop-snapshot',
'{"data-collections": ["FREEPDB1.BOOKSHOP.ORDER_LINE"], "type": "incremental"}');
COMMIT;
Reference: Debezium — Ad hoc snapshot stop signals
{"type": "stop-snapshot", "data": {"type": "INCREMENTAL"}}
The type inside data is required for stop-snapshot. Without it the snapshot is not stopped.
pause-snapshot and resume-snapshot
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE) VALUES ('pause-2026-11-09-2200', 'pause-snapshot');
COMMIT;
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE) VALUES ('resume-2026-11-10-0400', 'resume-snapshot');
COMMIT;
Pausing does not name tables: the whole incremental snapshot pauses at its current position. The connector emits
PAUSED and RESUMED notifications, and the snapshot MBean reports SnapshotPaused and
SnapshotPausedDurationInSeconds.
Connector-specific actions
set-binlog-position (MySQL and MariaDB) repositions the binlog reader. Moving forward skips changes; moving backward
replays them. In a migration it is a disaster-recovery tool only: every skipped change is a difference between the
legacy and the new database that must then be repaired with an incremental snapshot.
INSERT INTO debezium_signal (id, type, data) VALUES (
'set-gtid-001',
'set-binlog-position',
'{"gtid_set": "3E11FA47-71CA-11E1-9E33-C80AA9429562:1-100"}'
);
On Oracle, log-pending-transactions and drop-transaction deal with long-running transactions that hold back the
LogMiner mining window, a common problem with legacy batch jobs that update millions of rows in one transaction.
Dropping a transaction discards its changes for good, so use it only after confirming with the legacy team that the
transaction will never commit or does not matter to the new system.
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE) VALUES ('log-tx-2026-11-09-1', 'log-pending-transactions');
COMMIT;
-- after reading the transaction id from the connector log
INSERT INTO BOOKSHOP.DEBEZIUM_SIGNAL (ID, TYPE, DATA)
VALUES ('drop-tx-2026-11-09-1', 'drop-transaction', '{"transaction-id": "1a.2b.001f"}');
COMMIT;
Custom actions
A custom action implements io.debezium.pipeline.signal.actions.SignalAction and is registered through a
SignalActionProvider, whose map key becomes the signal type. Like custom channels, the JAR goes into every connector’s
plugin directory, with the provider declared in
META-INF/services/io.debezium.pipeline.signal.actions.SignalActionProvider.
@FunctionalInterface
public interface SignalAction<P extends Partition> {
boolean arrived(SignalPayload<P> signalPayload) throws InterruptedException;
}
public interface SignalActionProvider {
<P extends Partition> Map<String, SignalAction<P>> createActions(
EventDispatcher<P, ? extends DataCollectionId> dispatcher,
CommonConnectorConfig connectorConfig);
}
Reference: Debezium — Defining a custom action
Notifications
Enabling notifications
notification.enabled.channels lists the channels (no default, so notifications are off until it is set). The built-in
channels are:
-
sink: writes notifications through Kafka Connect to the topic named bynotification.sink.topic.name, which is required with this channel. -
log: appends them to the connector log. -
jmx: exposes them in theNotificationsattribute of the MBeandebezium.<connector-type>.management.notifications.<server>, and as JMX notifications of typedebezium.notification. Theresetoperation clears the attribute. -
a custom channel implementing
io.debezium.pipeline.notification.channels.NotificationChannel.
{
"notification.enabled.channels": "sink,log",
"notification.sink.topic.name": "legacy.notifications"
}
Reference: Debezium — Enabling Debezium notifications
The notification format
| Field | Content |
|---|---|
|
A unique id. For incremental snapshots it is the id of the |
|
What the notification is about: |
|
The status, for example |
|
A map of string keys to string values: |
|
Creation time in milliseconds since the epoch. |
On the sink topic, each notification is a Kafka Connect record. In 3.7.1 the record key is a struct with the field
id, and the value is a struct with id, type, aggregate_type, additional_data (an optional map of strings) and
timestamp (an int64). Its serialized form therefore depends on the converter. The Bookshop pipeline uses JsonConverter with
schemas.enable=true, so each value is wrapped in {"schema": ..., "payload": ...}, and the payload looks like the
examples below. With schemas.enable=false the value is just that object (the official examples show timestamp as a string; the
converter writes the int64 as a number). With Avro it is Avro. Consumers should handle the form their pipeline uses.
Reference: Debezium — Debezium notification format
Initial snapshot notifications
type |
Meaning and additional_data |
|---|---|
|
The initial snapshot began. |
|
A table is being read. |
|
A table finished. |
|
The whole snapshot finished; streaming follows (unless the mode is |
|
The snapshot was interrupted. |
|
No snapshot was needed, for example because offsets already existed or the mode is |
{
"id": "6d82a3ec-ba86-4b36-9168-7423b0dd5c1d",
"aggregate_type": "Initial Snapshot",
"type": "TABLE_SCAN_COMPLETED",
"additional_data": {
"connector_name": "legacy",
"data_collection": "FREEPDB1.BOOKSHOP.BOOK, FREEPDB1.BOOKSHOP.AUTHOR",
"scanned_collection": "FREEPDB1.BOOKSHOP.BOOK",
"total_rows_scanned": "184233",
"status": "SUCCEEDED"
},
"timestamp": 1762680046353
}
{
"id": "ff81ba59-15ea-42ae-b5d0-4d74f1f4038f",
"aggregate_type": "Initial Snapshot",
"type": "COMPLETED",
"additional_data": {
"connector_name": "legacy"
},
"timestamp": 1762680112904
}
The 3.7.1 source code also defines a TABLE_CHUNK_COMPLETED status, sent per chunk by chunk-based parallel snapshots
(with chunk_index and total_chunks); it is not listed in the notification documentation, so consumers should
ignore types they do not know rather than fail on them.
Incremental snapshot notifications
type |
Meaning and additional_data |
|---|---|
|
The snapshot began. |
|
After a |
|
A chunk is being processed. |
|
A table finished. |
|
Stopped by a |
|
All requested tables are done. |
{
"id": "backfill-orders-2024",
"aggregate_type": "Incremental Snapshot",
"type": "IN_PROGRESS",
"additional_data": {
"connector_name": "legacy",
"data_collections": "FREEPDB1.BOOKSHOP.ORDERS",
"current_collection_in_progress": "FREEPDB1.BOOKSHOP.ORDERS",
"maximum_key": "98123456",
"last_processed_key": "41877120",
"total_rows": "1250000",
"total_chunks": "306",
"chunk_index": "131"
},
"timestamp": 1762683900211
}
chunk_index / total_chunks gives a progress percentage. total_rows is a best-effort estimate from database
statistics, so the ratio is an indication, not a guarantee; the documentation states that the reported progress never
exceeds 100 %.
Custom notification channels
A custom channel implements NotificationChannel (name(), init(CommonConnectorConfig), send(Notification),
close()), is declared in META-INF/services/io.debezium.pipeline.notification.channels.NotificationChannel, and is
deployed into each connector’s plugin directory. A typical migration use is a channel that posts COMPLETED and
ABORTED to the team’s chat or incident tool.
Reference: Debezium — Custom notification channels
Waiting for the initial snapshot in a runbook
A CDC migration runbook has steps that must not start before the initial snapshot has finished: start the JDBC sink
bookshop-pg-mirror-sink with full parallelism, start the bookshop consumers in group bookshop-legacy-sync, run the
first reconciliation, switch read traffic for the first strangler slice. Polling the Connect REST API does not help,
because a connector in the snapshot phase and one in the streaming phase are both RUNNING. The Initial Snapshot
notifications on legacy.notifications answer the question directly.
The program below uses plain kafka-clients and Jackson, so that it can run from a runbook without a Spring context.
It does not join a consumer group: it assigns every partition of the notification topic and reads from the beginning,
so a notification sent before the program started is not missed. To ignore notifications from an earlier run (for
example after the connector was deleted and registered again), it takes the registration time as a lower bound for the
notification timestamp. It accepts both plain JSON values and the schema/payload envelope.
<?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.bookshop</groupId>
<artifactId>snapshot-waiter</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kafka.version>4.4.0</kafka.version>
<jackson.version>3.3.0</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>${kafka.version}</version>
</dependency>
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
</project>
Reference: Debezium — Debezium notification format
package com.example.bookshop.migration;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;
/**
* Blocks until the Debezium connector reports that its initial snapshot finished.
*
* <p>Reads the notification topic (notification.sink.topic.name) from the beginning,
* ignores notifications older than the given start time or from another connector,
* and exits with a status code that a runbook script can test.
*
* <ul>
* <li>0: the initial snapshot COMPLETED</li>
* <li>2: the initial snapshot was ABORTED or a table scan failed</li>
* <li>3: the snapshot was SKIPPED (offsets already existed, or no snapshot mode)</li>
* <li>4: no final notification arrived before the timeout</li>
* </ul>
*/
public final class InitialSnapshotWaiter {
private static final String INITIAL_SNAPSHOT = "Initial Snapshot";
private static final JsonMapper MAPPER = JsonMapper.builder().build();
private InitialSnapshotWaiter() {
}
public static void main(String[] args) {
String bootstrapServers = args.length > 0 ? args[0] : "localhost:9092";
String topic = args.length > 1 ? args[1] : "legacy.notifications";
String connectorName = args.length > 2 ? args[2] : "legacy"; // the topic.prefix
long sinceEpochMillis = args.length > 3 ? Long.parseLong(args[3]) : 0L;
Duration timeout = args.length > 4 ? Duration.parse(args[4]) : Duration.ofHours(12);
System.exit(waitForInitialSnapshot(bootstrapServers, topic, connectorName, sinceEpochMillis, timeout));
}
static int waitForInitialSnapshot(String bootstrapServers, String topic, String connectorName,
long sinceEpochMillis, Duration timeout) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.CLIENT_ID_CONFIG, "bookshop-snapshot-waiter");
Instant deadline = Instant.now().plus(timeout);
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
// No consumer group: assign every partition and read the topic from the start,
// so that a notification sent before this program started is not missed.
List<TopicPartition> partitions = consumer.partitionsFor(topic, Duration.ofSeconds(30)).stream()
.map(info -> new TopicPartition(info.topic(), info.partition()))
.toList();
consumer.assign(partitions);
consumer.seekToBeginning(partitions);
while (Instant.now().isBefore(deadline)) {
for (ConsumerRecord<String, String> record : consumer.poll(Duration.ofSeconds(5))) {
Integer exitCode = handle(record.value(), connectorName, sinceEpochMillis);
if (exitCode != null) {
return exitCode;
}
}
}
}
System.err.println("Timed out waiting for the initial snapshot of connector " + connectorName);
return 4;
}
/**
* Returns an exit code when the notification ends the wait, or null to keep waiting.
*/
static Integer handle(String json, String connectorName, long sinceEpochMillis) {
if (json == null) {
return null; // tombstone
}
JsonNode root = MAPPER.readTree(json);
// With JsonConverter and schemas.enable=true the record is wrapped in {"schema":..., "payload":...}
JsonNode notification = root.has("payload") ? root.get("payload") : root;
String aggregateType = notification.path("aggregate_type").asString();
String type = notification.path("type").asString();
long timestamp = Long.parseLong(notification.path("timestamp").asString("0"));
Map<String, String> data = new TreeMap<>();
notification.path("additional_data").propertyStream()
.forEach(entry -> data.put(entry.getKey(), entry.getValue().asString()));
if (!INITIAL_SNAPSHOT.equals(aggregateType)
|| !connectorName.equals(data.get("connector_name"))
|| timestamp < sinceEpochMillis) {
return null;
}
System.out.printf("%s %s %s%n", Instant.ofEpochMilli(timestamp), type, data);
return switch (type) {
case "COMPLETED" -> 0;
case "ABORTED" -> 2;
case "SKIPPED" -> 3;
case "TABLE_SCAN_COMPLETED" -> "SQL_EXCEPTION".equals(data.get("status")) ? 2 : null;
default -> null; // STARTED, IN_PROGRESS, TABLE_CHUNK_COMPLETED
};
}
}
Design notes:
-
The code uses Jackson 3 (
tools.jackson), the version Spring Boot 4 uses. With Jackson 2, change the imports tocom.fasterxml.jackson.databind, callasText()instead ofasString(), iterate withfields(), and handle the checkedJsonProcessingException. -
timestampis read as a string and parsed, which works whether the converter wrote a number or a string. -
Exit code 3 (
SKIPPED) is not treated as success. It usually means the connector found existing offsets (it was registered before, under the same name andtopic.prefix), so the runbook should stop and let a person decide. -
On a secured cluster add the client security properties (
security.protocol, SASL or TLS settings) toprops; see Kafka Security. -
In a Spring Boot 4.1 service, the same logic fits in a
@KafkaListeneronlegacy.notificationswith a dedicated group id andauto.offset.reset=earliest; see Spring Boot and Kafka.
#!/usr/bin/env bash
set -euo pipefail
CONNECT=http://localhost:8083
START_MS=$(( $(date +%s) * 1000 ))
curl -fsS -X POST -H 'Content-Type: application/json' \
--data @bookshop-oracle-source.json "$CONNECT/connectors"
set +e
java -cp "target/snapshot-waiter-1.0.0.jar:target/dependency/*" \
com.example.bookshop.migration.InitialSnapshotWaiter \
localhost:9092 legacy.notifications legacy "$START_MS" PT12H
rc=$?
set -e
case "$rc" in
0) echo "Initial snapshot completed, starting the JDBC sink"
curl -fsS -X POST -H 'Content-Type: application/json' \
--data @bookshop-pg-mirror-sink.json "$CONNECT/connectors" ;;
3) echo "Snapshot skipped: the connector already had offsets. Check before continuing." >&2; exit 3 ;;
*) echo "Initial snapshot did not complete (exit code $rc). See the connector log." >&2; exit "$rc" ;;
esac
Reference: Apache Kafka — Kafka Connect REST API
The classpath assumes mvn package dependency:copy-dependencies, which writes the dependency JARs to
target/dependency.
Verifying signaling and notifications
Before the production run, check the whole loop once on the rehearsal environment:
-
Send a
logsignal through the signal table and look for its message in the connector log. This proves that the signal table name, supplemental logging, the channel list and the commit all work. -
Send the same
logsignal throughlegacy.signalswith the keylegacy. This proves the Kafka channel. -
Start an incremental snapshot of the smallest table (
AUTHOR) and read the notifications with the console consumer shown below. -
Check that
STARTED,TABLE_SCAN_COMPLETEDwithstatusSUCCEEDED, andCOMPLETEDarrive, and that the watermark rows appear in (or, withinsert_delete, disappear from)BOOKSHOP.DEBEZIUM_SIGNAL.
docker compose exec kafka /kafka/bin/kafka-console-consumer.sh --bootstrap-server kafka:9092 \
--topic legacy.notifications --from-beginning --formatter-property print.key=true
What goes wrong
| Symptom | Cause and fix |
|---|---|
A signal row is inserted but the connector does nothing. |
Not committed; |
A Kafka signal is ignored. |
Wrong message key (must be the |
A signal was processed twice after a restart. |
Kafka signals are read by an internal consumer; a crash between processing and committing can repeat a signal. Make signals idempotent in effect (an incremental snapshot repeated is harmless for upserting consumers) and check the notifications. |
|
The |
No notifications appear on |
|
The runbook waiter never finishes. |
It filters on |
The notification |
With several incremental snapshots in progress, all notifications carry the id of the last signal. Kafka signals have
a generated id. Match on |