00:00

Apache Kafka Introduction

Last updated:

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.

Direct connections compared with Kafka Without Kafka, the orders service connects directly to the inventory, payments and email services, which means three connections to build and maintain, and every new service needs another connection. With Kafka, the orders service publishes each event once to the orders topic, and the inventory, payments and email services each read from the topic independently, so a new service can simply start reading. WITHOUT KAFKAWITH KAFKA Orders Inventory Payments Email 3 direct connections to build and maintain each new service = another connection Orders publish once Kafkaorders topic Inventory Payments Email each service reads the topic on its own new service = just start reading
Figure 1: Without Kafka, the order service must call every other service directly. With Kafka, it publishes each event once, and any number of services can read it without changing the order service.

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

FeatureMeaning
High throughputKafka can handle millions of messages per second across a cluster, ideal for real-time applications
ScalabilityAdd more servers (brokers) without stopping the system and spread the load across them
Fault toleranceData is copied to several brokers; if one fails, the data is still available from another
DurabilityMessages are stored on disk, not just in memory, so data survives restarts
Real-time processingData is processed as it arrives, for live tracking, monitoring and streaming analytics
Multiple consumersMany consumers can read the same data independently, each tracking its own position
Loose couplingProducers 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. Kafka Architecture

Here is a simple diagram showing the main components of a Kafka system:

Apache Kafka architecture Producers, an order service and a web app, publish events to a Kafka cluster of three brokers. The topic orders has three partitions with replication factor 2: broker 1 leads partition 0 and holds a copy of partition 2, broker 2 leads partition 1 and holds a copy of partition 0, and broker 3 leads partition 2 and holds a copy of partition 1. KRaft controllers inside the cluster manage metadata and elect partition leaders. Two consumer groups read the events independently: group A with two billing instances that share the partitions, and group B with one analytics instance. PRODUCERSKAFKA CLUSTERCONSUMERS Order Service Web App publish Topic orders: 3 partitions, replication factor 2 Broker 1 orders-P0leader orders-P2follower copy Broker 2 orders-P1leader orders-P0follower copy Broker 3 orders-P2leader orders-P1follower copy KRaft controllerscluster metadata · partition leader election Group A: billing Billing #1 Billing #2 Group B: analytics Analytics readread Partition leader (handles reads and writes) Follower copy (backup on another broker)
Figure 2: Producers write to partition leaders, followers on other brokers keep copies for fault tolerance, and each consumer group reads every event independently, with the instances in a group sharing the partitions.

Read more about Kafka Architecture

5. Core Kafka Concepts

ConceptShort meaning
Producer (app)Sends messages to Kafka topics
Consumer (app)Reads messages from Kafka topics
TopicA named channel where related Kafka messages are stored
PartitionA topic is divided into partitions for scalability and parallel processing
OffsetA unique position of a message within a partition
BrokerA Kafka server that stores and serves messages
ClusterA group of Kafka brokers working together
Consumer groupA group of consumers that share the work of reading a topic
ReplicationCopies of partitions on several brokers, for fault tolerance and high availability
LeaderThe replica that handles reads and writes for a partition
FollowerA replica that copies data from the partition leader
RetentionHow long Kafka keeps messages before removing them
RebalancingRedistributing partitions among consumers when consumers join or leave a group
ISRIn-sync replicas: followers that are fully caught up with the leader
KeyDecides which partition a message goes to; same key, same partition
SerializationConverting a Java object into bytes before sending it to Kafka
DeserializationConverting Kafka message bytes back into a Java object

6. 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.

A Kafka topic partition is an ordered log Partition 0 of the topic orders holds four events in order: offset 0 order placed, offset 1 payment received, offset 2 order packed and offset 3 order shipped. New events are added at the end, at offset 4. Two consumers read the same log at their own positions: the analytics service is reading at offset 0 and the email service at offset 3. Topic orders, partition 0 offset 0 Orderplaced 1 Paymentreceived 2 Orderpacked 3 Ordershipped 4 next event older events → newer events Analyticsreads at offset 0 Email servicereads at offset 3 New eventsadded at the end
Figure 3: A partition is an append-only log: each event gets the next offset, and every consumer keeps its own position, so Analytics and the Email service read the same events at their own pace.

7. Simple Kafka Flow

  1. A producer sends a message to a Kafka topic.
  2. Kafka stores the message safely on disk and copies it to other brokers.
  3. A consumer reads the message from the topic.
  4. The consumer processes the message and records how far it has read.

8. Running Kafka on Your Computer

The quickest way to try Kafka is with Docker:

Start Kafka 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:

Start Kafka from the download
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.

9. 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>.)

Create a topic
bin/kafka-topics.sh --create --topic orders \
  --bootstrap-server localhost:9092 --partitions 3
Send messages (type a line and press Enter)
bin/kafka-console-producer.sh --topic orders --bootstrap-server localhost:9092
> Order placed: book
> Order placed: laptop
Read messages
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.

10. Your First Kafka Program in Java

Add the client library to your Maven project:

pom.xml
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>4.0.0</version>
</dependency>
HelloKafkaProducer.java
package com.javabytechie.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");
        }
    }
}
HelloKafkaConsumer.java
package com.javabytechie.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.

11. Kafka with Spring Boot

With Spring Boot, add the spring-kafka dependency and set the broker address:

application.yml
spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      group-id: order-notifications
      auto-offset-reset: earliest
OrderEvents.java
package com.javabytechie.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.

12. Kafka vs Traditional Message Queues

AspectKafkaTraditional message queue
StorageKeeps messages for a set time, even after they are readUsually removes messages once they are acknowledged
ReadersMany independent consumer groups read the same dataEach message usually goes to one consumer
ReplayYes, by moving back to an earlier offsetUsually not
OrderingGuaranteed within a partitionPer queue, often weaker with several consumers
ScaleVery high throughput through partitionsGood for moderate volumes
StrengthsEvent streaming, data pipelines, historyTask queues, routing rules, per-message features

See Kafka vs RabbitMQ for a detailed comparison.

13. Where Kafka Is Commonly Used

Use caseExample
Microservices communicationServices publish and react to events such as “OrderPlaced”
Real-time data pipelinesMove data from databases and apps into data warehouses continuously
Log aggregationCollect logs from many servers in one place
Streaming analyticsLive dashboards, fraud detection, recommendations
Event-driven architecturesKeep a history of every business event
Activity trackingClicks, searches and page views on websites and apps
IoT and sensorsReadings from vehicles, devices and machines

See Kafka Use Cases for real-world examples.

14. Advantages and Limitations

14.1 Advantages

  • Very high throughput and low latency.
  • Scales horizontally by adding brokers.
  • Durable, replicated storage.
  • Many consumers and replay of history.
  • Large ecosystem and community.

14.2 Limitations

  • More moving parts than a simple queue; needs operational know-how.
  • Ordering only within a partition.
  • Not designed for request-reply or per-message priorities.
  • Not a query database; data is read in order, not searched.
  • Default message size limit of about 1 MB.

15. 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.