Kafka Tutorial for Beginners

Apache Kafka Explained

Apache Kafka is an open source system that stores streams of events in topics, so producers can write them and many consumers can read them independently at any time. This beginner tutorial explains topics and partitions, then consumer groups and offsets, and ends with a local broker you write to and read from.

Last updated: Proudly published by: Jeff Wahl10 min read

What is Apache Kafka?

Apache Kafka is an open source system for storing streams of events and letting many applications write and read them independently. A producer appends events to a topic and Kafka keeps them on disk, where any number of consumers can read them at their own pace, even long after they were written.

That makes Kafka the layer in a data pipeline where events from databases and services land before they go anywhere else. A data engineer uses it to decouple the systems that produce data from the systems that process it: a slow consumer never slows a producer, and a new consumer can start from the oldest retained event without asking the producer to send anything again.

This tutorial is written for beginners who will run the software themselves. It explains the 6 ideas the rest of Kafka rests on, then walks through a local broker on version 4.4.0, the latest release at the time of writing. Every default quoted comes from the Apache Kafka 4.4 documentation.

Prepare for the interview
01 / Open invite
02min.

Know Kafka Tutorial the way the interviewer who asks it knows it.

a Kafka Tutorial query, the same shape a screen would give you.
The diff against expected. Where ties broke. What you missed.
sandbox
1source → bronze → silver → gold
2 ingest : CDC + Kafka
3 transform : dbt + Airflow
4 serve : Snowflake
5
Execute your solution0.4s avg.
LinkedInInterview question
Solve a Kafka Tutorial problem

How partitions and consumer groups work

A topic is split into partitions, and a partition is an append-only log: new events go on the end and each one gets an offset, its position in that partition. Events with the same key are written to the same partition, and a consumer reads a partition's events in the order they were written.

Consumers that share a group.id form a consumer group, and each partition is consumed by exactly 1 consumer within the group. The figure draws 3 partitions read by a group of 4 consumers. Consumers 1 to 3 own a partition each and the last one has nothing to read. The partition count is therefore the ceiling on a group's parallelism: adding a consumer beyond it adds an idle process, not throughput.

Events with keys a, b and c are appended to 3 partitions, one partition per key, in order. A consumer group of 4 consumers reads them: consumers 1, 2 and 3 each own one partition and consumer 4 is idle.Events with keys a, b and c are appended to 3 partitions, one partition per key, in order. A consumer group of 4 consumers reads them: consumers 1, 2 and 3 each own one partition and consumer 4 is idle.

A second group reading the same topic is independent of the first. Each group keeps its own offsets, so a billing job and a dashboard job can read the same events without coordinating.

Events, topics, brokers and retention explained

An event records that something happened. It carries a key and a value plus a timestamp, and it can have optional headers; Kafka also calls it a record or a message. Producers publish events, consumers subscribe to them, and the 2 never wait for each other.

A broker is a Kafka server that stores partitions and serves reads and writes. A cluster is a set of brokers, and each partition is replicated to several of them so that losing a machine does not lose the log. The documentation notes that a replication factor of 3 is common in production.

Retention decides how long events stay. The topic setting retention.ms defaults to 604,800,000 milliseconds, which is 7 days, and retention.bytes defaults to -1, so by default only time limits a log. Consuming an event never deletes it. That is the difference from a classic queue, and it is why replaying history is just reading from an earlier offset.

How to install and run Kafka locally

You need Java 17 or newer and a download of the Apache Kafka binaries from the Apache Kafka quickstart, which uses kafka_2.13-4.4.0.tgz. Kafka runs in KRaft mode, so there is nothing else to install: you generate a cluster ID, format the storage directory with it and start the server. The standalone option of the format command sets up a single-node cluster, which is what a laptop needs.

Open 3 terminals. The first runs the broker and stays busy, the second creates a topic and writes events, the third reads them. The commands in the next listing are the quickstart's own. The Apache project also publishes Docker images, so docker run -p 9092:9092 apache/kafka:4.4.0 starts a broker without a download.

Commands to start a broker, create a topic and send events

# Start a broker (Java 17 or newer is required)
tar -xzf kafka_2.13-4.4.0.tgz
cd kafka_2.13-4.4.0
KAFKA_CLUSTER_ID="$(bin/kafka-storage.sh random-uuid)"
bin/kafka-storage.sh format --standalone -t $KAFKA_CLUSTER_ID -c config/server.properties
bin/kafka-server-start.sh config/server.properties

# In a second terminal: create a topic and look at it
bin/kafka-topics.sh --create --topic quickstart-events --bootstrap-server localhost:9092
bin/kafka-topics.sh --describe --topic quickstart-events --bootstrap-server localhost:9092

# Write events: type a line, press Enter, stop with Ctrl-C
bin/kafka-console-producer.sh --topic quickstart-events --bootstrap-server localhost:9092

# In a third terminal: read them back from the start
bin/kafka-console-consumer.sh --topic quickstart-events --from-beginning --bootstrap-server localhost:9092

Create your first topic and read what Kafka reports

The describe command prints 1 line for the topic and 1 per partition. Read the partition line from left to right: the partition number, the broker that is its leader, the brokers holding a replica of it and the in-sync replicas, written Isr. On a single local broker all 3 point at broker 0, because there is nowhere else to replicate to.

A write to a partition is not considered committed until all in-sync replicas have received it, and only members of that set can be elected leader. On a laptop the set has 1 member. On a production cluster it is the number you protect with the replication settings, min.insync.replicas among them.

What describe prints for a 1 partition topic

kafka-topics.sh describe
Topic: quickstart-events        TopicId: NPmZHyhbR9y00wMglMH2sg PartitionCount: 1       ReplicationFactor: 1    Configs:
Topic: quickstart-events Partition: 0    Leader: 0   Replicas: 0 Isr: 0

Output as shown in the Apache Kafka quickstart; your TopicId differs

How Kafka producers send events and choose partitions

A producer sends events in batches. With the defaults, it waits up to linger.ms of 5 milliseconds for more events to fill a batch of up to batch.size 16,384 bytes, trading a few milliseconds of delay for far fewer requests. compression.type defaults to none.

The safe settings are the defaults. acks is all, so a write counts only once the in-sync replicas have it, and enable.idempotence is true, so a retried send cannot write the same event twice. Retries are effectively unlimited, bounded by delivery.timeout.ms, which defaults to 120,000 milliseconds, 2 minutes.

The key decides the partition. Say a key hashes to 17. On a topic with 3 partitions it lands in partition 17 mod 3 = 2. If you add a partition, the same key now maps to 17 mod 4 = 1, so its new events are in a different log from its old ones. The documentation warns that after adding partitions, messages with the same key may be routed to different partitions, and that Kafka does not support reducing a topic's partition count. Choose the count with growth in mind, and choose a key such as a customer or device ID that groups the events whose order matters.

Producer and topic defaults in Kafka 4.4

Defaults from the Apache Kafka 4.4 configuration reference
acks
all
enable.idempotence
true
linger.ms
5
batch.size
16,384 bytes
delivery.timeout.ms
120,000 (2 minutes)
retention.ms
604,800,000 (7 days)
min.insync.replicas
1
cleanup.policy
delete

How consumers, offsets and lag work

A consumer's progress in a partition is a single number, the offset of the next event it will read. A group stores 1 number per partition, so tracking what has been consumed is cheap, and rewinding means moving that number back.

When a consumer starts with no stored offset, auto.offset.reset decides where it begins, and the default is latest: it sees only events that arrive after it joins. That surprises beginners who write events, then start a consumer and see nothing. The console consumer in the quickstart is told to read from the beginning for exactly this reason.

A pair of timeouts keep a group healthy. A consumer that stops sending heartbeats for session.timeout.ms (45 seconds by default) is removed, and a consumer that goes more than max.poll.interval.ms (5 minutes by default) between calls to poll() is removed too. Either way its partitions move to the other members.

The bin/kafka-consumer-groups.sh tool, run with its describe option for a group, shows CURRENT-OFFSET and LOG-END-OFFSET for each partition, along with LAG. If the log end is 1,200 and the group's current offset is 1,150, the lag is 1,200 - 1,150 = 50 events. A lag that grows over time means the group reads slower than producers write, and the fix is more consumers up to the partition count or faster processing.

At most once, at least once and exactly once delivery

The design documentation names 3 delivery semantics. At most once means messages may be lost but are never redelivered. At least once means messages are never lost but may be redelivered. Exactly once means each message is processed once and only once. Which one you get depends on when the consumer commits its offset relative to processing: committing before processing means a crash loses events, and committing after means a crash repeats them.

Durability on the write side comes from replication. Take a topic with a replication factor of 3 and min.insync.replicas of 2. With acks=all, a write succeeds only if at least 2 replicas, the leader included, have it, so the topic keeps accepting writes with 1 replica down and refuses them when fewer than 2 remain. The default min.insync.replicas is 1, so raise it deliberately on topics that matter.

At least once plus idempotent processing is the common practical choice in pipelines. Writing a consumer's output so that a repeated event changes nothing is the same discipline as an idempotent data pipeline.

Log compaction: keeping the latest value per key

The default cleanup.policy is delete, which discards old segments when their time or size limit is reached. Setting it to compact changes the promise: Kafka retains at least the last known value for each message key, and compaction never reorders messages, it only removes some.

A message with a key and a null payload is treated as a delete for that key. A compacted topic therefore works as a changelog of current state, such as the latest address for each customer, which a new consumer can read from the start to rebuild a table.

Kafka Connect and Kafka Streams: moving and processing data

Besides the command line tools, Kafka has 5 core APIs. Producer and Consumer handle sending and reading events, Admin manages topics, and Kafka Streams and Kafka Connect cover processing and moving data. You will write against Producer and Consumer when an application sends or reads events itself.

Kafka Connect runs reusable connectors that import data from external systems into topics and export topics to external systems, so moving a table or a file does not need custom code. The quickstart demonstrates it by copying lines from a text file into a topic and back out to another file. Kafka Streams is a client library for Java and Scala that processes the events in topics with transformations, including joins and windowed aggregations.

In a pipeline, Connect or a change data capture tool fills topics from source systems. Streams or another processing engine transforms them, and sinks write results to storage. How change capture feeds a topic is covered in what CDC is, and the place of a log like Kafka beside scheduled loads in batch vs streaming pipelines.

What Kafka does not do for you

Kafka orders events within a partition only. If 2 events must be seen in order, they need the same key, and a topic with many partitions gives no order across keys. Reading the log is also not a query: finding 1 event by a field means scanning, so lookups belong in a store that consumers write to.

Partition counts only grow, and growing them changes where keys land, as the hash arithmetic for a key shows. A group's parallelism stops at its partition count. And the safe durability settings are a choice per topic: with a replication factor of 1, the local quickstart setting, a broker failure loses the partition.

Where Kafka shows up in data engineer interviews

Interviewers use Kafka to see whether you can reason about what breaks: why a key is chosen, what happens when a consumer is slower than the producers, and how you would avoid double counting after a restart. The Kafka interview questions cover those topics, and the data pipeline interview questions place Kafka inside the wider design.

To practice designing the pipeline around a topic, work through the data pipeline practice problems. The system design round guide shows how interviewers expect an event pipeline to be walked through.

Kafka tutorial FAQ

What is Apache Kafka used for?+
Kafka stores streams of events durably and lets many applications write and read them independently. Data engineers use it to move events between systems and to feed streaming jobs, and it keeps a replayable record of what happened.
Is Kafka a message queue?+
It behaves like one when a consumer group splits a topic's partitions among its members, but its log differs from a classic queue: events stay in the topic until retention expires, so consumers can read them again and many groups can read the same events.
Do I need ZooKeeper to run Kafka?+
No. Current Kafka runs in KRaft mode, where each server is a broker or a controller, or plays both roles, set by the `process.roles` property. The 4.4.0 quickstart formats storage and starts a broker with no ZooKeeper process.
What is the difference between a topic and a partition?+
A topic is a named stream of events. A partition is one ordered log inside a topic, and a topic is spread over its partitions so reads and writes can run in parallel. Kafka guarantees order within a partition, not across the whole topic.
How many partitions should a topic have?+
At least as many as the consumers you expect to run in 1 group, because each partition is read by exactly 1 consumer in a group. A group of 4 consumers on 3 partitions leaves 1 idle. Kafka cannot reduce a topic's partition count, so start with room to grow.
What does consumer lag mean?+
Lag is how far a consumer group is behind the end of the log in a partition: the log end offset minus the group's current offset. With a log end of 1,200 and a current offset of 1,150, the lag is 50.
How long does Kafka keep events?+
As long as the topic's retention allows. The default `retention.ms` is 604,800,000, which is 7 days, and `retention.bytes` defaults to -1, no size limit. Reading an event does not delete it.
Which language do I need to learn Kafka?+
None to start: the command line tools that ship with Kafka are enough for the first topic. Kafka's 5 APIs are written for Java and Scala, and Kafka clients exist in other languages.
02 / Why practice

The candidate who gets the offer

  1. 01

    Reading a solution is not the same as writing one

    Every engineer who has frozen on a query they had read a dozen times knows the gap. The only preparation that closes it is producing the answer yourself, under time, before the interview does it for you

  2. 02

    76% of hiring managers reject on the coding task, not the resume

    From HackerRank's 2024 Developer Skills Report. Candidates who look strong on paper still fail the live screen if they haven't done timed, executable practice

  3. 03

    System design comes down to the calls you defend out loud

    Ingestion, batch vs streaming, the bronze/silver/gold layers, idempotency, backfill and replay. Sketching the pipeline and naming the failure modes is the signal, not the boxes

Related guides