Kafka Connect: moving data without writing producers
Kafka Connect runs connectors that copy data between Kafka and other systems, so that you configure a pipeline instead of writing producer and consumer code. This page explains how a worker runs connectors and tasks, then runs a real worker and broker inside each program to show offsets, converters, transforms, error handling and connector management.
Contents
How Kafka Connect works
Most data pipelines around Kafka do the same few things: read rows, files or events from a system, write them to a topic, and copy topics into a database, a search index or object storage. Kafka Connect, part of Apache Kafka since version 0.9, is a framework that runs this work for you. You pick a connector, give it a configuration, and Connect handles the producer and consumer, the offsets, retries, scaling and restarts.
A Connect deployment has a few moving parts:
- Worker: a JVM process that runs connectors and tasks. Several workers with the same
form a Connect cluster.group.id - Connector: a plugin that knows one external system. It reads its configuration and splits the work into task configurations, for example one task per database table.
- Task: the part that moves data. A source task polls the external system and returns
s; a sink task receivesSourceRecord s and writes them out. Each task runs on its own thread.SinkRecord - Converter: turns Connect's internal data (a schema and a value) into the bytes stored in Kafka, and back. JSON, Avro and Protobuf are the common formats.
- Transform: a single message transform (SMT) that changes each record on its way through, such as renaming a field or routing to another topic.
The data flows through the same stages every time. For a source connector: the task's poll()put()connect-<connector name>
| Mode | Offsets and configs stored in | Best for |
|---|---|---|
Standalone (connect-standalone.sh | A local file, configs passed at start-up | Development, a single machine, agents that read local files |
Distributed (connect-distributed.sh | Three compacted Kafka topics | Production: tasks move to other workers when one fails |
Each program on this page starts its own single-node KRaft broker inside the JVM with EmbeddedKafkaKraftBrokerspring-kafka-testconnect-runtimeconnect-standalone.shHerder
A source connector and its offsets
FileStreamSourceConnector
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorOffsets;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class FileSourceToTopic {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String bootstrap = broker.getBrokersAsString();
Path dir = Files.createTempDirectory("connect");
Path input = dir.resolve("orders.txt");
Files.writeString(input, "order-1,apple\norder-2,pear\n");
Map<String, String> connector = Map.of(
"name", "orders-file",
"connector.class", "FileStreamSource",
"file", input.toString(),
"topic", "orders",
"tasks.max", "1");
StandaloneHerder herder = startWorker(bootstrap, dir);
FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
herder.putConnectorConfig("orders-file", connector, false, created);
ConnectorInfo info = created.get().result();
System.out.println("created " + info.name() + ", type " + info.type()
+ ", tasks " + info.tasks());
try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
consumer.subscribe(List.of("orders"));
read(consumer, 2);
Files.writeString(input, "order-3,plum\n", StandardOpenOption.APPEND);
read(consumer, 1);
Thread.sleep(1500); // let the worker flush its source offsets
FutureCallback<ConnectorOffsets> offsets = new FutureCallback<>();
herder.connectorOffsets("orders-file", offsets);
offsets.get().offsets().forEach(o -> System.out.println(
"stored source offset: " + o.offset() + " for "
+ Path.of(o.partition().get("filename").toString()).getFileName()));
herder.stop();
System.out.println("worker stopped");
Files.writeString(input, "order-4,fig\n", StandardOpenOption.APPEND);
StandaloneHerder again = startWorker(bootstrap, dir);
FutureCallback<Herder.Created<ConnectorInfo>> recreated = new FutureCallback<>();
again.putConnectorConfig("orders-file", connector, false, recreated);
recreated.get();
System.out.println("worker restarted with the same offset file");
read(consumer, 1);
again.stop();
} finally {
broker.destroy();
}
}
static void read(KafkaConsumer<String, String> consumer, int count) {
int seen = 0;
while (seen < count) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
System.out.println(" " + r.topic() + "-" + r.partition() + " offset "
+ r.offset() + " key=" + r.key() + " value=" + r.value());
seen++;
}
}
}
static KafkaConsumer<String, String> consumer(String bootstrap) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
"group.id", "reader", "auto.offset.reset", "earliest"),
new StringDeserializer(), new StringDeserializer());
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
created orders-file, type source, tasks [orders-file-0]
orders-0 offset 0 key=null value={"schema":{"type":"string","optional":false},"payload":"order-1,apple"}
orders-0 offset 1 key=null value={"schema":{"type":"string","optional":false},"payload":"order-2,pear"}
orders-0 offset 2 key=null value={"schema":{"type":"string","optional":false},"payload":"order-3,plum"}
stored source offset: {position=40} for orders.txt
worker stopped
worker restarted with the same offset file
orders-0 offset 3 key=null value={"schema":{"type":"string","optional":false},"payload":"order-4,fig"}
- The connector got one task,
. A file connector cannot split one file, so it always creates a single task, whateverorders-file-0 says.tasks.max - Each line became a record with a
key, because the task sets no key. The value is a JSON envelope with anull and aschema , which is whatpayload writes by default. The next section looks at this.JsonConverter - The appended line arrived as offset 2 a moment later: the task keeps polling the file.
- The stored source offset is
, keyed by the file name. The three lines are 14, 13 and 13 bytes including the newline, so 40 is the byte where the next read starts.{position=40} - After the restart, only
arrived. The new worker read the offset file, and the task seeked to byte 40 instead of re-reading the file.order-4
The worker writes source offsets every offset.flush.interval.mslibs/connect-file-4.2.2.jarplugin.path
Converters decide the bytes on the topic
A converter sits between the connector and Kafka, and it is chosen by the worker (key.convertervalue.converter
import ch.qos.logback.classic.Level;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaAndValue;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.storage.Converter;
import org.apache.kafka.connect.storage.StringConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConverterBytes {
public static void main(String[] args) {
// each converter logs its configuration at INFO; Logback's Logger is named in
// full because org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.WARN);
Schema schema = SchemaBuilder.struct().name("shop.Order")
.field("id", Schema.INT64_SCHEMA)
.field("item", Schema.STRING_SCHEMA)
.field("qty", Schema.INT32_SCHEMA)
.build();
Struct order = new Struct(schema).put("id", 42L).put("item", "pear").put("qty", 3);
Converter withSchema = json(true);
Converter noSchema = json(false);
Converter string = new StringConverter();
string.configure(Map.of(), false);
show("JsonConverter, schemas.enable=true", withSchema.fromConnectData("t", schema, order));
show("JsonConverter, schemas.enable=false", noSchema.fromConnectData("t", schema, order));
show("StringConverter", string.fromConnectData("t", schema, order));
byte[] plain = "{\"id\":7,\"item\":\"fig\",\"qty\":1}".getBytes(StandardCharsets.UTF_8);
SchemaAndValue loose = noSchema.toConnectData("t", plain);
System.out.println("plain JSON read with schemas.enable=false:");
System.out.println(" schema " + loose.schema() + ", value " + loose.value()
+ " (" + loose.value().getClass().getSimpleName() + ")");
System.out.println(" qty is a " + ((Map<?, ?>) loose.value()).get("qty").getClass()
.getSimpleName());
try {
withSchema.toConnectData("t", plain);
} catch (DataException e) {
System.out.println("plain JSON read with schemas.enable=true:");
System.out.println(" " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
static Converter json(boolean schemas) {
JsonConverter converter = new JsonConverter();
converter.configure(Map.of("schemas.enable", String.valueOf(schemas)), false);
return converter;
}
static void show(String label, byte[] bytes) {
System.out.println(label + " (" + bytes.length + " bytes):");
System.out.println(" " + new String(bytes, StandardCharsets.UTF_8));
}
}
JsonConverter, schemas.enable=true (263 bytes):
{"schema":{"type":"struct","fields":[{"type":"int64","optional":false,"field":"id"},{"type":"string","optional":false,"field":"item"},{"type":"int32","optional":false,"field":"qty"}],"optional":false,"name":"shop.Order"},"payload":{"id":42,"item":"pear","qty":3}}
JsonConverter, schemas.enable=false (31 bytes):
{"id":42,"item":"pear","qty":3}
StringConverter (29 bytes):
Struct{id=42,item=pear,qty=3}
plain JSON read with schemas.enable=false:
schema null, value {item=fig, qty=1, id=7} (HashMap)
qty is a Long
plain JSON read with schemas.enable=true:
DataException: JsonConverter with schemas.enable requires "schema" and "payload" fields and may not contain additional fields. If you are trying to deserialize plain JSON data, set schemas.enable=false in your converter configuration.
- With
, the default,schemas.enable=true wrote 263 bytes: the schema with field names, types and the struct name, then the 31-byte payload. Every record repeats the whole schema.JsonConverter - With
it wrote only the 31 bytes of plain JSON. The types are lost, so a sink that needs them, such as a JDBC sink that creates tables, cannot work from this.schemas.enable=false calledStringConverter on thetoString() . The result is not JSON and cannot be read back.Struct- Plain JSON read with
became a schemalessschemas.enable=false , and the number became aHashMap , the widest integer type.Long - Plain JSON read with
failed with aschemas.enable=true . The message names the fix. A sink reading topics written by ordinary producers needsDataException .schemas.enable=false
The envelope format is fine for experiments, but it is wasteful. Production pipelines that need schemas usually use Avro, Protobuf or JSON Schema converters with a schema registry, which store the schema once and put a small schema id in each record; see value.converter
Single message transforms
An SMT changes one record at a time inside the worker, without a stream processor. Kafka ships 16 of them in connect-transformstransforms
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class TransformChain {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String bootstrap = broker.getBrokersAsString();
Path dir = Files.createTempDirectory("connect");
Path input = dir.resolve("orders.txt");
Files.writeString(input, "order-1,apple\norder-2,pear\n");
Map<String, String> connector = Map.ofEntries(
Map.entry("name", "orders-file"),
Map.entry("connector.class", "FileStreamSource"),
Map.entry("file", input.toString()),
Map.entry("topic", "orders"),
// converter settings can be overridden per connector
Map.entry("value.converter", "org.apache.kafka.connect.json.JsonConverter"),
Map.entry("value.converter.schemas.enable", "false"),
Map.entry("transforms", "wrap,tag,header,route"),
Map.entry("transforms.wrap.type",
"org.apache.kafka.connect.transforms.HoistField$Value"),
Map.entry("transforms.wrap.field", "line"),
Map.entry("transforms.tag.type",
"org.apache.kafka.connect.transforms.InsertField$Value"),
Map.entry("transforms.tag.static.field", "source"),
Map.entry("transforms.tag.static.value", "legacy-export"),
Map.entry("transforms.header.type",
"org.apache.kafka.connect.transforms.InsertHeader"),
Map.entry("transforms.header.header", "pipeline"),
Map.entry("transforms.header.value.literal", "connect-demo"),
Map.entry("transforms.route.type",
"org.apache.kafka.connect.transforms.RegexRouter"),
Map.entry("transforms.route.regex", "orders"),
Map.entry("transforms.route.replacement", "raw.$0"));
StandaloneHerder herder = startWorker(bootstrap, dir);
try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
herder.putConnectorConfig("orders-file", connector, false, created);
created.get();
consumer.subscribe(List.of("raw.orders"));
int seen = 0;
while (seen < 2) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
System.out.println("topic " + r.topic() + ", value " + r.value());
for (Header h : r.headers()) {
System.out.println(" header " + h.key() + " = "
+ new String(h.value(), StandardCharsets.UTF_8));
}
seen++;
}
}
try (Admin admin = Admin.create(Map.of("bootstrap.servers", bootstrap))) {
System.out.println("topics on the broker: "
+ new TreeSet<>(admin.listTopics().names().get()));
}
} finally {
herder.stop();
broker.destroy();
}
}
static KafkaConsumer<String, String> consumer(String bootstrap) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
"group.id", "reader", "auto.offset.reset", "earliest"),
new StringDeserializer(), new StringDeserializer());
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
topic raw.orders, value {"line":"order-1,apple","source":"legacy-export"}
header pipeline = connect-demo
topic raw.orders, value {"line":"order-2,pear","source":"legacy-export"}
header pipeline = connect-demo
topics on the broker: [raw.orders]
turned the string line into a struct with one field,HoistField$Value .line addedInsertField$Value with a fixed value. It can also add the topic, partition, offset or timestamp of the record.source added the headerInsertHeader .pipeline = connect-demo replaced the topicRegexRouter withorders , whereraw.orders is the whole match. The topic list shows that$0 was never created: routing happens before the producer sends anything.orders- The value is plain JSON without an envelope, because this connector overrides
.value.converter.schemas.enable
The worker created raw.orderstopic.creation.default.replication.factortopic.creation.default.partitionsTopicNameMatchesHasHeaderKeyRecordIsTombstone
The first attempt at this program failed with Missing required configuration "name"namePUT /connectors/{name}/config
Sink errors and the dead letter queue
A sink reads whatever producers wrote, and sooner or later a record does not match the converter. This topic gets three records, the middle one not JSON, and two file sinks read it: one with the default error handling, one with errors.tolerance=all
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorStateInfo;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class SinkDeadLetterQueue {
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String bootstrap = broker.getBrokersAsString();
Path dir = Files.createTempDirectory("connect");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(
Map.of("bootstrap.servers", bootstrap),
new StringSerializer(), new StringSerializer())) {
producer.send(new ProducerRecord<>("payments", "p1", "{\"id\":1,\"amount\":10}"));
producer.send(new ProducerRecord<>("payments", "p2", "amount=20"));
producer.send(new ProducerRecord<>("payments", "p3", "{\"id\":3,\"amount\":30}"));
}
StandaloneHerder herder = startWorker(bootstrap, dir);
try {
Path strictFile = dir.resolve("strict.txt");
create(herder, sink("strict", strictFile));
Path tolerantFile = dir.resolve("tolerant.txt");
Map<String, String> tolerant = new HashMap<>(sink("tolerant", tolerantFile));
tolerant.putAll(Map.of(
"errors.tolerance", "all",
"errors.deadletterqueue.topic.name", "payments.dlq",
"errors.deadletterqueue.topic.replication.factor", "1",
"errors.deadletterqueue.context.headers.enable", "true"));
create(herder, tolerant);
while (!herder.connectorStatus("strict").tasks().get(0).state().equals("FAILED")) {
Thread.sleep(200);
}
Thread.sleep(2000); // the tolerant sink flushes its file
for (String name : List.of("strict", "tolerant")) {
ConnectorStateInfo status = herder.connectorStatus(name);
ConnectorStateInfo.TaskState task = status.tasks().get(0);
System.out.println(name + ": task " + task.state());
if (task.trace() != null) {
System.out.println(" " + task.trace().lines().findFirst().orElseThrow());
}
}
System.out.println("strict.txt: " + Files.readAllLines(strictFile));
System.out.println("tolerant.txt: " + Files.readAllLines(tolerantFile));
try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
consumer.subscribe(List.of("payments.dlq"));
int seen = 0;
while (seen < 1) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
System.out.println("payments.dlq: key " + r.key() + ", value " + r.value());
for (Header h : r.headers()) {
String value = new String(h.value(), StandardCharsets.UTF_8);
System.out.println(" " + h.key() + " = "
+ value.lines().findFirst().orElse(""));
}
seen++;
}
}
}
} finally {
herder.stop();
broker.destroy();
}
}
static Map<String, String> sink(String name, Path file) {
return Map.of(
"name", name,
"connector.class", "FileStreamSink",
"topics", "payments",
"file", file.toString(),
"value.converter", "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable", "false");
}
static void create(StandaloneHerder herder, Map<String, String> config) throws Exception {
FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
herder.putConnectorConfig(config.get("name"), config, false, created);
created.get();
}
static KafkaConsumer<String, String> consumer(String bootstrap) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
"group.id", "reader", "auto.offset.reset", "earliest"),
new StringDeserializer(), new StringDeserializer());
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// the worker logs every failed record at ERROR; this program prints the task
// status instead, so logging is off. Logback's Logger is named in full:
// org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
strict: task FAILED
org.apache.kafka.connect.errors.ConnectException: Tolerance exceeded in error handler
tolerant: task RUNNING
strict.txt: []
tolerant.txt: [{amount=10, id=1}, {amount=30, id=3}]
payments.dlq: key p2, value amount=20
__connect.errors.topic = payments
__connect.errors.partition = 0
__connect.errors.offset = 1
__connect.errors.connector.name = tolerant
__connect.errors.task.id = 0
__connect.errors.stage = VALUE_CONVERTER
__connect.errors.class.name = org.apache.kafka.connect.json.JsonConverter
__connect.errors.exception.class.name = org.apache.kafka.connect.errors.DataException
__connect.errors.exception.message = Converting byte[] to Kafka Connect data failed due to serialization error:
__connect.errors.exception.stacktrace = org.apache.kafka.connect.errors.DataException: Converting byte[] to Kafka Connect data failed due to serialization error:
- The strict sink's task is
with "Tolerance exceeded in error handler". The default,FAILED , stops the task at the first bad record, and it stays failed until someone restarts it.errors.tolerance=none is empty, although the first record was valid. The worker converts the whole batch it fetched before callingstrict.txt , so the bad record stopped the good one too.put()- The tolerant sink skipped the bad record and wrote the other two.
wrote each value withFileStreamSink , which is why the lines look like Java maps.toString() - The bad record went to
with its original key and bytes. Thepayments.dlq headers say where it came from (topic, partition 0, offset 1), which stage failed (__connect.errors.* ) and why.VALUE_CONVERTER
Error tolerance covers conversion and transform failures, and it retries failed operations for errors.retry.timeoutput()ErrantRecordReportererrors.log.enable=true
Managing connectors and offsets
A worker exposes a REST API on port 8083 by default, and that API is the usual way to operate Connect: create, check, pause and restart connectors. This program runs the operations behind the main endpoints, including the offset management added in KIP-875, which lets you replay a source from the start:
import ch.qos.logback.classic.Level;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConfigInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConfigInfos;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo;
import org.apache.kafka.connect.runtime.rest.entities.Message;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ManageConnector {
static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String bootstrap = broker.getBrokersAsString();
Path dir = Files.createTempDirectory("connect");
Path input = dir.resolve("orders.txt");
Files.writeString(input, "order-1\norder-2\norder-3\n");
StandaloneHerder herder = startWorker(bootstrap, dir);
try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
// PUT /connector-plugins/FileStreamSource/config/validate
FutureCallback<ConfigInfos> validation = new FutureCallback<>();
herder.validateConnectorConfig(Map.of("connector.class", "FileStreamSource",
"name", "orders-file", "file", input.toString()), validation);
System.out.println("validate: " + validation.get().errorCount() + " error(s)");
for (ConfigInfo c : validation.get().configs()) {
c.configValue().errors().forEach(e ->
System.out.println(" " + c.configValue().name() + ": " + e));
}
// PUT /connectors/orders-file/config
Map<String, String> config = Map.of("name", "orders-file",
"connector.class", "FileStreamSource",
"file", input.toString(), "topic", "orders",
"value.converter", "org.apache.kafka.connect.storage.StringConverter");
FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
herder.putConnectorConfig("orders-file", config, false, created);
System.out.println("created: " + created.get().created());
consumer.subscribe(List.of("orders"));
read(consumer, 3);
status(herder);
// PUT /connectors/orders-file/pause
herder.pauseConnector("orders-file");
Thread.sleep(1000);
status(herder);
Files.writeString(input, "order-4\n", StandardOpenOption.APPEND);
System.out.println("records while paused: " + consumer.poll(Duration.ofSeconds(3))
.count());
// PUT /connectors/orders-file/resume
herder.resumeConnector("orders-file");
read(consumer, 1);
// PUT /connectors/orders-file/stop, then DELETE /connectors/orders-file/offsets
FutureCallback<Void> stopped = new FutureCallback<>();
herder.stopConnector("orders-file", stopped);
stopped.get();
while (!herder.connectorStatus("orders-file").connector().state().equals("STOPPED")) {
Thread.sleep(100);
}
status(herder);
FutureCallback<Message> reset = new FutureCallback<>();
herder.resetConnectorOffsets("orders-file", reset);
System.out.println("reset: " + reset.get().message());
herder.resumeConnector("orders-file");
System.out.println("after the reset and resume:");
read(consumer, 4);
} finally {
herder.stop();
broker.destroy();
}
}
// GET /connectors/orders-file/status returns this JSON
static void status(StandaloneHerder herder) throws Exception {
System.out.println("status: " + JSON.writeValueAsString(
herder.connectorStatus("orders-file")));
}
static void read(KafkaConsumer<String, String> consumer, int count) {
int seen = 0;
while (seen < count) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
System.out.println(" offset " + r.offset() + ": " + r.value());
seen++;
}
}
}
static KafkaConsumer<String, String> consumer(String bootstrap) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
"group.id", "reader", "auto.offset.reset", "earliest"),
new StringDeserializer(), new StringDeserializer());
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.ERROR);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
validate: 1 error(s)
topic: Missing required configuration "topic" which has no default value.
created: true
offset 0: order-1
offset 1: order-2
offset 2: order-3
status: {"name":"orders-file","connector":{"state":"RUNNING","worker_id":"worker-1","version":"4.2.2"},"tasks":[{"id":0,"state":"RUNNING","worker_id":"worker-1","version":"4.2.2"}],"type":"source"}
status: {"name":"orders-file","connector":{"state":"PAUSED","worker_id":"worker-1","version":"4.2.2"},"tasks":[{"id":0,"state":"PAUSED","worker_id":"worker-1","version":"4.2.2"}],"type":"source"}
records while paused: 0
offset 3: order-4
status: {"name":"orders-file","connector":{"state":"STOPPED","worker_id":"worker-1","version":"4.2.2"},"tasks":[],"type":"source"}
reset: The offsets for this connector have been reset successfully
after the reset and resume:
offset 4: order-1
offset 5: order-2
offset 6: order-3
offset 7: order-4
- Validation found one error:
is required.topic returns this list without creating anything, which makes it a cheap check in a deployment pipeline.PUT /connector-plugins/{type}/config/validate - The status JSON is the body of
: one state for the connector and one per task, each with the worker that runs it. In a distributed cluster theGET /connectors/orders-file/status values tell you which host to check.worker_id - While
, the task kept its resources but polled nothing, so the new line produced no records for 3 seconds. After resume it arrived as offset 3.PAUSED shut the tasks down completely: the status showsstop and an empty task list. Offsets can only be changed in this state.STOPPED- Resetting the offsets and resuming made the task read the file from byte 0 again, so all four lines were written a second time, as offsets 4 to 7. Downstream consumers must be able to handle such replays.
The main endpoints, from the Kafka 4.2 documentation, were not run here:
| Request | Does |
|---|---|
GET /connector-plugins | Lists installed connector plugins |
PUT /connectors/{name}/config | Creates or updates a connector; safe to repeat |
PATCH /connectors/{name}/config | Changes some keys; null |
GET /connectors/{name}/status | Connector and task states, with failure traces |
POST /connectors/{name}/restart?includeTasks=true&onlyFailed=true | Restarts the failed parts only |
PUT /connectors/{name}/pause/resume/stop | Changes the target state |
GETPATCHDELETE /connectors/{name}/offsets | Reads, alters or resets offsets; the last two need STOPPED |
PUT /admin/loggers/{name} | Changes a log level at runtime |
curl -s -X PUT -H "Content-Type: application/json" \
http://localhost:8083/connectors/orders-file/config \
-d '{"connector.class": "FileStreamSource", "file": "/data/orders.txt", "topic": "orders"}'
curl -s http://localhost:8083/connectors/orders-file/status
Prefer PUT .../configPOST /connectorsPOST
Distributed mode in production
In distributed mode every worker runs the same configuration, and the workers share all state through Kafka. The configuration below follows the Kafka 4.2 documentation; it was not run here, since it needs a cluster of workers:
# connect-distributed.properties, the same on every worker
bootstrap.servers=kafka-1:9092,kafka-2:9092,kafka-3:9092
group.id=connect-orders
config.storage.topic=connect-orders-configs
offset.storage.topic=connect-orders-offsets
status.storage.topic=connect-orders-status
config.storage.replication.factor=3
offset.storage.replication.factor=3
status.storage.replication.factor=3
key.converter=org.apache.kafka.connect.storage.StringConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
plugin.path=/opt/connect/plugins
listeners=http://0.0.0.0:8083
exactly.once.source.support=enabled
- The three topics: the config topic must have one partition, the offset topic should have many, and all three must be compacted and replicated. Create them yourself so their settings are not left to the broker's defaults.
: workers with the same id form one cluster. It must not clash with a consumer group id, and two Connect clusters must not share the three topics.group.id- Rebalancing: when a worker joins or leaves, the cluster reassigns connectors and tasks. Since Kafka 2.3, incremental cooperative rebalancing moves only the affected tasks, and waits
(5 minutes) for a lost worker to return before moving its tasks.scheduled.rebalance.max.delay.ms - Exactly-once sources:
makes source tasks write records and offsets in one Kafka transaction (KIP-618). It works only in distributed mode, and an existing cluster needs two rolling restarts, the first with the valueexactly.once.source.support=enabled .preparing : each connector goes in its own directory there, and Connect loads it with an isolated class loader, so two connectors can use different versions of the same library.plugin.path
Choosing how to use Connect
| Situation | Setup |
|---|---|
| Copy a database, a file system or a SaaS API into Kafka | An existing source connector, such as Debezium for change data capture |
| Copy topics into a database, a search index or object storage | A sink connector with a dead letter queue and errors.tolerance=all |
| Local experiments and agents on single machines | Standalone mode with an offset file |
| Production pipelines | Distributed mode, at least two workers, replicated internal topics |
| Topics written by ordinary producers in plain JSON | JsonConverterschemas.enable=false |
| Typed data shared between teams | Avro or Protobuf converters with a schema registry |
| Rename fields, mask values, route topics | Built-in SMTs |
| Joins, aggregation, enrichment | Kafka Streams between a source and a sink |
| No connector exists for your system | Write one: |
To copy topics between Kafka clusters, Connect runs MirrorMaker 2, covered on