Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice. Everything here runs for free on your own computer with Docker: one Kafka container is enough until stage 4, where you start three.
Stage 1 · Beginner Kafka fundamentals
Kafka is a distributed, append-only log. Almost everything else (consumer groups, replication, retention, exactly-once) follows from that one idea, so take the time to really understand topics, partitions and offsets before writing application code.
Why Kafka: event streaming and the log
An event is a record that something happened: "order 42 was paid", "sensor 7 read 21.5 °C". Apache Kafka stores streams of events durably, in order, and lets many applications read them independently, at their own pace, now or days later. That makes it the backbone for moving data between services, feeding analytics, and building systems that react to changes as they happen.
The key difference from a classic message queue (RabbitMQ, SQS): a queue hands each message to one worker and deletes it, while Kafka keeps events for a configured time and each reader tracks its own position. Ten different services can read the same orders stream, and a new one can start from the beginning. The price is more concepts to learn and a cluster to run.
What to learn
- What an event is: key, value, timestamp and headers
- A log versus a queue: events are kept and re-readable instead of deleted after delivery
- Typical uses: service-to-service events, activity tracking, log and metrics pipelines, change data capture, stream processing
- When Kafka is the wrong tool: a few jobs a minute, request/response calls, or a team with nobody to run it
- The ecosystem in one sentence each: brokers, clients, Kafka Connect, Kafka Streams, Schema Registry
Free resources
Practice
Pick an app you know (a shop, a food delivery app). List ten events it produces, write each as a key and a small JSON value, and decide which services would want to read each one. Mark the two where order matters.
Prerequisites: Linux, Docker and a JVM language
Kafka is a Java application, its command-line tools are shell scripts, and you will run it in containers. You don't need to be an expert, but you should be comfortable in a terminal, able to start containers with Docker Compose, and able to read Java (see the Java roadmap; the official clients, Kafka Streams and most examples are Java; Python, Go, Node.js and .NET clients exist too). Skip this topic if all of that is already familiar.
What to learn
- Terminal basics: files, processes, environment variables and reading logs
- Docker and Docker Compose: images, containers, ports, volumes and networks
- Enough Java to read classes, generics, lambdas and Maven or Gradle builds
- Networking basics: hostnames, ports, DNS and what "advertised address" might mean
- JSON, plus the idea of serialising objects to bytes
Free resources
Practice
Write a compose.yaml that starts a PostgreSQL container with a named volume, start it, connect with psql, stop it, start it again and check the data survived. You'll reuse the pattern for Kafka.
Topics, partitions, offsets and brokers
A topic is a named stream of events, such as orders. Each topic is split into partitions; each partition is an ordered, append-only log where every event gets the next number, its offset. Partitions are how Kafka scales: they are spread over the servers in the cluster (brokers) and read in parallel.
Ordering is only guaranteed within one partition. Producers usually set a key (say, the order id), and events with the same key always go to the same partition, so all events for one order stay in order. Consumers remember how far they have read by storing offsets, which is why they can stop, restart and carry on, or rewind and read again.
What to learn
- Topic, partition, offset, broker and cluster, and how they fit together
- Why ordering holds only within a partition, and how keys keep related events together
- What happens to events with a null key
- Consumers track their own position; reading doesn't delete anything
- Why the partition count limits how many consumers in a group can work in parallel
Free resources
Practice
On paper, draw a topic with 3 partitions. Send 9 events with keys A, B, C, A, A, C, B, A, C (assume A → 0, B → 1, C → 2) and write each event's partition and offset. Then answer: in what order does a consumer see the A events? Can it see B's events before A's?
Run Kafka locally
The fastest start is the official Docker image: one container runs a single node that acts as both broker and controller (KRaft "combined" mode), which is perfect for learning. You can also download the release, which needs Java 17 or newer, format a storage directory and start the server with the scripts in bin/.
The setting that trips everyone up is advertised.listeners: the address the broker tells clients to connect to. If a client outside Docker gets told "connect to kafka:9092" it fails, even though the first connection worked. Learn what listeners are now and you'll save hours later.
# Single-node Kafka 4.4 in Docker (KRaft, no ZooKeeper)
docker run -d --name kafka -p 9092:9092 apache/kafka:4.4.0
# The CLI tools live inside the image
docker exec -it kafka /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --create --topic orders --partitions 3
What to learn
- Starting Kafka with the official
apache/kafka image and with the downloaded release
- What
kafka-storage.sh format does and why a cluster has an id
- Listeners versus advertised listeners, and the classic "works inside Docker, fails outside" problem
- Where data lives on disk (
log.dirs) and what a log segment file is
- A multi-node cluster in Docker Compose (you'll need it for replication)
Free resources
Practice
Start Kafka in Docker, create a topic, write three events with the console producer and read them back with the console consumer. Then write a Compose file for a 3-broker cluster, start it, and confirm all three brokers appear in kafka-metadata-quorum.sh describe --status.
The command-line tools
Kafka ships with scripts for nearly every admin task, and you will use them daily even if you later add a web UI. kafka-topics.sh creates and describes topics, kafka-console-producer.sh and kafka-console-consumer.sh write and read events, kafka-consumer-groups.sh shows consumer lag and resets offsets, and kafka-configs.sh changes topic and broker settings without a restart.
# Produce keyed events: type "key:value" per line
kafka-console-producer.sh --bootstrap-server localhost:9092 --topic orders \
--property parse.key=true --property key.separator=:
# Read from the start, showing key, partition and offset
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders \
--from-beginning --group demo \
--property print.key=true --property print.partition=true --property print.offset=true
# How far behind is the group?
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group demo
What to learn
- Create, list, describe and delete topics, and add partitions
- Produce keyed events and consume with keys, partitions and offsets shown
- Describe a consumer group: current offset, log end offset and lag
- Reset a group's offsets (to earliest, latest, a time or a shift) with a dry run first
- Change a topic config (for example retention) at runtime
Free resources
Practice
Produce 100 keyed events to a 3-partition topic. Consume half of them with a group, stop, and use kafka-consumer-groups.sh to see the lag. Reset the group to the earliest offset (dry run, then execute) and consume everything again.
Replication, leaders and in-sync replicas
Each partition is copied to several brokers; the replication factor (usually 3) says how many. One copy is the leader and handles all writes; the others are followers that fetch from it. Followers that are fully caught up form the in-sync replica set (ISR). If the leader's broker dies, the controller picks a new leader from the ISR, and clients carry on.
Durability comes from combining three settings: replication factor 3 on the topic, min.insync.replicas=2, and producers using acks=all. Then a write only succeeds once at least two brokers have it, and losing any one broker loses no acknowledged data. Recent versions add eligible leader replicas (ELR) to make leader election safer still.
What to learn
- Replication factor, leader and followers, and why clients talk to the leader
- The ISR: when a replica drops out and rejoins (
replica.lag.time.max.ms)
- How
min.insync.replicas and acks=all together prevent data loss
- Unclean leader election: what it trades away and why it's off by default
- Rack awareness: spreading replicas over availability zones
Free resources
Practice
On your 3-broker cluster, create a topic with replication factor 3 and min.insync.replicas=2. Describe it to see leaders and ISR. Stop one broker: does producing with acks=all still work? Stop a second one: what error do you get, and why is that the right behaviour?
KRaft: how the cluster manages itself
Every cluster needs one place that knows which brokers are alive, which topics exist and who leads each partition. Kafka used to keep that in Apache ZooKeeper. Since Kafka 4.0 (March 2025) ZooKeeper is gone: a small group of controllers runs the Raft consensus protocol (KRaft) and stores cluster metadata in an internal log that brokers replicate, just like any other topic.
For developers this mostly means one less system to run. Operators need to know the roles (process.roles=broker, controller or both), the controller quorum (three controllers survive one failure, five survive two) and the tools to inspect it. Old guides that mention --zookeeper flags or zookeeper.connect are out of date.
What to learn
- What the controller does: broker membership, topic metadata and leader election
- Combined mode (dev) versus dedicated controllers (production)
- Quorum sizes: why 3 or 5 controllers, and what a majority means
- Inspecting the quorum with
kafka-metadata-quorum.sh
- Spotting outdated ZooKeeper-era advice, and how old clusters were migrated
Free resources
Practice
Change your Compose cluster to three dedicated controllers plus three brokers. Use kafka-metadata-quorum.sh describe --replication to find the active controller, stop it, and watch another take over while producers keep working.
Retention, segments and log compaction
Kafka doesn't delete events when they're read. A topic's cleanup policy decides when they go. With delete (the default), whole log segments are removed once they're older than retention.ms (7 days by default) or the partition is bigger than retention.bytes. With compact, Kafka keeps at least the latest event for every key and removes older ones in the background, so the topic becomes a durable table of "current value per key".
Compacted topics power a lot of Kafka: consumer offsets and Kafka Streams state changelogs are compacted topics. To delete a key from a compacted topic, you write a tombstone (the key with a null value).
What to learn
- Time and size retention, and why deletion works on whole segments
- Log compaction: latest value per key, tombstones and
delete.retention.ms
- Using
compact,delete together
- Choosing retention: replay needs, disk cost and privacy rules (deleting personal data)
- The internal
__consumer_offsets topic and why it is compacted
Free resources
Practice
Create a compacted topic with a small segment.ms (say 60 s) and a low min.cleanable.dirty.ratio. Write 20 updates for 3 keys plus one tombstone, wait a few minutes, and read from the beginning. Which events are left?
Am I ready? Stage 1 quiz
Events for order 42 must be processed in the order they were sent. How do you guarantee that?
- Give the topic a single consumer group
- Use a replication factor of 1
- Use the order id as the key so all its events land in the same partition
- Set the retention to forever
Kafka only orders events within a partition. The same key always maps to the same partition (while the partition count doesn't change).
A topic has replication factor 3 and min.insync.replicas=2. Producers use acks=all. Two of the three brokers holding a partition go down. What happens to writes to that partition?
- They fail with a not-enough-replicas error until a broker comes back
- They succeed and are stored on the one remaining broker
- They succeed but the data is lost
- Kafka creates new replicas on other brokers automatically and carries on
With only one in-sync replica left, Kafka refuses acks=all writes instead of accepting data it can't keep safe.
What replaced ZooKeeper in Kafka 4.0?
- etcd
- A relational database inside the broker
- Nothing: brokers no longer need metadata
- KRaft: controllers running the Raft protocol and storing metadata in an internal log
KRaft has been the only mode since 4.0. The metadata lives in a replicated log managed by a controller quorum.
You want a topic that always holds the latest address for every customer id, forever, without growing without limit. Which cleanup policy fits?
delete with retention.ms=-1compact, keyed by customer iddelete with a 7-day retention- No policy: use a bigger disk
Compaction keeps the latest value per key and drops older ones, so the topic behaves like a table.
A consumer reads every event in a topic. What happens to the events?
- They are deleted from the partition
- They move to a "read" topic
- Nothing: they stay until retention or compaction removes them, and other consumers can still read them
- They are marked as read so no other group can read them
Reading doesn't change the log. Each consumer group just stores its own offset.
Stage 2 · Beginner → Intermediate Producers and consumers
This is where most Kafka bugs live: lost events, duplicates, stuck consumers and endless rebalances. Learn what each client setting really does, and test what happens when brokers and consumers fail, not only the happy path.
Writing a producer
A producer turns your objects into bytes with a serializer, picks a partition (by hashing the key, or spreading keyless events around with the sticky partitioner), collects events into batches per partition and sends them to each partition's leader. send() is asynchronous: it returns at once, and you learn whether the write worked in a callback or from the returned future.
Properties p = new Properties();
p.put("bootstrap.servers", "localhost:9092");
p.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
p.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
try (KafkaProducer<String, String> producer = new KafkaProducer<>(p)) {
var record = new ProducerRecord<>("orders", "order-42", "{\"status\":\"PAID\"}");
producer.send(record, (meta, err) -> {
if (err != null) System.err.println("Failed: " + err);
else System.out.printf("Wrote to partition %d at offset %d%n", meta.partition(), meta.offset());
});
} // close() flushes anything still buffered
What to learn
- Serializers for keys and values, and why the key choice decides ordering and load spread
- Asynchronous
send(), callbacks, futures and flush() / close()
- Batching and throughput:
batch.size, linger.ms and compression.type
- Headers for metadata such as trace ids and event types
- Hot partitions: what happens when one key gets most of the traffic
Free resources
Practice
Write a producer that sends 100,000 small JSON events. Measure the time with linger.ms=0 and no compression, then with linger.ms=20 and compression.type=lz4. Print how many events landed in each partition.
Reliable producers: acks, retries and idempotence
Networks fail mid-request, so a producer sometimes can't tell whether a write landed. It retries, which used to create duplicates. Today the defaults are safe: acks=all (wait for all in-sync replicas) and enable.idempotence=true, which gives each producer an id and numbers its batches so brokers drop retried duplicates and keep the order within a partition.
The setting to tune is delivery.timeout.ms: how long the producer keeps retrying before it gives up and reports an error. What your code does with that error (log, retry later, write to a fallback store) decides whether you lose data, so never ignore send failures.
What to learn
acks=0, 1 and all: the trade between speed and durability
- Idempotent producers: producer id, sequence numbers and why order survives retries
retries, delivery.timeout.ms, request.timeout.ms and max.in.flight.requests.per.connection
- Retriable versus fatal errors (a timeout versus "record too large" or an authorisation error)
- Message size limits on the producer, broker and topic (
max.request.size, message.max.bytes)
Free resources
Practice
Produce numbered events in a loop to your 3-broker cluster and kill the partition leader in the middle. Consume everything and check: are any numbers missing or duplicated? Repeat with acks=1 and idempotence off, and compare.
Writing a consumer
A consumer subscribes to topics and calls poll() in a loop; each call returns a batch of records from the partitions it has been assigned. After processing, it commits offsets so that, after a restart, it continues from where it got to. Where a brand-new group starts is set by auto.offset.reset: earliest reads all retained history, latest only new events.
Properties p = new Properties();
p.put("bootstrap.servers", "localhost:9092");
p.put("group.id", "billing");
p.put("enable.auto.commit", "false"); // commit only after processing
p.put("auto.offset.reset", "earliest");
p.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
p.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(p)) {
consumer.subscribe(List.of("orders"));
while (running) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
handle(r.key(), r.value());
}
consumer.commitSync(); // after the whole batch is handled
}
}
What to learn
- The poll loop, deserializers and
max.poll.records
- Auto commit versus committing yourself after processing, sync versus async commits
auto.offset.reset and what "committed offset" means
- Shutting down cleanly with
wakeup() so the group isn't left waiting
- Bad records ("poison pills"): skip, retry or send to a dead-letter topic
Free resources
Practice
Write a consumer that stores each order in a local SQLite or PostgreSQL table and commits only after the insert. Kill it with kill -9 in the middle of a batch, restart it, and check which rows were processed twice. Then make the insert safe to repeat (an upsert on the order id).
Consumer groups and rebalancing
Consumers with the same group.id share the work: each partition is read by exactly one member of the group, so a topic with 6 partitions can use up to 6 consumers in parallel (a 7th sits idle). Different groups read independently. When members join, leave or crash, partitions are moved between them: a rebalance.
Kafka 4.0 made the new consumer group protocol (KIP-848) generally available: the broker-side group coordinator computes assignments and moves partitions one by one, so the rest of the group keeps working instead of pausing for a "stop the world" rebalance. You opt in with group.protocol=consumer on the client. A consumer that takes longer than max.poll.interval.ms between polls is still considered dead and loses its partitions, the most common cause of rebalance loops.
What to learn
- Partition assignment inside a group, and why consumers beyond the partition count are idle
- The classic protocol versus the new consumer protocol (
group.protocol=consumer)
- Session timeouts, heartbeats and
max.poll.interval.ms
- Static membership (
group.instance.id) to avoid rebalances during rolling restarts
- Consumer lag: what it measures and how to watch it
Free resources
Practice
Run 1, then 3, then 4 copies of your consumer on a 3-partition topic and log which partitions each one gets. Add a sleep longer than max.poll.interval.ms in one of them and watch the group rebalance. Repeat with group.protocol=consumer and compare the logs.
Delivery guarantees: at most, at least and exactly once
When you commit offsets decides what a crash costs you. Commit before processing and a crash loses events (at most once). Commit after and a crash means some events are processed again (at least once), which is the normal choice. Exactly once needs more: either Kafka transactions when you read from and write to Kafka (stage 3), or making the side effect idempotent so doing it twice is harmless.
In practice, design every consumer to tolerate duplicates: use an event id or a natural key, upsert instead of insert, and keep a table of processed ids where needed.
What to learn
- The three guarantees and which commit order produces each
- Where duplicates come from: producer retries, consumer crashes and rebalances
- Idempotent consumers: event ids, upserts and deduplication tables
- Why "exactly once" really means "effectively once" when external systems are involved
- Retry topics and dead-letter topics for events that keep failing
Free resources
Practice
Build a "send welcome email" consumer that prints instead of emailing. Make it at least once, then crash it at random points and count duplicate "emails". Add a processed-ids table and show the duplicates disappear.
Serialization, schemas and Schema Registry
Kafka only stores bytes, so producers and consumers must agree on the format. Plain JSON works until someone renames a field and breaks every reader. Teams usually describe events with Avro, Protobuf or JSON Schema and store the schemas in a schema registry (Confluent Schema Registry or the open-source Apicurio Registry). Each event carries a small schema id; the registry checks every new schema version against a compatibility rule before producers may use it.
What to learn
- Avro, Protobuf and JSON Schema compared: size, tooling and code generation
- How a registry serializer works: schema id in the payload, schemas cached by clients
- Backward, forward and full compatibility, and which changes each allows
- Safe changes: adding optional fields with defaults; unsafe: renaming or changing types
- Subject naming (one schema per topic, or several event types in one topic)
Free resources
Practice
Run a schema registry in Docker. Register an Avro schema for OrderPaid, produce with it, then try three changes: add an optional field with a default, remove a required field, and change a field's type. Note which ones the registry rejects under BACKWARD compatibility.
Clients in other languages and frameworks
The Java client is the reference implementation and gets new features first. Most other official-looking clients wrap librdkafka, a fast C library: confluent-kafka for Python, Go and .NET. There are also pure implementations such as franz-go (Go) and KafkaJS (Node.js). In Java shops you'll often meet Spring for Apache Kafka, which hides the poll loop behind @KafkaListener methods. The concepts from this stage are the same everywhere; only the setting names sometimes differ.
What to learn
- Which client your language uses and whether it supports idempotence, transactions and the new group protocol
- librdkafka configuration names versus Java client names
- Spring Kafka: listeners, error handlers and retry topics
- Running several consumers in one process safely (a consumer isn't thread-safe)
- Where to find each client's changelog and compatibility notes
Free resources
Practice
Rewrite your Java producer in a second language and check the two interoperate: produce in one, consume in the other, with the same keys landing in the same partitions.
Queues for Kafka: share groups
A consumer group can never have more active members than partitions, and one slow event holds up its whole partition. Share groups (KIP-932, generally available since Kafka 4.2) give Kafka queue-like behaviour: many share consumers read the same partitions together, each record is handed to one consumer at a time, and every record is acknowledged on its own (accept, release for another try, or reject). Records that fail too often can now go to a dead-letter topic (Kafka 4.4).
Use share groups for job-style work where order doesn't matter and you want to scale workers freely; keep consumer groups when per-key order matters.
What to learn
- Consumer groups versus share groups: ordering, scaling and acknowledgement
- The
KafkaShareConsumer API and accept, release and reject acknowledgements
- Delivery counts, lock timeouts and what happens when a consumer dies holding records
- Managing share groups with
kafka-share-groups.sh
- When a classic queue (RabbitMQ, SQS) is still the simpler choice
Free resources
Practice
Put 1,000 "resize image" jobs on a 1-partition topic. Process them with a consumer group, then with a share group of four consumers that sleep a random 50–500 ms per job. Compare total time, and release a few jobs on purpose to see them redelivered.
Testing Kafka applications
Test at three levels. Unit tests keep your business logic free of Kafka types, or use the client's MockProducer and MockConsumer. Integration tests start a real broker in a container with Testcontainers and check the whole produce–consume path, including serialization. Kafka Streams apps get the TopologyTestDriver, which runs a topology without any broker (stage 3).
What to learn
- Keeping handlers testable: separate "decode event" from "do the work"
MockProducer and MockConsumer for fast unit tests
- Integration tests against a real broker with Testcontainers
- Waiting for asynchronous results without flaky sleeps (poll with a timeout)
- Contract tests for event schemas between teams
Free resources
Practice
Add a Testcontainers test to your billing consumer: produce three orders, one of them malformed, and assert that two rows end up in the database and the bad one lands on a dead-letter topic.
Am I ready? Stage 2 quiz
A topic has 4 partitions and your consumer group has 6 members. How many members receive records?
- 6, sharing each partition
- 4; the other 2 sit idle
- 1, the group leader
- 2, because 6 doesn't divide by 4
In a consumer group each partition goes to exactly one member, so extra members wait as standbys. (Share groups don't have this limit.)
Your consumer commits offsets right after poll() and then processes the records. It crashes halfway through a batch. What happens?
- The batch is processed again after restart
- Kafka rolls back the commit automatically
- Nothing is lost because the producer retries
- The unprocessed half of the batch is skipped: at-most-once delivery
The committed offset already points past those records, so after the restart they are never read again. Commit after processing for at least once.
What does enable.idempotence=true protect against?
- Duplicates and reordering in a partition caused by producer retries
- Consumers processing the same event twice
- Data loss when all replicas fail
- Two different producers sending the same business event
Brokers use the producer id and sequence numbers to drop retried batches. It doesn't cover consumer-side duplicates or separate producers.
A consumer keeps getting kicked out of its group and rebalancing. Processing one batch sometimes takes 10 minutes. What is the likely cause?
- The topic has too many partitions
auto.offset.reset is set to earliest- The time between polls exceeds
max.poll.interval.ms - The producer uses
acks=all
If poll() isn't called within max.poll.interval.ms (5 minutes by default) the consumer is treated as failed. Use smaller batches, faster processing or a higher limit.
Under BACKWARD compatibility in a schema registry, which change is allowed?
- Renaming a field
- Adding an optional field with a default value
- Changing a field's type from string to int
- Adding a required field with no default
Consumers using the new schema must still read old data; a default fills in the new field for old events.
Stage 3 · Intermediate Event design, integration and stream processing
Now you build systems instead of single clients: design events other teams can rely on, move data in and out of databases without writing glue code, and process streams continuously with Kafka Streams.
Designing events, topics and event-driven systems
Good events are the API between teams, so design them as carefully as an HTTP API. Decide whether an event is a notification ("order 42 changed", fetch the rest yourself) or carries state (the whole order), what the key is, how topics are named, and how many partitions to start with (adding partitions later changes which partition a key maps to).
Then learn the patterns built on events: event-carried state transfer so services keep local copies of data, event sourcing where the log is the source of truth, CQRS to build read models from it, and the transactional outbox to publish events reliably from a service that also writes to its database.
What to learn
- Notification events versus state-carrying events, and facts versus commands
- Choosing keys, topic names and the starting partition count
- One event type per topic or several, and what that means for ordering and schemas
- Event sourcing, CQRS and event-carried state transfer
- The dual-write problem and the transactional outbox pattern
Free resources
Practice
Design the events for a checkout flow (cart, order, payment, shipping): names, keys, topics, partition counts and one schema each. Write down which service owns each topic and which ones read it, then find one place where you'd need the outbox pattern.
Kafka Connect
Most data enters or leaves Kafka through Kafka Connect instead of hand-written code. Source connectors pull data in (from databases, files, SaaS APIs) and sink connectors push it out (to S3, Elasticsearch, a warehouse). You configure a connector with JSON through a REST API; Connect workers run it, spread its tasks over the cluster and restart them on failure.
Each connector has a converter (JSON, Avro, Protobuf) that turns data into bytes, optional single message transforms (SMTs) for small changes such as renaming fields or routing to another topic, and an error policy: fail, or skip bad records into a dead-letter queue.
curl -X PUT localhost:8083/connectors/orders-to-files/config \
-H "Content-Type: application/json" -d '{
"connector.class": "org.apache.kafka.connect.file.FileStreamSinkConnector",
"topics": "orders",
"file": "/tmp/orders.txt",
"tasks.max": "1",
"errors.tolerance": "all",
"errors.deadletterqueue.topic.name": "orders-dlq"
}'
What to learn
- Source versus sink connectors, workers and tasks
- Standalone versus distributed mode and the internal config, offset and status topics
- Converters and single message transforms
- Error handling:
errors.tolerance and dead-letter queues
- Managing connectors through the REST API: create, pause, restart and check status
Free resources
Practice
Run a Connect worker in distributed mode next to your cluster. Create a file sink connector from the example, then send a few events it can't handle and confirm they appear on the dead-letter topic with error headers. Pause, resume and delete the connector over REST.
Change data capture with Debezium
Change data capture (CDC) reads a database's own transaction log (PostgreSQL's WAL, MySQL's binlog) and turns every insert, update and delete into an event. Debezium is the standard open-source set of CDC source connectors for Kafka Connect. It lets you stream a legacy database into Kafka without touching the application, keep caches and search indexes in sync, and implement the outbox pattern with its outbox event router.
What to learn
- Why log-based CDC beats polling a table for changes
- Debezium's change event format: before, after, operation and source metadata
- Initial snapshots, then streaming changes
- Replication slots in PostgreSQL and the risk of a slot that never advances
- The outbox event router to publish clean domain events
Free resources
Practice
Stream a PostgreSQL customers table into Kafka with Debezium. Insert, update and delete rows and read the change events. Then add an outbox table, write an order and its outbox row in one transaction, and route the outbox rows to an order-events topic.
Kafka Streams: the basics
Kafka Streams is a Java library (not a separate cluster) for processing streams: you describe a topology of steps (filter, map, group, aggregate, join) and run it inside your own app; start more copies and the work spreads over them like a consumer group. A KStream is a stream of independent events; a KTable is a changelog where each key's latest value wins, the same stream–table duality you met with compaction.
StreamsBuilder b = new StreamsBuilder();
b.stream("orders", Consumed.with(Serdes.String(), Serdes.String()))
.filter((id, json) -> json.contains("\"status\":\"PAID\""))
.groupByKey()
.count() // KTable: paid events per order
.toStream()
.to("paid-counts", Produced.with(Serdes.String(), Serdes.Long()));
Properties p = new Properties();
p.put(StreamsConfig.APPLICATION_ID_CONFIG, "paid-counter");
p.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
new KafkaStreams(b.build(), p).start();
What to learn
- Topologies, sources, processors and sinks, and the
application.id
- KStream versus KTable versus GlobalKTable
- Stateless operations: filter, map, flatMap, branch and merge
- Serdes, and repartitioning when you change the key
- Testing a topology with
TopologyTestDriver
Free resources
Practice
Build a Streams app that reads raw page-view events, drops bots (by user agent), re-keys by user id and writes clean events to a new topic. Cover it with a TopologyTestDriver test, then run two instances and watch the partitions split between them.
Stateful streams: aggregations, windows and joins
Counting, summing and joining need state. Kafka Streams keeps it in local state stores (RocksDB by default) and backs each store with a compacted changelog topic, so when an instance dies another one rebuilds the state and carries on. Windows group events by time (tumbling, hopping, sliding and session windows), using each event's timestamp rather than the clock, which raises the question of what to do with late events (grace periods).
Joins combine streams and tables: enrich every order with the customer's latest details (stream–table), or match payments to orders within 10 minutes (windowed stream–stream). Both sides must be co-partitioned: same key and same partition count.
What to learn
- Aggregations: count, reduce and aggregate, and the state stores behind them
- Changelog topics, standby replicas and restoring state
- Event time versus processing time, windows and grace periods for late events
- Stream–stream, stream–table and table–table joins, and co-partitioning
- Interactive queries: reading a state store from a REST endpoint
Free resources
Practice
Extend your page-view app: count views per page in 1-minute tumbling windows, join each view with a users KTable to add the country, and expose "top pages in the last minute" through a small HTTP endpoint using an interactive query.
Transactions and exactly-once processing
A Kafka transaction lets one producer write to several partitions and commit consumer offsets atomically: either all of it becomes visible or none of it does. Consumers using isolation.level=read_committed never see aborted writes. Together this gives exactly-once processing for read–process–write pipelines that stay inside Kafka.
In Kafka Streams it's one setting: processing.guarantee=exactly_once_v2. With plain clients you set a transactional.id, call initTransactions(), and wrap each batch in beginTransaction() … sendOffsetsToTransaction() … commitTransaction(). Exactly-once stops at Kafka's edge: writing to an external database still needs idempotence there.
What to learn
- The read–process–write loop and what transactions make atomic
transactional.id, fencing of "zombie" producers and the transaction coordinator
read_committed versus read_uncommitted consumers
exactly_once_v2 in Kafka Streams and its cost in latency
- Why external side effects still need idempotent design
Free resources
Practice
Write a transactional "currency converter" that reads payments, converts them and writes them to a new topic, committing offsets in the same transaction. Abort every tenth transaction on purpose and show that a read_committed consumer never sees those outputs while a read_uncommitted one does.
Apache Flink and streaming SQL
Kafka Streams is a library for Java apps. Apache Flink is a separate processing engine that reads from and writes to Kafka, scales to very large stateful jobs, and offers Flink SQL, so analysts can write streaming queries without Java. It has become the common choice for streaming SQL; Confluent's older ksqlDB is still around but sees far less new adoption. Learn Flink when you need SQL, very large state, or processing across many sources.
What to learn
- Kafka Streams versus Flink: library versus cluster, Java versus SQL
- Flink's Kafka connector and tables over Kafka topics
- Streaming SQL: continuous queries, windows and watermarks
- Checkpoints and exactly-once in Flink
- Writing streams into lakehouse tables (Apache Iceberg)
Free resources
Practice
Run Flink's SQL client in Docker, declare a table over your page-views topic and write the "views per page per minute" query from the stateful streams topic in SQL. Compare the amount of code with your Kafka Streams version.
Am I ready? Stage 3 quiz
A service saves an order to PostgreSQL and then publishes an OrderCreated event. Sometimes the app crashes between the two. Which pattern fixes this?
- Publish the event first, then save the order
- Use
acks=all on the producer - Retry the publish in a background thread
- Transactional outbox: write the event to an outbox table in the same database transaction and relay it to Kafka (for example with Debezium)
The outbox makes "save" and "publish" one database transaction; a relay or CDC connector then delivers the event at least once.
What is the difference between a KStream and a KTable?
- A KTable is stored in a database; a KStream is in Kafka
- A KStream is a sequence of independent events; a KTable keeps the latest value per key
- A KTable can't be joined
- A KStream only works with string keys
That's the stream–table duality: a table is a stream of updates where each key's newest value wins.
A Kafka Connect sink connector keeps failing on a few malformed records. You want it to keep going and keep the bad records for later. What do you configure?
errors.tolerance=all with a dead-letter queue topic- A higher
tasks.max - A shorter topic retention
- Standalone mode instead of distributed mode
The dead-letter queue keeps failed records (with error details in headers) while the connector carries on.
A stream–stream join between orders (6 partitions) and payments (4 partitions), both keyed by order id, gives wrong results. Why?
- Joins only work on KTables
- The keys must be numbers
- The topics aren't co-partitioned: matching keys can land in different partition numbers
- Windows aren't allowed in joins
Joins need both inputs to have the same partition count and key, so the same key is on the same partition number. Repartition one side first.
Which consumer setting hides writes from aborted Kafka transactions?
enable.auto.commit=falseauto.offset.reset=latestacks=allisolation.level=read_committed
Read-committed consumers only return records from committed transactions (and non-transactional ones).
Stage 4 · Intermediate → Advanced Running Kafka in production
Whether you run your own cluster or use a managed service, someone has to size it, secure it, watch it and fix it at 3 a.m. Developers need enough of this to choose sensible settings and read a dashboard; administrators need all of it.
Cluster design and sizing
Size a cluster from the workload: write throughput, how many times each event is read (fan-out), retention and replication factor give you disk and network needs. Kafka loves fast sequential disks, lots of page cache (free RAM the OS uses to cache the log) and good networking; it needs surprisingly little CPU and a modest JVM heap. Spread brokers and replicas over at least three availability zones with broker.rack.
Partition count is the decision people get wrong most. Enough partitions give you parallelism; too many add memory, open files, recovery time and leader elections. Start from target throughput per partition and consumer parallelism, and leave room to grow.
What to learn
- Capacity maths: throughput × replication × retention, plus read fan-out on the network
- Disks, page cache, heap size and the Java version (17 or newer; 25 recommended for 4.4)
- Choosing the partition count and why you can add but never remove partitions
- Rack awareness and spreading brokers over availability zones
- Separate controllers, and when to split one big cluster into several
Free resources
Practice
Size a cluster for 50 MB/s of writes, read by 3 consumer groups, kept for 7 days with replication factor 3. Work out total disk, inbound and outbound network, and a broker count with 40% headroom. Then pick partition counts for three topics and justify each.
Performance tuning: throughput versus latency
Most tuning is choosing between throughput and latency. Bigger batches (batch.size, linger.ms), compression and larger fetches (fetch.min.bytes, fetch.max.wait.ms) raise throughput and add a little delay; the opposite lowers latency at higher cost. Measure before and after with the bundled kafka-producer-perf-test.sh and kafka-consumer-perf-test.sh tools, change one setting at a time, and watch the p99, not the average.
What to learn
- Producer settings for throughput: batching, linger, compression type and buffer memory
- Consumer settings: fetch sizes, wait times and
max.poll.records
- Broker settings: network and I/O threads, and why defaults are usually fine
- Benchmarking with the perf-test tools and reading percentiles
- Quotas to stop one client from starving the others
Free resources
Practice
Run kafka-producer-perf-test.sh against your 3-broker cluster with four settings combinations (linger 0/20 ms × compression none/zstd). Record throughput and p99 latency in a table and write one sentence on when you'd choose each.
Security: TLS, SASL and ACLs
A default Kafka install has no encryption, no login and no permissions: anyone who can reach port 9092 can read and delete everything. Production clusters need three layers. Encryption with TLS on every listener. Authentication with mutual TLS or SASL (SCRAM passwords, OAUTHBEARER tokens from your identity provider, or Kerberos in older enterprises). Authorisation with ACLs that give each application only the topics and groups it needs.
# Let the billing app read "orders" with its own consumer group, nothing else
kafka-acls.sh --bootstrap-server kafka:9093 --command-config admin.properties \
--add --allow-principal User:billing \
--operation Read --topic orders --group billing
What to learn
- Listeners and security protocols: PLAINTEXT, SSL, SASL_PLAINTEXT and SASL_SSL
- TLS keystores and truststores, and mutual TLS for clients
- SASL mechanisms: SCRAM, OAUTHBEARER and when to use each
- ACLs: principals, operations, resources and prefixed patterns
- Keeping credentials out of code and rotating them
Free resources
Practice
Secure your Compose cluster: TLS with a self-signed CA, SASL/SCRAM users for an admin and two apps, and ACLs so the producer can only write orders and the consumer can only read it. Prove that each app is refused everything else.
Monitoring and alerting
Kafka exposes hundreds of JMX metrics; a few matter most. On brokers: under-replicated partitions (should be 0), offline partitions (must be 0), the active controller count, request latency, disk usage and network throughput. On clients: consumer lag (how far each group is behind), producer error rate and request latency. The common open-source stack is the Prometheus JMX exporter, a lag exporter, Prometheus and Grafana dashboards.
What to learn
- The key broker metrics and what "under-replicated" or "offline" really mean
- Consumer lag in records and in time, and alerting on lag that keeps growing
- Exporting JMX metrics to Prometheus and building Grafana dashboards
- Client metrics: send error rate, retries and request latency
- Writing alerts that wake people only for problems that need a human
Free resources
Practice
Add Prometheus, Grafana and both exporters to your Compose file. Build a dashboard with under-replicated partitions, bytes in/out per broker and lag per group. Stop a broker and a consumer and check that both problems show up and alert.
Day-2 operations: upgrades, reassignment and scaling
Running Kafka is mostly routine changes done safely. Rolling restarts and upgrades one broker at a time, waiting for under-replicated partitions to return to 0 in between, then bumping the metadata.version feature level when all nodes are upgraded. Adding brokers, which receive no data until you move partitions to them with kafka-reassign-partitions.sh (throttled so clients don't suffer) or a balancer such as Cruise Control. Preferred leader election to spread leadership again after restarts.
What to learn
- Rolling restarts and upgrades, and feature levels with
kafka-features.sh
- Reassigning partitions with throttles, and verifying the result
- Adding and removing brokers and controllers
- Preferred leader election and keeping leadership balanced
- Automated balancing with Cruise Control
Free resources
Practice
Add a fourth broker to your cluster while a producer and consumer run. Move a third of the partitions to it with a throttled reassignment, verify it, run a preferred leader election, and do a rolling restart of all brokers without the clients logging a single failed send.
Tiered storage
Keeping months of data on broker disks is expensive and makes broker replacement slow. Tiered storage (KIP-405) keeps recent segments on local disk and moves older ones to cheap remote storage such as S3; consumers can still read the old data, just with higher latency. It makes long retention affordable and brokers lighter, at the cost of a remote storage plugin to choose and run.
What to learn
- Local versus remote tier, and
local.retention.ms versus retention.ms
- Remote storage manager plugins and object storage
- What changes for consumers reading old data
- Limits: which topic types and features tiered storage doesn't support
- Cost comparison: disk on brokers versus object storage
Free resources
Practice
Using the cluster from your sizing topic, compare the monthly cost of 30 days of retention on broker disks versus 1 day local plus 29 days in object storage, using your cloud provider's public prices.
Multiple clusters and disaster recovery
One cluster across three zones survives a zone failure. Surviving a region failure, or moving data between teams and clouds, needs a second cluster and a replication tool. MirrorMaker 2 (built on Kafka Connect) copies topics, consumer group offsets and configs between clusters. The hard parts are not the copying but the plan: which side is active, how consumers fail over with translated offsets, and how you fail back.
What to learn
- Stretched clusters versus separate clusters per region
- Active–passive and active–active layouts
- MirrorMaker 2: replication flows, topic naming and offset syncing
- Failover and failback runbooks, and testing them
- Recovery point and recovery time objectives for streaming data
Free resources
Practice
Run two single-node clusters and MirrorMaker 2 between them. Produce to the first, consume half with a group, "lose" the first cluster, and move the consumer to the second so it continues near where it stopped. Write the runbook as you go.
Kafka on Kubernetes and managed services
You don't have to run brokers yourself. Managed services (Confluent Cloud, Amazon MSK, Aiven and others) handle provisioning, upgrades and much of the operations. On Kubernetes, the Strimzi operator (a CNCF project) runs clusters, topics, users and Connect from YAML resources. There are also Kafka-compatible systems that speak the Kafka protocol with a different engine (Redpanda, or designs that write straight to object storage). Compare them on cost, which Kafka features and versions they support, and what you still have to operate.
What to learn
- What a managed service takes off your hands, and what stays your job (topics, clients, security, cost)
- Strimzi custom resources: Kafka, KafkaNodePool, KafkaTopic and KafkaUser
- Storage, networking and external access for Kafka on Kubernetes
- Kafka-compatible engines and how to check their protocol and feature support
- Pricing models: per broker, per partition, per GB in/out and storage
Free resources
Practice
Install Strimzi on a local kind or minikube cluster and create a 3-node Kafka cluster, a topic and a SCRAM user from YAML. Connect your producer to it. Then price the same workload on one managed service and compare.
Troubleshooting common problems
The same handful of problems cause most incidents. Growing lag: consumers too slow, too few partitions or a stuck partition. Rebalance storms: slow processing beyond max.poll.interval.ms or crash loops. Clients can't connect: advertised listeners, TLS or DNS. Record too large, not enough replicas, hot partitions from a skewed key, and full disks. Learn to go from symptom to cause with the CLI tools, client logs and your dashboards.
What to learn
- Diagnosing lag: per-partition lag, consumer throughput and stuck partitions
- Reading client logs for rebalances, retries and connection errors
- Fixing listener and advertised-listener mistakes
- Finding hot partitions and skewed keys
- Writing a short incident review: timeline, cause, fix and follow-ups
Free resources
Practice
Ask a friend (or write a script) to break your cluster in three secret ways from this list. Find and fix each using only the CLI tools, logs and your Grafana dashboard, and write a one-paragraph incident review for each.
Capstone project and certification
Bring it together in one project you can show: for example an online shop's order pipeline. Orders arrive through an API and an outbox, Debezium streams them into Kafka with Avro schemas, a Kafka Streams app computes live sales per minute with exactly-once, a sink connector loads results into a database, and the whole thing runs on a secured 3-broker cluster with dashboards and alerts, all in one Compose file or on Strimzi.
If you want a certificate, Confluent offers the Certified Developer for Apache Kafka (CCDAK) and the Certified Administrator for Apache Kafka (CCAAK): proctored, online, multiple-choice exams. Read the official exam guide for the current topics, format and price before booking; the filter on this page maps topics to each exam.
What to learn
- Write a short design document: events, topics, keys, partition counts and guarantees
- Build the pipeline with schemas, Connect, Streams and exactly-once
- Secure it, monitor it and load-test it
- Break it on purpose and show it recovers without losing data
- Review the exam guide and close any gaps if you are taking CCDAK or CCAAK
Free resources
Practice
Publish the capstone on GitHub with a README covering the architecture diagram, how to run it with one command, the guarantees it gives, a chaos test you ran, and dashboard screenshots.
Am I ready? Stage 4 quiz
Which broker metric should be 0 in a healthy cluster and is the first sign that replicas are falling behind?
- Under-replicated partitions
- Bytes in per second
- Number of topics
- Request handler idle ratio
Under-replicated partitions mean some followers aren't in sync, so durability is reduced. Alert on it staying above 0.
You add a new broker to a busy cluster. A day later it has almost no data. Why?
- New brokers need a restart of the whole cluster first
- The controller only uses new brokers after a week
- Existing partitions don't move by themselves; you must reassign them (or use a balancer such as Cruise Control)
- The broker's disk is too small
Only new topics and partitions land on new brokers automatically. Move existing ones with a throttled reassignment.
Clients connect to a broker in Docker on localhost:9092, then fail with "connection to kafka:9092 failed". What is wrong?
- The topic doesn't exist
advertised.listeners tells clients to use an address they can't reach- The client needs SASL
- The replication factor is too low
The first request only fetches metadata; after that clients connect to the advertised address. It must be reachable from where the client runs.
Which combination gives encryption, authentication and least-privilege access?
- PLAINTEXT listeners and a firewall
- TLS only
- SASL/PLAIN over PLAINTEXT and no ACLs
- SASL_SSL (TLS plus SCRAM or OAUTHBEARER) and ACLs per application
TLS encrypts, SASL (or mutual TLS) identifies the client, and ACLs limit each identity to what it needs.
You need 6 months of retention but brokers are running out of disk, and old data is rarely read. What fits best?
- Tiered storage: keep recent segments locally and older ones in object storage
- Lower the replication factor to 1
- Turn on log compaction for every topic
- Increase
batch.size on producers
Tiered storage moves old segments to cheap remote storage while consumers can still read them.