Kafka Connect: Integrating with External Systems
7 min read
Hello, data engineer. 🎧
Welcome to the Plumbing Department of the Apache Kafka ecosystem.
By now, you understand how to write producers and consumers in code (Java, Python, Node.js). But imagine this scenario: You work for a company that uses PostgreSQL for transactions, Elasticsearch for search, and Amazon S3 for long-term archiving.
Your manager asks you to sync data between all of them.
- Every time a user signs up (Postgres), send it to Kafka.
- From Kafka, send it to Elasticsearch so we can search for them.
- From Kafka, send it to S3 so we have a backup.
The "Old School" Nightmare:
You would have to write:
- A Python script polling Postgres every 5 seconds (inefficient).
- A Java app reading Kafka and pushing to Elasticsearch (complex error handling).
- A Node.js script reading Kafka and uploading files to S3 (batching issues).
That is three separate codebases to maintain. Now multiply that by 50 microservices. You would spend your entire life writing "glue code."
Kafka Connect solves this. It is a tool to stream data between Kafka and other systems without writing a single line of code.
1. Kafka Connect Overview: Data Integration Without Code
Definition
Kafka Connect is a framework included with Apache Kafka that standardizes moving data into and out of Kafka. It is not a separate software you download; it comes with the Kafka binary.
How It Works (The Universal Adapter)
Think of Kafka Connect like a universal power adapter.
- Source Connectors: Plugs that fit into external systems (Databases, Message Queues) and push data into Kafka.
- Sink Connectors: Plugs that take data from Kafka and push it into external systems (S3, HDFS, Elasticsearch).
Core Concepts (The Alphabet)
Before we build sentences, let's learn the letters:
- Connectors: The high-level logic. It defines where data comes from or goes to (e.g., "AWS S3 Connector").
- Tasks: The actual workers. The connector splits the work into "Tasks" to copy data in parallel.
- Workers: The running process (JVM) that executes the connectors and tasks.
- Converters: The code that translates data formats. For example, turning a Postgres row into a JSON payload or Avro message.
Interesting Fact: Before Kafka Connect (released in 0.9.0, Nov 2015), companies like LinkedIn used a tool called "Camus" to load Kafka data into Hadoop. It was difficult to configure and crash-prone. Kafka Connect replaced the "wild west" of custom ingestion scripts.
2. Source Connectors: Pulling Data In (Postgres CDC)
A Source Connector imports data from an external system into a Kafka topic.
The Problem with Polling
The naive way to get data from a database is to run a query like SELECT * FROM users WHERE created_at > last_check.
- Cons: You miss records if they are deleted. You burden the database with constant queries. You waste resources if nothing changed.
The Solution: CDC (Change Data Capture)
CDC is a method of tracking row-level changes in database tables. Instead of querying the table, we read the database's transaction log.
Real-World Example: Debezium with Postgres
Debezium is the industry-standard open-source platform for CDC on Kafka Connect.
How Debezium Postgres works:
- PostgreSQL writes every change (INSERT, UPDATE, DELETE) to a Write-Ahead Log (WAL).
- Debezium connects to Postgres as a "replication node."
- It reads the WAL and converts every change into a Kafka message.
Configuration (JSON)
In a production Distributed Mode (more on this later), you configure connectors via a REST API. You do not write Java code; you write JSON.
Here is a standard configuration to capture changes from a Postgres database:
{
"name": "inventory-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"tasks.max": "1",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "postgres",
"database.password": "postgres",
"database.dbname": "inventory",
"topic.prefix": "dbserver1",
"plugin.name": "pgoutput",
"slot.name": "debezium_slot"
}
}topic.prefix: If you have a table namedcustomers, the Kafka topic will bedbserver1.public.customers.plugin.name: Usespgoutput, the standard logical decoding plugin in Postgres 10+.
Outcome:
When you insert a user into Postgres, a message immediately appears in the Kafka topic dbserver1.public.users containing the "before" and "after" state of the row.
3. Sink Connectors: Pushing Data Out (S3, Elasticsearch)
A Sink Connector exports data from a Kafka topic to an external system.
Scenario A: Long-term Storage (Amazon S3)
You want to archive all events for compliance or data lake analysis.
Configuration (Confluent S3 Sink):
{
"name": "s3-sink",
"config": {
"connector.class": "io.confluent.connect.s3.S3SinkConnector",
"tasks.max": "1",
"topics": "dbserver1.public.users",
"s3.region": "us-west-2",
"s3.bucket.name": "my-company-data-lake",
"flush.size": "1000",
"storage.class": "io.confluent.connect.s3.storage.S3Storage",
"format.class": "io.confluent.connect.s3.format.json.JsonFormat",
"partitioner.class": "io.confluent.connect.storage.partitioner.DefaultPartitioner"
}
}flush.size: S3 is an object store, not a stream. We cannot write one byte at a time. This setting tells Connect to accumulate 1,000 messages before writing a file to S3.
Scenario B: Real-time Search (Elasticsearch)
You want to search for users by name instantly.
Configuration (Elasticsearch Sink):
{
"name": "elasticsearch-sink",
"config": {
"connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
"connection.url": "http://elasticsearch:9200",
"tasks.max": "1",
"topics": "dbserver1.public.users",
"type.name": "_doc",
"key.ignore": "true",
"schema.ignore": "true"
}
}key.ignore: If true, Elasticsearch will generate its own document ID. If false, it uses the Kafka message key (useful for deduplication).
4. Workers and Tasks: Distributed vs. Standalone Mode
This is the most critical architectural decision you will make.
🏠 Standalone Mode
A single process runs your connectors. Configuration is passed via files (e.g., my-connector.properties) at startup.
- Command:
bin/connect-standalone.sh worker.properties connector.properties - Use Case: Development, testing on your laptop, or simple tasks like reading a local log file.
- Limit: If the process dies, your pipeline stops. It cannot scale across multiple machines.
🏢 Distributed Mode
This is the production standard. You run a cluster of workers (similarly to how you run a cluster of Kafka brokers).
- Command:
bin/connect-distributed.sh worker.properties - Configuration: You do not pass connector files at startup. Instead, the cluster starts up empty, and you use a REST API to submit JSON configurations (like the examples above).
- Scalability:
- Workers form a group (using
group.id). - If you have a Connector with
tasks.max": "10"and you have 2 Workers, each Worker will handle 5 tasks. - If you add a 3rd Worker, the cluster automatically "rebalances" and moves some tasks to the new worker.
- Workers form a group (using
- Fault Tolerance: If a Worker crashes, its tasks are automatically restarted on the remaining workers.
Imagination Check: Imagine Standalone mode as a single freelancer doing all the work. If they get sick, work stops. Distributed mode is a corporation. If an employee is sick, the manager (the protocol) reassigns their files to others.
🧪 Hands-On: The "Glue Code" Lab
We will simulate a Distributed Connect environment.
1. Requirements
You generally need a Docker Compose environment with:
- Zookeeper
- Kafka
- Schema Registry (Optional but recommended)
- Kafka Connect (Image:
confluentinc/cp-kafka-connect) - Postgres (Source)
- Elasticsearch (Sink)
2. Starting the Connector
Assuming your Connect cluster is running on localhost:8083.
Check status:
curl localhost:8083/
# Output: {"version":"7.5.0","commit":"..."}Register the Postgres Source (Debezium):
curl -X POST -H "Content-Type: application/json" \
--data '{
"name": "postgres-source",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "postgres",
"database.port": "5432",
"database.user": "dbuser",
"database.password": "dbpass",
"database.dbname": "customers_db",
"topic.prefix": "pg",
"plugin.name": "pgoutput"
}
}' \
http://localhost:8083/connectorsCheck Connector Status:
curl localhost:8083/connectors/postgres-source/status | jq- Look for
state: "RUNNING".
3. Debugging Tips
- Serialization Errors: "JsonParseException". This usually means you are trying to read Avro data with a JSON converter. Check your
value.convertersetting in the worker properties. - Missing Plugins: "Failed to find any class that implements Connector". You must mount the JAR files for the connector (e.g., Debezium JARs, S3 JARs) into the
/usr/share/javadirectory of the Connect container.
📚 References & Further Reading
- Official Docs: Apache Kafka Connect Documentation
- Debezium: Debezium Documentation for Postgres
- Confluent Hub: Find Connectors Here
- REST API: Connect REST Interface
Summary:
Don't be a glue-code writer. Be a pipeline architect. Use Kafka Connect to snap systems together like LEGO bricks. 🧱
Challenge
You are a data engineer responsible for creating a real-time data pipeline. Your task is to write the complete JSON configuration payload that would be sent to the Kafka Connect REST API to register a new Debezium PostgreSQL source connector.
Your configuration must meet the following precise specifications:
- The connector's name must be
inventory-source-pg. - It must use the official Debezium connector class for PostgreSQL.
- The connector should be configured to run as a single task.
- Database connection details are as follows:
- Hostname:
pg.prod.internal - Port:
5432 - User:
connect_user - Password:
db_secret_k@fka - Database Name:
production_db
- Hostname:
- The connector must use PostgreSQL's native
pgoutputlogical decoding plugin to capture changes. - The logical server name, which serves as a prefix for all Kafka topic names, must be set to
ecom_prod. - The connector should only capture changes from the
productstable, which resides in thepublicschema. - For data serialization, both the message key and value must be converted using Kafka Connect's built-in
JsonConverter. A critical requirement is that the final JSON payload in Kafka should not include the schema definition.
Expected result
Your final output should be a single, valid JSON object representing the complete configuration for the Kafka Connect connector. All string values, including numbers represented as strings like tasks.max, must be properly quoted.