Introduction to Kafka & Event Streaming

7 min read

Introduction to Kafka & Event Streaming

Hello there. Welcome to the Apache Kafka course.

We are about to step into the world of Event Streaming. This guide is designed to be calm, structural, and strictly educational. We will build your understanding from the ground up—starting with the alphabet of data before forming words and sentences.

There is no rush. Take a deep breath. Let us begin with the fundamental nature of data in motion.


1. Welcome to the Stream: What is Event Streaming?

To understand Kafka, we must first understand the paradigm it serves.

Definition: Event

In the digital realm, an Event is a record that states "something happened." It is a discrete piece of data describing an occurrence at a specific point in time.

An event is immutable (it cannot be changed once it has occurred) and typically consists of:

  • Key: The identifier (e.g., "User_101").
  • Value: The data payload (e.g., "Clicked_Signup_Button").
  • Timestamp: When it happened.

Definition: Event Streaming

Event Streaming is the practice of capturing data in real-time from event sources (like databases, sensors, mobile devices) in the form of streams of events; storing these event streams durably for later retrieval; and manipulating, processing, and reacting to the event streams in real-time as well as retrospectively.

The Shift: Batch vs. Stream

Historically, systems relied on Batch Processing.

  • Batch: Data is collected over time (e.g., a day), stored in a file, and processed all at once. This is high-latency. The system is "blind" until the batch runs.
  • Stream: Data is processed as it is generated. This is low-latency. The system reacts immediately.

Concept: If Batch Processing is checking your mailbox once a day, Event Streaming is carrying a walkie-talkie. (Note: This is a comparison, but we will strictly define the technical mechanism next).

🧱 Fact: The concept of the "Log" (an append-only sequence of records) which powers Kafka is actually one of the oldest data structures in computer science, predating modern databases.


2. The Problem Kafka Solves: Moving Beyond Traditional Message Queues

Before Kafka, systems communicated using two primary patterns: Point-to-Point connections or Traditional Message Queues.

The Problem: Spaghetti Architecture

As a system grows, you might need to send data from a "Signup Service" to an "Email Service", "Analytics Service", and "Database".

  • If you connect them directly, you create a web of dependencies.
  • If the "Analytics Service" goes down, the "Signup Service" might fail or lose data.
  • This tight coupling creates a fragile system.

The Limitation of Traditional Queues (e.g., RabbitMQ, ActiveMQ)

Traditional message queues solve the coupling problem but introduce a data persistence limitation.

  1. Transient Data: In a traditional queue, once a message is consumed (read), it is deleted.
  2. Single Consumer Focus: Usually, a message is intended for one worker to process.
  3. No Replay: If you deploy a new service today that needs data from yesterday, a traditional queue cannot help you; that data is gone.

The Kafka Solution: The Distributed Commit Log

Kafka is not just a queue; it is a Distributed Event Streaming Platform.

  • Durability: Kafka writes events to a disk-based log. It does not delete them immediately after consumption.
  • Retention: Events stay for a configured time (e.g., 7 days) or size.
  • Decoupling: Producers write to the log. Consumers read from the log at their own pace.
  • Multi-Consumer: Multiple independent services can read the same stream of events without interfering with each other.

Concept: Kafka acts as the Central Nervous System. All data signals pass through it, available to any organ (service) that needs them, now or later.


3. The Big Picture: Brokers, Topics, Producers, and Consumers

Let us strictly define the four pillars of the Kafka architecture.

1. Topic

A Topic is a logical category or feed name to which records are published.

  • It is the "folder" or "table" concept in Kafka.
  • Topics are append-only logs.
  • Partitioning: To scale, a topic is split into Partitions. This allows the topic to be hosted on multiple servers and read in parallel.

2. Producer

A Producer is a client application that publishes (writes) events to the Kafka cluster.

  • The producer decides which topic (and strictly speaking, which partition) to send data to.
  • It does not care who reads the data.

3. Consumer

A Consumer is a client application that subscribes to (reads) topics.

  • Offset: The consumer tracks its own progress. It marks the index of the last message it read. This is called the Offset.
  • Because the consumer tracks the offset, it can "rewind" and re-read data if needed (replayability).

4. Broker

A Broker is a single Kafka server.

  • It receives messages from producers.
  • It assigns offsets to them.
  • It commits the messages to storage on disk.
  • A Cluster is a group of brokers working together.

🧠 Did you know? LinkedIn originally built Kafka to handle their massive activity stream data (likes, views, clicks) because existing message queues couldn't handle the throughput. They open-sourced it in 2011.


4. Your First Kafka Cluster: Local Environment Setup via Docker

We will set up a modern Kafka cluster using KRaft (Kafka Raft Metadata).

  • Legacy Note: Older Kafka versions required a separate system called Zookeeper. Modern Kafka (v3.3+) enables KRaft mode, removing this dependency for a simpler architecture. We will use the modern approach.

Prerequisites

  • Docker installed.
  • Docker Compose installed.

Step 1: Create the Configuration

Create a file named docker-compose.yml in a new folder.

yaml
version: '3'
services:
  kafka:
    image: apache/kafka:latest
    container_name: kafka
    ports:
      - "9092:9092"
    environment:
      # ID for this specific broker node
      KAFKA_NODE_ID: 1
      # Roles this node plays: it is both a broker (data) and controller (metadata)
      KAFKA_PROCESS_ROLES: broker,controller
      # Listeners: Standard communication channels
      KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093
      # Advertised Listeners: What the broker tells clients to connect to
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
      # Listener for the controller plane
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      # Mapping security protocols
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT
      # Voters for the consensus algorithm (KRaft)
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093
      # Where to store data for durability
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_NUM_PARTITIONS: 3

Step 2: Start the Cluster

Open your terminal in the folder and run:

bash
docker-compose up -d

Wait a few moments for the container to stabilize.

Step 3: Create a Topic

We will execute commands inside the running container.

bash
docker exec -it kafka /opt/kafka/bin/kafka-topics.sh \
--create \
--topic user-events \
--bootstrap-server localhost:9092 \
--partitions 1 \
--replication-factor 1
  • --topic user-events: The name of our stream.
  • --bootstrap-server: The address of the broker.

Step 4: Produce Events (Write)

We will open a console producer to type messages manually.

bash
docker exec -it kafka /opt/kafka/bin/kafka-console-producer.sh \
--topic user-events \
--bootstrap-server localhost:9092

Now, type a few lines and hit Enter after each:

user_1: logged_in
user_1: viewed_product
user_2: purchased_item

(Press Ctrl+C to exit).

Step 5: Consume Events (Read)

Now, let's read them back.

bash
docker exec -it kafka /opt/kafka/bin/kafka-console-consumer.sh \
--topic user-events \
--from-beginning \
--bootstrap-server localhost:9092

You should see the messages you typed appear on the screen.

Observation

Notice that you read the messages after you wrote them. Unlike a traditional queue where reading often removes the message, you can run that Consumer command again, and you will see the messages again. They are persisted in the Log.


Summary

You have successfully:

  1. Defined Event Streaming and contrasted it with Batch.
  2. Identified Kafka's role as a durable, distributed commit log.
  3. Learned the terminology: Topic, Broker, Producer, Consumer.
  4. Spun up a KRaft-based Kafka cluster and exchanged your first events.

The foundation is laid. The stream is flowing.


📚 References & Further Reading

Challenge

You are tasked with setting up a single-node, KRaft-based Kafka cluster and interacting with it. Your goal is to write both the Docker Compose configuration and the necessary shell commands to manage a topic.

Part 1: Docker Compose Configuration

Write a complete docker-compose.yml file to launch a single Kafka broker. The service should be named kafka and use the confluentinc/cp-kafka:latest image. Configure it with the following specifications:

  • The container name must be kafka.
  • Map host port 9092 to the container's port 9092.
  • It must run in KRaft mode (combined broker and controller roles) without a Zookeeper dependency.
  • Use the cluster ID: MkU3OEVBNTcwNTJENDM2Qo.
  • The advertised listener for clients should be on localhost:9092.

Part 2: Shell Commands

After conceptually starting the cluster, write the sequence of shell commands to perform the following actions. Assume you are executing these commands from within another container on the same Docker network or have the Kafka binaries on your host.

  1. Create Topic: Create a topic named order-confirmations with a single partition and a replication factor of 1. The command must target the broker at localhost:9092.
  2. Produce Messages: Write the command to start the console producer to send messages to the order-confirmations topic. The producer must be configured to parse keys, using a colon (:) as the separator.
  3. Consume Messages: Write the command to start a console consumer that reads all messages from the order-confirmations topic, starting from the very first message (the beginning of the log).

Expected result

Your submission should contain a valid docker-compose.yml file and three distinct shell commands as described.

Docker Compose Configuration

The docker-compose.yml should look like this:

yaml
services:
  kafka:
    image: confluentinc/cp-kafka:latest
    container_name: kafka
    ports:
      - '9092:9092'
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: 'CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT'
      KAFKA_ADVERTISED_LISTENERS: 'PLAINTEXT://localhost:9092'
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_PROCESS_ROLES: 'broker,controller'
      KAFKA_CONTROLLER_QUORUM_VOTERS: '1@localhost:9093'
      KAFKA_LISTENERS: 'PLAINTEXT://localhost:9092,CONTROLLER://localhost:9093'
      KAFKA_INTER_BROKER_LISTENER_NAME: 'PLAINTEXT'
      KAFKA_CONTROLLER_LISTENER_NAMES: 'CONTROLLER'
      CLUSTER_ID: 'MkU3OEVBNTcwNTJENDM2Qo'

Shell Commands

The three shell commands should be as follows:

  1. Create Topic
    sh
    kafka-topics --create --topic order-confirmations --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1
  2. Produce Messages
    sh
    kafka-console-producer --topic order-confirmations --bootstrap-server localhost:9092 --property "parse.key=true" --property "key.separator=:"
  3. Consume Messages
    sh
    kafka-console-consumer --topic order-confirmations --bootstrap-server localhost:9092 --from-beginning
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.