Docsity

Kafka/EXTRACT TRANSFORM LOAD, Study notes of Data Warehousing

Toggle sidebar
bg1
UNIT 2
APACHE KAFKA
Distributed Event Streaming Platform
Rahul Inchal
Topics Covered
Introduction to Apache Kafka
Need for Kafka in Modern Data Systems
Kafka vs Traditional Message Brokers: RabbitMQ, AWS SQS
Kafka Architecture
Kafka Cluster and Broker
Topics and Partitions
Kafka Producer and Consumer
Message Serialization: Avro, Protobuf and Schema Registry
Consumer Groups
Single-Node and Multi-Broker Kafka Setup
Basic Kafka Commands and Operations
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36

Partial preview of the text

Download Kafka/EXTRACT TRANSFORM LOAD and more Study notes Data Warehousing in PDF only on Docsity!

UNIT 2

APACHE KAFKA

Distributed Event Streaming Platform

Rahul Inchal

Topics Covered

Introduction to Apache Kafka Need for Kafka in Modern Data Systems Kafka vs Traditional Message Brokers: RabbitMQ, AWS SQS Kafka Architecture Kafka Cluster and Broker Topics and Partitions Kafka Producer and Consumer Message Serialization: Avro, Protobuf and Schema Registry Consumer Groups Single-Node and Multi-Broker Kafka Setup Basic Kafka Commands and Operations

Table of Contents

  • Table of Contents
    1. Introduction to Apache Kafka
    • 1.1 Definition
    • 1.2 The Easiest Way to Understand Kafka
    • 1.3 History and Evolution
    • 1.4 What exactly is an Event?
    • 1.5 The Three Capabilities of Kafka
    • 1.6 The Kafka Ecosystem
    • 1.7 Where Kafka is Used โ€” Real Applications
    1. Need for Kafka in Modern Data Systems
    • 2.1 How Data Systems Have Changed
    • 2.2 Problem 1: The N ร— M Integration Problem
    • 2.3 The Kafka Solution: N + M
    • 2.4 Problem 2: Batch Processing is Too Slow
    • 2.5 Problem 3: Traditional Queues Cannot Replay
    • 2.6 Problem 4: Tight Coupling Between Services
    • 2.7 Summary of Kafka's Advantages
    1. Kafka vs Traditional Message Brokers (RabbitMQ, AWS SQS)
    • 3.1 Two Fundamentally Different Philosophies
    • 3.2 RabbitMQ in Brief
    • 3.3 AWS SQS in Brief
    • 3.4 Full Comparison Table
    • 3.5 A Simple Decision Guide
    1. Kafka Architecture
    • 4.1 The Complete Architecture
    • 4.2 Every Component Explained
    • 4.3 How Data is Physically Stored
    • 4.4 Replication, Leader and ISR
    • 4.5 ZooKeeper versus KRaft
    • 4.6 Why Kafka is Extremely Fast
    1. Kafka Cluster and Broker
    • 5.1 What is a Broker?
    • 5.2 What is a Cluster?
    • 5.3 The Controller Broker
    • 5.4 What Happens When a Broker Fails โ€” Step by Step
    • 5.5 Fault Tolerance and Replication Factor
    • 5.6 Important Broker Configuration Properties
    1. Topics and Partitions
    • 6.1 Topic
    • 6.2 Partition
    • 6.3 The Ordering Rule โ€” Explained With an Example
    • 6.4 How the Partition is Chosen
    • 6.5 Offsets
    • 6.6 Retention and Log Compaction
    • 6.7 Choosing the Number of Partitions
    1. Kafka Producer and Consumer
    • 7.1 The Kafka Producer
    • 7.2 The Kafka Consumer
    • 7.3 Message Delivery Semantics
    1. Message Serialization: Avro, Protobuf and Schema Registry
    • 8.1 What is Serialization and Why is it Needed?
    • 8.2 Why Plain JSON is a Bad Idea at Scale
    • 8.3 Apache Avro
    • 8.4 Protocol Buffers (Protobuf)
    • 8.5 Comparison of Serialization Formats
    • 8.6 Schema Registry
    1. Consumer Groups
    • 9.1 What is a Consumer Group?
    • 9.2 The Golden Rules
    • 9.3 Group Sizes โ€” Three Cases
    • 9.4 Two Groups Reading the Same Topic
    • 9.5 Group Coordinator and Group Leader
    • 9.6 Rebalancing
    • 9.7 Partition Assignment Strategies
    • 9.8 Important Consumer Group Settings
    • 9.9 Consumer Lag โ€” The Key Metric
    • 9.10 Scaling a Consumer Group โ€” Worked Example
    1. Single-Node and Multi-Broker Kafka Setup
    • 10.1 Prerequisites
    • 10.2 Single-Node Single-Broker Setup
    • 10.3 Single-Node Multi-Broker Setup
    • 10.4 Multi-Node (True Distributed) Cluster
    • 10.5 KRaft Mode Setup (No ZooKeeper)
    • 10.6 Running Kafka With Docker (Quick Alternative)
    • 10.7 Common Setup Mistakes
    1. Basic Kafka Commands and Operations
    • 11.1 Topic Commands
    • 11.2 Producer Commands
    • 11.3 Consumer Commands
    • 11.4 Consumer Group Commands
    • 11.5 Configuration Commands
    • 11.6 Testing and Maintenance Commands
    • 11.7 Quick Command Reference
    1. End-to-End Case Study: A Food Delivery App
    • 12.1 The Requirement
    • 12.2 The Design
    • 12.3 Design Decisions Explained
    • 12.4 What Happens When Things Go Wrong
    1. Summary and Quick Revision
    • 13.1 Glossary
    • 13.2 Points to Remember
  1. Introduction to Apache Kafka

1.1 Definition

Apache Kafka is an open-source, distributed event streaming platform used to publish,

store, process and subscribe to streams of records in real time.

Let us break this definition into simple pieces, because every word in it is important.

Word in the Definition What It Actually Means Open-source Free to use, source code is public, maintained by the Apache Software Foundation Distributed Runs on many servers (called brokers) at the same time, not on one machine Event / Record A small piece of data describing "something that happened" Streaming Data keeps flowing continuously instead of arriving in one big batch Publish Applications write data into Kafka Subscribe Applications read data from Kafka Store Kafka keeps the data safely on disk for a configured time Real time Data becomes available to readers within milliseconds

1.2 The Easiest Way to Understand Kafka

Imagine a very long notebook kept in a library. The notebook has the following rules:

โ— Anyone can come and write a new line, but only at the end of the notebook.

Nothing already written can be changed or erased.

โ— Every line gets a line number automatically: 0, 1, 2, 3, and so on.

โ— Many readers can read the notebook at the same time. Each reader keeps a

bookmark showing which line they have reached.

โ— Reading a line does not remove it. Ten different readers can read line number 57

independently.

โ— The library makes photocopies of the notebook and stores them in other rooms,

so if one room catches fire, no data is lost.

โ— Very old pages are thrown away after a fixed number of days to save space.

That notebook is exactly what Kafka is. In Kafka language: the notebook is a partition,

the line number is the offset, the writers are producers, the readers are consumers, the

bookmark is a committed offset, the photocopies are replicas, and throwing away old

pages is retention.

+-------------------------------------------------------+ | Key | "user_101" | | | decides the partition; may be null | +------------+------------------------------------------+ | Value | {"item":"Laptop","amount":45000} | | | the actual business data (bytes) | +------------+------------------------------------------+ | Timestamp | 2026-09-18T10:35:12Z | | | when it happened or when it was written | +------------+------------------------------------------+ | Headers | source=mobile-app, version=2 | | | optional metadata, like HTTP headers | +------------+------------------------------------------+ | Partition | 2 (assigned by the producer) | | Offset | 57 (assigned by the broker) | +------------+------------------------------------------+ Figure 1.2 โ€” Detailed structure of a Kafka record

Important point about size: Kafka is designed for small messages. The default maximum

message size is 1 MB (message.max.bytes). If you need to send a 500 MB video, you store

the video in cloud storage such as S3 and send only the URL through Kafka. This is called

the claim-check pattern.

1.5 The Three Capabilities of Kafka

Kafka is often confused with a message queue, but it actually combines three different

systems into one.

Capability Traditionally Provided By What Kafka Gives You Example Messaging RabbitMQ, ActiveMQ, JMS Publishโ€“subscribe between applications Order service notifies billing service Storage Databases, HDFS Durable, replicated, ordered log on disk Keep 7 days of orders and replay them Stream processing Spark Streaming, Flink Filter, join and aggregate data as it flows Count orders per city every minute

1.6 The Kafka Ecosystem

Around the core broker, Kafka provides four APIs and several supporting tools. You

should know their names and purposes.

Component Purpose Producer API Lets an application publish records to topics Consumer API Lets an application subscribe to topics and read records Streams API A Java library for transforming, joining and aggregating streams Connect API Ready-made connectors to move data in and out of Kafka without writing code

Component Purpose Admin API Programmatically create topics, change configs, inspect the cluster Schema Registry Stores and versions the schemas of messages (Confluent component) ksqlDB Lets you write SQL queries over Kafka streams MirrorMaker 2 Replicates topics between two different Kafka clusters

1.7 Where Kafka is Used โ€” Real Applications

Use Case How Kafka Helps Real Example Activity tracking Every click and page view becomes an event LinkedIn, Flipkart, YouTube recommendations Log aggregation Logs from 1000 servers flow into a single stream Centralised logging into Elasticsearch Metrics and monitoring Application metrics streamed to dashboards Live server-health dashboards Real-time analytics Aggregations computed within seconds of an event Sales in the last 5 minutes by city Event-driven microservices Services react to events instead of calling each other Uber trip lifecycle events Change Data Capture Every database insert/update becomes an event Syncing MySQL to a data warehouse IoT and telemetry Millions of sensors publish readings continuously Smart meters, vehicle GPS tracking Fraud detection Each transaction checked against rules in milliseconds Credit-card fraud alerts Event sourcing The event log itself becomes the source of truth Banking ledgers, audit trails

Website ---+ +---> Database | +----------------+ | Mobile ---+---> | | ----+---> Analytics | | KAFKA | | Sensors ---+---> | (central hub) | ----+---> Email Service | | | | Billing ---+---> +----------------+ ----+---> Data Warehouse PRODUCERS one shared CONSUMERS source of truth Benefits:

  • Sources do not know or care who the targets are
  • A target can go down and catch up later
  • New target = new consumer group, zero producer change Figure 2.2 โ€” Kafka as the central nervous system of the company

2.4 Problem 2: Batch Processing is Too Slow

In the old ETL model, data was extracted from databases at night, transformed, and

loaded into a warehouse by morning. This means business decisions are always based on

data that is up to 24 hours old.

Example where this fails: A credit-card company detects fraud using a nightly batch job.

A stolen card is used at 10 AM. The fraud is detected at 2 AM the next day โ€” sixteen

hours and twenty transactions too late. With Kafka the transaction event reaches the

fraud engine within 50 milliseconds and the card is blocked before the second purchase

completes.

BATCH (old) STREAMING (Kafka) 10:00 event happens 10:00:00.000 event happens ...waiting... 10:00:00.020 written to Kafka ...waiting... 10:00:00.050 fraud engine reads 02:00 (next day) job runs 10:00:00.080 card blocked 02:30 fraud detected Delay: 16 hours Delay: 80 milliseconds Figure 2.3 โ€” Batch delay versus streaming delay

2.5 Problem 3: Traditional Queues Cannot Replay

In a traditional message queue, a message is deleted as soon as a consumer

acknowledges it. That sounds efficient, but it creates a serious operational problem.

Scenario: A consumer has a bug in its calculation logic. It has processed 10 lakh

messages incorrectly over three days. With a traditional queue, those messages are gone

forever โ€” the data cannot be recovered. With Kafka, the team fixes the bug, resets the

consumer group offset back three days, and simply reprocesses everything correctly.

This ability to rewind is one of the biggest practical reasons companies choose Kafka.

2.6 Problem 4: Tight Coupling Between Services

When Service A calls Service B directly over HTTP, three things go wrong:

โ— Availability coupling: if B is down, A fails too.

โ— Speed coupling: if B is slow, A becomes slow.

โ— Knowledge coupling: A must know B's address, protocol and data format.

With Kafka, A only writes an event and moves on. If B is down, the event waits safely in

Kafka and B processes it when it comes back. This is called temporal decoupling.

TIGHT COUPLING LOOSE COUPLING (Kafka) +---+ HTTP +---+ +---+ +-------+ +---+ | A | --------> | B | | A | ---> | KAFKA | ---> | B | +---+ (blocks) +---+ +---+ +-------+ +---+ | If B is down -> A fails If B is down -> event waits If B is slow -> A waits A is never affected Adding C -> change A Adding C -> just add a consumer Figure 2.4 โ€” Coupling before and after Kafka

2.7 Summary of Kafka's Advantages

Advantage Explanation How Kafka Achieves It High throughput Millions of messages per second Sequential disk I/O, batching, zero-copy, compression Horizontal scalability Grow by adding machines, not bigger machines Partitions spread across many brokers Durability Data survives crashes Written to disk and replicated to other brokers Fault tolerance Cluster keeps working when a broker dies Leader election from the ISR Decoupling Producers and consumers are independent Pull model plus shared topics Replay Old data can be read again Retention based on time, not on consumption Ordering Events are read in the order written Strict ordering inside each partition Low latency Typically under 10 milliseconds In-memory page cache and efficient protocol Multiple consumers Same data serves many teams Independent consumer groups

โ— Weaknesses: lower throughput, no replay, clustering is harder, performance drops

when queues grow long.

3.3 AWS SQS in Brief

Amazon SQS is a fully managed cloud queue. There is no server to install, patch or scale

โ€” AWS handles everything. You simply call an API to send and receive messages.

Queue Type Throughput Ordering Delivery Standard Nearly unlimited Not guaranteed (best effort) At-least-once (duplicates possible) FIFO About 3,000 msg/sec with batching Strictly guaranteed Exactly-once processing

โ— Strengths: zero operations, automatic scaling, pay only for what you use, deep

integration with AWS Lambda and SNS.

โ— Weaknesses: maximum retention is 14 days, message size limit 256 KB, no replay

after deletion, AWS lock-in, one queue feeds one consumer group only (SNS is

needed for fan-out).

3.4 Full Comparison Table

Feature Apache Kafka RabbitMQ AWS SQS Category Distributed event streaming log Message broker (queue) Managed cloud queue Protocol Custom binary over TCP AMQP, MQTT, STOMP HTTPS REST API Delivery model Pull (consumer fetches) Push (broker pushes) Pull (long polling) Message retention Time/size based, default 7 days, kept after reading Deleted after acknowledgement Deleted after explicit delete, max 14 days Replay old data Yes โ€” reset the offset No No Throughput Very high, millions per second Tens of thousands per second High (Standard), low (FIFO) Latency Very low, 2โ€“10 ms Very low, under 1 ms Higher, tens of ms (HTTP) Ordering Guaranteed per partition Guaranteed per queue Only in FIFO queues Routing logic Simple: topic and partition Rich: direct, topic, fanout, headers Very simple, none Fan-out to many readers Native, via consumer groups Needs a fanout exchange and extra queues Needs SNS plus several queues Message size Default 1 MB, configurable Up to 128 MB (not advised) 256 KB (2 GB via S extension)

Feature Apache Kafka RabbitMQ AWS SQS Priority messages Not supported Supported Not supported Delayed delivery Not built in Supported via plugin Supported up to 15 minutes Scaling Add brokers and partitions Add nodes, clustering is complex Fully automatic by AWS Storage model Disk log, replicated Mainly memory, disk optional Managed by AWS Operational effort High โ€” you run the cluster Medium Almost zero Cost model Server and storage cost Server cost Per request and per GB Best suited for Streaming, analytics, event sourcing, very high volume Task queues, complex routing, RPC Simple decoupling inside AWS

3.5 A Simple Decision Guide

WHICH ONE SHOULD I USE? Do you need to REPLAY old messages? YES ----------------------------> KAFKA NO | v Is the volume more than ~100k msg/sec? YES ----------------------------> KAFKA NO | v Do many different teams need the SAME data? YES ----------------------------> KAFKA NO | v Do you need priority / delay / complex routing? YES ----------------------------> RABBITMQ NO | v Are you fully on AWS and want zero operations? YES ----------------------------> AWS SQS NO ----------------------------> RABBITMQ Figure 3.3 โ€” Decision flow for choosing a messaging system

Practical note: These systems are not enemies. A typical large company uses RabbitMQ

or SQS for small internal task queues such as "send this email", and Kafka for the

high-volume event backbone that feeds analytics, machine learning and the data

warehouse.

Component Role Key Point to Remember ZooKeeper / KRaft The coordination layer KRaft is the modern replacement Consumer Group A team of consumers Shares partitions; scales the reading side

4.3 How Data is Physically Stored

A partition is not one giant file. Kafka splits each partition into segment files so that old

data can be deleted cheaply by simply removing whole files.

/kafka-logs/orders-0/ <-- topic "orders", partition 0 00000000000000000000.log <-- segment: actual messages 00000000000000000000.index <-- offset -> byte position 00000000000000000000.timeindex <-- timestamp -> offset 00000000000000123456.log <-- next segment starts at 123456 00000000000000123456.index leader-epoch-checkpoint

  • The file name is the base offset of that segment.
  • Only the newest segment is "active" and receives writes.
  • Retention deletes whole old segment files - very cheap.
  • The .index file lets Kafka jump directly to an offset instead of scanning the file from the start. Figure 4.2 โ€” Segment files on disk inside one partition

4.4 Replication, Leader and ISR

Replication is how Kafka survives hardware failure. Each partition is copied to several

brokers. One copy is the leader; the rest are followers.

โ— All reads and writes go to the leader only. Followers never serve clients; they only

copy data. This keeps consistency simple.

โ— Followers continuously fetch from the leader, just like a consumer would.

โ— A follower that is up to date is part of the ISR (In-Sync Replica set). A follower that

falls behind by more than replica.lag.time.max.ms is removed from the ISR.

โ— If the leader dies, the controller picks a new leader from the ISR โ€” never from an

out-of-sync replica, because that would lose data.

Topic "orders", Partition 0, Replication Factor = 3 +-----------+ copy +-----------+ | Broker 1 | ------------> | Broker 2 | | P0 LEADER | | P0 follow | +-----------+ \ +-----------+ ^ \ copy | \ +-----------+ write/read | ------> | Broker 3 | | | P0 follow | [Producer/Consumer] +-----------+ ISR = { Broker1, Broker2, Broker3 } Broker 1 crashes: ISR = { Broker2, Broker3 } -> Broker 2 becomes LEADER

Clients automatically reconnect to the new leader. RF = 3 tolerates the loss of 2 brokers. Figure 4.3 โ€” Replication and automatic leader election

High Watermark

A record is only visible to consumers after it has been copied to all in-sync replicas. The

offset up to which all ISR members have the data is called the high watermark. This

prevents a consumer from reading a record that could still be lost if the leader crashed

immediately after writing it.

Leader log: [0][1][2][3][4][5][6] Follower A: [0][1][2][3][4] Follower B: [0][1][2][3][4] ^ High Watermark = 4 Consumers can read offsets 0 to 4 only. Offsets 5 and 6 exist but are not yet safe. Figure 4.4 โ€” The high watermark protects consumers from unsafe reads

4.5 ZooKeeper versus KRaft

For most of its life, Kafka needed a second system called ZooKeeper to store metadata

and elect the controller. This meant running and monitoring two distributed systems.

KRaft removes that dependency by letting Kafka manage its own metadata using the

Raft consensus algorithm.

Point ZooKeeper Mode (old) KRaft Mode (new) Metadata storage Separate ZooKeeper ensemble Internal Kafka topic @metadata Processes to run ZooKeeper cluster + Kafka brokers Kafka only (controller and broker roles) Setup complexity Higher โ€” two systems Lower โ€” one system Partition limit Around 200,000 partitions Millions of partitions Controller failover Slow โ€” must reload all metadata Almost instant โ€” metadata already in memory Security Two systems to secure separately One security model Status Deprecated; removed in Kafka 4.0 Production-ready from Kafka 3.

4.6 Why Kafka is Extremely Fast

Students are often asked this in exams. There are six main reasons.

1. Sequential disk writes. Kafka only appends to the end of a file. Sequential disk

access is hundreds of times faster than random access and can even beat random

access in RAM.

5. Kafka Cluster and Broker

5.1 What is a Broker?

A broker is one Kafka server process running on one machine. Its job is simple but

critical: accept writes, store them on disk, and serve reads.

โ— Unique identity: every broker has an integer ID set by broker.id (or node.id in

KRaft). No two brokers in a cluster may share an ID.

โ— Stores partitions: a broker holds a subset of the partitions of many topics, as

segment files under log.dirs.

โ— Stateless about consumers: the broker does not remember which consumer read

which message. That is the consumer's job. This is why Kafka scales so well.

โ— Acts as a bootstrap server: a client connects to any one broker and immediately

receives the full cluster metadata โ€” the list of all brokers, topics, partitions and

leaders.

โ— Handles replication: as a leader it serves followers; as a follower it fetches from

other leaders.

5.2 What is a Cluster?

A cluster is a group of brokers that know about each other and share the work. Partitions

and replicas are distributed so that no broker holds all the leaders and no two replicas of

the same partition sit on the same machine.

KAFKA CLUSTER (3 brokers) +-------------+ +------------+ +------------+ | Broker 0 | | Broker 1 | | Broker 2 | | (Controller)| | | | | | | | | | | | orders-P0 L | | orders-P0 F| | orders-P0 F| | orders-P1 F | | orders-P1 L| | orders-P1 F| | orders-P2 F | | orders-P2 F| | orders-P2 L| +-------------+ +------------+ +------------+ Topic "orders": 3 partitions, replication factor 3 Each broker leads exactly one partition -> balanced load Every partition has a copy on all 3 brokers -> safe L = Leader, F = Follower Figure 5.1 โ€” Partitions and replicas spread across a 3-broker cluster

5.3 The Controller Broker

Exactly one broker in the cluster plays an additional role called the controller. It is elected

automatically. Its responsibilities are:

โ— Watching which brokers are alive and which have failed.

โ— Electing a new leader for every partition that lost its leader.

โ— Handling topic creation, deletion and partition count changes.

โ— Propagating updated metadata to all other brokers.

โ— Managing partition reassignment when brokers are added or removed.

If the controller itself fails, the remaining brokers elect a new controller within seconds.

The cluster never depends on one machine permanently.

5.4 What Happens When a Broker Fails โ€” Step by Step

1. The broker stops sending heartbeats to the controller.

2. After zookeeper.session.timeout.ms (or the KRaft equivalent), the controller marks

it as dead.

3. The controller finds every partition whose leader was on that broker.

4. For each such partition, it selects a new leader from the ISR.

5. The controller sends the updated metadata to all brokers.

6. Producers and consumers receive a NOT_LEADER error, refresh their metadata,

and reconnect to the new leader automatically.

7. When the failed broker restarts, it rejoins as a follower and copies the data it

missed until it is back in the ISR.

Total impact: a few seconds of retries inside the client libraries. Applications usually do

not even notice.

5.5 Fault Tolerance and Replication Factor

A cluster with replication factor R survives the failure of (R โˆ’ 1) brokers without losing

data.

Replication Factor Brokers That Can Fail Data Stored Used For 1 0 1 copy Local development only โ€” no safety at all 2 1 2 copies Small clusters, limited safety 3 2 3 copies Recommended standard for production 4 or more 3 or more 4+ copies Very critical data; costs more disk and network

โ— Replication factor can never be greater than the number of brokers. With 2

brokers you cannot create a topic with RF = 3.

โ— min.insync.replicas works together with acks=all. If RF = 3 and

min.insync.replicas = 2, a write succeeds only when at least 2 replicas have it. If