Kafka
Join our Slack community or Get in touch with the dltHub Customer Success team.
Kafka is an open-source distributed event streaming platform, organized
in the form of a log with message publishers and subscribers.
The Kafka dlt verified source loads data using the Confluent Kafka API to the destination of your choice.
See a pipeline example.
Every run reads the messages up to the end that each partition had when the run started. Then the
run stops. The pipeline state keeps the last offset read from each partition, and the next run
continues after it. dlt does not commit offsets to the Kafka consumer group. The source works with
confluent-kafka>=2.13.2,<3 and dlt>=1.28.1.
The resource that can be loaded:
| Name | Description |
|---|---|
| kafka_consumer | Extracts messages from Kafka topics |
Setup guide
Grab Kafka cluster credentials
- Follow the Kafka Setup to tweak a project.
- Follow the Configuration to get the project credentials.
Initialize the verified source
To get started with your data pipeline, follow these steps:
-
Enter the following command:
dlt init kafka duckdbThis command will initialize the pipeline example with Kafka as the source and duckdb as the destination.
-
If you'd like to use a different destination, simply replace
duckdbwith the name of your preferred destination. -
After running this command, a new directory will be created with the necessary files and configuration settings to get started.
Add credentials
-
In the
.dltfolder, there's a file calledsecrets.toml. It's where you store sensitive information securely, like access tokens. Keep this file safe.Use the following format for Confluent Cloud API keys and the other
SASLmechanisms (PLAIN,SCRAM-SHA-256,SCRAM-SHA-512):
[sources.kafka.credentials]
bootstrap_servers="web.address.gcp.confluent.cloud:9092"
security_protocol="SASL_SSL"
sasl_mechanisms="PLAIN"
sasl_username="example_username"
sasl_password="example_secret"
The credential fields are librdkafka properties with underscores instead of periods. For
example, bootstrap_servers is bootstrap.servers. group_id is optional, and its default is
dlt.
For SSL with client certificates (mTLS), give the certificates as PEM strings. You can also give
file paths in ssl_ca_location, ssl_certificate_location and ssl_key_location:
[sources.kafka.credentials]
bootstrap_servers="broker:9093"
security_protocol="SSL"
ssl_ca_pem="""-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----"""
ssl_certificate_pem="""-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----"""
ssl_key_pem="""-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----"""
For OAuth, use OIDC client credentials:
[sources.kafka.credentials]
bootstrap_servers="broker:9093"
security_protocol="SASL_SSL"
sasl_mechanisms="OAUTHBEARER"
sasl_oauthbearer_method="oidc"
sasl_oauthbearer_token_endpoint_url="https://idp.example.com/oauth2/token"
sasl_oauthbearer_client_id="client_id"
sasl_oauthbearer_client_secret="client_secret"
sasl_oauthbearer_scope="kafka"
For Azure Event Hubs, use SASL_SSL with PLAIN on port 9093. Set sasl_username to
$ConnectionString and sasl_password to the connection string of the namespace.
For Amazon MSK with IAM access control, install aws-msk-iam-sasl-signer-python. When
aws_region is set, the credentials sign tokens with the default AWS credentials chain. You can
also set aws_profile or aws_role_arn:
[sources.kafka.credentials]
bootstrap_servers="b-1.cluster.kafka.eu-central-1.amazonaws.com:9098"
aws_region="eu-central-1"
Put any other librdkafka property in consumer_config. Kerberos needs its properties there.
On Linux, Kerberos also needs confluent-kafka built from source. To read open transactions,
set the isolation level:
[sources.kafka.credentials.consumer_config]
"isolation.level"="read_uncommitted"
- Enter credentials for your chosen destination as per the docs.
Run the pipeline
-
Before running the pipeline, ensure that you have installed all the necessary dependencies by running the command:
pip install -r requirements.txt -
You're now ready to run the pipeline! To get started, run the following command:
python kafka_pipeline.py -
Once the pipeline has finished running, you can verify that everything loaded correctly by using the following command:
dlt pipeline <pipeline_name> show
For more information, read the Walkthrough: Run a pipeline.
A run ends when dlt reads every partition to the offset that it had when the run started. A run
also ends when no message arrives within batch_timeout. Under the default
isolation.level=read_committed, messages of open transactions load on a later run.
Sources and resources
dlt works on the principle of sources and
resources.
Source kafka_consumer
This function retrieves messages from the given Kafka topics.
@dlt.resource(name="kafka_messages", standalone=True)
def kafka_consumer(
topics: Union[str, list[str]],
credentials: Union[KafkaMskIamCredentials, KafkaCredentials, Consumer] = dlt.secrets.value,
msg_processor: Union[BatchProcessor, Callable[[Message], dict[str, Any]]] = default_msg_processor,
batch_size: int = 3000,
batch_timeout: float = 3,
start_from: Optional[TAnyDateTime] = None,
end_time: Optional[TAnyDateTime] = None,
request_timeout: float = 30,
schema_registry: Optional[SchemaRegistryCredentials] = None,
on_type_change: Literal["strict", "skip"] = "strict",
) -> Iterable[TDataItem]:
...
topics: A list of Kafka topics to be extracted.
credentials: By default, it is initialized with the data from
the secrets.toml. You can also pass an initialized Kafka Consumer. If you pass a Consumer,
set enable.partition.eof in it. Then the run ends after dlt reads all partitions.
msg_processor: Converts the messages before dlt loads them. A function gets every message and
returns a dict. The _kafka.topic key of the dict names the table. See the
default processor
as an example. The default processor loads keys and values as UTF-8 text, or as binary when they
are not valid UTF-8. Tombstones have a null value. _kafka_msg_id is a hash of topic, partition
and key, so messages with the same key share it. To load JSON or Avro values as typed columns,
pass a JsonProcessor or an AvroProcessor. See Use Schema Registry.
batch_size: The number of messages to extract from the cluster
at once. It can be set to tweak performance.
batch_timeout: The maximum time (in seconds) to wait for a batch. The run stops when no message
arrives in this time.
start_from: A timestamp. The run reads the messages from this time on. dlt asks the Kafka
cluster for the first offset with a timestamp at or after it. When the state has a later offset for
a partition, the partition continues after that offset. The next runs with the same start_from
read only new messages.
end_time: A timestamp. The run reads the messages before this time. With end_time, dlt does
not use or update the offsets in the state. You can load a window of messages, for example into
another pipeline. The window does not change what the next incremental run reads.
request_timeout: The timeout of the requests for topic metadata and offsets, in seconds. When dlt
cannot connect to a broker, the run fails after this time.
schema_registry: A Schema Registry with the Confluent API. By default, dlt takes it from
[sources.kafka.schema_registry] in secrets.toml. See
Use Schema Registry.
on_type_change: What happens when a new schema version changes the type of a column that dlt
already loaded. See Column type changes.
Customization
Create your own pipeline
-
Configure the pipeline by specifying the pipeline name, destination, and dataset as follows:
pipeline = dlt.pipeline(
pipeline_name="kafka", # Use a custom name if desired
destination="duckdb", # Choose the appropriate destination (e.g., duckdb, redshift, post)
dataset_name="kafka_data" # Use a custom name if desired
) -
To extract several topics:
topics = ["topic1", "topic2", "topic3"]
resource = kafka_consumer(topics)
pipeline.run(resource, write_disposition="replace") -
To extract messages and process them in a custom way:
def custom_msg_processor(msg: confluent_kafka.Message) -> dict[str, Any]:
key, value = msg.key(), msg.value()
return {
"_kafka": {
"topic": msg.topic(), # required field
"key": key.decode("utf-8") if key is not None else None,
"partition": msg.partition(),
},
# tombstones have no value
"data": value.decode("utf-8") if value is not None else None,
}
resource = kafka_consumer("topic", msg_processor=custom_msg_processor)
pipeline.run(resource) -
To extract messages from a timestamp on, pass
start_from. The next runs continue after the last message that dlt read:from datetime import datetime, timezone
resource = kafka_consumer("topic", start_from=datetime(2023, 12, 15, tzinfo=timezone.utc))
pipeline.run(resource) -
To load a window of messages and keep the offsets in the state as they are:
resource = kafka_consumer(
"topic",
start_from=datetime(2023, 12, 1, tzinfo=timezone.utc),
end_time=datetime(2023, 12, 15, tzinfo=timezone.utc),
)
pipeline.run(resource)