Writing a custom Kafka Connect connector

When no existing connector fits your system, you can write one with the Connect API: a connector class that plans the work and task classes that move the data. This page builds a source connector with offsets and parallel tasks, a sink with a dead letter queue, config validation and a custom transform, and runs each on a real Connect worker.

Share

Contents

What a connector plugin is made of

Hundreds of connectors exist, but sometimes none fits: an internal API, an unusual file format, a system no vendor supports. The Connect API in the connect-api artifact lets you write your own and run it on any Connect worker, with the worker providing offsets, scaling, restarts, converters and error handling. Your code only talks to the external system.

A connector plugin has two halves that run in different places:

  • The connector class runs once per connector, on one worker. It reads and validates the configuration and decides how to split the work. Its taskConfigs(maxTasks) returns one configuration map per task, for example one list of tables per task. It does not move data.
  • The task class runs once per task configuration, each on its own thread, possibly on different workers. A source task returns records from poll(); a sink task receives records in put().

Tasks never talk to each other or to the connector directly. Everything they share goes through their configuration maps, which the worker stores and hands out, and through offsets. If the external system changes, for example a new table appears, the connector calls context.requestTaskReconfiguration(), and the worker asks it for new task configurations and restarts the tasks.

The plugin types of the Connect API
Interface or classYou implementBest for
SourceConnector + SourceTasktaskConfigs, pollReading an external system into Kafka
SinkConnector + SinkTasktaskConfigs, put, flushWriting topics to an external system
Transformation<R>applyChanging single records in any connector
Predicate<R>testDeciding when a transformation applies
Converter, HeaderConverterfromConnectData, toConnectDataA wire format Connect does not have
ConfigProvidergetReading secrets from a vault into configs

Declare org.apache.kafka:connect-api with the provided scope, because the worker supplies it at runtime. Each program on this page starts its own single-node KRaft broker in the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test; a real cluster has 3 or more brokers. It then starts a Kafka 4.2.2 standalone worker in the same JVM, without the REST server, and calls the Herder methods behind the REST endpoints. The plugin classes are public static nested classes, so that each program stays in one file; a real plugin uses top-level classes in its own jar.

A source connector with offsets and several tasks

The source below emits numbered events for a list of regions. Regions make a good example because each one is an independent stream with its own position, which is exactly what a source partition is. The program runs it with three regions and two tasks, then restarts the worker with a higher limit:

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.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.data.Schema;
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.TaskInfo;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.source.SourceConnector;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.source.SourceTask;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.ConnectorUtils;
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 RegionSource {

    // The connector: reads its config and splits the regions across tasks
    public static class RegionSourceConnector extends SourceConnector {
        static final ConfigDef CONFIG = new ConfigDef()
                .define("topic", Type.STRING, Importance.HIGH, "Topic to write to")
                .define("regions", Type.LIST, Importance.HIGH, "Regions to read")
                .define("events.per.region", Type.INT, 2, ConfigDef.Range.atLeast(1),
                        Importance.MEDIUM, "Stop after this sequence number");
        private Map<String, String> props;
        private List<String> regions;

        @Override
        public void start(Map<String, String> props) {
            this.props = props;
            regions = new AbstractConfig(CONFIG, props).getList("regions"); // validates too
        }

        @Override public Class<? extends Task> taskClass() { return RegionSourceTask.class; }
        @Override public ConfigDef config() { return CONFIG; }
        @Override public void stop() { }
        @Override public String version() { return "1.0"; }

        @Override
        public List<Map<String, String>> taskConfigs(int maxTasks) {
            List<Map<String, String>> configs = new ArrayList<>();
            for (List<String> group : ConnectorUtils.groupPartitions(regions,
                    Math.min(maxTasks, regions.size()))) {
                Map<String, String> task = new HashMap<>(props);
                task.put("regions", String.join(",", group));
                configs.add(task);
            }
            return configs;
        }
    }

    // The task: emits numbered events per region and resumes from stored offsets
    public static class RegionSourceTask extends SourceTask {
        private String topic;
        private int last;
        private final Map<String, Long> next = new TreeMap<>();

        @Override public String version() { return "1.0"; }

        @Override
        public void start(Map<String, String> props) {
            topic = props.get("topic");
            last = Integer.parseInt(props.getOrDefault("events.per.region", "2"));
            for (String region : props.get("regions").split(",")) {
                Map<String, Object> offset = context.offsetStorageReader()
                        .offset(Map.of("region", region));
                long seq = offset == null ? 1 : (Long) offset.get("seq") + 1;
                next.put(region, seq);
            }
        }

        @Override
        public List<SourceRecord> poll() throws InterruptedException {
            List<SourceRecord> batch = new ArrayList<>();
            for (Map.Entry<String, Long> e : next.entrySet()) {
                long seq = e.getValue();
                if (seq > last) {
                    continue;
                }
                batch.add(new SourceRecord(
                        Map.of("region", e.getKey()), Map.of("seq", seq), topic, null,
                        Schema.STRING_SCHEMA, e.getKey(),
                        Schema.STRING_SCHEMA, e.getKey() + " event " + seq));
                e.setValue(seq + 1);
            }
            if (batch.isEmpty()) {
                Thread.sleep(200); // nothing new: do not spin
                return null;
            }
            return batch;
        }

        @Override public void stop() { }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        Path dir = Files.createTempDirectory("connect");
        Map<String, String> config = new HashMap<>(Map.of(
                "name", "regions",
                "connector.class", RegionSourceConnector.class.getName(),
                "topic", "events", "regions", "eu,us,apac", "tasks.max", "2",
                "value.converter", "org.apache.kafka.connect.storage.StringConverter"));

        try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
            consumer.subscribe(List.of("events"));
            StandaloneHerder herder = startWorker(bootstrap, dir);
            create(herder, config);
            FutureCallback<List<TaskInfo>> tasks = new FutureCallback<>();
            herder.taskConfigs("regions", tasks);
            for (TaskInfo t : tasks.get()) {
                System.out.println("task " + t.id().task() + " got regions="
                        + t.config().get("regions"));
            }
            read(consumer, 6);
            Thread.sleep(1500); // let the worker flush source offsets
            herder.stop();

            System.out.println("restart with events.per.region=3");
            config.put("events.per.region", "3");
            StandaloneHerder again = startWorker(bootstrap, dir);
            create(again, config);
            read(consumer, 3);
            again.stop();
        } finally {
            broker.destroy();
        }
    }

    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();
    }

    // reads records and prints them sorted, since two tasks send at the same time
    static void read(KafkaConsumer<String, String> consumer, int count) {
        List<String> lines = new ArrayList<>();
        while (lines.size() < count) {
            for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
                lines.add("  key=" + r.key() + " value=" + r.value());
            }
        }
        lines.stream().sorted().forEach(System.out::println);
    }

    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() {
        // logging is off: the worker logs some normal events, such as creating the
        // dead letter topic, at ERROR. 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.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
task 0 got regions=eu,us
task 1 got regions=apac
  key=apac value=apac event 1
  key=apac value=apac event 2
  key=eu value=eu event 1
  key=eu value=eu event 2
  key=us value=us event 1
  key=us value=us event 2
restart with events.per.region=3
  key=apac value=apac event 3
  key=eu value=eu event 3
  key=us value=us event 3
  • ConnectorUtils.groupPartitions split three regions into two groups: task 0 got eu,us and task 1 got apac. The connector caps the task count at the number of regions, since an extra task would have nothing to do.
  • Each record carries a source partition, {region=eu}, and a source offset, {seq=2}. The worker stores the latest offset per partition, here in the standalone offset file.
  • After the restart, each region continued at event 3. In start(), the task asked context.offsetStorageReader() for its last offsets and began after them. Without that lookup, a restart would send events 1 and 2 again.
  • The two tasks sent at the same time, so the program sorts the records before printing. Within one region, the order is kept, because each region's records come from one task and go to one key.

A few rules apply to every source task. poll() runs on a dedicated thread and may block, but it should return null or wait briefly when there is no data, so that the worker can still stop the task. Partitions and offsets are stored as JSON, so use strings, numbers and booleans in them, and expect any whole number to come back as a Long. The worker writes offsets every offset.flush.interval.ms (60 seconds by default), only for records the producer has acknowledged; commitRecord() tells the task about each acknowledged record if it needs to confirm something in the source system.

A sink connector and the errant record reporter

A sink task gets records in batches, writes them, and lets the worker commit consumer offsets once the writes are safe. The example writes account balances into a table, held in memory here, where a key with a null value deletes the row. One record has a balance that is not a number:

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.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
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.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.config.ConfigDef;
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.Task;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.errors.DataException;
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.sink.ErrantRecordReporter;
import org.apache.kafka.connect.sink.SinkConnector;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
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 BalanceSink {

    // stands in for a database table: account to balance
    static final Map<String, Long> TABLE = new ConcurrentSkipListMap<>();

    public static class BalanceSinkConnector extends SinkConnector {
        private Map<String, String> props;

        @Override public void start(Map<String, String> props) { this.props = props; }
        @Override public Class<? extends Task> taskClass() { return BalanceSinkTask.class; }
        @Override public ConfigDef config() { return new ConfigDef(); }
        @Override public void stop() { }
        @Override public String version() { return "1.0"; }

        @Override
        public List<Map<String, String>> taskConfigs(int maxTasks) {
            return Collections.nCopies(maxTasks, props);
        }
    }

    public static class BalanceSinkTask extends SinkTask {
        private ErrantRecordReporter reporter;

        @Override public String version() { return "1.0"; }

        @Override
        public void start(Map<String, String> props) {
            reporter = context.errantRecordReporter(); // can be null: check before use
        }

        @Override
        public void put(Collection<SinkRecord> records) {
            for (SinkRecord r : records) {
                String account = (String) r.key();
                if (r.value() == null) {
                    TABLE.remove(account);
                    System.out.println("  offset " + r.kafkaOffset() + ": delete " + account);
                    continue;
                }
                try {
                    long balance = Long.parseLong((String) r.value());
                    TABLE.put(account, balance);
                    System.out.println("  offset " + r.kafkaOffset() + ": upsert " + account
                            + " = " + balance);
                } catch (NumberFormatException e) {
                    if (reporter == null) {
                        throw new DataException("bad balance at offset " + r.kafkaOffset(), e);
                    }
                    System.out.println("  offset " + r.kafkaOffset() + ": reported " + e);
                    reporter.report(r, e);
                }
            }
        }

        @Override
        public void flush(Map<TopicPartition, OffsetAndMetadata> offsets) {
            // a real sink makes its writes durable here, before Connect commits offsets
        }

        @Override public void stop() { }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String bootstrap = broker.getBrokersAsString();
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", bootstrap),
                new StringSerializer(), new StringSerializer())) {
            String[][] data = {{"alice", "10"}, {"bob", "20"}, {"alice", "15"},
                {"carol", "ten"}, {"bob", null}};
            for (String[] d : data) {
                producer.send(new ProducerRecord<>("balances", d[0], d[1]));
            }
        }

        StandaloneHerder herder = startWorker(bootstrap, Files.createTempDirectory("connect"));
        try {
            Map<String, String> config = Map.of(
                    "name", "balances-sink",
                    "connector.class", BalanceSinkConnector.class.getName(),
                    "topics", "balances",
                    "value.converter", "org.apache.kafka.connect.storage.StringConverter",
                    "errors.tolerance", "all",
                    "errors.deadletterqueue.topic.name", "balances.dlq",
                    "errors.deadletterqueue.topic.replication.factor", "1",
                    "errors.deadletterqueue.context.headers.enable", "true");
            System.out.println("put() calls on the task thread:");
            FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
            herder.putConnectorConfig("balances-sink", config, false, created);
            created.get();

            try (KafkaConsumer<String, String> dlq = consumer(bootstrap)) {
                dlq.subscribe(List.of("balances.dlq"));
                ConsumerRecord<String, String> bad = null;
                while (bad == null) {
                    for (ConsumerRecord<String, String> r : dlq.poll(Duration.ofMillis(500))) {
                        bad = r;
                    }
                }
                String stage = new String(bad.headers().lastHeader("__connect.errors.stage")
                        .value(), StandardCharsets.UTF_8);
                System.out.println("balances.dlq: key " + bad.key() + ", value " + bad.value()
                        + ", stage " + stage);
            }
            Thread.sleep(1500); // the worker commits offsets every offset.flush.interval.ms
            System.out.println("table: " + TABLE);
            try (Admin admin = Admin.create(Map.of("bootstrap.servers", bootstrap))) {
                System.out.println("committed offsets of group connect-balances-sink: "
                        + admin.listConsumerGroupOffsets("connect-balances-sink")
                                .partitionsToOffsetAndMetadata().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() {
        // logging is off: the worker logs some normal events, such as creating the
        // dead letter topic, at ERROR. 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.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
put() calls on the task thread:
  offset 0: upsert alice = 10
  offset 1: upsert bob = 20
  offset 2: upsert alice = 15
  offset 3: reported java.lang.NumberFormatException: For input string: "ten"
  offset 4: delete bob
balances.dlq: key carol, value ten, stage TASK_PUT
table: {alice=15}
committed offsets of group connect-balances-sink: {balances-0=OffsetAndMetadata{offset=5, leaderEpoch=null, metadata=''}}
  • The task handled the five records in order on its own thread: two upserts for alice, one for bob, then a delete for bob when the tombstone at offset 4 arrived. The table ends with only alice=15.
  • The record at offset 3 converted fine, because StringConverter accepts any text, but the task could not parse "ten". A converter-level dead letter queue cannot catch this; the task reported the record itself with ErrantRecordReporter.report.
  • The reported record landed in balances.dlq with stage TASK_PUT, unlike the VALUE_CONVERTER stage on the Kafka Connect page, so whoever reads the dead letter queue can tell the two kinds of failure apart.
  • The worker committed offset 5 for the group connect-balances-sink, the next record to read. The committed offset is the only progress a sink keeps: after a restart, the task starts there.

errantRecordReporter() was added in Kafka 2.6 (KIP-610), and the documentation warns that it can return null, so the task checks it and otherwise fails with a DataException. Throwing an exception from put() stops the task. To ask for a short pause instead, throw RetriableException, and the worker calls put() again with the same records after context.timeout(ms).

The worker calls flush(), through preCommit(), before it commits offsets. A sink that buffers writes must make them durable there, or records can be lost: the offset would be committed while the data is still in memory. A sink that writes idempotently, for example an upsert keyed by the record key as above, can be replayed safely after a crash. When partitions move between tasks during a rebalance, the worker calls close() and open() with the partitions involved.

Validating the configuration

A connector declares its settings in a ConfigDef, with a type, a default, a validator and documentation. The worker uses this to reject bad configurations before starting anything, and the REST API serves it to tools that build forms. This connector has four common kinds of setting and one rule that spans two keys:

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.util.List;
import java.util.Map;
import org.apache.kafka.common.config.Config;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.config.ConfigValue;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.json.JsonConverter;
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.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.source.SourceConnector;
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 ValidateConnector {

    public static class TablePollConnector extends SourceConnector {
        static final ConfigDef CONFIG = new ConfigDef()
                .define("url", Type.STRING, ConfigDef.NO_DEFAULT_VALUE,
                        new ConfigDef.NonEmptyString(), Importance.HIGH, "JDBC URL")
                .define("mode", Type.STRING, "bulk",
                        ConfigDef.ValidString.in("bulk", "incrementing", "timestamp"),
                        Importance.HIGH, "How new rows are found")
                .define("incrementing.column", Type.STRING, "", Importance.MEDIUM,
                        "Column for mode=incrementing")
                .define("poll.interval.ms", Type.INT, 5000, ConfigDef.Range.atLeast(100),
                        Importance.LOW, "Time between polls")
                .define("password", Type.PASSWORD, "", Importance.HIGH, "Database password");

        // checks that involve more than one key
        @Override
        public Config validate(Map<String, String> props) {
            Config config = super.validate(props);
            if ("incrementing".equals(props.get("mode"))
                    && props.getOrDefault("incrementing.column", "").isBlank()) {
                for (ConfigValue v : config.configValues()) {
                    if (v.name().equals("incrementing.column")) {
                        v.addErrorMessage("required when mode=incrementing");
                    }
                }
            }
            return config;
        }

        @Override public void start(Map<String, String> props) { }
        @Override public Class<? extends Task> taskClass() { return null; }
        @Override public List<Map<String, String>> taskConfigs(int maxTasks) { return List.of(); }
        @Override public void stop() { }
        @Override public ConfigDef config() { return CONFIG; }
        @Override public String version() { return "1.0"; }
    }

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        StandaloneHerder herder = startWorker(broker.getBrokersAsString(),
                Files.createTempDirectory("connect"));
        try {
            String type = TablePollConnector.class.getName();
            validate(herder, "valid", Map.of("name", "a", "connector.class", type,
                    "url", "jdbc:h2:mem:shop", "mode", "incrementing",
                    "incrementing.column", "id", "password", "s3cret"));
            validate(herder, "invalid", Map.of("name", "b", "connector.class", type,
                    "url", "", "mode", "incrementing", "poll.interval.ms", "10",
                    "tasks.max", "0", "transforms", "mask"));
        } finally {
            herder.stop();
            broker.destroy();
        }
    }

    // PUT /connector-plugins/{type}/config/validate runs the same check
    static void validate(StandaloneHerder herder, String label, Map<String, String> props)
            throws Exception {
        FutureCallback<ConfigInfos> result = new FutureCallback<>();
        herder.validateConnectorConfig(props, result);
        ConfigInfos infos = result.get();
        System.out.println(label + ": " + infos.errorCount() + " error(s), groups "
                + infos.groups());
        for (ConfigInfo info : infos.configs()) {
            var value = info.configValue();
            if (!value.errors().isEmpty()) {
                System.out.println("  " + value.name() + " = " + value.value() + ": "
                        + String.join("; ", value.errors()));
            } else if (value.name().equals("password")) {
                System.out.println("  password = " + value.value() + " (type "
                        + info.configKey().type() + ")");
            }
        }
    }

    // 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() {
        // logging is off: the worker logs some normal events, such as creating the
        // dead letter topic, at ERROR. 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.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
valid: 0 error(s), groups [Common, Transforms, Predicates, Error Handling, Topic Creation, Exactly Once Support, offsets.topic]
  password = [hidden] (type PASSWORD)
invalid: 5 error(s), groups [Common, Transforms, Predicates, Error Handling, Topic Creation, Exactly Once Support, offsets.topic, Transforms: mask]
  tasks.max = 0: Invalid value 0 for configuration tasks.max: Value must be at least 1
  transforms.mask.type = null: Missing required configuration "transforms.mask.type" which has no default value.
  url = : Invalid value  for configuration url: String must be non-empty
  incrementing.column = : required when mode=incrementing
  poll.interval.ms = 10: Invalid value 10 for configuration poll.interval.ms: Value must be at least 100
  password = [hidden] (type PASSWORD)
  • The valid configuration had 0 errors. The groups list shows that the worker also checked its own settings: transforms, predicates, error handling, topic creation, exactly-once support and the offsets topic.
  • The invalid one had 5 errors, two from the worker and three from the connector. tasks.max=0 broke the framework's minimum of 1, and the transform alias mask had no transforms.mask.type.
  • url failed NonEmptyString, and poll.interval.ms=10 failed the Range validator with its minimum of 100. These came from the ConfigDef without any code.
  • incrementing.column failed the rule in the overridden validate(). A ConfigDef validator sees one value at a time, so cross-field checks belong there.
  • The PASSWORD type made the value appear as [hidden], in the validation result as in the worker's logs. Use it for every secret.

Validation runs again when a connector is created or updated, and a failure there returns HTTP 400 with the same messages. Better still, keep secrets out of the configuration altogether: with a ConfigProvider such as the built-in FileConfigProvider, enabled on the worker with config.providers=file, a value like ${file:/etc/secrets/db.properties:password} is resolved on the worker when the connector starts.

A custom single message transform

A transform is the smallest plugin: one class with configure, apply, config and close. This one masks e-mail addresses in chosen value fields. It is generic in R extends ConnectRecord<R>, so the same class works for source and sink records. The program tests it directly, as a unit test would, without a worker:

Java
import ch.qos.logback.classic.Level;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.connect.connector.ConnectRecord;
import org.apache.kafka.connect.data.Schema;
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.source.SourceRecord;
import org.apache.kafka.connect.transforms.Transformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EmailMaskTransform {

    // Masks the local part of e-mail addresses in the configured value fields
    public static class EmailMask<R extends ConnectRecord<R>> implements Transformation<R> {
        static final ConfigDef CONFIG = new ConfigDef().define("fields", Type.LIST,
                ConfigDef.NO_DEFAULT_VALUE, ConfigDef.ValidList.anyNonDuplicateValues(false, false),
                Importance.HIGH, "Value fields that hold e-mail addresses");
        private List<String> fields;

        @Override
        public void configure(Map<String, ?> props) {
            fields = new AbstractConfig(CONFIG, props).getList("fields");
        }

        @Override
        public R apply(R record) {
            Object value = record.value();
            if (value == null) {
                return record; // tombstones pass through unchanged
            }
            Object masked;
            if (value instanceof Struct struct) {
                Struct copy = new Struct(struct.schema());
                for (var field : struct.schema().fields()) {
                    Object v = struct.get(field);
                    copy.put(field, fields.contains(field.name()) ? mask(v) : v);
                }
                masked = copy;
            } else if (value instanceof Map<?, ?> map) {
                Map<Object, Object> copy = new HashMap<>(map);
                fields.forEach(f -> copy.computeIfPresent(f, (k, v) -> mask(v)));
                masked = copy;
            } else {
                throw new DataException("EmailMask needs a Struct or Map value, got "
                        + value.getClass().getSimpleName());
            }
            return record.newRecord(record.topic(), record.kafkaPartition(),
                    record.keySchema(), record.key(), record.valueSchema(), masked,
                    record.timestamp());
        }

        static Object mask(Object v) {
            if (!(v instanceof String s) || s.indexOf('@') < 1) {
                return v;
            }
            return s.charAt(0) + "***" + s.substring(s.indexOf('@'));
        }

        @Override public ConfigDef config() { return CONFIG; }
        @Override public void close() { }
    }

    public static void main(String[] args) {
        // AbstractConfig logs every parsed config 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);
        EmailMask<SourceRecord> smt = new EmailMask<>();
        smt.configure(Map.of("fields", "email,backup"));

        Schema schema = SchemaBuilder.struct().name("Customer")
                .field("id", Schema.INT32_SCHEMA)
                .field("email", Schema.STRING_SCHEMA)
                .field("backup", Schema.OPTIONAL_STRING_SCHEMA)
                .build();
        Struct struct = new Struct(schema).put("id", 7).put("email", "alice@example.com");
        System.out.println("struct:     " + smt.apply(record(schema, struct)).value());
        System.out.println("original:   " + struct);

        Map<String, Object> map = Map.of("id", 8, "email", "bob@example.org", "note", "x@y");
        System.out.println("map:        " + new TreeMap<>(
                (Map<?, ?>) smt.apply(record(null, map)).value()));
        System.out.println("tombstone:  " + smt.apply(record(null, null)).value());

        try {
            smt.apply(record(Schema.STRING_SCHEMA, "carol@example.com"));
        } catch (DataException e) {
            System.out.println("string:     " + e.getMessage());
        }
        try {
            new EmailMask<SourceRecord>().configure(Map.of("fields", ""));
        } catch (ConfigException e) {
            System.out.println("bad config: " + e.getMessage());
        }
    }

    static SourceRecord record(Schema schema, Object value) {
        return new SourceRecord(Map.of(), Map.of(), "customers", 0, null, null, schema, value);
    }
}
Output
struct:     Struct{id=7,email=a***@example.com}
original:   Struct{id=7,email=alice@example.com}
map:        {email=b***@example.org, id=8, note=x@y}
tombstone:  null
string:     EmailMask needs a Struct or Map value, got String
bad config: Configuration 'fields' must not be empty. Valid values include: any non-empty value
  • For a Struct value, the transform built a new struct with the same schema and masked email. The optional backup field was null and stayed so.
  • The original struct still holds alice@example.com. Records may be shared, so a transform must return a new record through newRecord instead of changing the old one.
  • For a schemaless Map, it masked email and left note alone, because note was not configured. Values without a schema come from JsonConverter with schemas.enable=false, so a transform should handle both shapes.
  • A tombstone passed through untouched. Dropping or changing tombstones would break compacted topics and deletes in sinks.
  • A plain string value was rejected with a DataException, which the worker treats like a conversion error, so errors.tolerance applies to it.
  • An empty fields list failed in configure, through the ValidList validator, before any record was seen.

To use it, put the class in a plugin jar and add transforms=mask, transforms.mask.type=com.example.EmailMask and transforms.mask.fields=email to a connector. Keep apply fast and free of I/O: it runs for every record on the task thread.

Packaging and installing a plugin

Workers load plugins from the directories in plugin.path. Each plugin goes in its own subdirectory, either as one jar with its dependencies or as a directory of jars, and gets its own class loader, so that two plugins can depend on different versions of one library. The layout below follows the Kafka documentation; it was not run here:

Text
/opt/connect/plugins/
  balance-sink/
    balance-sink-1.0.jar
    postgresql-42.7.4.jar
  email-mask/
    email-mask-1.0.jar

Do not put the Kafka jars, such as connect-api or kafka-clients, in a plugin directory: the worker provides them, and a second copy causes class loading errors. Since Kafka 3.6 (KIP-898), a worker can find plugins through Java's ServiceLoader instead of scanning every class. Each jar then lists its plugin classes in files named after the interface:

Text
META-INF/services/org.apache.kafka.connect.sink.SinkConnector
    com.example.BalanceSinkConnector
META-INF/services/org.apache.kafka.connect.transforms.Transformation
    com.example.EmailMask

The worker setting plugin.discovery decides how plugins are found. Its default, read from the 4.2.2 worker configuration, is hybrid_warn: scan, and log a warning for every plugin without a manifest. service_load uses only the manifests and starts much faster with many plugins. The connect-plugin-path.sh tool has a list command that shows which plugins have manifests, and a sync-manifests command that writes the missing ones.

Two more methods matter for source connectors in distributed clusters. The first is exactlyOnceSupport(). Return SUPPORTED only if the task's offsets fully describe its position, so that the worker can commit records and offsets in one transaction. The second is alterOffsets(), which the worker calls when a user changes offsets through PATCH /connectors/{name}/offsets. Override it to reject offsets your task cannot use, as KIP-875 describes.

Choosing what to build

Needs and the plugin that fits
NeedBuild
Read a system that has positions you can store, such as ids, timestamps or file offsetsSourceConnector and SourceTask, with offsets in each record
Read a system with independent streams in parallelOne source partition per stream, split across tasks in taskConfigs
Write topics to a systemSinkConnector and SinkTask, with idempotent writes and a real flush
Bad records the task itself detectsErrantRecordReporter with a dead letter queue
Cross-field configuration rulesOverride Connector.validate
Change single records in existing connectorsA Transformation, tested without a worker
Joins, aggregations or calls to other services per recordNo plugin: a Kafka Streams application or a consumer
Something an existing connector already doesUse the existing connector and configure it

The worker settings, converters and REST operations that every plugin depends on are on Kafka Connect. The serializers a converter is often built on are covered in Kafka serialization, and the producer settings that a source task's records go through in the Kafka producer.