Apache Kafka Introduction
Apache Kafka is a distributed event streaming platform used to publish, store and process large amounts of data in real time. In simple words, Kafka helps different applications talk to each other by sending messages (events) quickly, reliably and at scale.
This beginner’s guide explains what Kafka is, why it is needed, its core concepts and how it works, and then gets you started: running Kafka locally, sending your first messages from the command line, and writing your first Java and Spring Boot programs.
1. What Is Apache Kafka?
Kafka’s distributed architecture makes it horizontally scalable: new servers can be added to a cluster easily, and consumers can read messages at their own pace.
Kafka was originally developed at LinkedIn to handle its huge flow of activity data and logs. It was released as open source in 2011 and became a top-level Apache Software Foundation project in 2012. Since then it has grown into a general-purpose platform for handling data streams in many scenarios. Kafka itself is written in Java and Scala, but clients exist for a wide range of programming languages.
Kafka is commonly used in modern applications such as banking systems, e-commerce platforms, real-time analytics, logging systems and microservices architectures.
2. Why Kafka Is Needed
In traditional systems, applications communicate directly with each other. As the system grows, this direct communication becomes slow, complex and difficult to manage: every new service needs new connections, and if one service is down, others fail too.
Without Kafka: With Kafka:
Orders ----> Inventory Orders ---+
Orders ----> Payments v
Orders ----> Email [ Kafka: orders topic ]
Orders ----> Analytics | | | |
Inventory Payments Email Analytics
Each new service = new connection New service = just start reading
Kafka solves this problem by acting as a central messaging system that decouples producers (senders) and consumers (receivers). Producers write events once; any number of consumers read them independently, even if they are temporarily offline.
3. Key Features of Apache Kafka
| Feature | Meaning |
|---|---|
| High throughput | Kafka can handle millions of messages per second across a cluster, ideal for real-time applications |
| Scalability | Add more servers (brokers) without stopping the system and spread the load across them |
| Fault tolerance | Data is copied to several brokers; if one fails, the data is still available from another |
| Durability | Messages are stored on disk, not just in memory, so data survives restarts |
| Real-time processing | Data is processed as it arrives, for live tracking, monitoring and streaming analytics |
| Multiple consumers | Many consumers can read the same data independently, each tracking its own position |
| Loose coupling | Producers and consumers do not need to know about each other, so systems are easier to change |
See Kafka Features for a detailed look at each feature.
4. Core Kafka Concepts
| Concept | Short meaning |
|---|---|
| Producer (app) | Sends messages to Kafka topics |
| Consumer (app) | Reads messages from Kafka topics |
| Topic | A named channel where related Kafka messages are stored |
| Partition | A topic is divided into partitions for scalability and parallel processing |
| Offset | A unique position of a message within a partition |
| Broker | A Kafka server that stores and serves messages |
| Cluster | A group of Kafka brokers working together |
| Consumer group | A group of consumers that share the work of reading a topic |
| Replication | Copies of partitions on several brokers, for fault tolerance and high availability |
| Leader | The replica that handles reads and writes for a partition |
| Follower | A replica that copies data from the partition leader |
| Retention | How long Kafka keeps messages before removing them |
| Rebalancing | Redistributing partitions among consumers when consumers join or leave a group |
| ISR | In-sync replicas: followers that are fully caught up with the leader |
| Key | Decides which partition a message goes to; same key, same partition |
| Serialization | Converting a Java object into bytes before sending it to Kafka |
| Deserialization | Converting Kafka message bytes back into a Java object |
5. How Kafka Works
Kafka runs on a group of servers (brokers) working together. If you need more power, you add more servers. Programs that read data from Kafka can do so whenever they are ready, without being forced to keep up with the sender.
Kafka saves every message in order, one after another, like entries in a diary. This is called a log. Each message has an optional key and a value. Many traditional message queues remove a message once it has been read. Kafka instead keeps messages for as long as you choose, so you can go back and read them again. This is useful when you need to replay past events or rebuild something from its history.
Topic "orders", partition 0
offset: 0 1 2 3
+--------+-----------+--------------+-------------+
| Order | Payment | Order | Order | <- new events are
| placed | received | packed | shipped | added at the end
+--------+-----------+--------------+-------------+
^ ^
Analytics reads here Email service reads here
6. Simple Kafka Flow
- A producer sends a message to a Kafka topic.
- Kafka stores the message safely on disk and copies it to other brokers.
- A consumer reads the message from the topic.
- The consumer processes the message and records how far it has read.
7. Simple Real-World Example
Imagine an online shopping application:
- A user places an order.
- The order service sends an event called “Order Placed” to Kafka.
- Several services consume this event independently:
| Service | What it does with “Order Placed” |
|---|---|
| Inventory service | Updates stock |
| Payment service | Processes the payment |
| Notification service | Sends an email or SMS |
| Analytics service | Updates sales dashboards |
All these services work independently, and Kafka makes sure each of them receives the event reliably and in real time. If the notification service is down for a while, it simply catches up when it comes back, without the order service noticing.
8. Kafka Architecture at a Glance
Producers Kafka cluster Consumers
+-------------------------------------+
Order app ---> | Broker 1 Broker 2 Broker 3 | ---> Billing (group A)
Web app ---> | orders-P0 orders-P1 orders-P2 | ---> Analytics (group B)
| (+ copies of other partitions) |
| KRaft controllers manage metadata |
+-------------------------------------+
- Brokers store partitions and serve producers and consumers.
- Each partition has a leader and followers on different brokers.
- Controllers manage cluster metadata, such as which broker leads each partition. Modern Kafka does this with its built-in KRaft protocol; older versions used a separate ZooKeeper cluster, which Kafka 4.0 no longer supports.
See Kafka Architecture for the full picture.
9. Running Kafka on Your Computer
The quickest way to try Kafka is with Docker:
docker run -d --name kafka -p 9092:9092 apache/kafka:4.0.0
Or download Kafka from the official Apache Kafka website, unpack it, and start a single-node cluster. Kafka 4.x brokers need Java 17 or later:
cd kafka_2.13-4.0.0
# 1. Create a cluster ID and format the storage directory (first time only)
KAFKA_CLUSTER_ID="$(bin/kafka-storage.sh random-uuid)"
bin/kafka-storage.sh format --standalone -t "$KAFKA_CLUSTER_ID" -c config/server.properties
# 2. Start the broker
bin/kafka-server-start.sh config/server.properties
Kafka now listens on localhost:9092. This single-node setup is for learning only; production clusters use several brokers.
10. Your First Topic, Producer and Consumer
Open new terminals in the Kafka folder and run these commands. (With Docker, run them inside the container with docker exec -it kafka /opt/kafka/bin/<script>.)
bin/kafka-topics.sh --create --topic orders \
--bootstrap-server localhost:9092 --partitions 3
bin/kafka-console-producer.sh --topic orders --bootstrap-server localhost:9092
> Order placed: book
> Order placed: laptop
bin/kafka-console-consumer.sh --topic orders --from-beginning \
--bootstrap-server localhost:9092
The consumer prints every message, including those sent before it started, because of --from-beginning. Start a second consumer and it receives the same messages too.
11. Your First Kafka Program in Java
Add the client library to your Maven project:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>4.0.0</version>
</dependency>
package com.example.kafka;
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
public class HelloKafkaProducer {
public static void main(String[] args) {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
producer.send(new ProducerRecord<>("orders", "order-1", "Order placed: book"));
System.out.println("Message sent");
}
}
}
package com.example.kafka;
import java.time.Duration;
import java.util.List;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
public class HelloKafkaConsumer {
public static void main(String[] args) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "hello-group");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(List.of("orders"));
while (true) {
for (ConsumerRecord<String, String> record : consumer.poll(Duration.ofMillis(500))) {
System.out.printf("Received key=%s value=%s%n", record.key(), record.value());
}
}
}
}
}
Run the consumer, then the producer, and the consumer prints the new order. See Kafka Producer and Kafka Consumer for the details.
12. Kafka with Spring Boot
With Spring Boot, add the spring-kafka dependency and set the broker address:
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: order-notifications
auto-offset-reset: earliest
package com.example.kafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class OrderEvents {
private final KafkaTemplate<String, String> kafkaTemplate;
public OrderEvents(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
// Producer: publish an event
public void orderPlaced(String orderId, String details) {
kafkaTemplate.send("orders", orderId, details);
}
// Consumer: react to events
@KafkaListener(topics = "orders")
public void onOrder(String details) {
System.out.println("Sending confirmation for: " + details);
}
}
Spring Boot creates the producer and consumer, and uses String serializers by default.
13. Kafka vs Traditional Message Queues
| Aspect | Kafka | Traditional message queue |
|---|---|---|
| Storage | Keeps messages for a set time, even after they are read | Usually removes messages once they are acknowledged |
| Readers | Many independent consumer groups read the same data | Each message usually goes to one consumer |
| Replay | Yes, by moving back to an earlier offset | Usually not |
| Ordering | Guaranteed within a partition | Per queue, often weaker with several consumers |
| Scale | Very high throughput through partitions | Good for moderate volumes |
| Strengths | Event streaming, data pipelines, history | Task queues, routing rules, per-message features |
See Kafka vs RabbitMQ for a detailed comparison.
14. Where Kafka Is Commonly Used
| Use case | Example |
|---|---|
| Microservices communication | Services publish and react to events such as “OrderPlaced” |
| Real-time data pipelines | Move data from databases and apps into data warehouses continuously |
| Log aggregation | Collect logs from many servers in one place |
| Streaming analytics | Live dashboards, fraud detection, recommendations |
| Event-driven architectures | Keep a history of every business event |
| Activity tracking | Clicks, searches and page views on websites and apps |
| IoT and sensors | Readings from vehicles, devices and machines |
See Kafka Use Cases for real-world examples.
15. The Kafka Ecosystem
| Component | Purpose |
|---|---|
| Kafka Connect | Moves data between Kafka and databases, storage and other systems using ready-made connectors |
| Kafka Streams | A Java library for processing and transforming data as it flows through Kafka |
| MirrorMaker 2 | Copies topics between Kafka clusters, for example for disaster recovery |
| Schema registry (third-party tools) | Stores message formats such as Avro or JSON Schema, so producers and consumers agree |
| Client libraries | Java, Python, Go, .NET, Node.js and more |
16. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Very high throughput and low latency | More moving parts than a simple queue; needs operational know-how |
| Scales horizontally by adding brokers | Ordering only within a partition |
| Durable, replicated storage | Not designed for request-reply or per-message priorities |
| Many consumers and replay of history | Not a query database; data is read in order, not searched |
| Large ecosystem and community | Default message size limit of about 1 MB |
17. What to Learn Next
- Kafka Architecture: how the pieces fit together.
- Kafka Topic, Kafka Partition and Kafka Offset: how data is organized.
- Kafka Producer and Kafka Consumer: writing and reading data.
- Kafka Broker and Kafka Cluster: running Kafka.
- Kafka Fault Tolerance and Kafka Security: production readiness.
18. Summary
Apache Kafka is a powerful and reliable platform for handling real-time data streams. It stores events in ordered, replicated logs called topics, lets producers write them once, and lets any number of consumers read them independently and replay them later. With features like high throughput, scalability, fault tolerance and durability, Kafka helps applications communicate efficiently by decoupling producers and consumers, and it has become a core technology in modern system design.
In short, if you need to process large volumes of data in real time and build scalable, event-driven systems, Kafka is an excellent choice.
19. Frequently Asked Questions (FAQ)
Q1. What is Apache Kafka in simple words?
Apache Kafka is a platform that lets applications send, store and read streams of events in real time. Producers write events to topics, Kafka stores them safely across several servers, and consumers read them whenever they are ready.
Q2. Is Kafka a message queue?
It can be used like one, but it is more than that. Kafka is an event streaming platform: it keeps messages after they are read, lets many independent consumers read the same data, and allows replaying past events. Traditional queues usually remove a message once it is consumed.
Q3. Who created Kafka?
Kafka was created at LinkedIn to handle large volumes of activity and log data. It was open-sourced in 2011 and became a top-level project of the Apache Software Foundation in 2012.
Q4. Is Apache Kafka free?
Yes. Apache Kafka is open source under the Apache License 2.0, and you can use it free of charge, including in commercial products. Several companies also sell managed Kafka services and support.
Q5. What is a Kafka topic?
A topic is a named stream of related messages, such as orders or payments. Producers write to a topic and consumers read from it. Each topic is split into partitions for scale.
Q6. What is the difference between a producer and a consumer?
A producer sends (writes) messages to Kafka topics. A consumer reads messages from topics and processes them. One application can be both, for example reading orders and writing payment events.
Q7. What is a Kafka broker?
A broker is a Kafka server. It stores partitions on disk and handles requests from producers and consumers. Several brokers together form a Kafka cluster.
Q8. Why does Kafka split topics into partitions?
Partitions let a topic be spread across several brokers and read by several consumers at once. This gives Kafka its high throughput and scalability. Messages stay in order within each partition.
Q9. How long does Kafka keep messages?
Seven days by default. You can change the retention time or size per topic, keep messages forever, or use log compaction to keep only the latest message for each key. Reading a message does not delete it.
Q10. Does Kafka still need ZooKeeper?
No. Modern Kafka manages its own metadata with KRaft. Kafka 4.0 removed ZooKeeper support completely, so new clusters run without it.
Q11. Which programming languages can I use with Kafka?
The official client is for Java. Popular clients also exist for Python, Go, C/C++, .NET, Node.js, Rust and others, and Spring Boot offers simple Kafka support for Java applications.
Q12. How do I install Kafka for learning?
The easiest way is Docker:
docker run -d --name kafka -p 9092:9092 apache/kafka:4.0.0
Alternatively, download Kafka from the Apache Kafka website, format the storage with kafka-storage.sh, and start it with kafka-server-start.sh. Kafka 4.x brokers need Java 17 or later.
Q13. Is Kafka only for big companies?
No, but it shines at scale. Small teams use Kafka for event-driven microservices and data pipelines, often through managed cloud services. For a small app with very few messages, a simpler queue may be easier to run.
Q14. Can Kafka lose data?
When configured properly, Kafka is very reliable. Use replication factor 3, min.insync.replicas=2 and producers with acks=all. With a single copy of data or acks=0, data can be lost if a broker fails.
Q15. Does Kafka keep messages in order?
Yes, within each partition. Messages with the same key go to the same partition, so all events for one order or customer stay in order. There is no ordering across different partitions.
Q16. What is a consumer group?
A set of consumers with the same group.id that share the work of reading a topic. Each partition is read by one member, so adding members increases processing speed. Different groups each get their own copy of every message.
Q17. Is Kafka a database?
Not in the usual sense. Kafka stores data durably and can keep it for a long time, but it is built for streaming events in order, not for searching or updating records. Most systems copy data from Kafka into a database for queries.
Q18. What is the difference between Kafka and RabbitMQ?
Kafka is a distributed log designed for high-volume event streams, long retention and replay by many consumers. RabbitMQ is a message broker with flexible routing, ideal for task queues and per-message features. Both are popular; the right choice depends on the use case.
Q19. How is Kafka used with Spring Boot?
Add spring-kafka, set spring.kafka.bootstrap-servers, send messages with KafkaTemplate, and receive them with @KafkaListener:
kafkaTemplate.send("orders", orderId, details);
@KafkaListener(topics = "orders")
public void onOrder(String details) { ... }
Q20. What should I learn after the Kafka introduction?
Continue with Kafka architecture, then topics, partitions and offsets, then producers and consumers. After that, learn about brokers and clusters, fault tolerance and security to run Kafka reliably in production.