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.

Share

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 group.id form a Connect cluster.
  • 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 SourceRecords; a sink task receives SinkRecords and writes them out. Each task runs on its own thread.
  • 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() returns records, the transforms run, the converter serializes them, and the worker's producer sends them. For a sink connector the order is reversed: the worker's consumer fetches, the converter deserializes, the transforms run, and the task's put() writes the batch. A source record carries a source partition and a source offset, such as a file name and a byte position. The worker stores these offsets, so that a restarted task continues where it stopped. Sink connectors use ordinary consumer group offsets, with the group connect-<connector name>.

Standalone and distributed workers
ModeOffsets and configs stored inBest for
Standalone (connect-standalone.sh)A local file, configs passed at start-upDevelopment, a single machine, agents that read local files
Distributed (connect-distributed.sh)Three compacted Kafka topicsProduction: tasks move to other workers when one fails

Each program on this page starts its own single-node KRaft broker inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test; a real cluster has 3 or more brokers. It then starts a standalone worker in the same JVM with Kafka 4.2.2's connect-runtime, built the way connect-standalone.sh builds it. One difference: the worker's REST server (Jetty) is not started, because the Jetty version available here does not match the one Connect 4.2 needs. The programs call the same Herder methods that the REST endpoints call, and the comments show the matching HTTP request. The REST calls themselves were not run.

A source connector and its offsets

FileStreamSourceConnector ships with Kafka as an example: it reads lines from a file and writes one record per line. A file is the simplest source whose offset you can check by hand, since it is a byte position. The program creates the connector, appends a line, then stops the worker and starts a new one with the same offset file:

Java
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);
        }
    }
}
Output
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, orders-file-0. A file connector cannot split one file, so it always creates a single task, whatever tasks.max says.
  • Each line became a record with a null key, because the task sets no key. The value is a JSON envelope with a schema and a payload, which is what JsonConverter writes by default. The next section looks at this.
  • The appended line arrived as offset 2 a moment later: the task keeps polling the file.
  • The stored source offset is {position=40}, 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.
  • After the restart, only order-4 arrived. The new worker read the offset file, and the task seeked to byte 40 instead of re-reading the file.

The worker writes source offsets every offset.flush.interval.ms, which defaults to 60 seconds; the program lowers it to 500 ms. Records sent after the last flush are sent again after a crash, so a source connector gives at-least-once delivery unless exactly-once support is turned on, which the distributed section covers. Since Kafka 3.2 the file connectors are no longer on the worker's classpath by default: add libs/connect-file-4.2.2.jar to plugin.path to use them with the scripts.

Converters decide the bytes on the topic

A converter sits between the connector and Kafka, and it is chosen by the worker (key.converter, value.converter), not by the connector. A wrong converter setting is a frequent reason for failing connectors. This program, which needs no broker, converts the same structured record three ways and then reads plain JSON back:

Java
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));
    }
}
Output
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 schemas.enable=true, the default, JsonConverter wrote 263 bytes: the schema with field names, types and the struct name, then the 31-byte payload. Every record repeats the whole schema.
  • With schemas.enable=false 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.
  • StringConverter called toString() on the Struct. The result is not JSON and cannot be read back.
  • Plain JSON read with schemas.enable=false became a schemaless HashMap, and the number became a Long, the widest integer type.
  • Plain JSON read with schemas.enable=true failed with a DataException. The message names the fix. A sink reading topics written by ordinary producers needs 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 Kafka Schema Registry. Both converter settings can be overridden per connector, as the next program does with 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-transforms. The program chains four, in the order listed in transforms, on the same file source: wrap each line in a struct, add a static field, add a header, and rename the topic:

Java
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);
        }
    }
}
Output
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]
  • HoistField$Value turned the string line into a struct with one field, line.
  • InsertField$Value added source with a fixed value. It can also add the topic, partition, offset or timestamp of the record.
  • InsertHeader added the header pipeline = connect-demo.
  • RegexRouter replaced the topic orders with raw.orders, where $0 is the whole match. The topic list shows that orders was never created: routing happens before the producer sends anything.
  • The value is plain JSON without an envelope, because this connector overrides value.converter.schemas.enable.

The worker created raw.orders through the broker's automatic topic creation, which most production clusters turn off. Connect can create topics itself with topic.creation.default.replication.factor and topic.creation.default.partitions in the connector configuration. A transform can also run only for some records, with a predicate such as TopicNameMatches, HasHeaderKey or RecordIsTombstone. Keep SMTs to small, stateless changes; joins, aggregations and lookups belong in Kafka Streams.

The first attempt at this program failed with Missing required configuration "name". A configuration created through the Java herder must contain name. With PUT /connectors/{name}/config, the REST layer adds it from the URL.

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 and a dead letter queue:

Java
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);
        }
    }
}
Output
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 FAILED with "Tolerance exceeded in error handler". The default, errors.tolerance=none, stops the task at the first bad record, and it stays failed until someone restarts it.
  • strict.txt is empty, although the first record was valid. The worker converts the whole batch it fetched before calling put(), so the bad record stopped the good one too.
  • The tolerant sink skipped the bad record and wrote the other two. FileStreamSink wrote each value with toString(), which is why the lines look like Java maps.
  • The bad record went to payments.dlq with its original key and bytes. The __connect.errors.* headers say where it came from (topic, partition 0, offset 1), which stage failed (VALUE_CONVERTER) and why.

Error tolerance covers conversion and transform failures, and it retries failed operations for errors.retry.timeout, which defaults to 0. It does not cover exceptions thrown by the sink task's own put(): those still fail the task, unless the connector reports them to the ErrantRecordReporter, as the custom connector page shows. Dead letter queues only work for sink connectors. The program turns logging off; with logging on, the worker logs the failure at ERROR, and errors.log.enable=true also logs every tolerated record.

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:

Java
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);
        }
    }
}
Output
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: topic is required. PUT /connector-plugins/{type}/config/validate returns this list without creating anything, which makes it a cheap check in a deployment pipeline.
  • The status JSON is the body of GET /connectors/orders-file/status: one state for the connector and one per task, each with the worker that runs it. In a distributed cluster the worker_id values tell you which host to check.
  • While PAUSED, 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.
  • stop shut the tasks down completely: the status shows STOPPED and an empty task list. Offsets can only be changed in this state.
  • 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:

Kafka Connect REST API
RequestDoes
GET /connector-pluginsLists installed connector plugins
PUT /connectors/{name}/configCreates or updates a connector; safe to repeat
PATCH /connectors/{name}/configChanges some keys; null removes a key
GET /connectors/{name}/statusConnector and task states, with failure traces
POST /connectors/{name}/restart?includeTasks=true&onlyFailed=trueRestarts the failed parts only
PUT /connectors/{name}/pause, /resume, /stopChanges the target state
GET, PATCH, DELETE /connectors/{name}/offsetsReads, alters or resets offsets; the last two need STOPPED
PUT /admin/loggers/{name}Changes a log level at runtime
Shell
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 .../config over POST /connectors in scripts: it creates the connector if it is missing and updates it otherwise, while POST fails with 409 when the connector exists.

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:

Properties
# 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.
  • group.id: 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.
  • 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 scheduled.rebalance.max.delay.ms (5 minutes) for a lost worker to return before moving its tasks.
  • Exactly-once sources: exactly.once.source.support=enabled 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 value preparing.
  • plugin.path: 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.

Choosing how to use Connect

Situations and the setup that fits
SituationSetup
Copy a database, a file system or a SaaS API into KafkaAn existing source connector, such as Debezium for change data capture
Copy topics into a database, a search index or object storageA sink connector with a dead letter queue and errors.tolerance=all
Local experiments and agents on single machinesStandalone mode with an offset file
Production pipelinesDistributed mode, at least two workers, replicated internal topics
Topics written by ordinary producers in plain JSONJsonConverter with schemas.enable=false
Typed data shared between teamsAvro or Protobuf converters with a schema registry
Rename fields, mask values, route topicsBuilt-in SMTs
Joins, aggregation, enrichmentKafka Streams between a source and a sink
No connector exists for your systemWrite one: building a custom connector

To copy topics between Kafka clusters, Connect runs MirrorMaker 2, covered on MirrorMaker 2 replication. The producer and consumer that a worker uses internally behave as described on the Kafka producer and the Kafka consumer pages, and sink lag is tracked like any consumer group, see consumer lag monitoring.