Apache Kafka Event-Driven Architecture

Apache Kafka and Event-Driven Architecture Explained

Network Insight · Engineering Guides

Apache Kafka and
Event-Driven Architecture Explained

Engineering reliable, scalable and fault-tolerant event streaming platforms for distributed applications, microservices, cloud infrastructure and real-time data processing.

Distributed Systems Apache Kafka Event Streaming Microservices KRaft Data Engineering
DISTRIBUTED EVENT STREAMING ARCHITECTURE ILLUSTRATIVE EVENT FLOW
PRODUCERS KAFKA CLUSTER CONSUMERS TOPIC: ORDER EVENTS Order Service Payment Service Application API OrderCreated PaymentReceived OrderUpdated BROKER 01 P0 · LEADER P2 · FOLLOWER BROKER 02 P1 · LEADER P0 · FOLLOWER BROKER 03 P2 · LEADER P1 · FOLLOWER Inventory Analytics Notifications Consumer Group A Consumer Group B Consumer Group C KRaft Controller Quorum Metadata · Consensus · Cluster Management
Event flow Partition leader Replica Metadata control plane

The Architectural Shift Towards Events

Modern distributed applications are rarely composed of a single application communicating with a single database. Instead, they consist of interconnected microservices, cloud platforms, databases, analytics systems and infrastructure components that continuously generate and consume information.

Traditional synchronous communication requires one application to contact another application and wait for a response. Although this model remains essential for many workloads, excessive synchronous dependencies can introduce latency, operational coupling and cascading failures.

Event-driven architecture introduces a different communication model. Rather than requiring every participating system to communicate directly, applications publish events describing changes that have occurred. Interested applications independently consume and process those events.

Traditional Synchronous Architecture
Service A
→
Service B
→
Service C

Direct request-response dependencies can propagate delays and failures between applications.

Event-Driven Architecture
Producer
→
Kafka
→
Consumer

Producers and consumers operate independently, communicating through retained event streams.

What Is Apache Kafka?

Apache Kafka is an open-source distributed event streaming platform designed to publish, store and process continuous streams of records across distributed infrastructure.

Kafka organises records into topics, which are divided into partitions. Each partition behaves as an ordered append-only log. Producers append records, while consumers retrieve records and maintain their processing positions using offsets.

Unlike traditional destructive message queues, Kafka does not normally remove a record simply because a consumer has read it. Records remain available according to configured retention and compaction policies, allowing independent consumer groups to process or replay available historical data.

CAPABILITY 01

Publish

Applications produce records representing business events, telemetry, transactions and infrastructure state changes.

CAPABILITY 02

Store

Distributed brokers retain records in partitioned logs, with configurable replication and durability characteristics.

CAPABILITY 03

Process

Independent consumers and stream-processing applications transform, analyse and react to available event streams.

ENGINEERING PRINCIPLE

Kafka is more than a message transport mechanism. Its distributed log provides a retained record of events that multiple applications can consume independently. However, ordering is guaranteed within a partition, not across an entire multi-partition topic.

Why Kafka Matters in Modern Infrastructure

Event streaming has become an important architectural pattern for applications that must process continuous flows of information without tightly coupling every participating system.

In financial platforms, Kafka can distribute transaction events to fraud detection and analytics applications. In cloud-native environments, it can connect microservices, data pipelines and operational monitoring platforms. In network infrastructure, Kafka can transport telemetry, security events, device state changes and operational measurements into downstream processing systems.

The engineering challenge is not simply deploying Kafka. It is designing partition distribution, replication, consumer parallelism, retention, network capacity and failure recovery around the requirements of the application.

USE CASE 01

Microservices

Decouple order processing, inventory management, payments and notification systems through asynchronous business events.

USE CASE 02

Network Telemetry

Stream infrastructure measurements, security alerts and device events into monitoring and incident analysis pipelines.

USE CASE 03

AI and Data Platforms

Deliver application events and changing data to feature pipelines, analytics platforms and downstream AI services.

What You Will Learn

This engineering guide combines architectural explanations with interactive visualisations and practical failure scenarios. The objective is to understand Kafka as a distributed system, rather than simply learning its terminology.

✓ Understand asynchronous event-driven communication.
✓ Explore Kafka brokers, topics and partitions.
✓ Understand offsets, partition keys and event ordering.
✓ Investigate producer acknowledgements and retries.
✓ Explore consumer groups, rebalancing and consumer lag.
✓ Investigate replication and broker failure recovery.
✓ Understand KRaft metadata consensus and controllers.
✓ Explore stream processing and event-driven services.
✓ Troubleshoot production Kafka infrastructure.
✓ Evaluate scalability, durability and delivery trade-offs.
THE NETWORK INSIGHT LEARNING APPROACH

Observe the architecture. Follow the event. Understand the distributed state. Introduce a failure. Investigate the evidence. Explain the outcome. Engineering knowledge develops through understanding how systems behave, not simply memorising architectural definitions.

Network Insight · Engineering Guide

Apache Kafka Engineering Navigator

Explore the complete architecture of distributed event streaming, from producers and partitioned logs to real-time processing, replication, metadata coordination and production troubleshooting.

09 Engineering
Sections
09 Interactive
Explorers
03 Learning
Stages
DISTRIBUTED EVENT STREAMING ARCHITECTURE
● ARCHITECTURE VISUALISATION
PRODUCERS Applications Business events Databases CDC streams Telemetry System events KAFKA BROKER CLUSTER BROKER 01 P0 · L P1 · F P2 · F BROKER 02 P0 · F P1 · L P2 · F BROKER 03 P0 · F P1 · F P2 · L KRAFT METADATA QUORUM CONSUMERS Microservices Business logic Kafka Streams Real-time processing Analytics Data platforms OBSERVABILITY Lag · ISR · Latency CAPTURE · DISTRIBUTE · REPLICATE · PROCESS · OBSERVE
Incoming events Metadata coordination Consumer delivery Operational telemetry
ENGINEERING TABLE OF CONTENTS
09 SECTIONS TO EXPLORE
01
Foundations

Understanding Event-Driven Architecture

Events, asynchronous communication, distributed applications and loosely coupled services.

EXPLORE SECTION
→
02
Core Infrastructure

Apache Kafka Core Architecture

Brokers, clusters, clients, distributed event storage and the Kafka data plane.

EXPLORE SECTION
→
03
Distributed Storage

Topics, Partitions and Distributed Logs

Partition keys, offsets, ordering, retention and the architecture of append-only event logs.

EXPLORE SECTION
→
04
Event Ingestion

Kafka Producer Architecture

Serialization, batching, partition selection, acknowledgements, retries and idempotent publishing.

EXPLORE SECTION
→
05
Event Consumption

Consumers, Consumer Groups and Rebalancing

Consumer coordination, partition assignment, committed offsets, processing parallelism and lag.

EXPLORE SECTION
→
06
Resilience

Replication and Fault Tolerance

Leaders, followers, in-sync replicas, durability guarantees and partition failure recovery.

EXPLORE SECTION
→
07
Control Plane

KRaft and Kafka Metadata Management

Controller quorums, metadata logs, Raft consensus, leader elections and control-plane resilience.

EXPLORE SECTION
→
08
Stream Processing

Real-Time Event Processing

Kafka Streams, Kafka Connect, stateful computation, windowing, stream joins and processing guarantees.

EXPLORE SECTION
→
09
Production Engineering

Production Kafka Architecture and Troubleshooting

Capacity planning, security, observability, disaster recovery and production incident investigation.

EXPLORE SECTION
→
YOUR ENGINEERING LEARNING PATH
STAGE 01 · SECTIONS 01–03 Architecture Foundations

Understand event-driven systems, Kafka infrastructure and distributed logs.

STAGE 02 · SECTIONS 04–07 Distributed System Behaviour

Explore publishing, consumption, replication and metadata coordination.

STAGE 03 · SECTIONS 08–09 Production Engineering

Investigate real-time processing, infrastructure resilience and operational failures.

01 Engineering Fundamentals · Event Streaming

Understanding Event-Driven Architecture

Event-driven architecture changes how distributed applications communicate by replacing many direct application dependencies with asynchronous streams of meaningful state changes.

Before examining Apache Kafka's internal architecture, we must understand the distributed systems problem that event streaming is designed to solve.

Consider a modern e-commerce platform containing independent services responsible for orders, payments, inventory, fraud detection, customer notifications and business analytics. Every completed transaction may require several of these systems to react.

Connecting every application directly to every other application creates a complex dependency graph. As the number of services increases, managing availability, latency, retries and failure propagation becomes increasingly difficult.

EVENT-DRIVEN APPLICATION ARCHITECTURE ILLUSTRATIVE EVENT STREAM
EVENT SOURCE EVENT PLATFORM INDEPENDENT CONSUMERS Order Service OrderCreated Apache Kafka TOPIC: ORDERS PARTITION 0 · RETAINED LOG 104 105 106 107 108 NEW Record retention Independent consumption Replay capability ✓ ✓ ✓ PUBLISH Inventory Service Payment Service Analytics Platform Notification Service Reserve stock Initiate payment workflow Update order metrics Send order confirmation GROUP A GROUP B GROUP C GROUP D ONE PUBLISHED EVENT · MULTIPLE INDEPENDENT REACTIONS
Figure 1 — An order event is appended to a Kafka partition. Multiple consumer groups independently fetch the same retained record. The arrows represent logical event delivery, not unsolicited broker pushes.

1.1 — Synchronous and Asynchronous Communication

In synchronous communication, an application sends a request to another application and waits for the corresponding response. REST APIs, database queries and many remote procedure calls follow this pattern.

Synchronous communication is particularly useful when the requesting application requires an immediate result before continuing its operation. However, each additional synchronous dependency can increase end-to-end latency and expose the requesting application to downstream failures.

Synchronous Request Chain

Order
→
Payment
→
Inventory

The order operation waits for downstream services to respond. An unavailable inventory service may delay or interrupt the request chain.

Downstream failure can block the request

Asynchronous Event Stream

Order
→
Kafka
→
Inventory

Once the event has been successfully published, inventory processing can occur independently, subject to retention and recovery requirements.

Producer and consumer processing are decoupled

Asynchronous communication does not eliminate dependencies altogether. It changes their nature. Applications become dependent on event contracts, platform availability, delivery guarantees and eventual processing rather than requiring every downstream service to respond immediately.

ARCHITECTURAL TRADE-OFF

Asynchronous communication can improve resilience and scalability, but it also introduces eventual consistency, duplicate processing risks and more complex distributed workflows. It should be selected according to business requirements rather than treated as a universal replacement for synchronous APIs.

1.2 — What Exactly Is an Event?

An event is a record describing something that has already happened within a system. It represents an observed fact or state transition that other applications may find useful.

For example, when a customer places an order, the order service may publish an OrderCreated event containing the information required by interested downstream systems.

EXAMPLE EVENT PAYLOAD · JSON
{
  "eventId": "evt-000108",
  "eventType": "OrderCreated",
  "schemaVersion": 1,
  "timestamp": "2026-11-24T13:45:00Z",
  "source": "order-service",
  "correlationId": "txn-90124",
  "data": {
    "orderId": "ORD-50182",
    "customerId": "CUST-2048",
    "amount": 149.99,
    "currency": "EUR",
    "status": "CREATED"
  }
}
EVENT ANATOMY 01

Identity

An event identifier distinguishes individual events and can help downstream applications detect duplicate processing.

EVENT ANATOMY 02

Metadata

Event type, timestamp, schema version and correlation identifiers provide context for interpretation and distributed tracing.

EVENT ANATOMY 03

Payload

The payload contains the business information describing the event. Its structure should follow an agreed and governed data contract.

This JSON structure is an example application-level event envelope, not a mandatory Kafka message format. Kafka records separately support a key, value, timestamp and optional headers. Applications choose how their event data is serialised.

1.3 — Events, Commands and Queries

Not every message exchanged between distributed applications represents an event. Understanding the distinction between events, commands and queries is important when designing service boundaries.

Message Type Purpose Example
Event Describes something that has happened. OrderCreated
Command Requests that an operation be performed. ReserveInventory
Query Requests information about existing state. GetOrderStatus
Event Stream Represents a sequence of related records. Order lifecycle events

Kafka can transport both events and commands. The architectural distinction depends on the meaning and ownership of the message rather than the transport platform itself.

1.4 — The Three Dimensions of Decoupling

Event-driven systems reduce several forms of coupling between applications. These characteristics allow services to evolve and operate more independently.

DIMENSION 01

Spatial Decoupling

Producers do not need to know the network addresses or individual identities of every downstream consumer. They publish to a shared event platform.

DIMENSION 02

Temporal Decoupling

Producers and consumers do not necessarily need to be active at the same time. Retained events allow consumers to resume processing after temporary interruptions.

DIMENSION 03

Execution Decoupling

A producer does not normally wait for every downstream consumer to complete its processing. Each consumer can operate at its own rate.

Decoupling does not remove the need for coordination. Producers and consumers must still agree on event semantics, schema compatibility, security policies and acceptable processing delays.

1.5 — Following an Event Through a Distributed System

Consider the following illustrative sequence after a customer places an order. The timings demonstrate asynchronous processing rather than measured Kafka performance.

T + 000 MS

Order Created

The order service records the new order in its application database.

T + 015 MS

Event Published

An outbox publisher or equivalent reliable publication mechanism sends the OrderCreated record to Kafka.

T + 025 MS

Record Acknowledged

The producer receives acknowledgement according to its configured durability and acknowledgement requirements.

T + 080 MS

Inventory Processing

The inventory consumer retrieves the event and attempts to reserve the required stock.

T + 140 MS

Payment Workflow

An independent payment consumer processes the event according to its business workflow. Additional coordination may be required before payment is authorised.

T + 350 MS

Analytics Updated

The analytics consumer incorporates the order event into operational reporting.

T + 2,000 MS

Notification Processed

The notification service sends an appropriate order acknowledgement to the customer.

DISTRIBUTED CONSISTENCY

Independent consumer groups do not provide a guaranteed global execution order. If payment must occur only after inventory reservation, the application must enforce that dependency through additional events, orchestration or another explicit coordination mechanism.

1.6 — Event Retention and Replay

One of Kafka's most important architectural characteristics is the separation between record retention and record consumption.

Reading a record does not normally remove it from Kafka. Instead, records remain available according to topic retention and compaction configuration. Consumers maintain their own processing positions.

INDEPENDENT CONSUMER POSITIONS RETAINED EVENT LOG
TOPIC: ORDERS · PARTITION 0 100 101 102 103 104 105 106 107 108 109 GROUP A · NEXT 102 GROUP B · NEXT 105 GROUP C · NEXT 108 READING A RECORD DOES NOT REMOVE IT FROM THE LOG
Figure 2 — Three independent consumer groups maintain different next-read positions within the same partition. A consumer can revisit earlier offsets while the corresponding records remain available.

This capability is particularly useful when recovering failed applications, rebuilding derived data, introducing new analytics consumers or investigating historical application behaviour.

Replay must nevertheless be carefully engineered. Reprocessing historical events may repeat external side effects such as sending notifications or initiating financial operations unless the consuming application implements appropriate idempotency and deduplication controls.

1.7 — What Happens When a Consumer Fails?

Suppose the analytics service becomes unavailable for thirty minutes while the order service continues publishing events.

Assuming Kafka remains available and the relevant records are retained, the order service does not need to wait for the analytics service to recover. Other independent consumer groups can continue processing events.

INCIDENT STAGE 01

Consumer Failure

The analytics application stops processing records. Its committed position stops advancing while producers continue publishing.

INCIDENT STAGE 02

Lag Accumulates

The difference between the available log end and the consumer group's committed position increases as new events arrive.

INCIDENT STAGE 03

Consumer Recovery

The recovered application resumes from its committed position, subject to offset availability, and processes its accumulated backlog.

Recovery requires sufficient processing capacity. If a recovered consumer processes events more slowly than producers generate them, its backlog will continue to increase.

PRODUCTION ENGINEERING INSIGHT

Kafka can absorb temporary differences between producer and consumer processing rates, but it does not provide unlimited buffering. Storage capacity, retention periods, consumer throughput and acceptable recovery times must be designed together.

1.8 — Engineering Challenges and Trade-Offs

Challenge Engineering Risk Design Approach
Duplicate events Repeated business operations Idempotent processing and deduplication
Event ordering Incorrect state transitions Appropriate partition keys and sequencing
Schema evolution Incompatible producers and consumers Versioned schemas and compatibility checks
Database consistency Database updated but event not published Transactional outbox and reliable publishing
Consumer lag Delayed downstream processing Monitoring, scaling and capacity planning
Distributed workflows Partially completed business transactions Saga patterns and compensating actions
Poison records Repeated processing failures Controlled retries and quarantine strategies
Event retention Unavailable historical records Retention policies and external archival

A well-designed event-driven architecture requires more than a reliable messaging platform. It requires explicit decisions about data ownership, event contracts, processing guarantees, security and operational recovery.

Kafka provides the distributed event-streaming infrastructure, but the correctness of the overall business workflow remains a responsibility of the applications and their architecture.

Engineering Takeaways

✓ Events describe observed facts and application state changes.
✓ Asynchronous communication reduces direct execution dependencies between services.
✓ Kafka retains records independently of consumer processing.
✓ Independent consumer groups can process the same event stream at different rates.
✓ Event replay requires careful handling of duplicate processing and external side effects.
✓ Event-driven architecture introduces eventual consistency and distributed coordination challenges.
✓ Platform durability and business transaction correctness are separate engineering concerns.
NETWORK INSIGHT / DISTRIBUTED SYSTEMS / 01

Event-Driven Architecture Explorer

Investigate asynchronous communication, service independence and the engineering value of retained event streams.

Orders submitted0
Events retained0
Completed orders0
Pending deliveries0
Rejected orders0
LIVE ARCHITECTURE VIEW SIMULATION ONLINE
Order Service Event producer 0 submitted Event Streaming Platform Retained event stream 0 retained events Payment Service Independent subscriber 0 processed Inventory Service Independent subscriber 0 processed Notification Service Independent subscriber 0 processed NI ENGINEERING VISUALISATION / LOGICAL EVENT FLOW
SERVICE HEALTH & BACKPRESSURE

Downstream Applications

RETAINED EVENT INSPECTOR

Order Event Stream

Select an event to inspect its JSON payload.

Waiting for an event...
INDEPENDENT EVENT REPLAY

Analytics Application

An analytics application can independently read historical events without removing them from the stream or changing another application's processing position.

0 events replayed
ENGINEERING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 01

The Unavailable Payment Service

Investigate whether asynchronous communication allows other applications to continue processing orders during a payment service outage.

1Disable the payment service.
2Generate at least five orders during the outage.
3Observe inventory and notification processing while payment events accumulate.
4Restore payment and allow its backlog to drain.
5Replay the retained events using the independent analytics application.
Investigation ready
Synchronous Communication

In this fail-fast request-response model, the order application depends on the immediate availability of every required downstream service. An unavailable dependency causes the request to be rejected.

Asynchronous Event Streaming

The producer publishes an event independently of downstream processing. Subscribers process at their own pace, while retained events support delayed consumption and replay.

02 Distributed Infrastructure · Kafka Architecture

Apache Kafka Core Architecture

Apache Kafka distributes event storage, client communication and record processing across a cluster of cooperating servers, allowing applications to scale beyond the capacity of a single messaging system.

At first glance, Kafka may appear to be a central messaging service positioned between producers and consumers. Internally, however, Kafka is a distributed storage and communication platform with multiple independently operating components.

Understanding the relationship between brokers, topics, partitions, replicas and controllers is fundamental to understanding how Kafka achieves scalability, durability and operational resilience.

3
Example Brokers
6
Partitions
3
Replication Factor
3
Controllers
DISTRIBUTED KAFKA CLUSTER TOPOLOGY ILLUSTRATIVE ARCHITECTURE
APPLICATION PRODUCERS Application API Telemetry Service Transaction Service PRODUCER CLIENT PRODUCER CLIENT PRODUCER CLIENT KAFKA DATA PLANE · TOPIC: EVENTS BROKER 01 BROKER 02 BROKER 03 P0 · LEADER P3 · LEADER P1 · REPLICA P2 · REPLICA P4 · REPLICA P5 · REPLICA P1 · LEADER P4 · LEADER P0 · REPLICA P2 · REPLICA P3 · REPLICA P5 · REPLICA P2 · LEADER P5 · LEADER P0 · REPLICA P1 · REPLICA P3 · REPLICA P4 · REPLICA INTER-BROKER REPLICATION Analytics Consumer Security Consumer Application Consumer GROUP A GROUP B GROUP C C1 C2 C3 KRaft Controller Quorum Metadata · Leadership · Cluster Coordination
Figure 1 — An illustrative Kafka cluster with three brokers, six partitions and a replication factor of three. Partition leadership is distributed across the brokers. Client paths and replication links represent logical communication rather than every individual protocol exchange.

2.1 — The Fundamental Kafka Components

Kafka's architecture can be understood through several cooperating components, each responsible for a distinct aspect of event production, storage, retrieval or cluster management.

COMPONENT 01

Producer

A client application that publishes records to Kafka topics. Producers determine partition placement using explicit partition selection, partitioning logic or record keys.

COMPONENT 02

Broker

A Kafka server that stores partition replicas, processes client requests and participates in distributed replication.

COMPONENT 03

Topic

A named logical collection of related records. Topics provide an organisational boundary for event streams and configuration policies.

COMPONENT 04

Partition

An independently ordered distributed log within a topic. Partitions provide the fundamental unit of Kafka parallelism.

COMPONENT 05

Consumer

A client application that fetches records from Kafka and processes them according to application requirements.

COMPONENT 06

Controller

A KRaft control-plane component responsible for managing cluster metadata through a replicated controller quorum.

2.2 — What Is a Kafka Broker?

A Kafka broker is an independently operating server process responsible for handling a portion of the cluster's event storage and communication workload.

Brokers accept producer requests, respond to consumer fetch requests, maintain local partition logs and communicate with other brokers to replicate partition data.

A broker does not necessarily contain every partition in a cluster. Partition placement depends on the number of brokers, replication factor and partition assignments.

INTERNAL BROKER ARCHITECTURE CONCEPTUAL CUTAWAY
PRODUCE REQUESTS FETCH REQUESTS REPLICA FETCHES NETWORK REQUEST HANDLING Listeners · Connections · Authentication · Network Threads REQUEST QUEUE PRODUCE PROCESSING FETCH PROCESSING REPLICATION HANDLING Validate and append Locate and return records Maintain replica state PARTITION LOG MANAGEMENT Log Segments · Offset Indexes · Retention · Compaction OPERATING SYSTEM PAGE CACHE PERSISTENT STORAGE Cached log data and buffered writes Partition segment files
Figure 2 — A conceptual broker cutaway. The processing blocks represent logical responsibilities, not necessarily dedicated thread pools or a mandatory execution sequence for every Kafka request.

2.3 — Inside the Broker Data Path

Kafka brokers expose network listeners that accept connections from producers, consumers and other brokers. Incoming protocol requests are handled by network and request-processing infrastructure.

When a producer sends a batch of records to a partition leader, the broker validates the request and appends accepted records to the partition log. The corresponding acknowledgement depends on producer configuration and replication state.

Consumer fetch requests retrieve records from specified partition offsets. Kafka can efficiently serve large batches of records, benefiting from sequential storage access, operating system caching and optimised network transfer mechanisms.

BROKER SUBSYSTEM 01

Network Processing

Handles client connections, protocol requests, authentication, request queues and network responses.

BROKER SUBSYSTEM 02

Log Management

Maintains partition segment files, indexes, record offsets, retention policies and configured log compaction.

BROKER SUBSYSTEM 03

Replication

Coordinates partition leader and follower behaviour, replica progress and the replication of partition records.

STORAGE ENGINEERING PRINCIPLE

A successful Kafka producer acknowledgement does not necessarily mean that every acknowledged record has been synchronously flushed to physical storage. Kafka commonly relies on replication and operating system page caching for performance. Durability must be evaluated using acknowledgement settings, replication, failure assumptions and storage configuration together.

2.4 — Topics Are Logical, Partitions Are Distributed

A topic provides a logical name for a collection of related records. Applications may use topics such as orders, network-telemetry, security-events or application-logs.

The topic itself is not a single physical log stored on a particular server. Instead, Kafka divides the topic into partitions and assigns partition replicas to brokers.

Consider the six-partition topic illustrated in Figure 1. Every partition has three replicas, one of which acts as the partition leader.

Partition Broker 01 Broker 02 Broker 03
Partition 0 Leader Follower Follower
Partition 1 Follower Leader Follower
Partition 2 Follower Follower Leader
Partition 3 Leader Follower Follower
Partition 4 Follower Leader Follower
Partition 5 Follower Follower Leader

This example distributes partition leadership evenly across three brokers. Each broker leads two partitions while hosting follower replicas for the remaining four.

The resulting architecture contains six logical partitions and eighteen physical partition replicas. Replication increases storage and network requirements, but provides additional copies of partition data that can support recovery after broker failures.

DISTRIBUTED ARCHITECTURE INSIGHT

Kafka does not have one universal data-plane leader responsible for every topic and partition. Leadership exists at partition level. A broker may simultaneously lead some partitions and follow others.

2.5 — How Kafka Clients Discover the Cluster

Kafka clients do not normally require a complete static configuration containing every broker and partition assignment.

Instead, clients initially connect to one or more addresses configured through the bootstrap.servers property. These addresses provide an entry point for discovering cluster metadata.

ILLUSTRATIVE CLIENT CONFIGURATION
# Initial Kafka cluster discovery

bootstrap.servers=broker1.example.net:9093,broker2.example.net:9093,broker3.example.net:9093

# TLS-encrypted client connection

security.protocol=SSL

# Producer identity for monitoring

client.id=network-telemetry-producer

The configuration above illustrates initial discovery and TLS transport. A working deployment may also require truststore, keystore or other authentication settings depending on the client library and security architecture.

DISCOVERY STAGE 01

Bootstrap Connection

The Kafka client establishes a connection to an available configured bootstrap broker.

DISCOVERY STAGE 02

Protocol and Security Negotiation

The client establishes the required security context and negotiates supported protocol capabilities where applicable.

DISCOVERY STAGE 03

Metadata Discovery

The client retrieves information about available brokers, topic partitions and partition leadership.

DISCOVERY STAGE 04

Direct Broker Connections

The client connects to the appropriate advertised broker endpoints for producing records, fetching data or coordinating consumer group operations.

DISCOVERY STAGE 05

Metadata Refresh

The client periodically refreshes metadata and responds to relevant errors or leadership changes by updating its understanding of the cluster.

NETWORK ENGINEERING INSIGHT

A successful connection to a Kafka bootstrap endpoint does not guarantee that the client can communicate with the entire cluster. The broker addresses returned through metadata must also be reachable from the client's network environment.

2.6 — Listeners and Advertised Listeners

Kafka's listener architecture is particularly important when deploying brokers across Kubernetes, cloud networks, private data centres and hybrid infrastructure.

The listeners configuration determines the addresses and ports on which a broker accepts connections.

The advertised.listeners configuration determines the broker endpoints advertised to clients through cluster metadata. These endpoints must be suitable for the network environment in which the clients operate.

ILLUSTRATIVE BROKER LISTENER FRAGMENT
# Broker socket bindings

listeners=INTERNAL://0.0.0.0:9092,EXTERNAL://0.0.0.0:9093

# Addresses returned to clients

advertised.listeners=INTERNAL://broker1.kafka.internal:9092,EXTERNAL://broker1.example.net:9093

# Listener security protocols

listener.security.protocol.map=INTERNAL:SSL,EXTERNAL:SSL,CONTROLLER:SSL

inter.broker.listener.name=INTERNAL

controller.listener.names=CONTROLLER

This is a listener configuration fragment for a broker-only KRaft deployment, not a complete production server configuration. Controller connectivity, node identity, quorum configuration, TLS certificates and other required settings must also be supplied.

NETWORK FAILURE 01

Incorrect DNS

The bootstrap address is reachable, but advertised broker hostnames cannot be resolved by the client.

NETWORK FAILURE 02

Blocked Broker Ports

Firewall or network policy rules allow bootstrap connectivity but prevent access to individual partition leaders.

NETWORK FAILURE 03

TLS Identity Mismatch

The advertised broker hostname does not match the certificate identity expected by the client, causing connection failures.

2.7 — Kafka Control Plane and Data Plane

Network engineers will recognise a familiar architectural distinction inside modern Kafka: the separation between control-plane responsibilities and data-plane operations.

Although the analogy is not identical to routing and switching infrastructure, it provides a useful way to understand the division of responsibilities.

Control Plane

Managed through the KRaft controller quorum.

Cluster metadata management
Broker registration and fencing
Topic and partition metadata
Partition leadership coordination
Metadata log replication and consensus

Data Plane

Operated primarily by the Kafka brokers.

Producer request processing
Consumer fetch processing
Partition log storage
Inter-broker record replication
Consumer group coordination

In modern Kafka deployments, KRaft provides the metadata management architecture without requiring an external ZooKeeper cluster. Kafka 4.x operates in KRaft mode.

Controllers may run as dedicated processes or in combined broker-controller configurations, depending on deployment requirements. Dedicated controller processes provide greater isolation for production control-plane workloads.

Kafka's controller quorum replicates cluster metadata. Topic records, however, are replicated through partition leader and follower mechanisms operating between brokers.

TWO DIFFERENT REPLICATION SYSTEMS

KRaft metadata replication and Kafka topic data replication solve different problems. The controller quorum maintains consistent cluster metadata, while partition replicas maintain copies of application records. Understanding this distinction is essential when investigating Kafka failures.

2.8 — How Kafka Achieves Horizontal Scalability

Kafka scales by distributing partition storage and leadership across multiple brokers. Increasing the number of partitions can provide additional opportunities for parallel production and consumption.

Adding brokers can increase available storage, network bandwidth and processing capacity. However, adding a broker does not automatically guarantee that existing partitions or leadership workloads become evenly distributed.

HORIZONTAL SCALING CONCEPT BEFORE AND AFTER
BEFORE · TWO BROKERS AFTER · THREE BROKERS BROKER 1 BROKER 2 P0 · LEADER P1 · LEADER P2 · LEADER P3 · LEADER P4 · LEADER P5 · LEADER BROKER 1 BROKER 2 BROKER 3 P0 · LEADER P1 · LEADER P3 · LEADER P4 · LEADER P2 · LEADER P5 · LEADER THREE LEADERS PER BROKER TWO LEADERS PER BROKER
Figure 3 — A separate illustrative scaling scenario showing six partition leaders distributed across two brokers and subsequently across three brokers. Replica placement is omitted for clarity. The resulting distribution requires appropriate partition placement and leadership management.

Scaling decisions must consider actual workload distribution. Two brokers hosting the same number of partition leaders may still experience very different traffic volumes if some partitions receive significantly more records than others.

Engineers must therefore evaluate partition throughput, storage utilisation, network capacity, request processing latency and consumer demand rather than relying exclusively on broker counts.

2.9 — Production Architecture Considerations

Design Area Engineering Consideration Potential Failure
Broker Placement Distribute brokers across independent failure domains. Correlated infrastructure failure
Partition Distribution Balance replica placement and leadership workloads. Broker hotspots
Network Capacity Account for production, consumption and replication traffic. Congestion and replication delays
Persistent Storage Size capacity around retention, replication and record volume. Disk exhaustion
Controller Quorum Maintain a resilient metadata consensus architecture. Loss of metadata update availability
Client Connectivity Validate advertised endpoints, DNS, TLS and routing. Intermittent client failures
Security Apply authentication, encryption and authorisation. Unauthorised access to event data
Observability Monitor broker health, replica state and client performance. Undetected degradation

2.10 — Engineering Incident: Bootstrap Works but Production Fails

Imagine a Kafka producer running inside a Kubernetes cluster. The producer successfully connects to its configured bootstrap endpoint but subsequently experiences repeated connection timeouts when publishing records.

The Kafka brokers appear healthy, and the initial TCP connection succeeds. However, metadata returned to the producer contains broker hostnames that are accessible only from a different private network.

INVESTIGATION 01

Observe

Bootstrap connectivity succeeds, but subsequent connections to individual broker endpoints time out.

INVESTIGATION 02

Investigate

Inspect returned broker metadata, advertised listeners, DNS resolution, routing and network security policies.

INVESTIGATION 03

Resolve

Correct the advertised listener architecture and ensure every required broker endpoint is reachable and correctly authenticated.

TROUBLESHOOTING METHODOLOGY

Follow the complete client communication path rather than testing only the initial connection. Separate DNS, TCP connectivity, TLS authentication, Kafka metadata discovery and partition-level request processing into distinct investigation stages.

Engineering Takeaways

✓ Kafka distributes event storage and request processing across cooperating brokers.
✓ Topics are logical event collections, while partitions provide distributed storage and parallelism.
✓ Partition leadership is distributed across brokers rather than centralised in one data-plane server.
✓ Clients discover cluster metadata through bootstrap connections and communicate with appropriate broker endpoints.
✓ Advertised listeners are critical to successful Kafka connectivity across network boundaries.
✓ KRaft controllers manage metadata, while brokers store and replicate application records.
✓ Horizontal scaling requires deliberate partition placement, workload distribution and capacity planning.
✓ Effective Kafka troubleshooting requires understanding both distributed application behaviour and underlying network infrastructure.
NETWORK INSIGHT / APACHE KAFKA / 02

Kafka Cluster Architecture Explorer

Explore how producers, brokers, distributed topic storage and consumer applications form an event-streaming platform.

Kafka brokers3
Events published0
Topics3
Partitions9
Events consumed0
DISTRIBUTED EVENT STREAMING INFRASTRUCTURE CLUSTER ONLINE
01 / PRODUCER APPLICATIONS 02 / KAFKA BROKER CLUSTER 03 / CONSUMER APPLICATIONS KAFKA-CLUSTER-01 Orders Payments Telemetry NETWORK INSIGHT / LOGICAL CLUSTER VIEW
DISTRIBUTED LOGICAL STORAGE

Topics and Partition Placement

Each topic contains three partitions distributed across the physical brokers.

APPLICATION CONNECTIVITY

Consumer Applications

Disconnect an application and observe how its topic continues receiving events.

INFRASTRUCTURE INSPECTION

Broker 01 — Storage Inspector

Hosted partitions 3
Stored events 0
Simulated data 0 KB
TOPIC PARTITION EVENTS STATE

Click any broker in the topology to inspect its local partition storage.

EVENT ROUTING EVIDENCE

Recent Published Events

EVENT TOPIC PARTITION DESTINATION
Waiting for producer traffic...
KAFKA ENGINEERING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 02

Discover the Distributed Cluster

Investigate the distinction between logical topics, physical brokers and independent consumer applications.

1Publish at least six events from the Order Application.
2Inspect all three brokers and discover where order partitions are stored.
3Publish at least three payment events and three telemetry events.
4Disconnect the Order Analytics consumer and publish at least three additional order events.
5Reconnect Order Analytics and observe it consume the outstanding events.
Investigation ready
Architecture model: A Kafka topic is a logical event stream. Its partitions are hosted on physical brokers. Producers publish to topics, while consumers read from the brokers hosting the relevant partitions. This introductory simulation uses fixed partition placement and round-robin publishing. Replication, metadata discovery and consumer group coordination are reserved for subsequent engineering labs.
03 Distributed Storage · Kafka Engineering

Topics, Partitions and Distributed Logs

Kafka achieves horizontal scalability by dividing logical event streams into independently ordered partitions, each implemented as a distributed, append-oriented log.

Understanding partitions is fundamental to understanding Apache Kafka. Partition architecture determines how records are distributed, how ordering is maintained, how consumers process events in parallel and how workloads are distributed across brokers.

Unlike a conventional database table, a Kafka partition is designed around sequential record insertion and offset-based retrieval. Records are appended to the end of the log, while consumers independently track their processing positions.

01
Logical Topic
03
Partitions
03
Example Keys
∞*
Growing Offset Space

*Conceptually growing offset sequences, subject to Kafka's numeric offset limits and operational constraints. Retained storage is finite.

TOPIC PARTITIONING AND RECORD DISTRIBUTION ILLUSTRATIVE KEY MAPPING
PRODUCER RECORDS KEY: CUSTOMER-A KEY: CUSTOMER-B KEY: CUSTOMER-C OrderCreated OrderUpdated OrderCreated PRODUCER PARTITIONING LOGIC Serialised Key · Partition Selection · Cluster Metadata TOPIC: CUSTOMER-ORDERS PARTITION 0 PARTITION 1 PARTITION 2 Broker 01 Broker 02 Broker 03 OFFSET 0 OFFSET 1 OFFSET 2 OFFSET 3 OFFSET 4 NEW · 5 OFFSET 8 OFFSET 9 OFFSET 10 OFFSET 11 OFFSET 12 NEW · 13 OFFSET 21 OFFSET 22 OFFSET 23 OFFSET 24 OFFSET 25 NEW · 26 INDEPENDENT PARTITION LOGS · INDEPENDENT OFFSET SEQUENCES
Figure 1 — Producer partitioning logic selects a destination partition for each record. Each partition maintains its own offset sequence. The key-to-partition assignments are illustrative, not calculated outputs from Kafka's actual partitioning algorithm. Follower replicas are omitted for clarity.

3.1 — Understanding Kafka Topics

A Kafka topic is a named logical collection of records representing a particular event stream or category of information.

An organisation may create separate topics for application transactions, infrastructure telemetry, security alerts, customer activity and database change events.

TOPIC EXAMPLE 01

customer-orders

Business events representing order creation, modification, cancellation and fulfilment.

TOPIC EXAMPLE 02

network-telemetry

Interface counters, device measurements, operational state changes and infrastructure performance observations.

TOPIC EXAMPLE 03

security-events

Authentication events, firewall observations, threat detections and security monitoring records.

Topics also provide a configuration boundary. Engineers can configure retention periods, cleanup policies, partition counts, minimum in-sync replica requirements and other topic-level characteristics.

The replication factor is established through replica assignment when a topic is created and can subsequently be changed through partition reassignment mechanisms.

3.2 — Partitions as the Unit of Parallelism

A Kafka topic can contain one or more partitions. Each partition is an independently ordered log with its own sequence of records and offsets.

Partitions allow Kafka to distribute storage, network traffic and processing across multiple brokers. Without partitioning, a single logical event stream would be constrained by the capacity of its single partition leader.

PARTITION PROPERTY 01

Independent Storage

Each partition maintains its own logical record sequence and physical log segments.

PARTITION PROPERTY 02

Independent Leadership

Each partition has a leader responsible for normal record production and coordinating its replica state.

PARTITION PROPERTY 03

Parallel Processing

Different partitions can be assigned to different members of a conventional consumer group, allowing concurrent processing.

FUNDAMENTAL KAFKA DESIGN PRINCIPLE

A partition is not simply a storage subdivision. It is simultaneously an ordering boundary, a replication unit, a leadership unit and a fundamental unit of consumer-group parallelism.

3.3 — Record Keys and Partition Selection

Kafka records can contain a key and a value, together with a timestamp and optional headers. The record key frequently represents the identity of a business entity or another grouping boundary.

For example, an order-processing application might use an order identifier as its record key. This allows related lifecycle events to be directed to the same partition under a stable key-based partitioning configuration.

ILLUSTRATIVE KEYED KAFKA RECORD
// Application-level record representation

{
  "topic": "customer-orders",
  "key": "ORD-50182",
  "value": {
    "eventType": "OrderUpdated",
    "orderId": "ORD-50182",
    "status": "PAYMENT_RECEIVED"
  }
}

When a partition is not explicitly specified, the standard Java producer's default keyed partitioning behaviour can be represented conceptually using the following expression.

Partition = PositiveHash(KeyBytes) % PartitionCount
Simplified representation of the standard Java producer's Murmur2-based keyed partition selection. Custom partitioners and other client implementations may behave differently.

The important architectural characteristic is that consistent key serialisation, partitioning behaviour and partition count can produce a stable mapping between a record key and its destination partition.

Record Key Event Illustrative Partition
ORD-50182 OrderCreated Partition 0
ORD-50182 PaymentReceived Partition 0
ORD-50182 OrderShipped Partition 0
ORD-50183 OrderCreated Partition 2
ORD-50184 OrderCreated Partition 1

Records without keys can be distributed using producer-specific partitioning behaviour designed to improve batching and workload distribution. Modern Kafka producers may use sticky or adaptive partition selection for unkeyed records.

Unkeyed records should not be assumed to follow strict record-by-record round-robin distribution.

PARTITION EXPANSION WARNING

Increasing a topic's partition count can change the destination partition calculated for existing record keys. Historical records are not automatically redistributed to preserve key locality. Applications requiring uninterrupted per-key ordering must explicitly plan partition expansion and migration.

3.4 — Understanding Kafka Offsets

Every record appended to a Kafka partition is associated with an offset. An offset identifies a position within that particular partition's logical record sequence.

Offsets are not globally unique across a Kafka topic. Partition 0 and Partition 1 can both contain a record at offset 105 without any relationship between those records.

A record's location within a Kafka cluster can therefore be described using its topic, partition and offset.

Record Location = Topic + Partition + Offset
Example: customer-orders / partition-0 / offset-105
PARTITION OFFSET AND VISIBILITY BOUNDARIES DISTRIBUTED LOG STATE
TOPIC: CUSTOMER-ORDERS · PARTITION 0 100 101 102 103 104 105 106 107 108 109 LOG START: 100 HIGH WATERMARK: 108 LOG END OFFSET: 110 COMMITTED CONSUMER OFFSET: 104 Next record to resume from REPLICATED VISIBILITY REGION NOT YET VISIBLE OFFSETS DESCRIBE LOG POSITIONS, NOT PHYSICAL BYTE ADDRESSES SIMPLIFIED NON-TRANSACTIONAL EXAMPLE
Figure 2 — The log start offset identifies the lower retained boundary. The log end offset identifies the next append position. The high watermark defines the replicated visibility boundary. A committed consumer offset identifies where a conventional consumer group can resume processing. Transactional read-committed consumers are additionally constrained by the last stable offset.
Offset Concept Example Meaning
Log Start Offset 100 Lower boundary of the currently available partition log.
Log End Offset 110 Next offset at the end of the local partition log.
High Watermark 108 Replicated boundary; records below this position can be eligible for normal consumer visibility.
Committed Consumer Offset 104 Stored next-consumption position for a conventional consumer group.
Last Stable Offset Transaction dependent Additional visibility boundary for consumers using read_committed isolation.
OFFSET ENGINEERING INSIGHT

Offsets are logical positions rather than physical file addresses or guaranteed record counts. Compaction, transactional control records and other log characteristics can create differences between an offset distance and the actual number of application records available for processing.

3.5 — Kafka Log Segments and Physical Storage

A partition appears to applications as a continuous logical log. Internally, Kafka divides that log into multiple segment files.

Segmentation allows Kafka to manage large event streams without treating an entire partition as one continuously growing physical file.

The active segment receives new records. When configured rolling conditions are reached, Kafka creates a new active segment and closes the previous segment for further appends.

INTERNAL PARTITION LOG SEGMENT ARCHITECTURE STORAGE CUTAWAY
BROKER STORAGE · CUSTOMER-ORDERS-0 SEGMENT 01 SEGMENT 02 SEGMENT 03 BASE OFFSET: 0 BASE OFFSET: 1000 BASE OFFSET: 2000 .log .log .log .index · Offset Index .index · Offset Index .index · Offset Index .timeindex · Time Index .timeindex · Time Index .timeindex · Time Index CLOSED FOR APPENDS CLOSED FOR APPENDS ACTIVE SEGMENT NEW RECORD BATCHES OLDER SEGMENTS Eligible for configured cleanup
Figure 3 — A conceptual partition directory containing closed segments and one active segment. Segment data files contain record batches, while sparse offset and timestamp indexes assist record location. Additional internal files and transactional indexes are omitted for clarity.
STORAGE FILE 01

.log

Contains Kafka record batches and their associated encoded record data.

STORAGE FILE 02

.index

Provides a sparse mapping from relative record offsets to positions within the segment data file.

STORAGE FILE 03

.timeindex

Assists timestamp-based record lookup through mappings between timestamps and relative offsets.

Kafka uses these indexes to locate relevant regions of the log efficiently rather than requiring a sequential scan of the entire partition for every fetch request.

3.6 — Event Ordering and Its Boundaries

Kafka preserves record order within an individual partition's log. This does not establish a single global ordering relationship across all partitions belonging to a topic.

Within One Partition

Created Offset 20
Paid Offset 21
Shipped Offset 22

The records have an explicit order within the partition log.

Partition-level ordering

Across Multiple Partitions

Event A P0 · Offset 20
Event B P1 · Offset 21
Event C P2 · Offset 22

These offsets belong to different logs. They do not establish a global event order.

No global offset ordering

Partition-level ordering also does not guarantee that every application processes records in that order. Parallel application processing, retries, asynchronous operations and multiple producers can affect the sequence in which business operations are observed.

Engineers requiring strict entity-level ordering should consider stable partition keys, producer delivery configuration, application processing concurrency and explicit event sequence numbers.

LOG ORDER VERSUS BUSINESS ORDER

Kafka preserves the order in which records appear in a partition. It does not automatically determine the correct causal order of business events generated by independent distributed applications.

3.7 — Retention and Segment Deletion

Kafka does not normally delete records simply because consumers have processed them. Instead, record availability is governed by configured cleanup policies.

With the delete cleanup policy, Kafka can remove eligible older log segments according to time and size-based retention requirements.

ILLUSTRATIVE TOPIC STORAGE CONFIGURATION
# Delete older eligible log segments

cleanup.policy=delete

# Seven-day time-based retention

retention.ms=604800000

# 10 GiB retention target per partition

retention.bytes=10737418240

# Approximately 1 GiB segment size

segment.bytes=1073741824

# Roll segments after approximately one hour

segment.ms=3600000

These settings are illustrative rather than universal production recommendations. Actual retention behaviour is influenced by segment rolling, cleanup scheduling and other storage configuration.

The retention.bytes setting applies per partition rather than to the entire topic. Time and size limits can independently make older segments eligible for deletion.

RETENTION IS NOT A CONSUMER GUARANTEE

Kafka does not normally retain records indefinitely simply because a consumer group has not processed them. If a consumer falls behind the retained log boundary, the missing historical records may no longer be available from that topic.

3.8 — Log Compaction and State Reconstruction

Kafka also supports log compaction, a cleanup mechanism designed to retain the latest known value associated with each record key, subject to compaction and deletion semantics.

Compaction is particularly useful for topics representing changing entity state rather than requiring every historical transition to remain available indefinitely.

Before Compaction

A = 10 Offset 0
B = 20 Offset 1
A = 15 Offset 2
C = 30 Offset 3
B = 25 Offset 4

Multiple historical values exist for keys A and B. Older superseded values may become eligible for compaction.

After Illustrative Compaction

A = 15 Offset 2
C = 30 Offset 3
B = 25 Offset 4

The latest values remain. Original offsets are preserved, leaving gaps where older records have been removed.

Compaction operates asynchronously and does not guarantee that only one record per key exists at every moment. Consumers must be prepared to encounter multiple historical values while reading a compacted topic.

A keyed record with a null value can act as a tombstone, representing deletion of the corresponding key. Tombstones are themselves subject to configured retention and compaction behaviour.

Cleanup Policy Primary Behaviour Typical Use Case
delete Removes eligible segments based on configured retention limits. Telemetry, application events and logs.
compact Removes superseded keyed records through asynchronous log cleaning. Entity state and configuration updates.
compact,delete Combines key-based compaction with segment retention policies. Bounded retained state streams.

3.9 — Partition Count and Consumer Parallelism

In a conventional Kafka consumer group, each partition is assigned to at most one active consumer group member at a given time.

A consumer can process multiple partitions, but adding more consumers than available subscribed partitions does not provide additional partition-level parallelism.

PARTITION-LEVEL CONSUMER PARALLELISM CONVENTIONAL CONSUMER GROUP
TOPIC: ORDERS · THREE PARTITIONS PARTITION 0 PARTITION 1 PARTITION 2 CONSUMER GROUP: ORDER-PROCESSING CONSUMER 1 CONSUMER 2 CONSUMER 3 CONSUMER 4 ACTIVE · P0 ACTIVE · P1 ACTIVE · P2 IDLE · NO PARTITION ADDITIONAL CONSUMERS DO NOT CREATE ADDITIONAL PARTITIONS
Figure 4 — Three partitions provide three active partition assignments within this conventional consumer group. A fourth consumer remains idle. Other Kafka consumption models, including share groups, have different assignment semantics.

Partition count must therefore be selected with future consumer parallelism in mind. However, excessively large partition counts also increase metadata, storage file, replication and operational management requirements.

3.10 — Partition Hotspots and Uneven Traffic Distribution

Distributing records across partitions does not automatically guarantee balanced workload distribution.

Consider a network telemetry platform using device identifiers as Kafka record keys. Most devices generate a moderate amount of telemetry, but one heavily utilised core router produces significantly more records.

If the router's records consistently map to one partition, that partition can become a hotspot even while other partitions remain underutilised.

Illustrative Partition Ingress Distribution

Example total: 100 MB/s across six partitions. Bar lengths represent each partition's share of total ingress.

P0
8 MB/s
P1
12 MB/s
P2
48 MB/s
P3
9 MB/s
P4
15 MB/s
P5
8 MB/s
Partition 2 receives 48% of all incoming data, approximately 2.88 times the mean partition rate. This identifies workload skew, not necessarily resource saturation.

Adding more brokers does not automatically divide the workload of an individual hot partition. Moving its leader may redistribute broker load, but the partition remains a single logical ordering and production boundary.

HOTSPOT CAUSE 01

Low Key Cardinality

Too few distinct keys can prevent effective distribution across the available partitions.

HOTSPOT CAUSE 02

Uneven Key Frequency

A small number of high-volume entities can dominate particular partition workloads.

HOTSPOT CAUSE 03

Uneven Record Sizes

Similar record counts can conceal substantial differences in partition bandwidth and storage requirements.

PARTITION KEY DESIGN TRADE-OFF

Introducing additional key components or key salting can distribute a high-volume entity across multiple partitions. However, doing so may remove the original entity-level ordering guarantee. Load distribution and ordering requirements must be designed together.

3.11 — Estimating Partition Storage Requirements

Storage planning requires an understanding of record ingestion rates, retention periods, compression and replication requirements.

Consider an illustrative topic receiving 20 MB/s of stored record data after compression. The topic uses seven-day retention and a replication factor of three.

Storage ≈ Stored Ingress × Retention × Replication Factor
Simplified steady-state estimate for a time-retained, fully replicated topic.
20
MB/s Ingress
7
Retention Days
3
Replica Copies
36.29
TB Estimated
ILLUSTRATIVE STORAGE CALCULATION
# Decimal storage units

Stored ingress       = 20 MB/s

Retention seconds    = 7 × 24 × 60 × 60
                     = 604,800 seconds

Logical retained data
                     = 20 × 604,800 MB
                     = 12,096,000 MB
                     = 12.096 TB

Replication factor   = 3

Replicated storage   = 12.096 × 3
                     = 36.288 TB

# Example: 30% of provisioned capacity kept free

Provisioned capacity = 36.288 / 0.70
                     = 51.84 TB

This calculation excludes index overhead, internal topics, segment cleanup delays, temporary replica movement, storage filesystem overhead and workload growth.

Production storage planning must also account for broker failure scenarios, recovery traffic and the uneven distribution of partition data. Aggregate cluster capacity alone does not guarantee that individual brokers have sufficient available disk space.

3.12 — Engineering Incident: The Hot Partition

Imagine a Kafka cluster containing six partitions distributed across three brokers. Overall broker CPU utilisation appears acceptable, and aggregate network throughput remains below the cluster's estimated capacity.

However, one consumer experiences continuously increasing lag while the other consumers remain close to their available log ends.

INVESTIGATION STAGE 01

Identify the Affected Partition

Examine consumer-group lag by topic and partition rather than relying exclusively on aggregate consumer lag.

INVESTIGATION STAGE 02

Compare Partition Ingress Rates

Determine whether the affected partition receives substantially more records or bytes than the remaining partitions.

INVESTIGATION STAGE 03

Investigate Consumer Processing

Compare fetch rates, processing latency, downstream service dependencies and application resource utilisation.

INVESTIGATION STAGE 04

Inspect Record Key Distribution

Sample authorised record metadata or application instrumentation to identify dominant keys and workload skew.

INVESTIGATION STAGE 05

Evaluate Architectural Remediation

Consider consumer processing optimisation, leader redistribution, revised partition keys or a controlled topic migration, depending on the verified bottleneck.

KAFKA ENGINEERING CLI · READ-ONLY INSPECTION
# Inspect topic partition and replica assignments

kafka-topics.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --topic network-telemetry

# Inspect consumer group offsets and lag

kafka-consumer-groups.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --group telemetry-processing

# Inspect topic-level configuration

kafka-configs.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --entity-type topics \
  --entity-name network-telemetry \
  --describe

These commands require an appropriate Kafka installation, reachable broker endpoints, client security configuration and authorised access. The example hostnames and consumer group names are placeholders.

3.13 — Production Partition Design Considerations

Design Area Engineering Decision Potential Risk
Partition Count Match expected throughput and consumer parallelism requirements. Insufficient parallelism or excessive partition management overhead.
Record Key Select an entity boundary that supports ordering and distribution. Hot partitions or incorrect entity-level ordering.
Retention Align available history with recovery and replay requirements. Unavailable historical events.
Segment Size Balance segment management, cleanup granularity and file overhead. Inefficient cleanup or excessive storage file management.
Compaction Use keyed state semantics where historical transitions are not all required. Loss of required event history.
Replication Evaluate durability, failure domains and storage amplification. Insufficient resilience or excessive resource consumption.
Partition Expansion Plan changes to key mapping and consumer assignments. Broken key locality and application ordering assumptions.
Observability Monitor partition-level throughput, lag, storage and replica health. Hidden hotspots and uneven workload distribution.

Engineering Takeaways

✓ Topics are logical event collections divided into independently ordered partition logs.
✓ Partitions provide Kafka's fundamental storage, replication and parallelism boundaries.
✓ Record keys influence partition selection and entity-level ordering.
✓ Offsets identify logical positions within individual partitions rather than global topic positions.
✓ Kafka divides physical partition logs into segments supported by sparse indexes.
✓ Retention and compaction determine which historical records remain available.
✓ Increasing partition count can affect existing key-to-partition mappings.
✓ Balanced partition counts do not necessarily indicate balanced traffic distribution.
✓ Storage capacity planning must account for retention, compression, replication and operational headroom.
✓ Effective Kafka troubleshooting requires partition-level evidence rather than aggregate cluster metrics alone.
NETWORK INSIGHT / APACHE KAFKA / 03

Kafka Partition & Offset Simulator

Explore deterministic key routing, append-only distributed logs, partition-level ordering and horizontal scalability.

Partitions 3
Stored records 0
Unique keys 0
Busiest partition —
Maximum offset —
PRODUCER PARTITIONING STRATEGY

Configure Event Routing

↗
Order Producer Key: customer-A Waiting for record
PARTITION SELECTION Hash(key) mod 3 Awaiting publication
▤
orders.created Destination: — Assigned offset: —
DISTRIBUTED APPEND-ONLY LOG / ORDERS.CREATED STORAGE ONLINE
RECORD INSPECTION

Kafka Event Payload

Select any stored record to inspect its partition, key, offset and event metadata.

No record selected.
DETERMINISTIC PARTITION MAPPING

Customer Key Routing Table

KEY HASH PARTITION

The mapping is calculated using Kafka-compatible Murmur2 hashing for the selected UTF-8 keys.

OFFSET EXPLORATION

Read From a Partition

Choose a partition and starting offset. Reading records does not delete them from the log.

Select a partition and starting offset.
WORKLOAD DISTRIBUTION

Partition Utilisation

Generate events to analyse workload distribution.
HORIZONTAL SCALABILITY

Partition Expansion Analysis

Increasing the partition count changes the modulo operation used for keyed routing. Existing records remain in their original partitions.

KEY 3 PARTITIONS 6 PARTITIONS IMPACT
Expand the topic to investigate the effect on future keyed records.
PARTITION ENGINEERING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 03

The Hot Partition Investigation

Investigate how key selection influences partition distribution, ordering and scalability.

1 Publish five records with the same customer key using key-based routing.
2 Inspect a stored record and examine its partition and offset.
3 Inject a hot-partition workload and observe concentrated event storage.
4 Read records from offset 2 of the overloaded partition.
5 Expand to six partitions and publish a key whose partition mapping changes.
Investigation ready
ENGINEERING PRINCIPLE 01

Partition-Level Ordering

Kafka maintains an ordered log within each partition. Offsets identify positions within that partition, not across the entire topic. Records in different partitions do not have a guaranteed global order.

ENGINEERING PRINCIPLE 02

Scalability Versus Key Skew

Additional partitions can enable more parallelism, but a disproportionately active key may still concentrate traffic in one partition. Partition expansion can also change future key placement.

04 Event Production · Kafka Engineering

Kafka Producer Architecture

The Kafka producer is an intelligent distributed systems client responsible for transforming application events into efficiently batched, compressed and reliably delivered records within a Kafka cluster.

Publishing an event to Apache Kafka involves considerably more than opening a network connection and transmitting a message. The producer must discover cluster metadata, serialise application data, select a destination partition, manage local memory, construct record batches and communicate with partition leaders.

Producer configuration directly influences application latency, network efficiency, broker resource consumption, ordering behaviour and the durability of published events. A poorly configured producer can create performance problems even when the Kafka brokers themselves are operating correctly.

INTERNAL KAFKA PRODUCER PIPELINE ANIMATED RECORD FLOW
APPLICATION SERVICE OrderCreated · DeviceTelemetry · PaymentReceived KAFKA PRODUCER CLIENT SERIALISERS Key and value to bytes JSON · Avro · Protobuf PARTITION SELECTION Key mapping and metadata Select destination partition CLUSTER METADATA Broker and leader discovery Metadata cache RECORD ACCUMULATOR · PER-PARTITION BATCHES PARTITION 0 PARTITION 1 PARTITION 2 BACKGROUND SENDER AND NETWORK CLIENT Produce requests · In-flight tracking · Retry handling BROKER 01 BROKER 02 BROKER 03 PARTITION 0 LEADER PARTITION 1 LEADER PARTITION 2 LEADER ACKNOWLEDGEMENT ASYNCHRONOUS PRODUCTION · PARTITION-AWARE BATCHING
Figure 1 — Simplified architecture of the standard Kafka producer. Application records are serialised, assigned to partitions and accumulated into batches. A background sender constructs produce requests directed towards the appropriate partition leaders. Compression is applied at record-batch level.

4.1 — Understanding the Producer Lifecycle

The Kafka producer provides an asynchronous interface between application code and the distributed Kafka storage system.

In the standard Java client, an application invokes the send method to submit a ProducerRecord. The producer performs the necessary serialisation and partition selection before appending the record to its local record accumulator.

A background sender thread subsequently manages network transmission, broker responses and eligible retries. The application can receive the eventual delivery result through a callback or Future.

PRODUCER STAGE 01

Application Submission

The application constructs a record containing a topic, optional key, value and optional metadata.

PRODUCER STAGE 02

Local Preparation

The producer serialises data, selects a partition and appends the record to a partition-specific batch.

PRODUCER STAGE 03

Network Delivery

The sender transmits produce requests, handles broker responses and reports delivery outcomes.

ASYNCHRONOUS DOES NOT MEAN DELIVERED

Successfully returning from an asynchronous send operation does not necessarily mean that the record has been stored by Kafka. Applications must inspect the eventual delivery result and implement appropriate error-handling behaviour.

4.2 — Serialisation and Event Contracts

Kafka stores record keys and values as byte sequences. It does not inherently understand the business meaning of an order, payment, security alert or infrastructure telemetry event.

Serialisers convert application-level objects into binary representations that can be transmitted and stored by Kafka.

FORMAT 01

JSON

Human-readable structured data with broad interoperability. Schema enforcement requires additional application or platform mechanisms.

FORMAT 02

Apache Avro

Schema-based binary serialisation commonly used with schema registries and controlled schema evolution.

FORMAT 03

Protocol Buffers

Compact structured binary messages with explicitly defined fields and schema compatibility considerations.

A schema registry is an additional architectural component rather than an intrinsic requirement of Kafka itself. It can provide centralised schema management, compatibility validation and schema identification.

ILLUSTRATIVE EVENT CONTRACT
{
  "eventId": "evt-90182",
  "eventType": "OrderCreated",
  "schemaVersion": 2,
  "orderId": "ORD-50182",
  "eventTime": "2026-11-24T10:30:00Z",
  "payload": {
    "customerId": "CUS-101",
    "currency": "EUR",
    "amount": 249.00
  }
}

Stable event identifiers, explicit schema versions and clearly defined compatibility rules help independently deployed services exchange events without requiring simultaneous application upgrades.

4.3 — Cluster Metadata and Leader Discovery

Kafka producers initially connect to one or more configured bootstrap servers to discover cluster metadata.

Bootstrap servers are initial contact points. They are not necessarily the brokers that ultimately receive every application record.

Once the producer has discovered the relevant partition leadership information, it can establish connections to the brokers responsible for the destination partitions.

BOOTSTRAP AND METADATA DISCOVERY CONTROL AND DATA PATHS
PRODUCER METADATA CACHE P0 → Broker 02 P1 → Broker 03 BROKER 01 BROKER 02 BROKER 03 BOOTSTRAP CONTACT PARTITION 0 LEADER PARTITION 1 LEADER METADATA REQUEST METADATA RESPONSE PRODUCE REQUEST · P0 PRODUCE REQUEST · P1
Figure 2 — The producer uses a bootstrap broker to discover cluster metadata and subsequently communicates with the appropriate partition leaders. A bootstrap broker may also host partition leaders.
NETWORK ENGINEERING CONSIDERATION

A producer may successfully connect to its bootstrap server but fail to publish records if the broker addresses returned through advertised.listeners are unreachable from the client network. This is particularly important in Kubernetes, containerised environments, private cloud networks and hybrid deployments.

4.4 — Record Accumulation and Batching

Kafka achieves high throughput partly by grouping multiple records into record batches rather than treating every application event as an independent network transaction.

The producer maintains partition-specific batches in its record accumulator. Batches can be included together in produce requests destined for the same broker.

Individual Record Transmission

R1
R2
R3
R4
REQ 1
REQ 2
REQ 3
REQ 4

Sending each record independently can increase protocol overhead, request processing and network utilisation.

Batched Record Transmission

RECORD BATCH · PARTITION 0
R1
R2
R3
R4
SINGLE PRODUCE REQUEST

Grouping records can amortise request overhead and improve compression efficiency.

CONFIGURATION 01

batch.size

Controls the target batch allocation size in bytes. Individual records larger than this target may require larger allocations, subject to applicable size limits.

CONFIGURATION 02

linger.ms

Allows additional batching time before sending a partially filled batch. Full batches can become eligible for sending without waiting for the linger interval.

CONFIGURATION 03

buffer.memory

Defines the approximate memory budget for buffered producer records. Additional memory is required for other producer operations.

Larger batches generally improve throughput efficiency when sufficient records are available. However, waiting for additional records introduces a latency trade-off, particularly in low-volume event streams.

RECORD BATCH READINESS TIMELINE ILLUSTRATIVE TIMING
SCENARIO A · BATCH FILLS EARLY R1 R2 R3 R4 BATCH READY Size target reached LINGER DEADLINE SCENARIO B · PARTIAL BATCH R1 R2 BATCH READY LINGER INTERVAL EXPIRES
Figure 3 — A batch can become ready when its size target is reached or its linger interval expires. Actual transmission may occur later because of broker availability, throttling, network conditions or producer backpressure.

4.5 — Compression and Network Efficiency

Kafka supports compression at record-batch level. Compression reduces the amount of data transmitted across the network and can reduce broker storage requirements.

Larger batches containing similar records can often achieve better compression ratios than independently compressed small records.

Compression General Characteristics Engineering Consideration
none No producer-side compression. Higher bandwidth and storage demand.
gzip Often provides strong compression. Potentially higher CPU cost.
snappy Designed for fast compression. Compression ratio depends on workload.
lz4 Fast compression and decompression. Useful candidate for latency-sensitive workloads.
zstd Flexible speed and compression trade-offs. Benchmark compression level and CPU cost.
RECORD BATCH COMPRESSION CUTAWAY ILLUSTRATIVE 4:1 RATIO
UNCOMPRESSED RECORD DATA RECORD GROUP A RECORD GROUP B RECORD GROUP C RECORD GROUP D COMPRESSION BATCH LEVEL COMPRESSED RECORD DATA 64 KiB 16 KiB EXCLUDES PROTOCOL AND BATCH HEADER OVERHEAD
Figure 4 — Illustrative compression of record payload data from 64 KiB to 16 KiB. Actual compression ratios depend on data characteristics, batch size, codec and compression level.

Compression does not eliminate resource consumption. It exchanges some CPU processing for potentially lower network bandwidth and storage demand. Broker configuration can also influence whether producer compression is preserved or recompressed.

4.6 — Producer Acknowledgements

The producer's acknowledgement configuration determines what response is required from Kafka before a produce request is considered successful.

The three principal acknowledgement settings are acks=0, acks=1 and acks=all.

ACKNOWLEDGEMENT MODE

acks=0

The producer does not wait for a broker acknowledgement. It cannot confirm whether the broker successfully appended the record.

ACKNOWLEDGEMENT MODE

acks=1

The partition leader acknowledges the append without waiting for all current in-sync replicas to replicate the record.

ACKNOWLEDGEMENT MODE

acks=all

Successful acknowledgement requires the record to reach the current in-sync replica set, subject to minimum ISR requirements.

REPLICATION-AWARE ACKNOWLEDGEMENT PATH ACKS=ALL
PRODUCER acks=all PARTITION LEADER BROKER 01 FOLLOWER 01 FOLLOWER 02 BROKER 02 · IN-SYNC BROKER 03 · IN-SYNC PRODUCE SUCCESS RECORD REPLICATED ACROSS CURRENT ISR REPLICATION FACTOR 3 · ISR SIZE 3 · MINIMUM ISR 2
Figure 5 — Simplified acknowledgement sequence with acks=all. Followers replicate through fetch requests, and the leader tracks their progress. The diagram represents logical replication and progress reporting rather than exact wire-level request sequencing.
REPLICATION IS NOT THE SAME AS DISK FLUSHING

A successful Kafka acknowledgement does not necessarily mean that every replica has synchronously flushed the record to persistent physical media. Kafka durability relies heavily on replication, operating system storage behaviour and correctly designed failure domains.

4.7 — Minimum In-Sync Replicas

The min.insync.replicas configuration establishes a minimum in-sync replica requirement for successful writes using acks=all.

Consider a partition with replication factor three and min.insync.replicas configured to two.

Replica State ISR Size acks=all Write Outcome
All replicas in-sync 3 Writes can succeed
One follower unavailable 2 Writes can still succeed
Both followers unavailable 1 Writes rejected or fail
No available partition leader Unavailable Normal production unavailable

These outcomes assume the indicated ISR state has been established, a valid leader exists where required and no unrelated errors prevent delivery.

A configuration of min.insync.replicas=2 does not mean that acks=all always waits for exactly two replicas. If three replicas are currently in-sync, acknowledgement depends on the current ISR rather than merely the configured minimum.

DURABILITY VERSUS WRITE AVAILABILITY

Increasing the minimum ISR requirement can strengthen the replication conditions required for successful writes, but it can also reduce write availability during replica failures. The appropriate configuration depends on application durability requirements and acceptable failure behaviour.

4.8 — Retries and Ambiguous Delivery Outcomes

Distributed systems frequently experience transient failures. Network connections can be interrupted, brokers can become unavailable and partition leadership can change while a producer request is in progress.

Kafka producers can retry eligible failures automatically, subject to configured retry and delivery timeout limits.

However, a timeout does not necessarily establish that a record was never written. A broker may successfully append a record before the response is lost.

AMBIGUOUS DELIVERY AND RETRY SEQUENCE LOST RESPONSE SCENARIO
PRODUCER PARTITION LEADER 01 · PRODUCE EVENT E101 APPEND SUCCESSFUL 02 · RESPONSE LOST REQUEST TIMEOUT 03 · RETRY EVENT E101 POSSIBLE DUPLICATE E101 · E101 SIMPLIFIED SCENARIO WITHOUT PRODUCER IDEMPOTENCE
Figure 6 — A lost acknowledgement creates uncertainty about the original delivery outcome. Retrying without an appropriate deduplication mechanism can create duplicate records.
Configuration Purpose
retries Limits eligible retry attempts, also constrained by delivery timeout.
retry.backoff.ms Influences the delay before retrying failed requests.
request.timeout.ms Controls how long the client waits for a request response.
delivery.timeout.ms Bounds the time available to report delivery success or failure after send returns, including batching and retries.
max.block.ms Bounds relevant blocking waits for metadata and buffer allocation in producer API operations.

4.9 — Idempotent Producer Architecture

Kafka's idempotent producer mechanism is designed to prevent duplicate log appends resulting from eligible producer retries.

The producer uses a producer identifier, producer epoch and partition-specific sequence numbers. Brokers maintain producer state and use this information to identify duplicate batches and detect invalid sequence progression.

PRODUCER IDENTITY AND SEQUENCE TRACKING IDEMPOTENCE ENABLED
IDEMPOTENT PRODUCER PRODUCER ID: 812 PRODUCER EPOCH: 0 BATCH A · SEQUENCE 0–2 BATCH B · SEQUENCE 3–5 RETRY B · SEQUENCE 3–5 PARTITION LEADER TRACKED PRODUCER STATE PID 812 · EPOCH 0 · LAST SEQUENCE 5 BATCH A · APPENDED BATCH B · APPENDED DUPLICATE RECOGNISED · NO NEW APPEND RETRY HANDLED WITHOUT AN ADDITIONAL LOG APPEND
Figure 7 — Conceptual idempotent producer sequence tracking. The broker recognises an eligible repeated batch from the same producer identity and epoch, avoiding an additional append.
IDEMPOTENT JAVA PRODUCER CONFIGURATION
enable.idempotence=true

acks=all

retries=2147483647

max.in.flight.requests.per.connection=5

delivery.timeout.ms=120000

The standard Java producer requires compatible acknowledgement, retry and in-flight request settings for idempotence. Modern Kafka Java clients generally enable idempotence by default when no conflicting settings are supplied.

IDEMPOTENCE HAS A DEFINED SCOPE

Producer idempotence prevents certain duplicate appends caused by producer retries. It does not automatically deduplicate independent application send operations, arbitrary business events or records republished by unrelated producer sessions. Application-level idempotency may still be required.

4.10 — Delivery Guarantees and Transactions

Event-driven architectures commonly distinguish between at-most-once, at-least-once and exactly-once processing semantics.

These guarantees must be evaluated across the complete application workflow rather than inferred solely from producer configuration.

DELIVERY MODEL 01

At-Most-Once

An event may be lost, but the workflow avoids repeated delivery or processing within its defined guarantee boundary.

DELIVERY MODEL 02

At-Least-Once

Events are retried or reprocessed as necessary under defined recovery assumptions. Duplicate processing remains possible.

DELIVERY MODEL 03

Exactly-Once Semantics

A defined processing result becomes visible once within a supported transactional boundary, despite eligible retries and recovery operations.

Kafka transactions allow producers to group writes across multiple topic partitions into a transactional operation. They can also support atomic coordination of consumed offsets and produced output records in Kafka-to-Kafka processing workflows.

TRANSACTIONAL KAFKA PROCESSING BOUNDARY ATOMIC COMMIT
INPUT TOPIC OrderCreated P0 · Offset 105 PROCESSING SERVICE Consume input Apply business logic Produce output records Commit transaction TRANSACTIONAL WRITE SET OUTPUT TOPIC A OUTPUT TOPIC B CONSUMER GROUP OFFSET OrderValidated InventoryRequested NEXT OFFSET: 106 COMMIT OR ABORT KAFKA-TO-KAFKA TRANSACTIONAL PROCESSING
Figure 8 — A Kafka-to-Kafka processing workflow can transactionally coordinate output records and consumed offsets. Consumers using read_committed isolation do not return aborted transactional records.
EXTERNAL SYSTEMS REQUIRE ADDITIONAL DESIGN

Kafka transactions do not automatically make arbitrary external database updates, HTTP requests or payment operations exactly-once. External side effects require additional coordination, deduplication or application idempotency mechanisms.

4.11 — Producer Backpressure and Memory Management

The producer's local record buffer decouples application event generation from network transmission.

If an application produces records faster than Kafka can accept them, buffered records can accumulate until the producer approaches its available memory limits.

When buffer allocation cannot proceed, application send operations may block and eventually fail, depending on the client implementation and configured timeout limits.

Producer Resource Pressure

Illustrative incident telemetry. Each bar represents utilisation relative to its own example capacity or operational threshold.

Buffer memory
92%
Application CPU
38%
Network capacity
46%
Retry threshold
78%
Latency threshold
95%
INVESTIGATION REQUIRED — High buffer utilisation and delivery latency suggest that the producer is struggling to drain its accumulated records. These measurements alone do not establish the underlying cause.

Increasing producer buffer memory can absorb temporary traffic bursts. It does not resolve a sustained mismatch between application production rate and Kafka ingestion capacity.

4.12 — Throughput and Capacity Engineering

Producer capacity planning should consider record size, event generation rate, compression, replication traffic and request-processing overhead.

Consider an application generating 100,000 records per second, with an average serialised record payload of 1,000 bytes.

Payload Throughput = Records/s × Average Record Bytes
Simplified payload calculation before protocol headers, batch overhead and retransmissions.
100K
Records/s
1 KB
Record Payload
100
Raw MB/s
25
Compressed MB/s
ILLUSTRATIVE NETWORK CAPACITY CALCULATION
Event rate          = 100,000 records/s

Average payload     = 1,000 bytes

Raw payload rate    = 100,000 × 1,000
                    = 100 MB/s
                    = 800 Mb/s

Compression ratio   = 4:1

Producer ingress    = 25 MB/s
                    = 200 Mb/s

Replication factor  = 3

Follower replication
                    = 25 × 2
                    = 50 MB/s

Combined producer and replication transfers
                    = 25 + 50
                    = 75 MB/s
                    = 600 Mb/s

This example assumes steady-state replication, preserved compression and two follower copies. It excludes consumer traffic, protocol overhead, metadata requests, retransmissions, encryption overhead and replica recovery traffic.

The combined transfer rate is an aggregate directional traffic estimate, not the bandwidth requirement of any individual broker interface.

4.13 — Production Producer Configuration

A production producer configuration should be derived from application requirements rather than copied indiscriminately from another workload.

ILLUSTRATIVE DURABLE PRODUCER PROFILE
# Cluster discovery

bootstrap.servers=broker1.example.net:9093,broker2.example.net:9093

# Client identification

client.id=order-event-producer

# Serialization

key.serializer=org.apache.kafka.common.serialization.StringSerializer

value.serializer=org.apache.kafka.common.serialization.StringSerializer

# Delivery reliability

acks=all
enable.idempotence=true
retries=2147483647

# Batching and compression

batch.size=65536
linger.ms=5
compression.type=zstd

# Memory and concurrency

buffer.memory=67108864
max.in.flight.requests.per.connection=5

# Timeout boundaries

request.timeout.ms=30000
delivery.timeout.ms=120000
max.block.ms=60000

# TLS example

security.protocol=SSL

This profile illustrates a durable Java producer configuration with moderate batching and compression. It is not a universally optimised production profile.

The TLS example assumes that the broker certificates are trusted by the client and that any additional authentication, truststore or client certificate requirements have been configured separately.

4.14 — Application-Level Delivery Handling

Applications should inspect asynchronous delivery outcomes rather than treating record submission as confirmation of successful persistence.

JAVA PRODUCER · DELIVERY CALLBACK
// Illustrative Java producer fragment

ProducerRecord<String, String> record =
    new ProducerRecord<>(
        "customer-orders",
        "ORD-50182",
        eventJson
    );

try {

    producer.send(record, (metadata, exception) -> {

        if (exception != null) {

            // Report and classify delivery failure.
            // Outcome may be ambiguous after timeout.

            logger.error(
                "Kafka delivery failed",
                exception
            );

        } else {

            logger.info(
                "Delivered topic={} partition={} offset={}",
                metadata.topic(),
                metadata.partition(),
                metadata.offset()
            );

        }

    });

} catch (KafkaException exception) {

    // Handle synchronous producer submission errors.

    logger.error(
        "Producer submission failed",
        exception
    );

}

This fragment demonstrates delivery reporting. A complete application also requires producer lifecycle management, exception classification, metrics, shutdown handling and a deliberate strategy for failed or uncertain delivery outcomes.

4.15 — Producer Observability

Producer-side metrics provide evidence about application publishing behaviour before records reach the Kafka storage layer.

Java Producer Metric What It Reveals Investigation Area
record-send-rate Record transmission rate. Throughput changes.
record-error-rate Record delivery errors. Broker, network or client failures.
record-retry-rate Record retry activity. Transient delivery problems.
batch-size-avg Average batch size in bytes. Batching efficiency.
compression-rate-avg Compressed-to-uncompressed batch ratio. Compression efficiency.
buffer-available-bytes Available producer buffer memory. Memory pressure and backpressure.
record-queue-time-avg Average record batching queue time. Local producer delay.
request-latency-avg Average network request latency. Broker and network response time.
produce-throttle-time-avg Average producer throttling duration. Quota enforcement.
requests-in-flight Outstanding network requests. Request concurrency and stalled delivery.

Metrics should be correlated across producer clients, brokers, partitions and infrastructure. An increase in producer latency can originate from local queueing, network delay, replication problems, broker processing or quota enforcement.

4.16 — Engineering Incident: The Stalled Producer

Imagine an enterprise event-processing platform that normally publishes 100,000 records per second. Following an infrastructure change, application publishing latency increases and producer buffers begin to fill.

100K
Generated Records/s
60K
Accepted Records/s
40K
Rate Deficit/s
92%
Buffer Utilisation

The application is generating events faster than the cluster is accepting them. Unless production slows or ingestion capacity recovers, the system will experience increasing backpressure.

INVESTIGATION STAGE 01

Establish the Delivery Failure Boundary

Determine whether application submission, local record accumulation, network transmission or broker acknowledgement is experiencing delay.

INVESTIGATION STAGE 02

Inspect Producer Metrics

Examine buffer availability, record queue time, request latency, retry activity and producer error rates.

INVESTIGATION STAGE 03

Validate Network Reachability

Confirm DNS resolution, broker advertised addresses, TCP connectivity, TLS negotiation and relevant firewall policy.

INVESTIGATION STAGE 04

Examine Broker and Replica Health

Inspect partition leadership, ISR membership, under-replicated partitions, broker request processing and storage performance.

INVESTIGATION STAGE 05

Investigate Quota Enforcement

Determine whether client or user quotas are throttling produce requests and contributing to the ingestion deficit.

INVESTIGATION STAGE 06

Apply Evidence-Based Remediation

Resolve the verified bottleneck, restore replica health, correct network connectivity, adjust appropriate quotas or reduce application production pressure.

PRODUCER CONNECTIVITY AND CLUSTER INSPECTION
# Inspect DNS resolution

dig broker1.example.net

# Test TCP reachability

nc -vz broker1.example.net 9093

# Inspect TLS negotiation and hostname verification

openssl s_client \
  -connect broker1.example.net:9093 \
  -servername broker1.example.net \
  -verify_hostname broker1.example.net \
  -verify_return_error

# Inspect broker protocol capabilities

kafka-broker-api-versions.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties

# Inspect topic leadership and replica assignments

kafka-topics.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --topic customer-orders

These diagnostic commands use illustrative endpoints and require the appropriate tools, credentials, trusted certificates and authorised network access.

4.17 — Producer Engineering Trade-Offs

Design Decision Potential Benefit Potential Trade-Off
Larger batches Higher throughput efficiency. Additional buffering requirements.
Longer linger interval More opportunities to combine records. Additional batching latency.
Stronger compression Lower bandwidth and storage demand. Additional CPU consumption.
acks=all Replication-aware delivery confirmation. Dependence on ISR health and replication latency.
Producer idempotence Protection against eligible retry duplicates. Compatible configuration requirements.
Larger memory buffer Greater temporary burst absorption. Higher memory demand and potentially more queued data.
Longer delivery timeout More opportunity for transient recovery. Delayed failure reporting.
Transactions Atomic coordination of Kafka writes and offsets. Additional coordination and visibility constraints.

Engineering Takeaways

✓ Kafka producers are partition-aware distributed systems clients rather than simple message senders.
✓ Bootstrap servers enable discovery of broker endpoints and partition leadership.
✓ Record batching improves network and request-processing efficiency.
✓ Compression exchanges CPU processing for potentially reduced network and storage demand.
✓ Acknowledgement configuration determines the broker confirmation required for successful production.
✓ Minimum ISR requirements influence durability and write availability during replica failures.
✓ Lost acknowledgements can create ambiguous delivery outcomes.
✓ Producer idempotence prevents eligible retry-related duplicate log appends.
✓ Kafka transactions provide atomicity within defined Kafka transactional boundaries.
✓ Producer buffering cannot resolve a sustained ingestion capacity deficit.
✓ Production troubleshooting requires correlated client, broker, replication and network evidence.
NETWORK INSIGHT / APACHE KAFKA / 04

Kafka Producer Delivery Simulator

Investigate batching, compression, acknowledgements, retry behaviour and reliable event delivery.

Generated 0
Buffered 0
Unique stored 0
Retries 0
Duplicates 0
Failed / unknown 0
PRODUCER CONFIGURATION

Configure the Delivery Pipeline

Teaching equivalent of a byte-based batch.size limit.
Maximum intentional batching delay in this model.
Illustrative compression ratios.
Controls the producer acknowledgement requirement.
Maximum additional attempts per batch.
Topic min.insync.replicas is fixed at 2.

LIVE PRODUCER DELIVERY PIPELINE ENGINE ONLINE
KAFKA PRODUCER PROCESS Application Producer API 0 records Record Accumulator 0 buffered Compression Engine NONE Network ONLINE KAFKA LEADER 0 stored ISR 3 / 3 BROKER ACKNOWLEDGEMENT DELIVERY STATE READY
RECORD ACCUMULATOR

Producer Buffer

Waiting for application records.

TRANSMISSION INSPECTION

In-Flight Batch

Batch ID—
Records0
Attempt—
Delivery stateIDLE
Required ACK—
CONTROLLED FAULT INJECTION

Producer Reliability Laboratory

Inject delivery failures and inspect the difference between a failed request and a successfully stored record whose acknowledgement never reaches the producer.

Network online. No acknowledgement fault armed.
TRANSMISSION EFFICIENCY

Compression Telemetry

Uncompressed attempted payload 0 KiB
Compressed attempted payload 0 KiB
Estimated payload savings 0%

Each generated record represents 1 KiB of application data. Compression ratios are illustrative and include retry attempts, not actual measured network traffic.

DELIVERY SEMANTICS

Reliability Evidence

Acknowledged records 0
Sent without ACK 0
Duplicate writes prevented 0
Physical log entries 0
Generate records to begin investigating delivery behaviour.
BROKER STORAGE EVIDENCE

Partition Log Inspector

OFFSET RECORD ID BATCH PRODUCER SEQUENCE WRITE RESULT

The same application record can appear at multiple offsets when a non-idempotent producer retries a successfully stored batch after losing its acknowledgement.

PRODUCER ENGINEERING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 04

The Lost Acknowledgement Incident

Investigate duplicate delivery and determine how idempotent production changes the outcome of a retry.

1 Publish a batch successfully with idempotence disabled.
2 Drop the next acknowledgement and publish another batch.
3 Observe the retry create duplicate records in the partition log.
4 Enable idempotent production, drop another acknowledgement and publish a new batch. Observe duplicate prevention.
5 Reduce the ISR count to one and publish another batch. Restore the ISR count to at least two before retries expire, and observe successful delivery.
Investigation ready
ENGINEERING PRINCIPLE 01

Acknowledgement Is Not Consumption

A producer acknowledgement confirms a broker-side delivery condition. It does not indicate that a downstream consumer has processed the event or completed its business transaction.

ENGINEERING PRINCIPLE 02

Idempotence Is Not End-to-End Exactly Once

Producer idempotence prevents duplicate log entries caused by supported producer retries. End-to-end exactly-once processing requires additional transactional or application-level guarantees.

05 Distributed Event Consumption · Kafka Engineering

Kafka Consumer Architecture

Kafka consumers transform distributed event logs into independent application workflows through partition-aware fetching, coordinated consumer groups, offset tracking and fault-tolerant workload distribution.

Unlike traditional messaging architectures in which a central queue removes messages after delivery, Kafka maintains records independently of the applications consuming them.

Each consumer group can maintain its own processing progress, allowing multiple applications to consume the same event stream independently and at different speeds.

This separation between event storage and application processing is fundamental to Kafka's ability to support microservices, real-time analytics, security monitoring, distributed data pipelines and event-driven systems.

DISTRIBUTED CONSUMER GROUP ARCHITECTURE PARALLEL EVENT PROCESSING
KAFKA TOPIC · CUSTOMER-ORDERS PARTITION 0 PARTITION 1 PARTITION 2 PARTITION 3 PARTITION 4 PARTITION 5 CONSUMER GROUP A · ORDER PROCESSING CONSUMER A1 CONSUMER A2 CONSUMER A3 P0 + P1 P2 + P3 P4 + P5 CONSUMER GROUP B · ANALYTICS CONSUMER B1 CONSUMER B2 P0 + P1 + P2 P3 + P4 + P5 INDEPENDENT GROUP OFFSETS · SHARED EVENT LOG LOGICAL RECORD FLOW · CONSUMERS INITIATE FETCH REQUESTS
Figure 1 — Two independent consumer groups read the same Kafka topic. Each group distributes the six partitions among its own members and maintains independent committed offsets. Arrows represent logical record flow rather than broker-initiated message delivery.

5.1 — The Consumer as a Distributed Systems Client

A Kafka consumer is responsible for discovering cluster metadata, establishing broker connections, obtaining partition assignments, fetching records, deserialising data and coordinating processing progress.

Applications using the standard Kafka consumer API commonly execute a poll loop that retrieves available records and passes them to application processing logic.

CONSUMER COMPONENT 01

Fetch Manager

Retrieves record batches from the appropriate brokers and manages partition-specific fetching progress.

CONSUMER COMPONENT 02

Group Membership

Coordinates membership, partition assignment and group lifecycle operations when using automatic group management.

CONSUMER COMPONENT 03

Offset Management

Tracks consumption positions and supports committing restart positions for subsequent recovery.

5.2 — Pull-Based Event Consumption

Kafka consumers normally retrieve records through a pull-based architecture. Rather than brokers independently pushing every new record to applications, consumers issue fetch requests identifying partitions and desired offsets.

This allows consumers to regulate their own retrieval and processing behaviour according to application capacity.

CONSUMER FETCH REQUEST SEQUENCE PULL-BASED ARCHITECTURE
KAFKA CONSUMER PARTITION BROKER FETCH REQUEST · P0 · OFFSET 104 READ AVAILABLE RECORDS 104 · 105 · 106 · 107 FETCH RESPONSE · RECORD BATCHES BUFFER AND DESERIALISE Deliver records to application NEXT FETCH · OFFSET 108 FETCH PROGRESS IS INDEPENDENT OF OFFSET COMMIT PROGRESS
Figure 2 — Simplified fetch request lifecycle. Consumers request records beginning at a specified offset. Internal fetching and application polling are not necessarily one-to-one operations. Fetching commonly targets partition leaders, although supported rack-aware configurations can permit fetching from preferred replicas.
Configuration Purpose Engineering Consideration
fetch.min.bytes Desired minimum data for a fetch response. Larger values may improve batching efficiency.
fetch.max.wait.ms Maximum broker wait for the minimum fetch data. Influences low-volume fetch latency.
fetch.max.bytes Target maximum data returned in a fetch response. Not an absolute limit for the first oversized batch.
max.partition.fetch.bytes Target fetch data limit per partition. Influences memory use and retrieval efficiency.
max.poll.records Maximum records returned by a single poll. Controls application batch size, not underlying fetch size.

5.3 — Consumer Groups and Workload Distribution

A consumer group represents a logical application or processing workload composed of one or more consumer instances.

Within a conventional automatically managed consumer group, each partition is assigned to at most one active consumer at a time. A consumer can own multiple partitions.

Different consumer groups can independently consume the same partition without interfering with each other's committed offsets.

APPLICATION GROUP A

Order Fulfilment

Processes incoming orders and initiates fulfilment operations.

APPLICATION GROUP B

Real-Time Analytics

Calculates business metrics from the same order event stream.

APPLICATION GROUP C

Fraud Detection

Independently evaluates transaction patterns and suspicious application behaviour.

ARCHITECTURAL DECOUPLING

Adding a new consumer group does not require existing producers to understand the new application's processing logic. However, additional groups increase broker read traffic, network utilisation and potentially storage read pressure.

5.4 — Partition Assignment and Parallelism

Partition count establishes an important upper boundary for active partition ownership within a conventional consumer group.

Consider a topic containing six partitions. Three consumer instances can divide these partitions between themselves, while six consumers can potentially own one partition each.

Three Consumer Instances

Consumer 1 P0 P1
Consumer 2 P2 P3
Consumer 3 P4 P5

Each consumer manages two partitions. All six partitions have active owners.

Eight Consumer Instances

Consumer 1 P0
Consumer 2 P1
Consumer 3 P2
Consumer 4 P3
Consumer 5 P4
Consumer 6 P5
Consumers 7–8 IDLE

Two consumers have no partition assignment. Adding further consumers does not increase partition-level ownership parallelism.

Active Consumers ≤ min(Partitions, Group Members)
Simplified conventional consumer group with all members subscribing to the same single topic. Application-level worker concurrency is a separate design consideration.

Increasing partition count can improve opportunities for parallel processing, but it also introduces additional metadata, replication, storage and operational overhead.

Applications must also consider ordering requirements. Kafka provides ordering within an individual partition, not a global ordering guarantee across all partitions.

5.5 — The Consumer Group Coordinator

Consumer group management is coordinated by a Kafka broker acting as the group coordinator. This coordinator manages group membership and participates in offset management and assignment coordination.

Kafka stores committed consumer offsets in an internal compacted topic named __consumer_offsets. Group coordination is associated with the broker responsible for the relevant internal topic partition.

GROUP COORDINATION CONTROL PLANE MEMBERSHIP AND OFFSET STATE
KAFKA CLUSTER GROUP COORDINATOR Membership · Commit Handling __consumer_offsets Internal Group State Storage DATA PARTITION BROKERS Record Fetch Responses CONSUMER 01 CONSUMER 02 CONSUMER 03 Partitions 0–1 Partitions 2–3 Partitions 4–5 GROUP CONTROL TRAFFIC RECORD FETCH TRAFFIC COORDINATION AND RECORD DELIVERY ARE DISTINCT FUNCTIONS
Figure 3 — Consumers communicate with the group coordinator for group-related operations and with data brokers for record retrieval. The coordinator and data broker roles can reside on the same physical broker.

Classic Group Protocol

Uses the classic group membership and rebalance mechanism. A selected group member computes partition assignments using the negotiated assignment strategy.

Common protocol operations include JoinGroup, SyncGroup and Heartbeat.

New Consumer Group Protocol

The newer consumer rebalance protocol moves assignment responsibility towards the broker coordinator and supports incremental reconciliation of consumer assignments.

Its configuration and heartbeat behaviour differ from the classic protocol. Availability depends on compatible Kafka broker and client versions.

5.6 — Consumer Offsets and Processing Positions

Every Kafka partition contains records identified by monotonically increasing offsets.

Consumer position and committed offset are related but distinct concepts. The current consumer position represents the next offset to be returned to the application, while the committed offset represents a stored restart position.

A correctly designed processing workflow normally commits offsets only after the corresponding application processing has reached its intended completion boundary.

OFFSET AND PROCESSING POSITION CUTAWAY PARTITION 0
DISTRIBUTED LOG · PARTITION 0 100 101 102 103 104 105 106 107 108 109 COMMITTED OFFSET 104 POSITION 107 END OFFSET 110 COMMITTED PROCESSING RANGE DELIVERED · NOT COMMITTED NOT YET DELIVERED RESTART FROM COMMITTED OFFSET 104
Figure 4 — The committed offset is 104, the current consumer position is 107 and the illustrated end offset is 110. Records 104–106 have been delivered to the application but their processing progress has not been committed. A restart may therefore cause those records to be delivered again.
OFFSET COMMIT CONVENTION

If an application has successfully processed record offset 106 and all required preceding records, it normally commits offset 107. The committed offset identifies the next restart position, not the last processed record.

5.7 — Automatic and Manual Offset Commits

Kafka consumer applications can use automatic offset commits or explicitly control when processing progress is committed.

COMMIT MODEL 01

Automatic Commit

The client periodically commits consumption positions. Correctness depends on how the application coordinates polling and processing.

COMMIT MODEL 02

Synchronous Commit

The application explicitly commits offsets and waits for the operation to complete or fail.

COMMIT MODEL 03

Asynchronous Commit

The application submits offset commits without waiting synchronously, requiring deliberate error and ordering management.

Automatic commits are not an acknowledgement that an external database operation, payment transaction or business workflow has succeeded.

When application processing is asynchronous, committing a position beyond unfinished records can cause those records to be skipped after consumer recovery.

JAVA CONSUMER · MANUAL OFFSET COMMIT
// Configure enable.auto.commit=false

consumer.subscribe(
    List.of("customer-orders")
);

try {

    while (true) {

        ConsumerRecords<String, String> records =
            consumer.poll(Duration.ofMillis(500));

        for (ConsumerRecord<String, String> record : records) {

            // Must complete successfully or throw.

            processEvent(record);

        }

        // Commit only after the entire returned batch
        // has been successfully processed.

        if (!records.isEmpty()) {

            consumer.commitSync();

        }

    }

} finally {

    consumer.close();

}

This simplified Java example illustrates sequential batch processing followed by a synchronous commit. It assumes processing failures terminate the loop rather than being silently ignored.

Production implementations require appropriate shutdown handling, commit error handling, bounded processing time, duplicate-safe side effects and recovery behaviour.

5.8 — Consumer Failures and Event Redelivery

Consumer recovery is based on the group's stored processing positions. When a consumer fails, another consumer can eventually acquire its partitions and resume from the relevant committed offsets.

PROCESSING FAILURE AND OFFSET RECOVERY DUPLICATE PROCESSING SCENARIO
01 · ORIGINAL CONSUMER 02 · EXTERNAL SIDE EFFECT 03 · CONSUMER FAILURE 04 · REPLACEMENT CONSUMER Read event 104 from the partition. Database transaction succeeds. Offset 105 was not committed. Resume consumption from committed offset 104. EVENT 104 DATABASE UPDATED COMMIT MISSING EVENT 104 AGAIN EXTERNAL SIDE EFFECT MAY BE EXECUTED TWICE
Figure 5 — A consumer successfully updates an external database but fails before committing its next offset. Recovery from the earlier committed position causes the event to be delivered again.

Applications requiring duplicate-safe processing can use stable event identifiers, database uniqueness constraints, transactional inbox patterns or other application-level idempotency mechanisms.

Processing Sequence Failure Window Potential Outcome
Commit before processing Failure after commit but before processing. Event processing may be lost.
Process before commit Failure after processing but before commit. Event may be processed again.
Kafka transactional processing Failure before transactional completion. Uncommitted output can be aborted and input retried.
Idempotent external processing Previously processed event is delivered again. Duplicate side effects can be prevented.

5.9 — Consumer Group Rebalancing

Rebalancing is the process through which Kafka adjusts partition ownership when consumer group membership or relevant subscription state changes.

Rebalancing can occur when consumers join or leave, membership expires, topic subscriptions change or subscribed topics gain additional partitions.

CONSUMER FAILURE AND PARTITION REDISTRIBUTION GROUP RECOVERY
STATE A · HEALTHY CONSUMER GROUP CONSUMER 01 CONSUMER 02 CONSUMER 03 P0 P1 P2 P3 P4 P5 CONSUMER 02 FAILURE MEMBERSHIP EXPIRES OR IS REMOVED GROUP ASSIGNMENT RECONCILIATION P2 AND P3 REQUIRE NEW OWNERS STATE B · RECOVERED GROUP CONSUMER 01 CONSUMER 03 P0 P1 P2 · NEW P4 P5 P3 · NEW ALL PARTITIONS HAVE ACTIVE OWNERS AGAIN
Figure 6 — Illustrative partition redistribution after a consumer failure. The actual assignment depends on the selected group protocol, assignment strategy, subscription state and group membership.

5.10 — Eager and Cooperative Rebalancing

The way partitions are revoked and reassigned influences application availability during membership changes.

Eager Rebalancing

PROCESS
ALL REVOKED
RESUME

Consumers revoke their existing assignments before receiving new assignments, potentially creating a broad processing interruption.

Cooperative Rebalancing

PROCESS
MOVE
PROCESS

Only partitions that need to change ownership are revoked during incremental reassignment. Unaffected partitions can continue processing.

Cooperative rebalancing in the classic group protocol can require multiple coordination rounds. It reduces unnecessary revocations but does not eliminate every interruption.

Classic Assignment Strategy Behaviour
RangeAssignor Assigns partition ranges on a per-topic basis.
RoundRobinAssignor Distributes partitions across eligible members using a round-robin approach.
StickyAssignor Attempts balanced assignments while preserving existing ownership where possible.
CooperativeStickyAssignor Combines sticky assignment objectives with cooperative partition reassignment.

These are classic Java consumer assignment strategies. The newer consumer group protocol uses broker-side assignment mechanisms and different configuration controls.

5.11 — Heartbeats, Session Timeouts and Poll Intervals

Consumer group coordination must distinguish between healthy members, failed members and applications that remain connected but are no longer making appropriate processing progress.

LIVENESS CONTROL

heartbeat.interval.ms

Controls heartbeat frequency for compatible classic-protocol consumers. Heartbeats communicate continued group membership.

FAILURE DETECTION

session.timeout.ms

Establishes the classic-protocol membership expiration boundary when expected heartbeat activity is missing.

PROCESSING PROGRESS

max.poll.interval.ms

Limits the permitted interval between application poll calls when using consumer group management.

HEARTBEAT AND POLL PROGRESS TIMELINE ILLUSTRATIVE CLASSIC GROUP
BACKGROUND HEARTBEAT ACTIVITY HB HB HB APPLICATION PROCESSING PROGRESS LONG-RUNNING APPLICATION PROCESSING POLL OVERDUE MAX POLL INTERVAL LAST POLL CONNECTION LIVENESS DOES NOT GUARANTEE APPLICATION PROGRESS
Figure 7 — A consumer can maintain background heartbeat activity while application processing delays the next poll. Exceeding the maximum poll interval can disrupt group membership. Static membership changes the timing of subsequent partition reassignment.
PROTOCOL VERSION CONSIDERATION

With the newer consumer group protocol, heartbeat interval and session timeout controls are managed through broker-side configuration rather than the corresponding classic client settings. Engineers must validate the active protocol before tuning these parameters.

5.12 — Static Consumer Group Membership

Static membership allows compatible consumer instances to identify themselves using a stable group.instance.id.

This can reduce unnecessary partition redistribution during short-lived restarts, particularly in environments where application instances have persistent identities.

STATIC CONSUMER MEMBERSHIP EXAMPLE
group.id=order-processing

group.instance.id=order-worker-01

client.id=order-worker-01

# Every active static member requires
# a unique group.instance.id.

Static membership is particularly relevant to orchestrated application deployments with stable instance identifiers. It must be configured carefully because duplicate identities can result in fencing and longer failure detection boundaries can delay recovery.

5.13 — Understanding Consumer Lag

Consumer lag measures the distance between a consumer group's processing position and an applicable partition end position.

Operational tools commonly calculate committed offset lag by subtracting the group's committed offset from the reported log end offset.

Committed Offset Lag = End Offset − Committed Offset
Offset distance rather than a guaranteed count of application records. Compaction, transactional records and isolation levels can affect interpretation.
125K
End Offset
100K
Committed Offset
25K
Offset Lag
20%
End Offset Ratio*

*The ratio is illustrative only and is not a recommended general-purpose Kafka lag metric. Offset origins and retention boundaries vary.

Partition-Level Consumer Lag

Illustrative monitoring snapshot · order-processing consumer group · common scale of 0–60,000 offsets.

Partition 0
2,000
Partition 1
3,000
Partition 2
60,000
Partition 3
1,500
Partition 4
12,000
Partition 5
2,500
INVESTIGATION REQUIRED — Partition 2 accounts for 60,000 of the group's 81,000 offset lag. Investigate partition traffic distribution, consumer assignment and processing bottlenecks before increasing consumer count.

A single aggregate lag measurement can hide significant partition-level imbalance.

A hot partition may be receiving disproportionately high traffic because of skewed partition keys. Alternatively, its assigned consumer may be experiencing slow external operations, resource contention or repeated processing failures.

5.14 — Backlog Growth and Recovery Capacity

Consumer lag grows when new records arrive faster than the application can successfully process them.

Backlog Growth = Arrival Rate − Processing Rate
Simplified steady-rate model assuming one offset increment per application record and prompt commits.
80K
Arrival Rate/s
60K
Processing Rate/s
20K
Backlog Growth/s
1.2M
Growth Per Minute
CONSUMER BACKLOG GROWTH AND RECOVERY CAPACITY MODEL
1.2M 900K 600K 300K 0 CAPACITY RESTORED +20K/s −10K/s 0s 60s 120s 180s CONSTANT ARRIVAL RATE · PROCESSING CAPACITY CHANGES AT 60 SECONDS
Figure 8 — A processing deficit of 20,000 records per second creates a backlog of 1.2 million records in 60 seconds. Increasing processing capacity to 90,000 records per second provides 10,000 records per second of net recovery capacity.
Recovery Time = Backlog ÷ (Processing Rate − Arrival Rate)
Applicable only when processing capacity exceeds incoming event rate and the assumed rates remain stable.
CONSUMER BACKLOG RECOVERY CALCULATION
Current backlog       = 1,200,000 records

Incoming event rate   = 80,000 records/s

New processing rate   = 90,000 records/s

Net recovery capacity = 90,000 - 80,000

                      = 10,000 records/s

Estimated recovery    = 1,200,000 / 10,000

                      = 120 seconds

                      = 2 minutes

Merely restoring processing capacity to match the incoming event rate stops further backlog growth but does not eliminate the accumulated backlog.

5.15 — Consumer Concurrency and Backpressure

The standard Java KafkaConsumer is not generally thread-safe. Applications should avoid invoking its methods concurrently from arbitrary worker threads.

A common architecture uses a dedicated consumer thread for polling and partition management, combined with bounded application worker queues.

CONSUMER WORKER POOL ARCHITECTURE BOUNDED PROCESSING
KAFKA PARTITIONS Fetch Responses DEDICATED CONSUMER THREAD Poll · Pause · Resume · Commit · Assignment PARTITION 0 QUEUE PARTITION 1 QUEUE PARTITION 2 QUEUE BOUNDED CAPACITY BOUNDED CAPACITY BOUNDED CAPACITY WORKER A WORKER B WORKER C PROCESS RECORDS PROCESS RECORDS PROCESS RECORDS CONTIGUOUS COMPLETION TRACKER Safe Commit Positions Returned to Consumer Thread
Figure 9 — A conceptual consumer architecture separates Kafka API operations from application processing. Bounded queues, partition-aware processing and contiguous completion tracking prevent unsafe offset advancement.
OUT-OF-ORDER COMPLETION HAZARD

Suppose records 104, 105 and 106 are processed concurrently. If record 106 completes while record 105 remains unfinished, committing offset 107 may incorrectly skip unfinished work during recovery. Commit tracking must respect the contiguous successfully processed range.

Applications can use pause and resume operations to regulate retrieval from selected partitions while continuing to participate in group management. Pausing consumption does not remove the requirement to maintain the appropriate polling lifecycle.

5.16 — Offset Reset and Event Replay

Kafka's persistent event log enables applications to revisit historical events, provided those records remain available under the topic's retention and compaction policies.

Event replay is valuable for rebuilding application state, recovering from processing defects, creating new analytical models and reconstructing materialised views.

RESET POLICY 01

earliest

Starts from the earliest available offset when no valid committed offset exists.

RESET POLICY 02

latest

Starts from the applicable end position when no valid committed offset exists.

RESET POLICY 03

none

Reports an error instead of automatically selecting a replacement position when the committed offset is unavailable.

The auto.offset.reset setting is not a general instruction to replay a topic on every application restart. It applies when the consumer has no usable committed position.

CONSUMER GROUP OFFSET INSPECTION AND RESET
# Inspect consumer group offsets

kafka-consumer-groups.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --group order-processing

# Preview an offset reset
# Stop the target group's consumers first.

kafka-consumer-groups.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --group order-processing \
  --topic customer-orders \
  --reset-offsets \
  --to-earliest \
  --dry-run

# Execute only after reviewing the preview
# and validating duplicate-processing risks.

kafka-consumer-groups.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --group order-processing \
  --topic customer-orders \
  --reset-offsets \
  --to-earliest \
  --execute
PRODUCTION CHANGE CONTROL

Resetting consumer offsets changes application restart positions. It can trigger repeated processing, duplicate external side effects and substantial downstream load. Record the original offsets, validate the replay boundary and obtain appropriate operational approval before executing a production reset.

5.17 — Transactional Consumer Isolation

Kafka consumers can control the visibility of transactional records through the isolation.level configuration.

read_uncommitted

Can return records from transactions that have not committed, including records from transactions that are subsequently aborted.

read_committed

Returns non-transactional records and committed transactional records while excluding aborted transactional records.

A read_committed consumer is constrained by the last stable offset, which prevents it from reading beyond an unresolved transactional boundary.

Consequently, long-running or stalled transactions can delay visibility of later records even when those records have already been appended to the partition log.

TRANSACTIONAL VISIBILITY BOUNDARY READ_COMMITTED
200 201 202 203 204 205 206 207 VISIBLE VISIBLE VISIBLE OPEN TX OPEN TX WAITING WAITING WAITING LAST STABLE OFFSET 203 AVAILABLE TO CONSUMER TRANSACTIONAL VISIBILITY RESTRICTED VISIBILITY CAN ADVANCE AFTER TRANSACTION RESOLUTION
Figure 10 — An unresolved transaction beginning at offset 203 establishes the illustrated last stable offset. A read_committed consumer cannot advance beyond this boundary until the relevant transaction state is resolved.

5.18 — Production Consumer Configuration

Consumer configuration must balance processing latency, memory utilisation, failure recovery, partition assignment stability and application correctness.

ILLUSTRATIVE JAVA CONSUMER PROFILE
# Cluster discovery

bootstrap.servers=broker1.example.net:9093,broker2.example.net:9093

# Consumer identity

group.id=order-processing

client.id=order-consumer-01

# Deserialisation

key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

value.deserializer=org.apache.kafka.common.serialization.StringDeserializer

# Explicit processing progress management

enable.auto.commit=false

auto.offset.reset=earliest

isolation.level=read_committed

# Fetch and application batch controls

fetch.min.bytes=1

fetch.max.wait.ms=500

fetch.max.bytes=52428800

max.partition.fetch.bytes=1048576

max.poll.records=500

# Classic group protocol example

group.protocol=classic

session.timeout.ms=45000

heartbeat.interval.ms=3000

max.poll.interval.ms=300000

# Cooperative assignment

partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor

# TLS example

security.protocol=SSL

This is an illustrative profile for a compatible modern Java consumer using the classic group protocol. It is not a universally optimised production configuration.

Existing groups may require a coordinated migration procedure before changing assignment strategies. TLS trust, authentication, broker limits and application processing characteristics must also be validated.

5.19 — Consumer Observability and Performance Metrics

Effective consumer monitoring combines application processing measurements, Kafka client metrics, group coordination information and infrastructure telemetry.

Metric What It Reveals Investigation Area
records-consumed-rate Record consumption rate. Retrieval throughput changes.
records-lag-max Maximum observed consumer position lag. Partition-level consumption imbalance.
fetch-latency-avg Average fetch request latency. Broker or network response delay.
fetch-rate Fetch request activity. Retrieval efficiency and request patterns.
bytes-consumed-rate Consumer data retrieval rate. Network and workload demand.
commit-latency-avg Average offset commit latency. Coordinator responsiveness.
assigned-partitions Current partition assignment count. Workload distribution.
rebalance-rate-per-hour Rebalance frequency where exposed. Membership instability.
Application processing latency Business operation completion time. External services and processing bottlenecks.
Worker queue depth Locally accumulated unfinished work. Application backpressure.

Exact metric availability depends on client implementation, Kafka version and active group protocol.

Client-side consumption metrics do not necessarily represent completed business operations. An application may retrieve records quickly while processing them slowly in local worker queues.

5.20 — Engineering Incident: The Growing Consumer Backlog

Consider an event-driven order-processing platform with six Kafka partitions and six consumer instances. The application begins experiencing delayed order fulfilment despite healthy Kafka producer throughput.

6/6
Active Consumers
81K
Total Offset Lag
74%
Lag on Partition 2
850ms
P2 Processing p95
INVESTIGATION STAGE 01

Establish the Scope of Consumer Lag

Inspect committed offsets and lag for every partition. Determine whether the backlog affects the entire group or a limited subset of partitions.

INVESTIGATION STAGE 02

Identify the Responsible Consumer

Map the affected partition to its current consumer instance. Examine application logs, CPU, memory, garbage collection and worker queue utilisation.

INVESTIGATION STAGE 03

Compare Partition Arrival Rates

Determine whether the affected partition receives significantly more records than other partitions because of skewed event keys or uneven workload characteristics.

INVESTIGATION STAGE 04

Examine External Dependencies

Measure database query latency, connection pool utilisation, HTTP request duration and downstream service error rates.

INVESTIGATION STAGE 05

Validate Group Stability

Inspect consumer restarts, membership changes, poll interval violations, heartbeat problems and rebalance frequency.

INVESTIGATION STAGE 06

Validate Kafka and Network Performance

Compare fetch latency, broker resource usage, network throughput, TLS connectivity and transactional visibility boundaries.

INVESTIGATION STAGE 07

Restore Processing Capacity

Correct the verified bottleneck and ensure processing capacity exceeds the incoming event rate until the backlog has recovered.

ILLUSTRATIVE CONSUMER GROUP CLI EVIDENCE
$ kafka-consumer-groups.sh --describe ...

GROUP              PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG

order-processing   0          148000          150000          2000

order-processing   1          147000          150000          3000

order-processing   2          190000          250000          60000

order-processing   3          148500          150000          1500

order-processing   4          138000          150000          12000

order-processing   5          147500          150000          2500

# Simplified illustrative output.
# Actual CLI output includes additional columns.
ENGINEERING DIAGNOSIS

Adding a seventh consumer to this six-partition group does not create an additional active partition owner. If the bottleneck is isolated to partition 2, investigate key distribution, application processing and downstream dependencies before increasing consumer replica count.

5.21 — Consumer Engineering Trade-Offs

Design Decision Potential Benefit Potential Trade-Off
More consumer instances Greater partition ownership parallelism. Limited by available partitions.
More partitions Additional processing parallelism. Metadata overhead and key mapping changes.
Larger fetch responses Improved network efficiency. Greater consumer memory demand.
Larger poll batches Potentially improved processing efficiency. Longer processing and recovery windows.
Frequent offset commits Smaller potential replay ranges. Additional coordinator traffic.
Longer session timeout Greater tolerance of temporary interruptions. Potentially slower failure detection.
Cooperative rebalancing Reduced unnecessary partition revocations. Protocol compatibility and migration considerations.
Static membership Greater assignment stability during short restarts. Identity management and recovery timing.
Application worker pools Additional processing concurrency. Ordering and offset coordination complexity.
read_committed isolation Excludes aborted transactional records. Visibility delays behind unresolved transactions.

Engineering Takeaways

✓ Kafka consumers retrieve records through partition-aware fetch requests.
✓ Independent consumer groups can process the same event stream at different speeds.
✓ Partition count limits active partition ownership parallelism within conventional consumer groups.
✓ Consumer position and committed offset represent different stages of consumption progress.
✓ Offset commits must align with the application's actual processing completion boundary.
✓ Consumer failures can cause previously delivered records to be processed again.
✓ Group rebalancing redistributes partition ownership following relevant membership changes.
✓ Classic and newer consumer group protocols have different coordination and configuration behaviour.
✓ Heartbeat activity does not necessarily establish healthy application processing progress.
✓ Consumer lag must be investigated at partition level rather than relying solely on aggregate group measurements.
✓ Backlog recovery requires processing capacity greater than the incoming event rate.
✓ Concurrent application processing requires careful ordering and contiguous offset tracking.
✓ Event replay is constrained by available log history and application side-effect safety.
✓ Transactional isolation can influence record visibility and apparent consumer lag.
NETWORK INSIGHT / APACHE KAFKA / 05

Consumer Group & Rebalancing Lab

Explore parallel event processing, partition ownership, committed offsets, consumer failures and workload redistribution.

Partitions 6
Online consumers 2
Unique processed 0
Committed lag 0
Rebalances 0
Reprocessed 0
CONSUMER GROUP CONFIGURATION

Configure the Processing Environment

Total incoming topic workload.
Processing budget per online consumer.
Automatic model commits processed positions every 5 seconds.
Single-topic eager assignment model.
LIVE CONSUMER GROUP COORDINATION MATRIX ● STABLE
TOPIC / ORDERS.CREATED / SIX PARTITIONS CONSUMER GROUP / ORDER-PROCESSING-GROUP GROUP COORDINATOR Generation 1 / STABLE
GROUP MEMBERSHIP CONTROL

Consumer Application Instances

Crash or recover an individual consumer. The coordinator will initiate a new assignment for the remaining online members.

COORDINATION STATE MACHINE

Rebalance Timeline

01 / DETECT Membership change
02 / REVOKE Pause and release ownership
03 / ASSIGN Redistribute partitions
04 / RESUME Continue from committed offsets
Consumer group is stable. All six partitions are assigned.
OFFSET AND PARTITION OWNERSHIP

Partition State Inspection

PARTITION OWNER LOG END POSITION COMMITTED PROCESSING LAG COMMITTED LAG

Offsets represent the next record position. Committed offsets are the durable restart checkpoints used by this simulation.

REAL-TIME PROCESSING TELEMETRY

Consumer Lag Monitor

RECENT SIMULATION TICKS
Committed lag Processing lag
Start producer traffic to observe workload behaviour.
CAPACITY ANALYSIS

Processing Capacity versus Ingestion

Configured ingestion 0 records/sec
Effective processing ceiling 6 records/sec
Idle online consumers 0
Uncommitted processed records 0
Total processing attempts 0
Last tick processing 0 records
Capacity is determined by consumers with assigned partitions.
DELIVERY SEMANTICS AND RECOVERY

Recent Processing Evidence

CONSUMER PARTITION OFFSET GENERATION RESULT

Records processed before a crash but not committed may be processed again by the new partition owner. This is a fundamental at-least-once processing consideration.

CONSUMER GROUP ENGINEERING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 05

The Consumer Scaling and Recovery Incident

Investigate parallel processing limits, offset recovery and the effect of scaling a consumer group.

1 Scale the group to three online consumers and observe the completed partition assignment.
2 Scale the group to seven online consumers. Observe at least one idle consumer.
3 Enable manual commits, publish 60 records and allow at least six records to be processed without committing.
4 Crash a consumer with assigned partitions and uncommitted work. Observe the rebalance and subsequent record reprocessing.
5 Allow the outstanding records to finish processing, then commit the processed offsets until committed lag reaches zero.
Investigation ready
ENGINEERING PRINCIPLE 01

Partition-Level Parallelism

Within a conventional Kafka consumer group, a partition is assigned to at most one consumer at a time. A consumer may own multiple partitions, but adding consumers beyond the partition count does not create additional partition-level parallelism.

ENGINEERING PRINCIPLE 02

Processing versus Committing

Processing a record and committing its offset are separate operations. A crash between those operations can cause record reprocessing. Applications must account for repeated processing when implementing reliable business workflows.

06 Distributed Resilience · Kafka Engineering

Kafka Replication and Fault Tolerance

Apache Kafka achieves distributed resilience by maintaining multiple copies of partition logs across independent brokers, coordinating replica progress and transferring partition leadership when failures occur.

In a production event-driven architecture, hardware failures, network interruptions, storage degradation and application restarts are expected operational events. A distributed platform must continue operating through these failures wherever its configured durability and availability requirements permit.

Kafka addresses these challenges through partition-level replication, leader and follower relationships, in-sync replica management, producer acknowledgement policies and controller-coordinated leadership changes.

Understanding how these mechanisms interact is essential when engineering platforms that must preserve important business events while maintaining predictable service availability.

DISTRIBUTED KAFKA REPLICATION ARCHITECTURE HEALTHY REPLICA SET
EVENT PRODUCER Produce Request · Partition 0 AVAILABILITY ZONE A AVAILABILITY ZONE B AVAILABILITY ZONE C BROKER 1 BROKER 2 BROKER 3 P0 · LEADER P0 · FOLLOWER P0 · FOLLOWER 100 101 102 103 100 101 102 103 100 101 102 103 LOCAL PARTITION LOG REPLICATED LOG REPLICATED LOG REPLICATION FACTOR = 3 · ISR = {1, 2, 3} Three replica copies across independent failure domains LOGICAL RECORD FLOW · FOLLOWERS INITIATE REPLICA FETCH REQUESTS
Figure 1 — Partition 0 has three replicas across three availability zones. Broker 1 is the leader, while brokers 2 and 3 maintain follower copies. The green paths represent logical replicated record flow. Followers retrieve records through fetch requests rather than unsolicited leader pushes.

6.1 — Why Kafka Requires Replication

A partition stored on a single broker introduces a single point of failure for that partition. If the broker becomes unavailable, applications may temporarily lose access to its event log.

If the underlying storage is permanently destroyed and no independent replica or backup exists, the associated records may also be permanently lost.

RESILIENCE OBJECTIVE 01

Data Durability

Maintain redundant copies of important event records so that individual storage failures do not necessarily destroy the event history.

RESILIENCE OBJECTIVE 02

Service Availability

Allow eligible surviving replicas to assume leadership when the current partition leader becomes unavailable.

RESILIENCE OBJECTIVE 03

Operational Continuity

Support maintenance, broker restarts and infrastructure changes without requiring every application to stop processing events.

6.2 — Replication Factor

The replication factor defines the number of assigned replica copies for each partition. This includes the leader replica and its followers.

A replication factor of three means that Kafka maintains three assigned copies of each partition on three different brokers.

12
Topic Partitions
3
Replication Factor
36
Assigned Replicas
12
Healthy Leaders
Total Assigned Replicas = Partitions × Replication Factor
Example: 12 partitions × 3 replicas = 36 assigned partition replicas distributed across the cluster.
Replication Factor Replica Structure Engineering Implication
1 One leader and no followers. No redundant partition copy.
2 One leader and one follower. Redundant storage, but limited failure margin.
3 One leader and two followers. Common production starting point.
5 One leader and four followers. Additional redundancy with greater storage and replication overhead.
IMPORTANT ARCHITECTURAL DISTINCTION

Replication factor describes assigned redundancy. It does not guarantee that every assigned replica is currently available, sufficiently caught up or eligible to become the next leader.

6.3 — Partition Leaders and Followers

Kafka manages leadership independently for each partition. A broker can simultaneously act as the leader for some partitions and as a follower for other partitions.

Producers send records to the current partition leader. Follower replicas fetch records from that leader and append them to their local logs.

BROKER 01 ONLINE
P0 · LEADER
P1 · FOLLOWER
P2 · FOLLOWER
BROKER 02 ONLINE
P0 · FOLLOWER
P1 · LEADER
P2 · FOLLOWER
BROKER 03 ONLINE
P0 · FOLLOWER
P1 · FOLLOWER
P2 · LEADER

Distributing partition leadership across brokers helps distribute producer traffic, consumer traffic, replication activity and storage operations.

A cluster with evenly distributed partition replicas can still experience uneven workload distribution if leadership or partition traffic is concentrated on a subset of brokers.

6.4 — The Replica Fetch Protocol

Kafka followers replicate partition data using a pull-based fetch mechanism.

Each follower requests records beginning at its current replication position. The leader responds with available record batches, which the follower appends to its local partition log.

FOLLOWER REPLICATION PROTOCOL SEQUENCE REPLICA FETCH
FOLLOWER REPLICA LEADER REPLICA REPLICA FETCH · OFFSET 104 READ LEADER LOG Available records: 104 and 105 FETCH RESPONSE · RECORD BATCHES APPEND TO LOCAL LOG Follower log end advances to 106 NEXT REPLICA FETCH · OFFSET 106 TRACK REPLICA PROGRESS Evaluate replication and HW FOLLOWER FETCH POSITIONS PROVIDE REPLICATION PROGRESS INFORMATION
Figure 2 — A follower requests records from offset 104, appends the returned records and advances its fetch position to 106. Subsequent fetch activity allows the leader to track follower replication progress.

Replication operates independently of application consumer groups. Replica fetchers maintain broker redundancy rather than executing business workflows.

6.5 — In-Sync Replicas

The in-sync replica set, commonly abbreviated ISR, identifies replicas that satisfy Kafka's current synchronization requirements for a partition.

The leader is normally included in the ISR. Followers can remain in the ISR while temporarily trailing the leader, provided they continue to satisfy the applicable replication progress criteria.

Healthy Replication State

Broker 1 · Leader · ISR
Broker 2 · Follower · ISR
Broker 3 · Follower · ISR
Replicas = {1, 2, 3}
ISR = {1, 2, 3}

All three assigned replicas currently participate in the in-sync replica set.

Degraded Replication State

Broker 1 · Leader · ISR
Broker 2 · Follower · ISR
Broker 3 · Outside ISR
Replicas = {1, 2, 3}
ISR = {1, 2}

Broker 3 remains an assigned replica but no longer satisfies the current in-sync requirements.

Replica synchronization can deteriorate because of broker failures, slow storage, overloaded replica fetchers, network congestion or prolonged connectivity interruptions.

The broker configuration replica.lag.time.max.ms participates in determining when a follower has fallen sufficiently behind or stopped fetching for long enough to be removed from the ISR.

ISR DOES NOT MEAN IDENTICAL LOG END OFFSETS

In-sync followers are not required to have exactly the same log end offset as the leader at every instant. Short-lived replication differences are a normal consequence of asynchronous distributed data transfer.

6.6 — Log End Offset and High Watermark

Each replica maintains a log end offset, or LEO, identifying the next offset position at the end of its local log.

The partition high watermark represents the replicated visibility boundary. Records below the high watermark are available to ordinary consumers, subject to retention and transactional isolation requirements.

REPLICA LOG CUTAWAY · HIGH WATERMARK REPLICATION BOUNDARY
LEADER FOLLOWER 2 FOLLOWER 3 100 101 102 103 104 105 106 107 100 101 102 103 104 105 106 100 101 102 103 104 105 LEO 108 LEO 107 LEO 106 HIGH WATERMARK = 106 REPLICATED VISIBILITY RANGE PENDING REPLICATION HIGH WATERMARK IS AN EXCLUSIVE OFFSET BOUNDARY
Figure 3 — All three replicas remain in the ISR in this simplified snapshot. Their log end offsets are 108, 107 and 106. The illustrated high watermark is 106, meaning records through offset 105 have crossed the replication visibility boundary. Actual advancement depends on the leader's knowledge of replica progress and current partition state.
OFFSET BOUNDARY 01

Log End Offset

The next offset position at the end of an individual replica's local log.

OFFSET BOUNDARY 02

High Watermark

The replicated visibility boundary used to prevent ordinary consumers from reading an uncommitted replication tail.

OFFSET BOUNDARY 03

Last Stable Offset

A transactional visibility boundary that can further restrict read_committed consumers when unresolved transactions exist.

6.7 — Producer Acknowledgements and Durability

Producer acknowledgement settings determine the conditions under which a producer considers a write successful.

These settings interact directly with partition replication and the current ISR.

ACKNOWLEDGEMENT MODE 01

acks=0

The producer does not wait for a broker acknowledgement. It cannot reliably determine whether the broker accepted the record.

ACKNOWLEDGEMENT MODE 02

acks=1

The leader acknowledges after accepting the write into its local log, without waiting for follower replication.

ACKNOWLEDGEMENT MODE 03

acks=all

The producer waits for the required replication acknowledgement condition across the current in-sync replica set.

ACKS=ALL · REPLICATED WRITE LIFECYCLE DURABILITY PATH
01 · PRODUCE REQUEST 02 · LEADER APPEND 03 · FOLLOWER REPLICATION 04 · REPLICATION CONDITION SATISFIED 05 · PRODUCER ACKNOWLEDGEMENT Producer submits a record with acks=all. Leader appends the record to its local log. In-sync followers fetch and append the record. Required offset reaches the replication boundary. Successful response returned if ISR requirements hold. EVENT 108 LEADER LEO 109 ISR REPLICATED HW ≥ 109 SUCCESS SUCCESS REQUIRES THE APPLICABLE MINIMUM ISR CONDITION
Figure 4 — Simplified successful acks=all write. The producer acknowledgement depends on replication progress and the minimum ISR requirement. This does not imply that every replica has synchronously flushed the record to physical storage.

6.8 — Minimum In-Sync Replicas

The min.insync.replicas configuration defines the minimum ISR size required for successful writes using acks=all.

A common production configuration combines a replication factor of three, a minimum ISR of two and producer acknowledgements set to all.

3
Replication Factor
2
Minimum ISR
ALL
Producer Acks
1
Replica Failure Margin*

*From an initially healthy three-replica ISR, assuming an eligible leader remains available and the surviving replicas satisfy the write acknowledgement conditions.

Current ISR Size Minimum ISR acks=all Write State
3 2 Eligible for successful writes.
2 2 Writes remain possible with reduced redundancy.
1 2 Successful acks=all writes cannot satisfy the minimum ISR requirement.
No available leader 2 Partition unavailable for normal writes.
ACKS=ALL IS NOT ACKS=MINIMUM ISR

With three replicas currently in the ISR and min.insync.replicas set to two, acks=all does not simply acknowledge after any two replicas receive the record. The acknowledgement depends on replication across the current ISR, while minimum ISR establishes the required lower boundary for successful writes.

6.9 — Availability Versus Durability

Distributed systems must make explicit decisions about what happens when redundant infrastructure becomes unavailable.

Kafka can reject strongly acknowledged writes when the available ISR falls below the configured minimum. This protects the intended replication requirement at the expense of write availability.

Durability-Oriented Configuration

replication.factor=3
min.insync.replicas=2
acks=all

A successful write must satisfy the configured replication requirement. If the ISR becomes too small, the producer can receive replication related errors instead of a successful response.

Reduced Replication Requirement

replication.factor=3
min.insync.replicas=1
acks=all

Writes may remain possible with only one in-sync replica. This increases write availability in some failure scenarios but reduces the minimum redundancy requirement.

The correct configuration depends on business recovery objectives, event criticality, failure domains, producer retry behaviour and acceptable service interruption.

6.10 — Broker Failure and Leader Election

When a partition leader becomes unavailable, Kafka's controller coordinates a leadership transition to an eligible surviving replica.

In modern KRaft-based Kafka clusters, the active controller maintains cluster metadata and coordinates broker and partition state changes.

PARTITION LEADER FAILURE AND RECOVERY CONTROLLER-COORDINATED FAILOVER
STATE A · HEALTHY PARTITION BROKER 1 BROKER 2 BROKER 3 P0 · LEADER P0 · FOLLOWER P0 · FOLLOWER Leader epoch 12 ISR member ISR member BROKER 1 FAILURE Leader becomes unavailable ACTIVE KRAFT CONTROLLER Detect or process broker unavailability Select eligible replica and update metadata New leader epoch: 13 STATE B · LEADERSHIP RECOVERED BROKER 1 BROKER 2 BROKER 3 OFFLINE NEW LEADER FOLLOWER Outside ISR Leader epoch 13 Fetch from broker 2 LEADER = 2 · ISR = {2, 3} · REPLICATION FACTOR = 3
Figure 5 — Broker 1 fails and broker 2 becomes the new partition leader. Broker 3 follows broker 2. The assigned replication factor remains three, but the partition operates with a reduced ISR of two in this example. Recovery requires controller availability and an eligible surviving replica.

6.11 — The Leader Election Lifecycle

FAILOVER STAGE 01

Broker Unavailability

A broker fails, loses connectivity or becomes fenced through the cluster's broker lifecycle mechanisms.

FAILOVER STAGE 02

Partition Leadership Evaluation

The active controller identifies affected partitions and evaluates eligible surviving replicas according to the active election rules.

FAILOVER STAGE 03

Metadata Update

New partition leadership and associated epoch information are recorded through the cluster metadata mechanisms.

FAILOVER STAGE 04

Replica Role Transition

The selected broker becomes the new leader. Other surviving followers reconcile their replication state with the new leadership.

FAILOVER STAGE 05

Client Metadata Refresh

Producers and consumers discover updated partition leadership through metadata refresh and error recovery mechanisms.

FAILOVER STAGE 06

Application Traffic Recovery

Clients resume requests against the new leader, subject to retry limits, timeout boundaries and current partition availability.

6.12 — Leader Epochs and Stale Leadership

A leader epoch identifies a generation of partition leadership.

When leadership changes, the associated epoch advances. Epoch information helps brokers and clients distinguish current partition state from older leadership information.

PARTITION LEADERSHIP GENERATIONS LEADER EPOCH TRACKING
EPOCH 12 EPOCH 13 EPOCH 14 Leader: Broker 1 Leader: Broker 2 Leader: Broker 3 STALE LEADERSHIP INFORMATION MUST BE RECONCILED Epoch-aware requests and replica recovery help prevent divergent state LEADER EPOCHS ARE PARTITION-SPECIFIC
Figure 6 — Successive leadership generations for one partition. Leader epochs support stale-state detection and log reconciliation when partition leadership changes.

A broker returning after an interruption must reconcile its local partition state with the current leader. It cannot safely assume that its previous leadership information remains valid.

6.13 — Clean and Unclean Leader Elections

Under conventional ISR-based election behaviour, a clean leader election selects an eligible in-sync replica.

If no suitable replica remains available, an unclean leader election can permit a replica outside the ISR to become leader when that behaviour is enabled or explicitly requested.

Clean Leader Election

Broker 1 · Failed Leader
Broker 2 · Eligible New Leader
Broker 3 · In-Sync Follower

Leadership transfers to an eligible replica expected to preserve the committed replication history under normal failure assumptions.

Unclean Leader Election

Broker 1 · Failed Leader
Broker 2 · Unavailable ISR Member
Broker 3 · Previously Outside ISR

A stale replica may become leader to restore availability, potentially losing records that existed only on unavailable replicas.

UNCLEAN ELECTION · POTENTIAL DATA LOSS DIVERGENT LOG HISTORY
PREVIOUS LEADER · NOW UNAVAILABLE STALE REPLICA · POTENTIAL NEW LEADER 100 101 102 103 104 105 106 107 100 101 102 103 104 MISSING MISSING MISSING POTENTIAL LOST RECORD RANGE RESTORING AVAILABILITY CAN SACRIFICE DATA DURABILITY
Figure 7 — An out-of-sync replica lacks records 105–107. Electing that replica can establish a new authoritative log history without those records. Whether acknowledged records are lost depends on the previous replication and acknowledgement state.
MODERN KAFKA VERSION CONSIDERATION

Newer Kafka releases can support Eligible Leader Replicas, or ELR, which extend safe leader eligibility under specific conditions. The conventional ISR-only election examples in this section are simplified teaching models. Engineers should verify the cluster version and enabled metadata features before applying election assumptions to production systems.

6.14 — Replica Recovery and Log Reconciliation

When a failed broker returns, its local partition logs may be behind the current leader or may contain an uncommitted tail from an earlier leadership generation.

Kafka must reconcile this state before treating the returning replica as fully synchronized.

RETURNING BROKER · REPLICA RECOVERY LOG RECONCILIATION
01 · BROKER RETURNS 02 · RECONCILE LEADER EPOCH AND LOG 03 · FETCH MISSING RECORDS 04 · SATISFY ISR REJOIN CONDITIONS Local replica may contain older partition state. Identify divergence and truncate incompatible tail if required. Retrieve authoritative records from the current leader. Restore the replica to the in-sync set when eligible. RECOVERING RECONCILING CATCHING UP IN-SYNC BROKER ONLINE DOES NOT IMMEDIATELY MEAN REPLICA IN-SYNC
Figure 8 — Replica recovery requires more than restarting a broker. The returning replica reconciles its log with the current leader, retrieves missing data and satisfies the applicable synchronization requirements.

6.15 — Rack-Aware and Availability Zone Placement

Replication provides limited protection against correlated infrastructure failures when all replicas share the same physical failure domain.

Three replicas located in one rack may survive individual broker failures but remain vulnerable to a shared power, switching or rack-level outage.

FAILURE DOMAIN ENGINEERING PLACEMENT COMPARISON
DESIGN A · SHARED FAILURE DOMAIN RACK A · SHARED POWER AND NETWORK BROKER 1 BROKER 2 BROKER 3 P0 REPLICA P0 REPLICA P0 REPLICA ONE RACK FAILURE CAN REMOVE ALL THREE REPLICAS DESIGN B · DISTRIBUTED FAILURE DOMAINS RACK A RACK B RACK C BROKER 1 BROKER 2 BROKER 3 P0 LEADER P0 FOLLOWER P0 FOLLOWER DISTRIBUTED PLACEMENT REDUCES CORRELATED FAILURE EXPOSURE
Figure 9 — Replication factor alone does not describe infrastructure resilience. Rack-aware replica placement reduces the probability that one shared infrastructure failure removes every replica of a partition.
BROKER FAILURE DOMAIN CONFIGURATION
# Broker 1
broker.rack=zone-a

# Broker 2
broker.rack=zone-b

# Broker 3
broker.rack=zone-c

Kafka can use rack information during replica placement to improve failure-domain diversity. Existing replica assignments should be inspected and reassigned where necessary rather than assuming that changing rack labels automatically corrects every existing placement.

6.16 — Replication Network Architecture

Kafka replication introduces substantial east-west network traffic between brokers.

A cluster receiving high-volume producer traffic must provide sufficient network bandwidth for replication, consumer retrieval, metadata operations and recovery activity.

KAFKA DATA CENTRE TRAFFIC ARCHITECTURE EAST-WEST REPLICATION
PRODUCER APPLICATIONS CONSUMER APPLICATIONS SPINE 1 SPINE 2 LEAF 1 LEAF 2 LEAF 3 KAFKA BROKER 1 KAFKA BROKER 2 KAFKA BROKER 3 P0 LEADER P0 FOLLOWER P0 FOLLOWER REPLICATION TRAFFIC COMPETES FOR FABRIC AND BROKER RESOURCES SIMPLIFIED LOGICAL NETWORK PATHS
Figure 10 — Kafka replication generates east-west traffic across the data centre network. Network engineers must account for normal replication demand, failure recovery traffic, congestion and oversubscription. The topology illustrates logical traffic paths rather than a complete physical network design.

6.17 — Replication Bandwidth and Storage Amplification

Replication increases the aggregate amount of data transferred and stored by the cluster.

In a simplified steady-state model, a replication factor of three creates two follower copies for every record batch accepted by a leader.

Replication Traffic ≈ Ingress × (RF − 1)
Assumes equivalent record-batch byte sizes across leader ingress and follower replication, excluding protocol overhead, retries and recovery.
100
Ingress MB/s
3
Replication Factor
200
Replication MB/s
300
Aggregate Log MB/s
ILLUSTRATIVE STORAGE CAPACITY MODEL
Incoming stored event data = 100 MB/s

Daily event volume         = 100 × 86,400

                           = 8.64 TB/day

Retention period           = 7 days

Unreplicated retained data = 60.48 TB

Replication factor         = 3

Replicated retained data   = 181.44 TB

# Decimal units.
# Excludes indexes, filesystem overhead,
# compaction, deletion delays and capacity headroom.

Actual storage requirements depend on compressed record sizes, retention policies, segment management, compaction behaviour and operational capacity reserves.

6.18 — Under-Replicated and Offline Partitions

Kafka exposes operational indicators that help engineers distinguish degraded redundancy from complete partition unavailability.

DEGRADED REDUNDANCY

UnderReplicatedPartitions

Partitions whose ISR contains fewer replicas than their assigned replication factor.

DURABILITY THRESHOLD

UnderMinIsrPartitionCount

Partitions whose ISR size is below the configured minimum in-sync replica requirement.

SERVICE UNAVAILABILITY

OfflinePartitionsCount

Partitions without an available leader, preventing normal partition service.

An under-replicated partition can remain available for application traffic. A partition below minimum ISR can reject acks=all writes while still permitting eligible reads.

An offline partition represents a more severe availability condition because no normal leader-based partition service is available.

6.19 — Replication Failure Monitoring

REPLICATION INCIDENT TELEMETRY ILLUSTRATIVE INCIDENT
120 90 60 30 0 BROKER FAILURE REPLICA RECOVERY REDUCED REDUNDANCY 00:00 00:30 01:00 01:30 02:00 02:30 Under-replicated partitions Partitions below minimum ISR
Figure 11 — A broker failure produces 120 under-replicated partitions. The remaining replicas continue to satisfy the minimum ISR requirement in this hypothetical incident. Redundancy gradually returns as the failed broker recovers and its replicas catch up.
Operational Metric What It Indicates Investigation Area
UnderReplicatedPartitions Reduced replica synchronization. Broker, network and storage health.
UnderMinIsrPartitionCount ISR below required threshold. Producer write availability.
AtMinIsrPartitionCount Partitions operating at minimum ISR. Remaining failure margin.
OfflinePartitionsCount Partitions without an available leader. Controller and election state.
IsrShrinksPerSec Replica removal activity. Replication instability.
IsrExpandsPerSec Replica rejoin activity. Recovery or synchronization churn.
ReplicationBytesInPerSec Incoming replica data volume. Follower bandwidth demand.
ReplicationBytesOutPerSec Outgoing replica data volume. Leader replication bandwidth.
Replica fetcher lag Follower progress relative to leader. Storage and network bottlenecks.
Unclean leader election activity Potentially unsafe recovery events. Data integrity investigation.

Metric names, exposure locations and aggregation behaviour depend on the Kafka release and monitoring integration. Engineers should avoid double-counting cluster-wide metrics when aggregating broker and controller telemetry.

6.20 — Producer Errors During Replication Failure

Replication degradation and leadership changes can produce several categories of client errors.

Kafka Error Potential Condition Engineering Response
NOT_ENOUGH_REPLICAS ISR insufficient for the requested acknowledgement requirement. Inspect minimum ISR and replica health.
NOT_ENOUGH_REPLICAS_AFTER_APPEND Replication requirement could not be satisfied after the record was appended. Treat the write outcome carefully and examine retry behaviour.
NOT_LEADER_OR_FOLLOWER Request reached a broker that cannot serve the requested partition role. Refresh metadata and inspect leadership.
LEADER_NOT_AVAILABLE No suitable leader currently available or leadership transition in progress. Investigate partition and controller state.
REQUEST_TIMED_OUT Request did not complete within its applicable timeout. Inspect replication, broker load, network latency and retry limits.
AMBIGUOUS WRITE OUTCOMES

A producer timeout or replication error does not necessarily prove that a record was never appended. The broker may have accepted the record before the response was lost or the replication condition failed. Idempotent production and application-level event identity are important safeguards when retrying writes.

6.21 — Production Topic Configuration

A topic's replication configuration should reflect its business criticality and the underlying infrastructure failure domains.

CREATE REPLICATED KAFKA TOPIC
kafka-topics.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --create \
  --topic customer-orders \
  --partitions 12 \
  --replication-factor 3 \
  --config min.insync.replicas=2 \
  --config unclean.leader.election.enable=false \
  --config retention.ms=604800000
ILLUSTRATIVE PRODUCER DURABILITY PROFILE
# Replicated acknowledgement
acks=all

# Duplicate-safe protocol retries
enable.idempotence=true

# Compatible in-flight request limit
max.in.flight.requests.per.connection=5

# Illustrative timeout boundaries
request.timeout.ms=30000
delivery.timeout.ms=120000

# Example retry backoff
retry.backoff.ms=100

Idempotent production helps prevent duplicate log entries caused by supported producer retry scenarios. It does not automatically deduplicate independently submitted business events or guarantee exactly-once external side effects.

These configurations are illustrative starting points. Production settings must be validated against client versions, broker configuration, authentication requirements and workload behaviour.

6.22 — Engineering Incident: The Disappearing Replicas

Consider a production Kafka cluster supporting an enterprise order-processing platform.

The cluster contains six brokers distributed across three availability zones. A network degradation event causes replication progress to deteriorate for multiple partitions.

6/6
Registered Brokers
48
Under-Replicated
12
Below Minimum ISR
0
Offline Partitions

Although every broker remains registered, some followers cannot replicate quickly enough to maintain synchronization. Producer applications begin reporting replication-related write errors.

PARTITION REPLICATION EVIDENCE
kafka-topics.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --topic customer-orders

# Simplified illustrative output

Partition: 0   Leader: 1   Replicas: 1,3,5   Isr: 1,3,5

Partition: 1   Leader: 2   Replicas: 2,4,6   Isr: 2,4

Partition: 2   Leader: 1   Replicas: 1,4,6   Isr: 1

Partition: 3   Leader: 3   Replicas: 3,5,2   Isr: 3,5,2

Partition: 4   Leader: 2   Replicas: 2,5,6   Isr: 2,5

# Configured min.insync.replicas=2
INITIAL ENGINEERING OBSERVATION

Partition 2 retains an available leader but has only one in-sync replica. With minimum ISR configured to two, producers using acks=all cannot obtain successful writes under the current replica condition.

6.23 — Evidence-Based Replication Troubleshooting

INVESTIGATION STAGE 01

Establish the Failure Scope

Identify affected topics, partitions, brokers and availability zones. Determine whether the incident affects leadership, replication or both.

INVESTIGATION STAGE 02

Compare Assigned Replicas and ISR

Inspect topic metadata to identify replicas repeatedly disappearing from the ISR. Look for common broker or infrastructure placement patterns.

INVESTIGATION STAGE 03

Inspect Network Connectivity

Examine inter-broker TCP connectivity, packet loss, retransmissions, interface errors, congestion and cross-zone latency.

INVESTIGATION STAGE 04

Inspect Broker Storage

Compare disk latency, throughput, filesystem capacity, storage errors and log directory availability across affected brokers.

INVESTIGATION STAGE 05

Evaluate Replica Fetch Performance

Inspect follower replication lag, fetcher activity, request processing delays, replication bandwidth and configured quotas.

INVESTIGATION STAGE 06

Correlate Controller State

Examine broker registration, fencing, partition leadership changes and metadata quorum health to distinguish data-plane degradation from control-plane failure.

INVESTIGATION STAGE 07

Restore the Verified Bottleneck

Correct the identified network, storage or broker resource problem. Allow replicas to reconcile their logs and recover synchronization.

INVESTIGATION STAGE 08

Validate Durability Recovery

Confirm ISR restoration, stable leadership, successful producer acknowledgements and recovery of affected application workflows.

REPLICATION TROUBLESHOOTING CLI
# Identify under-replicated partitions

kafka-topics.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --under-replicated-partitions

# Identify unavailable partitions

kafka-topics.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --unavailable-partitions

# Inspect broker log directories

kafka-log-dirs.sh \
  --bootstrap-server broker1.example.net:9093 \
  --command-config client.properties \
  --describe \
  --broker-list 1,2,3,4,5,6

# Linux network and storage diagnostics

ss -tin

ip -s link

iostat -xz 1 5

df -h

CLI availability and supported options depend on the installed Kafka distribution and version. Operating system commands must be executed on the appropriate broker hosts with suitable permissions.

6.24 — Replication Is Not Disaster Recovery

Intra-cluster replication protects against selected broker and infrastructure failures. It does not independently provide complete disaster recovery protection.

Accidental topic deletion, destructive application behaviour, configuration mistakes and entire cluster failures may affect every replica.

PROTECTION LAYER 01

Local Replication

Protects partition availability and data redundancy within the Kafka cluster.

PROTECTION LAYER 02

Cross-Cluster Replication

Replicates selected event streams to another Kafka cluster using mechanisms such as MirrorMaker 2 or managed equivalents.

PROTECTION LAYER 03

Independent Recovery

Uses appropriately designed archives, backups, restoration procedures and tested disaster recovery workflows.

DISASTER RECOVERY ENGINEERING

Cross-cluster replication is commonly asynchronous. Recovery point objectives, recovery time objectives, consumer offset translation, application failover, security configuration and duplicate processing must be explicitly engineered and tested.

6.25 — Replication Engineering Trade-Offs

Design Decision Potential Benefit Potential Trade-Off
Higher replication factor Greater assigned data redundancy. More storage and network consumption.
Higher minimum ISR Stronger minimum replication requirement. Reduced write availability during failures.
acks=all Replication-aware write acknowledgement. Latency influenced by replica progress.
Rack-aware placement Reduced correlated failure exposure. Potential cross-zone traffic costs and latency.
Longer replica lag timeout Greater tolerance of transient lag. Potentially slower removal of degraded replicas.
Replication throttling Protects normal workloads during supported reassignment operations. Longer replica migration and recovery periods.
Unclean election disabled Avoids deliberate election of unsafe stale replicas. Partitions may remain unavailable without an eligible leader.
Cross-cluster replication Additional disaster recovery capability. Operational complexity and asynchronous replication lag.

Engineering Takeaways

✓ Kafka replicates partition logs across multiple brokers to improve durability and availability.
✓ Replication factor includes the leader and all assigned follower replicas.
✓ Followers retrieve partition records using replica fetch requests.
✓ The ISR identifies replicas satisfying Kafka's current synchronization requirements.
✓ The high watermark establishes the replicated consumer visibility boundary.
✓ Producer acknowledgements and minimum ISR jointly influence write durability.
✓ Acks=all is not equivalent to acknowledging after any minimum number of replicas respond.
✓ Broker failure recovery requires eligible surviving replicas and functioning control-plane coordination.
✓ Leader epochs support stale-state detection and replica log reconciliation.
✓ Unclean leader elections can restore availability at the expense of data integrity.
✓ Returning brokers must recover synchronization before normal redundancy is restored.
✓ Failure-domain-aware placement is essential for meaningful infrastructure resilience.
✓ Replication creates significant storage amplification and east-west network traffic.
✓ Under-replicated partitions, insufficient ISR and offline partitions represent different operational conditions.
✓ Replication troubleshooting requires correlated broker, storage, network and controller evidence.
✓ Intra-cluster replication is not a replacement for independently engineered disaster recovery.
NETWORK INSIGHT / APACHE KAFKA / 06

Broker Failure & Recovery Simulator

Investigate distributed log replication, leader elections, in-sync replicas, storage durability and failure recovery.

Online brokers 3/3
Partition leader B1
ISR members 3
High watermark 0
Leader elections 0
Lost committed records 0
PARTITION DURABILITY CONFIGURATION

Configure the Replication Environment

Minimum ISR required for acks=all writes.
Maximum catch-up capacity per follower.
Allows an out-of-sync replica to become leader when no eligible ISR replica is available.
DISTRIBUTED STORAGE FABRIC / REPLICATION FACTOR 3 ● HEALTHY
CLUSTER CONTROL PLANE Partition leader epoch 0 PRODUCER / ACKS=ALL Waiting for records
INFRASTRUCTURE FAULT INJECTION

Individual Broker Controls

Fail a broker or pause follower replication without disconnecting the entire server. Observe how each condition affects the partition's ISR membership.

PARTITION METADATA

Leader and Replica State

Topic orders.created
Partition P0
Replication factor 3
Leader epoch 0
Current ISR B1, B2, B3
Out-of-sync replicas None
Leader log end offset 0
DURABILITY AND AVAILABILITY

Write and Recovery Telemetry

Accepted records 0
Rejected writes 0
Current committed prefix 0 records
Uncommitted leader tail 0 records
Lost uncommitted records 0
Unclean elections 0
DISTRIBUTED LOG INSPECTION

Replica Storage Chambers

Compare the actual records stored on each broker. Green blocks represent the current committed prefix, amber blocks represent uncommitted records, and red blocks represent divergent records awaiting reconciliation.

Committed prefix Uncommitted Divergent Missing
REPLICATION TELEMETRY

Replica Synchronisation Table

BROKER ROLE STATUS LOG END OFFSET REPLICA LAG ISR MEMBER REPLICATION

Log end offset identifies the next append position. The high watermark represents the boundary of the committed prefix in this simplified replication model.

DESTRUCTIVE FAILURE SCENARIO

Unclean Election Investigation

This controlled scenario creates a stale replica and then fails the remaining in-sync brokers. Compare the durability-first outcome with the availability-first outcome.

Scenario ready. Preparing this scenario resets the current laboratory.
REPLICATION ENGINEERING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 06

The Broker Failure and Recovery Incident

Demonstrate clean leader failover, minimum ISR enforcement and follower recovery without losing committed records.

1 Publish six records and wait until all three replicas contain the committed records.
2 Fail the current partition leader. Observe a clean election and verify that committed records are preserved.
3 Publish another six records and wait for the remaining in-sync replicas to commit them.
4 Fail the remaining follower, leaving only one online broker. Attempt another write and observe minimum ISR rejection.
5 Recover all brokers and wait for replica catch-up. Publish another record and verify that the cluster commits it without data loss.
Investigation ready
ENGINEERING PRINCIPLE 01

Replication Factor Is Not the ISR Count

The replication factor describes the configured number of replicas. The ISR identifies replicas currently considered sufficiently synchronised with the leader. A topic configured with three replicas may temporarily have only one in-sync replica.

ENGINEERING PRINCIPLE 02

Availability versus Durability

Preventing out-of-sync replicas from becoming leaders protects committed data but may leave a partition unavailable. Permitting unclean elections can restore partition availability at the cost of potentially losing previously committed records.

07 Distributed Consensus · Kafka Engineering

KRaft and Kafka Metadata Management

Kafka's distributed event logs require a consistent control plane capable of coordinating broker membership, topic definitions, partition assignments, leadership transitions and cluster configuration.

KRaft, Kafka's Raft-based metadata architecture, integrates distributed metadata management directly into Kafka. Rather than relying on an external ZooKeeper ensemble, Kafka maintains an authoritative metadata log through a dedicated controller quorum.

This architecture separates the management of cluster state from the high-volume movement of application event records.

Understanding this separation is essential when investigating Kafka failures. A healthy broker data plane does not necessarily imply a healthy metadata control plane, and a functioning controller quorum does not guarantee that application partition replicas are synchronized.

KRAFT DISTRIBUTED CONTROL PLANE QUORUM ESTABLISHED
METADATA CONTROL PLANE CONTROLLER 101 CONTROLLER 102 CONTROLLER 103 ACTIVE CONTROLLER FOLLOWER VOTER FOLLOWER VOTER METADATA LOG METADATA LOG METADATA LOG COMMITTED CLUSTER METADATA APPLICATION DATA PLANE BROKER 1 BROKER 2 BROKER 3 P0 LEADER P0 FOLLOWER P0 FOLLOWER LOCAL METADATA IMAGE LOCAL METADATA IMAGE LOCAL METADATA IMAGE PRODUCER APPLICATIONS CONSUMER APPLICATIONS
Figure 1 — A dedicated three-controller KRaft quorum maintains cluster metadata. Brokers consume committed metadata and maintain local metadata images. Application records remain in broker-hosted topic partitions rather than passing through the controller quorum. Purple paths represent logical metadata flow.

7.1 — Why Kafka Needs a Distributed Control Plane

A Kafka cluster contains numerous independently operating brokers, partitions, replicas and clients. These components require a consistent understanding of cluster membership and partition ownership.

Without authoritative metadata, brokers could disagree about which partition leader is valid, which replicas belong to a topic or whether a broker is eligible to serve traffic.

CONTROL FUNCTION 01

Cluster Membership

Maintain broker registration, lifecycle information, fencing state and advertised network endpoints.

CONTROL FUNCTION 02

Partition Coordination

Maintain partition assignments, leader identities, replica membership and leadership generations.

CONTROL FUNCTION 03

Administrative State

Coordinate topic creation, configuration changes, feature levels, access-control metadata and other cluster operations.

7.2 — From ZooKeeper to KRaft

Earlier Kafka architectures depended on ZooKeeper for important cluster coordination and metadata functions. Kafka brokers interacted with an external ZooKeeper ensemble, while a Kafka controller coordinated partition state.

KRaft replaces this external dependency with an integrated metadata consensus architecture. Kafka 4.0 removed ZooKeeper mode, making KRaft the required metadata architecture for that major release and subsequent releases.

METADATA ARCHITECTURE EVOLUTION ZOOKEEPER → KRAFT
LEGACY ARCHITECTURE KRAFT ARCHITECTURE EXTERNAL ZOOKEEPER ENSEMBLE ZK 1 ZK 2 ZK 3 INTEGRATED CONTROLLER QUORUM C101 C102 C103 KAFKA BROKERS KAFKA BROKERS B1 B2 B3 B1 B2 B3 SEPARATE COORDINATION SYSTEM KAFKA-NATIVE METADATA CONSENSUS
Figure 2 — Legacy Kafka depended on an external ZooKeeper coordination system. KRaft integrates metadata consensus and controller management into Kafka itself.
Architecture Component ZooKeeper-Based Kafka KRaft-Based Kafka
Metadata coordination External ZooKeeper dependency. Integrated metadata quorum.
Controller architecture Controller selected from Kafka brokers. Active controller selected through KRaft quorum.
Metadata representation ZooKeeper state and Kafka controller state. Replicated metadata records and metadata images.
Infrastructure operations Kafka and ZooKeeper lifecycle management. Kafka broker and controller lifecycle management.
Kafka 4.0 Not supported. Required architecture.

7.3 — Controllers, Brokers and Combined Roles

KRaft introduces explicit server process roles. A Kafka server can operate as a broker, a controller or, in supported deployments, a combined broker and controller.

CONTROLLER NODE CONTROL
Metadata consensus
Broker lifecycle
Partition coordination
process.roles=controller
BROKER NODE DATA
Application partitions
Produce and fetch
Replica synchronization
process.roles=broker
COMBINED NODE HYBRID
Controller functions
Broker functions
Shared resources
process.roles=broker,controller

Dedicated controllers provide stronger resource isolation between metadata operations and application data processing.

Combined deployments can simplify development and smaller environments, but introduce shared CPU, memory, storage and failure-domain dependencies between the two roles.

PRODUCTION ARCHITECTURE PRINCIPLE

For critical production environments, dedicated controllers are generally preferable. Controller capacity and availability should not depend directly on the performance of high-volume application partition workloads.

7.4 — The Controller Quorum

The controller quorum consists of voting members participating in Kafka's metadata consensus protocol. One controller acts as the active leader while the other voters maintain replicated metadata state and participate in elections.

A quorum requires a majority of its configured voting members to make normal consensus progress. This majority requirement prevents two isolated minority groups from independently committing conflicting metadata histories.

Majority = floor(Voters / 2) + 1
Three voters require two. Five voters require three.
3
Controller Voters
2
Required Majority
1
Failure Tolerance
1
Active Controller
Voting Members Majority Maximum Voter Failures* Typical Design
1 1 0 Development environments.
2 2 0 No single-voter failure tolerance.
3 2 1 Common production configuration.
4 3 1 No additional failure tolerance over three.
5 3 2 Greater controller failure tolerance.
7 4 3 Theoretical majority model with greater overhead.

*Assumes the surviving majority can communicate, participate in consensus and elect an eligible leader. Larger quorum sizes are not automatically recommended.

7.5 — Raft Consensus Fundamentals

Raft is a distributed consensus approach designed to maintain an ordered, replicated log across multiple participating nodes.

Kafka's KRaft implementation adapts these principles to Kafka's log-oriented architecture, including a pull-based replication mechanism.

CONSENSUS PRINCIPLE 01

Leader Election

Voting members select an eligible leader for a particular leadership epoch.

CONSENSUS PRINCIPLE 02

Log Replication

Metadata records are replicated from the leader to follower voters through fetch requests and responses.

CONSENSUS PRINCIPLE 03

Commit Safety

Majority replication and epoch-aware consensus rules establish a committed metadata history.

7.6 — Controller Election Lifecycle

When the current quorum leader becomes unavailable, eligible voters can initiate a new election. A successful candidate must obtain the required majority of votes under the applicable log freshness and epoch rules.

KRAFT CONTROLLER ELECTION MAJORITY VOTING
STAGE A · ACTIVE CONTROLLER FAILURE CONTROLLER 101 CONTROLLER 102 CONTROLLER 103 UNAVAILABLE FOLLOWER FOLLOWER Previous leader epoch: 18 STAGE B · ELECTION REQUEST C102 · CANDIDATE Self vote · Epoch 19 C103 · VOTER Candidate eligibility validated VOTE REQUEST → ← VOTE GRANTED STAGE C · NEW QUORUM LEADER 2 OF 3 VOTES · MAJORITY ACHIEVED Active Controller: 102 · Leader Epoch: 19 Metadata consensus can resume after leadership is established SIMPLIFIED SUCCESSFUL ELECTION SEQUENCE
Figure 3 — Controller 101 becomes unavailable. Controller 102 initiates an election and obtains a majority using its own vote and the vote of controller 103. Actual election timing and eligibility depend on quorum state and protocol rules.
ELECTION STAGE 01

Detect Leadership Loss

Followers detect that valid communication with the current leader has not been maintained within the applicable timeout.

ELECTION STAGE 02

Begin Election

An eligible candidate initiates a new election with an advanced epoch.

ELECTION STAGE 03

Evaluate Candidate State

Voters evaluate epoch information, previous voting state and candidate log freshness.

ELECTION STAGE 04

Establish Majority

A candidate receiving the required majority becomes the new quorum leader.

ELECTION STAGE 05

Recover Controller Operations

The new active controller establishes its leadership state and resumes eligible metadata operations.

7.7 — The Kafka Metadata Log

KRaft represents cluster metadata as an ordered sequence of records in an internal metadata log, commonly identified as __cluster_metadata.

Instead of treating cluster state as a collection of unrelated configuration values, KRaft records changes that can be applied to reconstruct a consistent metadata image.

METADATA LOG CUTAWAY ORDERED CLUSTER STATE
__CLUSTER_METADATA · PARTITION 0 OFFSET 800 OFFSET 801 OFFSET 802 OFFSET 803 OFFSET 804 BROKER REGISTRATION TOPIC RECORD PARTITION RECORD CONFIG RECORD PARTITION CHANGE Broker 1 orders orders-0 retention.ms Leader update APPLY COMMITTED RECORDS IN LOG ORDER MATERIALIZED METADATA IMAGE BROKERS TOPICS PARTITIONS CONFIGURATION
Figure 4 — Illustrative metadata records are applied in order to construct a metadata image. Actual record batches, schemas and offsets depend on the Kafka version and cluster history.

7.8 — Metadata Record Types

Metadata records describe changes to the cluster's authoritative state.

Record Type Purpose Example Operation
RegisterBrokerRecord Records broker registration information. Broker joins the cluster.
BrokerRegistrationChangeRecord Updates broker registration state. Broker fencing or unfencing.
TopicRecord Defines topic identity and name. Create an orders topic.
PartitionRecord Defines partition metadata. Create partition assignments.
PartitionChangeRecord Updates existing partition state. Change leader or ISR membership.
ConfigRecord Represents configuration changes. Modify topic retention.
FeatureLevelRecord Records finalized feature levels. Metadata version advancement.
AccessControlEntryRecord Represents ACL metadata. Authorize a producer principal.
RemoveTopicRecord Represents topic removal. Delete a topic definition.
METADATA LOG IS NOT AN APPLICATION TOPIC

The KRaft metadata log is an internal control-plane mechanism. Applications do not publish business events into this log through ordinary Kafka producer workflows.

7.9 — Metadata Replication and Commit Boundaries

The active controller appends metadata records through the quorum leader. Follower voters retrieve records and maintain their own replicated metadata logs.

A metadata record being present on one controller does not automatically mean that the record is committed.

Majority replication, together with the applicable epoch and consensus rules, establishes the committed metadata boundary.

METADATA CONSENSUS · HIGH WATERMARK MAJORITY AVAILABLE
C101 · LEADER C102 · VOTER C103 · VOTER 800 801 802 803 804 805 800 801 802 803 804 805 800 801 802 803 PENDING PENDING QUORUM HIGH WATERMARK = 806 MAJORITY REPLICATED · 2 OF 3 VOTERS
Figure 5 — Controllers 101 and 102 contain records through offset 805. Controller 103 remains behind. Assuming current-epoch commit requirements are satisfied and replica progress is known, the metadata high watermark can advance to 806 without waiting for every voter.

7.10 — Metadata Consensus Versus Topic Replication

Although both mechanisms use replicated logs, Kafka's metadata quorum and application partition replication have different responsibilities and acknowledgement rules.

KRaft Metadata Quorum

Controller 101 · Leader
Controller 102 · Voter
Controller 103 · Voter
Voters = 3
Majority = 2
Consensus = Raft-based

Coordinates authoritative cluster metadata through majority-based consensus.

Application Partition Replication

Broker 1 · Partition Leader
Broker 2 · Follower
Broker 3 · Follower
Replication Factor = 3
Minimum ISR = 2
Producer Acks = all

Maintains application record redundancy through Kafka's partition replication and acknowledgement mechanisms.

Characteristic Metadata Quorum Application Partitions
Stored information Cluster metadata. Application event records.
Voting membership Controller voters. Not a Raft voting quorum.
Commit model Majority and epoch-aware consensus. Partition replication and ISR-based rules.
Leader selection Quorum election. Controller-coordinated partition election.
Producer acknowledgement Not governed by application producer acks. acks and minimum ISR configuration.
Failure impact Cluster coordination and metadata changes. Application partition durability and availability.

7.11 — Broker Registration and Broker Epochs

A broker must establish its identity and registration with the active controller before participating normally in cluster operations.

Broker registration includes information such as node identity, advertised endpoints, supported features and broker incarnation information.

Broker epochs help distinguish a current broker registration from stale requests associated with an earlier broker incarnation.

BROKER REGISTRATION PROTOCOL CLUSTER MEMBERSHIP
STARTING BROKER ACTIVE CONTROLLER BROKER REGISTRATION REQUEST → COMMIT REGISTRATION STATE ← REGISTRATION RESPONSE METADATA CATCH-UP Apply committed metadata HEARTBEAT · METADATA PROGRESS → EVALUATE UNFENCING ← HEARTBEAT RESPONSE · UNFENCED SIMPLIFIED SUCCESSFUL BROKER STARTUP
Figure 6 — A broker registers with the active controller, catches up with committed metadata and communicates its lifecycle state through heartbeat exchanges. The controller can unfence the broker once the applicable conditions are satisfied.

7.12 — Broker Heartbeats and Fencing

Broker heartbeats provide the controller with information about broker liveness, registration state and metadata progress.

If a broker stops maintaining the required communication with the controller, it may be fenced and excluded from eligible cluster operations.

LIFECYCLE STATE 01

Registered and Fenced

The broker has registration information but is not yet eligible for normal cluster service.

LIFECYCLE STATE 02

Unfenced

The broker satisfies the applicable lifecycle requirements and can participate in normal cluster operations.

LIFECYCLE STATE 03

Fenced After Failure

The controller excludes the broker from eligible service because its lifecycle or liveness requirements are no longer met.

TCP CONNECTIVITY IS NOT BROKER ELIGIBILITY

A broker process may be running and accepting TCP connections while its authoritative cluster state is fenced or otherwise unsuitable for normal partition service. Network reachability, process health and metadata eligibility must be investigated independently.

7.13 — Topic Creation Through KRaft

Creating a Kafka topic requires a coordinated metadata transaction rather than merely creating local directories on individual brokers.

An administrative request is routed to the appropriate controller operation. The active controller validates the request, determines the necessary metadata changes and records them through the metadata quorum.

TOPIC CREATION · CONTROL PLANE WORKFLOW METADATA COMMIT
01 · ADMINISTRATIVE REQUEST 02 · CONTROLLER VALIDATION 03 · METADATA RECORD APPEND 04 · QUORUM COMMIT 05 · BROKER METADATA APPLICATION Create topic orders · 3 partitions · RF 3 Validate request, configuration and replica assignments TopicRecord and PartitionRecord entries Majority replication and consensus requirements satisfied Brokers apply metadata and establish assigned replicas BROKER 1 BROKER 2 BROKER 3 P0 leader P1 leader P2 leader
Figure 7 — Topic creation produces authoritative metadata changes that brokers subsequently apply. Metadata commit and broker readiness are distinct stages. A successful administrative response does not necessarily mean every client and broker has already observed the new state.

7.14 — Metadata Images and Incremental Updates

Brokers maintain local metadata representations that allow them to operate without contacting the active controller for every application request.

Committed metadata records are applied to update these local images. Incremental changes can modify the relevant cluster state without reconstructing the entire image for every individual update.

Metadata Image · Before

Topic: orders
Partition: 0
Leader: Broker 1
Leader Epoch: 12
ISR: [1,2,3]

The broker's current metadata image identifies broker 1 as partition leader.

Metadata Image · After

Topic: orders
Partition: 0
Leader: Broker 2
Leader Epoch: 13
ISR: [2,3]

A committed partition change updates leadership and replica state.

Clients also maintain metadata caches describing topics, partitions and broker endpoints. These client caches are distinct from the broker's internal metadata image.

7.15 — Metadata Snapshots

Replaying an indefinitely growing metadata log from its beginning would become increasingly expensive as a cluster accumulates years of configuration and topology changes.

Metadata snapshots capture a consistent representation of metadata state at a particular log boundary.

Recovery can use an appropriate snapshot followed by subsequent metadata records, reducing the amount of historical log replay.

METADATA SNAPSHOT AND RECOVERY STATE RECONSTRUCTION
SNAPSHOT STATE Metadata records before offset 1000 SUBSEQUENT LOG RECORDS Offsets 1000 through 1049 LOAD SNAPSHOT Restore consistent metadata state REPLAY NEWER RECORDS Apply subsequent committed changes RECONSTRUCTED METADATA IMAGE State through committed offset 1049
Figure 8 — A snapshot captures metadata state before offset 1000. Subsequent committed records are replayed to reconstruct state through offset 1049. The example uses illustrative exclusive offset boundaries.
SNAPSHOTS ARE NOT INDEPENDENT BACKUPS

Metadata snapshots support state reconstruction and log management. They do not replace an independently engineered recovery strategy covering metadata storage, application partitions and cluster configuration.

7.16 — Controller Epochs, Broker Epochs and Partition Epochs

Kafka uses multiple generations of state information to distinguish current operations from stale or superseded operations.

Epoch Category Scope Purpose
Quorum Leader Epoch Metadata quorum. Identifies a generation of quorum leadership.
Broker Epoch Broker registration. Distinguishes current broker registration from stale incarnations.
Partition Leader Epoch Individual application partition. Identifies a generation of partition leadership.
Partition Epoch Individual partition metadata. Tracks partition metadata generations beyond leadership changes alone.
19
Quorum Leader Epoch
840
Broker Epoch
13
Partition Leader Epoch
27
Partition Epoch

These illustrative values belong to different state domains. A controller election does not automatically require every application partition leader epoch to advance.

7.17 — Network Partitions and Majority Isolation

Distributed consensus becomes particularly important when a network failure separates controller voters into isolated groups.

In a three-controller quorum, a connected group containing two eligible voters can establish a majority. An isolated single voter cannot independently commit new metadata changes.

CONTROLLER NETWORK PARTITION MINORITY ISOLATION
MINORITY · 1 OF 3 MAJORITY · 2 OF 3 CONTROLLER 101 CONTROLLER 102 CONTROLLER 103 ISOLATED NEW LEADER FOLLOWER Cannot form majority Epoch 20 Epoch 20 NO INDEPENDENT COMMIT CONSENSUS CAN CONTINUE MAJORITY RULES PROTECT THE COMMITTED METADATA HISTORY
Figure 9 — Controller 101 becomes isolated while controllers 102 and 103 remain connected. The connected majority can elect a leader. The isolated minority cannot independently commit a competing metadata history.

7.18 — Complete Quorum Loss

If two members of a three-controller quorum become unavailable, the remaining voter cannot form a majority.

Normal metadata consensus progress stops until a sufficient set of eligible voters becomes available again.

One Controller Failure

C101 · Unavailable
C102 · Leader
C103 · Follower
Available Voters = 2
Required Majority = 2
Consensus = Available

Two Controller Failures

C101 · Unavailable
C102 · Unavailable
C103 · Isolated Voter
Available Voters = 1
Required Majority = 2
Consensus = Unavailable

Quorum loss does not necessarily cause every existing application partition to stop serving requests immediately.

Existing broker leaders may continue serving some traffic using their previously applied metadata, provided the relevant partition state and data-plane conditions remain valid.

However, operations requiring new authoritative metadata changes cannot complete normally. Subsequent broker failures, ISR changes and leadership transitions can progressively reduce application availability.

Operation During Metadata Quorum Loss
Existing partition reads May continue while valid serving state remains available.
Existing partition writes May continue while leadership and replication requirements remain satisfied.
New topic creation Cannot normally commit required metadata.
Partition reassignment Metadata coordination is impaired.
New partition leadership Normal controller-coordinated transitions are impaired.
Configuration changes Changes requiring metadata commits cannot complete normally.

7.19 — Controller Network Architecture

Controller communication should be engineered as a critical infrastructure dependency. The network must support reliable communication between quorum voters and between brokers and the controller infrastructure.

DEDICATED CONTROL PLANE NETWORK TRAFFIC SEPARATION
CONTROLLER 101 CONTROLLER 102 CONTROLLER 103 ZONE A ZONE B ZONE C PROTECTED CONTROLLER COMMUNICATION CONTROLLER LISTENER · EXAMPLE TCP 9093 BROKER 1 BROKER 2 BROKER 3 APPLICATION LISTENER APPLICATION LISTENER APPLICATION LISTENER APPLICATION AND BROKER DATA COMMUNICATION PRODUCERS · CONSUMERS · ADMIN CLIENTS
Figure 10 — Logical separation between controller communication and application data communication. Dedicated listeners, network segmentation and authentication reduce unnecessary exposure of critical controller interfaces. Port numbers are deployment-specific.
NETWORK REQUIREMENT 01

Reliable Connectivity

Maintain stable controller-to-controller and broker-to-controller communication with predictable latency and packet loss.

NETWORK REQUIREMENT 02

Protected Listeners

Restrict controller listeners to required infrastructure participants and authorized administrative paths.

NETWORK REQUIREMENT 03

Failure Domain Diversity

Distribute controller voters so that a single infrastructure failure does not remove the required majority.

7.20 — Availability Zone Placement

A three-controller quorum distributed across three independent availability zones can tolerate the loss of one zone, assuming the remaining controllers retain connectivity.

Placement must account for correlated failures rather than simply counting controller processes.

Poor Failure Domain Distribution

Zone A · C101
Zone A · C102
Zone B · C103
Zone A Failure
Remaining Voters = 1
Majority Lost

Losing one zone removes two voting members and prevents normal consensus.

Distributed Failure Domains

Zone A · C101
Zone B · C102
Zone C · C103
Zone A Failure
Remaining Voters = 2
Majority Preserved

The surviving connected voters can maintain metadata consensus.

Geographical distribution also introduces latency considerations. Placing a controller quorum across distant regions can increase metadata commit latency and complicate failure detection.

7.21 — Static and Dynamic Controller Quorums

Kafka supports different controller membership approaches depending on the installed release and enabled quorum features.

Static Controller Membership

controller.quorum.voters=
101@c101:9093,
102@c102:9093,
103@c103:9093

Voting membership is defined through explicit controller configuration. Membership changes require the procedures supported by that static quorum deployment.

Dynamic Controller Membership

controller.quorum.bootstrap.servers=
c101:9093,c102:9093,c103:9093

Supported dynamic quorum deployments maintain voting membership through quorum state and administrative membership operations.

VERSION-SPECIFIC MEMBERSHIP OPERATIONS

Bootstrap server addresses are not themselves the authoritative dynamic voter set. Dynamic quorum initialization, controller addition and removal must follow the procedures supported by the cluster's Kafka version and finalized feature levels.

7.22 — Dedicated Controller Configuration

The following example illustrates the main configuration elements for a dedicated controller using a static three-voter quorum.

CONTROLLER 101 · LAB CONFIGURATION
# Dedicated KRaft controller

process.roles=controller
node.id=101

controller.quorum.voters=101@c101:9093,102@c102:9093,103@c103:9093

controller.listener.names=CONTROLLER

listeners=CONTROLLER://0.0.0.0:9093

listener.security.protocol.map=CONTROLLER:PLAINTEXT,BROKER:PLAINTEXT

inter.broker.listener.name=BROKER

metadata.log.dir=/var/lib/kafka/metadata

log.dirs=/var/lib/kafka/logs

# Controllers 102 and 103 use unique node IDs.
# All members must use consistent quorum configuration.
# PLAINTEXT is for isolated teaching environments.

7.23 — Dedicated Broker Configuration

A dedicated broker communicates with the controller quorum while exposing broker listeners for application and inter-broker communication.

BROKER 1 · LAB CONFIGURATION
# Dedicated Kafka broker

process.roles=broker
node.id=1

controller.quorum.voters=101@c101:9093,102@c102:9093,103@c103:9093

controller.listener.names=CONTROLLER

listeners=BROKER://0.0.0.0:9092

advertised.listeners=BROKER://broker1:9092

listener.security.protocol.map=CONTROLLER:PLAINTEXT,BROKER:PLAINTEXT

inter.broker.listener.name=BROKER

log.dirs=/var/lib/kafka/data

broker.rack=zone-a

default.replication.factor=3

min.insync.replicas=2

offsets.topic.replication.factor=3

transaction.state.log.replication.factor=3

transaction.state.log.min.isr=2

# Illustrative isolated lab configuration.

These examples assume a compatible static quorum deployment with three controllers and at least three brokers. They are not complete hardened production configurations.

PRODUCTION SECURITY REQUIREMENT

Production environments should implement appropriate TLS encryption, authentication, certificate validation, authorization and network access restrictions. Controller listeners should not be exposed as general application endpoints.

7.24 — Cluster Identity and Storage Initialization

KRaft storage initialization associates local Kafka storage with the intended cluster identity and node configuration.

All members of a newly initialized cluster must use the intended common cluster ID, while individual node IDs must remain unique within the cluster.

NEW STATIC QUORUM LAB INITIALIZATION
# Generate one cluster ID for the new lab cluster.

CLUSTER_ID=$(bin/kafka-storage.sh random-uuid)

echo "$CLUSTER_ID"

# Preserve and reuse this exact ID on every node.
# Example: initialize NEW controller storage.

bin/kafka-storage.sh format \
  --cluster-id "$CLUSTER_ID" \
  --config config/controller.properties

# Example: initialize NEW broker storage.

bin/kafka-storage.sh format \
  --cluster-id "$CLUSTER_ID" \
  --config config/broker.properties

# Run the appropriate configuration on each host.
# Start the configured controllers and brokers.

bin/kafka-server-start.sh config/controller.properties
STORAGE RECOVERY WARNING

Storage formatting is an initialization operation, not a routine quorum recovery procedure. Never delete existing metadata directories, generate a replacement cluster identity or force storage initialization merely to clear a controller startup error. Preserve existing state and investigate the supported recovery procedure first.

7.25 — Inspecting Metadata Quorum Status

Kafka provides administrative tools for inspecting quorum leadership, metadata replication and controller membership.

KRAFT METADATA QUORUM STATUS
bin/kafka-metadata-quorum.sh \
  --bootstrap-server broker1:9092 \
  describe --status

# Simplified illustrative output

ClusterId:          example-cluster-id
LeaderId:           101
LeaderEpoch:        19
HighWatermark:      1050
MaxFollowerLag:     0
MaxFollowerLagTimeMs: 12

CurrentVoters:      [101,102,103]

CurrentObservers:   [1,2,3]
Status Field Engineering Meaning
ClusterId Identity of the Kafka cluster.
LeaderId Current metadata quorum leader.
LeaderEpoch Current quorum leadership generation.
HighWatermark Committed metadata offset boundary.
MaxFollowerLag Reported maximum follower offset lag.
MaxFollowerLagTimeMs Reported time-based follower lag indicator.
CurrentVoters Current voting membership information.
CurrentObservers Non-voting metadata replication participants.

7.26 — Inspecting Metadata Replication

A quorum status summary provides an initial view of controller health. Per-node replication information helps identify which participants are falling behind.

METADATA REPLICATION EVIDENCE
bin/kafka-metadata-quorum.sh \
  --bootstrap-server broker1:9092 \
  describe --replication

# Simplified illustrative output

NodeId   LogEndOffset   Lag   Status

101      1050           0     Leader

102      1050           0     Follower

103      1020           30    Follower

1        1050           0     Observer

2        1048           2     Observer

3        1050           0     Observer

Controller 103 is thirty offsets behind the leader in this example. The leader and controller 102 remain synchronized, preserving a potential voting majority.

A single lag measurement does not establish a root cause. Engineers should examine whether the lag is increasing, recovering or repeatedly oscillating.

OBSERVERS DO NOT COUNT TOWARD MAJORITY

Broker metadata observers can retrieve metadata records and maintain local state, but they do not automatically become controller voters. Adding more brokers does not increase controller quorum failure tolerance.

7.27 — Controller Monitoring and Telemetry

KRaft monitoring should distinguish metadata consensus health, controller processing performance, broker lifecycle state and application partition availability.

MONITORING DOMAIN 01

Quorum Leadership

Monitor leader identity, current epoch, election frequency and the availability of voting members.

MONITORING DOMAIN 02

Metadata Replication

Monitor metadata log progress, high watermark advancement, follower lag and snapshot activity.

MONITORING DOMAIN 03

Controller Performance

Monitor controller event processing, request latency, queue delays, CPU utilization and storage latency.

Metric or Indicator Investigation Purpose
ActiveControllerCount Identify active controller presence.
current-leader Track quorum leadership identity.
current-epoch Detect repeated election activity.
high-watermark Observe committed metadata progress.
log-end-offset Compare metadata log positions.
commit-latency-avg Investigate metadata commit performance.
Fenced broker count Identify broker lifecycle degradation.
OfflinePartitionsCount Identify application partition availability impact.
Metadata application lag Investigate stale broker metadata images.
Controller event queue latency Identify controller processing bottlenecks.

Exact metric names, JMX object names and exposure locations vary with Kafka release, process role and monitoring integration. The table includes both example metric names and monitoring categories.

7.28 — Engineering Incident: The Unstable Controller

Consider a production Kafka deployment with six brokers and three dedicated controllers distributed across three availability zones.

Applications report intermittent administrative request failures, delayed topic creation and unstable partition leadership transitions.

6/6
Broker Processes Online
3/3
Controller Processes Online
12
Epoch Changes / 5 Min
850ms
Observed RTT Spike
CONTROLLER INCIDENT TELEMETRY ILLUSTRATIVE NETWORK DEGRADATION
CONTROLLER NETWORK RTT QUORUM LEADER EPOCH 900ms 450ms 0ms 31 25 19 NETWORK DEGRADATION NETWORK RECOVERY 00:00 01:00 02:00 03:00 04:00 05:00 CORRELATION REQUIRES VALIDATION WITH QUORUM AND NETWORK EVIDENCE
Figure 11 — Hypothetical network latency spikes coincide with repeated metadata leader epoch changes. Leadership stabilizes after network recovery. The correlation suggests a control-plane connectivity problem but does not independently prove the root cause.
CONTROLLER INCIDENT · EVIDENCE EXTRACT
# Synthetic incident evidence, not literal Kafka log output.

12:00:00  Quorum leader = 101, epoch = 19

12:01:02  Controller network RTT increases

12:01:04  Quorum election observed

12:01:05  Quorum leader = 102, epoch = 20

12:01:18  Metadata commit latency increases

12:01:24  Administrative request timeout

12:01:32  Further quorum election observed

12:02:10  Inter-zone TCP retransmissions increase

12:03:45  Network connectivity stabilizes

12:04:10  Quorum leader remains stable

12:05:00  Metadata operations recover

7.29 — Evidence-Based KRaft Troubleshooting

INVESTIGATION STAGE 01

Determine the Failure Domain

Establish whether the incident primarily affects metadata consensus, broker registration, application partitions or multiple architectural layers.

INVESTIGATION STAGE 02

Inspect Quorum Leadership

Identify the current leader, leader epoch, voter membership and evidence of repeated controller elections.

INVESTIGATION STAGE 03

Verify Majority Connectivity

Test the required controller communication paths. Confirm that an eligible majority can communicate, rather than relying on process uptime alone.

INVESTIGATION STAGE 04

Compare Metadata Replication Positions

Inspect metadata log end offsets, follower lag and high watermark progress to identify replication or commit problems.

INVESTIGATION STAGE 05

Investigate Controller Resources

Examine CPU saturation, garbage collection, memory pressure, disk latency, filesystem capacity and controller event processing.

INVESTIGATION STAGE 06

Validate Identity and Security

Verify cluster identity, unique node IDs, listener configuration, quorum membership, certificate validity and authentication.

INVESTIGATION STAGE 07

Correlate Broker Lifecycle State

Investigate broker registration, fencing, heartbeat behaviour and metadata application progress.

INVESTIGATION STAGE 08

Restore and Validate Consensus

Correct the verified infrastructure problem. Confirm stable leadership, metadata commit progress, broker eligibility and successful administrative operations.

7.30 — KRaft Troubleshooting CLI

CONTROL PLANE DIAGNOSTIC COMMANDS
# Inspect metadata quorum status

bin/kafka-metadata-quorum.sh \
  --bootstrap-server broker1:9092 \
  describe --status

# Inspect metadata replication

bin/kafka-metadata-quorum.sh \
  --bootstrap-server broker1:9092 \
  describe --replication

# Inspect storage identity information

bin/kafka-storage.sh info \
  --config config/controller.properties

# Inspect finalized Kafka feature levels

bin/kafka-features.sh \
  --bootstrap-server broker1:9092 \
  describe

# Inspect application partition state

bin/kafka-topics.sh \
  --bootstrap-server broker1:9092 \
  --describe

# Linux controller network diagnostics

getent hosts c101 c102 c103

ss -lntp

ss -tin

ip -s link

# Test an expected controller TCP path

nc -vz -w 3 c102 9093

# Controller resource diagnostics

iostat -xz 1 5

vmstat 1 5

df -h

# Inspect service logs where systemd is used

journalctl -u kafka-controller --since "15 minutes ago"

These commands are illustrative diagnostic operations. Executable paths, service names, available options, authentication configuration and permissions depend on the deployment.

7.31 — Common KRaft Failure Scenarios

Failure Scenario Typical Evidence Investigation Focus
Controller majority unavailable No sustainable leader or metadata commit progress. Voter availability and connectivity.
Repeated controller elections Rapid leader epoch changes. Network instability, resource pressure and timeouts.
Slow metadata storage Increased commit latency and replication lag. Disk performance and filesystem health.
Incorrect controller endpoints Connection failures and discovery problems. DNS, listeners, routing and quorum configuration.
Authentication failure TLS or SASL negotiation errors. Credentials, certificates and security configuration.
Cluster identity mismatch Registration or storage initialization errors. Cluster ID and existing metadata directories.
Broker remains fenced Process running but broker not eligible. Registration, heartbeats and metadata catch-up.
Stale broker metadata Delayed observation of cluster changes. Metadata replication and application progress.

7.32 — Production KRaft Design Principles

DESIGN PRINCIPLE 01

Dedicated Controllers

Isolate critical metadata operations from application partition resource contention.

DESIGN PRINCIPLE 02

Odd-Sized Quorums

Select an appropriate voting membership, commonly three or five controllers, based on failure tolerance requirements.

DESIGN PRINCIPLE 03

Failure Domain Diversity

Distribute voting members across independent infrastructure failure domains.

DESIGN PRINCIPLE 04

Reliable Metadata Storage

Use appropriately provisioned persistent storage with monitored latency and capacity.

DESIGN PRINCIPLE 05

Control Plane Security

Protect controller communication through authentication, encryption and restricted network access.

DESIGN PRINCIPLE 06

Independent Observability

Monitor quorum health separately from broker throughput and consumer lag.

DESIGN PRINCIPLE 07

Controlled Maintenance

Preserve a functioning majority during planned controller maintenance and validate recovery before proceeding.

DESIGN PRINCIPLE 08

Version Compatibility

Validate supported upgrade paths, metadata feature levels and quorum membership procedures.

DESIGN PRINCIPLE 09

Recovery Engineering

Test controller failures, network partitions and documented recovery procedures before production incidents.

Engineering Takeaways

✓ KRaft integrates distributed metadata consensus directly into Kafka.
✓ Kafka's metadata control plane is distinct from its application event data plane.
✓ Kafka 4.0 removed ZooKeeper mode.
✓ Dedicated controllers provide resource and operational isolation.
✓ Controller quorum availability depends on an eligible connected majority.
✓ Three controller voters tolerate one voter failure under normal connectivity assumptions.
✓ Controller elections use majority voting, epoch information and candidate log eligibility.
✓ The metadata log records authoritative cluster state changes.
✓ Metadata consensus and application partition replication use different commit mechanisms.
✓ Broker registration, heartbeats and fencing coordinate broker lifecycle state.
✓ Metadata snapshots reduce historical log replay during state reconstruction.
✓ Broker observers do not automatically participate in controller voting.
✓ Minority network partitions cannot independently commit competing metadata histories.
✓ Quorum loss can impair administrative operations before all existing application traffic stops.
✓ Controller placement must account for correlated infrastructure failures.
✓ Static and dynamic quorum membership require version-appropriate configuration.
✓ Controller troubleshooting requires correlated consensus, network, storage and broker evidence.
✓ Existing metadata storage must be protected during incident recovery.
NETWORK INSIGHT / APACHE KAFKA / 07

KRaft Controller Quorum Simulator

Explore distributed metadata, majority consensus, controller elections and Kafka control-plane resilience.

Reachable voters 3/3
Active controller C1
Raft term 1
Majority required 2
Committed records 0
Pending metadata 0
KRAFT CONTROL-PLANE CONFIGURATION

Configure the Controller Quorum

Changing the quorum size resets this demonstration.
Simulated follower catch-up capacity.
Manual mode allows examination of election conditions.
KRAFT METADATA CONSENSUS FABRIC ● QUORUM HEALTHY
ADMINISTRATIVE METADATA REQUESTS Awaiting operation KAFKA BROKER DATA PLANE CONTROLLER METADATA QUORUM IS SEPARATE FROM TOPIC DATA REPLICATION
CONTROLLER INFRASTRUCTURE

Individual Controller Fault Injection

Fail a controller or isolate it from the connected majority. An isolated controller remains powered on but cannot communicate with the other quorum voters.

RAFT ELECTION CHAMBER

Majority Voting

Latest election candidate C1
Election term 1
Votes granted 3/3

A candidate requires a majority of configured voters, not merely a majority of currently reachable controllers.

CONTROL-PLANE TELEMETRY

Metadata Consensus State

Configured voters 3
Controller failures 0
Successful elections 0
Failed elections 0
Rejected metadata operations 0
Discarded uncommitted records 0
DISTRIBUTED METADATA STORAGE

Controller Metadata Log Inspector

Each controller maintains a replicated metadata log. Records become committed when the simulated consensus rules are satisfied.

Committed Uncommitted Divergent Missing
COMMITTED METADATA IMAGE

Kafka Topic Registry

TOPIC PARTITIONS STATE

Only committed metadata operations modify this registry.

BROKER METADATA CONSUMPTION

Broker Metadata Images

BROKER APPLIED RECORDS METADATA LAG
Registered brokers 3

Brokers consume committed metadata independently of topic data replication.

CONSENSUS RESILIENCE ANALYSIS

Controller Failure Tolerance

CONTROLLERS MAJORITY FAILURES TOLERATED QUORUM LOST AT
3212 failures
5323 failures
7434 failures
Majority = floor(configured voters / 2) + 1. Adding an even-numbered voter does not necessarily increase failure tolerance.
KRAFT CONTROL-PLANE EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 07

The Controller Quorum Incident

Investigate a metadata control-plane outage, demonstrate majority-based recovery and verify that committed metadata survives controller failures.

1 Create three topics and wait until their metadata is committed.
2 Fail the active controller and observe a successful majority election.
3 Create another topic using the replacement controller.
4 Fail or isolate another controller until majority quorum is lost.
5 Attempt to create a topic and observe the rejected metadata operation.
6 Recover all controllers, create another topic and verify that all controller metadata logs converge.
Investigation ready
ENGINEERING PRINCIPLE 01

Metadata Is Not Application Data

The KRaft controller quorum manages cluster metadata, including topic definitions, partition assignments and broker registrations. Application events remain in topic partition logs hosted by Kafka brokers.

ENGINEERING PRINCIPLE 02

Quorum Loss Is Not Always a Total Data-Plane Outage

Existing healthy partition leaders may continue serving established workloads during a controller quorum outage. However, metadata changes and controller-dependent recovery operations can become unavailable.

NETWORK INSIGHT / APACHE KAFKA / 08

Real-Time Event Processing Pipeline

Engineer an event-driven processing architecture with Kafka Streams, stateful transformations, windowed analytics and downstream integrations.

Input events 0
Processing attempts 0
Output records 0
Input lag 0
Filtered events 0
Revenue processed €0
STREAM PROCESSING CONFIGURATION

Configure the Processing Topology

Records below the threshold are consumed but excluded from downstream processing.
Adjust processing throughput to investigate input lag.
Compare non-atomic output and offset commits with a simplified transactional model.
Uses simulated event timestamps. Changing the window resets the laboratory.
Continuous input can exceed processing capacity.
Orders are enriched using the current customer reference table.
REAL-TIME EVENT PROCESSING FACTORY ● PIPELINE HEALTHY
EVENT INGESTION KAFKA STREAMS PROCESSING TOPOLOGY EVENT DELIVERY SOURCE → INPUT TOPIC → FILTER → ENRICH → AGGREGATE → OUTPUT TOPIC → SINK
KAFKA INPUT TOPIC

Incoming Event Log

Topic orders.created
Log end offset 0
Committed next offset 0
Uncommitted input records 0

Input lag is calculated as the log end offset minus the committed next offset.

DOWNSTREAM EVENT TOPIC

Processed Order Stream

Topic orders.enriched
Kafka output records 0
Duplicate output records 0
Sink backlog 0

Output records are retained independently of the downstream sink's availability.

INPUT EVENT INSPECTOR

Original Kafka Record

Generate an order to inspect its event payload.
TRANSFORMATION INSPECTOR

Enriched Output Record

Awaiting a successfully processed event.
KTABLE REFERENCE DATA

Customer State Store

Each incoming order can be joined against the latest customer reference data using its customer identifier.

KEY REGION TIER
Reference-table changes affect future lookups. Previously emitted order records are not automatically rewritten.
STATEFUL STREAM PROCESSING

Regional Revenue State

State-store updates 0
Unique accepted orders 0
Duplicate revenue contribution €0

Non-atomic replay can update state more than once. This laboratory makes the resulting overcount visible.

WINDOWED STREAM ANALYTICS

Tumbling-Window Revenue Aggregation

Simulated event clock 0 seconds

Events are grouped into non-overlapping windows using their original simulated timestamps. Delayed processing retains the original event-time window.

KAFKA CONNECT INTEGRATION

Source Connector

Connector orders-source
External system Order database
Connector state RUNNING
Published source events 0

Kafka Connect source connectors ingest records from external systems. Stream processors consume those records and apply application-specific logic.

DOWNSTREAM DELIVERY

Sink Connector and Analytics Database

Connector analytics-sink
Connector state RUNNING
Delivered records 0
Unique database orders 0
Database revenue €0

The simulated sink uses order-ID upserts, demonstrating how an idempotent destination can avoid duplicate database rows.

PROCESSING TELEMETRY

Event Processing and Delivery Statistics

PIPELINE STAGE RECORDS ENGINEERING INTERPRETATION
STREAM PROCESSING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 08

The Real-Time Analytics Incident

Investigate filtering, processing lag, downstream failure and duplicate revenue caused by event replay.

1 Generate and successfully process at least five orders.
2 Configure the €100 filter and generate orders until at least one event is filtered.
3 Fail the stream processor and generate at least 12 uncommitted input records.
4 Recover the processor and allow input lag to return to zero.
5 Disconnect the sink, generate accepted orders and observe the downstream backlog. Reconnect the sink and drain the backlog.
6 Select Accept all orders and at-least-once processing. Generate an order, use Crash Before Commit, then recover the processor to observe a duplicate output.
7 Switch to the atomic Kafka processing model, repeat the crash experiment and verify that the aborted operation does not produce a duplicate output.
Investigation ready
ENGINEERING PRINCIPLE 01

Stateful Versus Stateless Processing

Filtering and simple transformations can operate independently on each event. Aggregations, joins and deduplication require state that can be maintained and recovered across processing operations.

ENGINEERING PRINCIPLE 02

Exactly-Once Has a Boundary

Kafka Streams exactly-once processing coordinates Kafka output records, state-store changelogs and consumed offsets through transactions. External databases and APIs require their own delivery and idempotency guarantees.

Network Insight · Distributed Systems · Section 08

Real-Time Event Processing

Stream processing, Kafka Streams, Kafka Connect, stateful computation and the engineering of real-time event-driven microservices.

Apache Kafka becomes significantly more powerful when applications move beyond publishing and consuming individual events. Modern distributed systems continuously transform, enrich, correlate and aggregate streams of information as events arrive.

Rather than waiting for a scheduled batch process to analyse accumulated records, stream processing enables applications to react to changing conditions with low latency. This architectural model supports fraud detection, infrastructure monitoring, financial transaction processing, operational analytics and event-driven automation.

Kafka provides the durable event backbone. Processing applications provide the computational logic that turns those events into meaningful decisions, derived datasets and new events.

ARCHITECTURE 08.01 / REAL-TIME PROCESSING PIPELINE
◉
Event Sources Applications, databases, telemetry
→
▤
Kafka Topics Partitioned durable event logs
→
◇
Stream Processor Filter, enrich, join, aggregate
→
▣
Output Systems Derived topics and downstream services
↕ Stateful processing · Local state stores · Kafka changelog topics
Logical event-processing architecture. Processing applications consume input topics, maintain state where required and publish derived results.

8.1 From Event Streaming to Stream Processing

Event streaming and stream processing are closely related but represent different responsibilities within a distributed architecture.

01 / TRANSPORT

Event Streaming

Captures, stores and distributes sequences of events through partitioned Kafka topics. Independent consumers can process or replay retained records at their own pace.

02 / COMPUTATION

Stream Processing

Executes continuous computational operations over event streams, producing transformed records, aggregations, alerts and derived application state.

Consider an online payment platform. Kafka receives transaction events from multiple applications. A processing service enriches each transaction with customer information, calculates recent spending activity and publishes potentially suspicious transactions to a separate fraud-detection topic.

The original transaction remains in its input topic according to the configured retention policy. The processing application creates additional information without requiring producers to understand downstream business logic.

8.2 Kafka Streams Architecture

Kafka Streams is a Java client library for building stream-processing applications that consume and produce Kafka records. It runs inside the application process rather than requiring a separate dedicated stream-processing cluster.

A Kafka Streams application defines a processing topology consisting of source nodes, processing operations and sink nodes. Kafka Streams divides the topology into tasks associated with input partitions and distributes those tasks across available application instances.

PROCESSING COMPONENT 01

Source Processors

Consume records from one or more Kafka topics and introduce those records into the processing topology.

PROCESSING COMPONENT 02

Processing Nodes

Apply transformations, filtering, joins, aggregation and application-specific logic to incoming records.

PROCESSING COMPONENT 03

State Stores

Maintain information required across multiple events, such as counters, historical values, windowed results and lookup tables.

PROCESSING COMPONENT 04

Sink Processors

Publish the results of processing operations to Kafka output topics for consumption by downstream applications.

Engineering principle

Kafka brokers primarily store and distribute records. Application-level stream-processing logic executes within processing clients or external processing frameworks, not inside the Kafka broker itself.

8.3 Stateless and Stateful Processing

Stream-processing operations can be classified according to whether they require information from previously processed records.

Operation Processing Model Example
Filtering Stateless Discard informational telemetry events
Transformation Stateless Convert temperature values into Celsius
Aggregation Stateful Calculate total transactions per customer
Windowing Stateful Count failures during a five-minute interval
Stream joins Stateful Correlate transactions with customer records
Deduplication Stateful Track previously processed event identifiers

Stateless operations can evaluate each record independently. Stateful operations require accumulated information and therefore introduce additional storage, recovery and consistency considerations.

Kafka Streams commonly maintains local state using persistent or in-memory state stores. Logged state stores use Kafka changelog topics to support reconstruction when a processing task moves to another application instance.

8.4 KStream, KTable and GlobalKTable

Kafka Streams provides abstractions that represent different interpretations of records within Kafka topics.

EVENT STREAM

KStream

Represents a sequence of individual events. Multiple records with the same key remain distinct events in the logical stream.

MATERIALISED STATE

KTable

Represents changing keyed state. A new value updates the logical value associated with that key, while a tombstone represents deletion.

REPLICATED LOOKUP

GlobalKTable

Maintains a full local copy of the source table on each application instance, enabling lookup operations without requiring the input stream to be co-partitioned with it.

DATA ENRICHMENT

Stream-Table Join

Enriches an incoming event using the corresponding table state available when the stream record is processed.

KStream: customer-transactions Customer-101 Purchase €120 Customer-101 Purchase €80 Customer-102 Purchase €250 KTable: customer-profiles Customer-101 Premium Customer-102 Standard Derived enriched events: Customer-101 €120 Premium Customer-101 €80 Premium Customer-102 €250 Standard

Stream-table joins allow processing applications to enrich events without making a synchronous remote database request for every incoming record. However, engineers must account for table update timing, state freshness and the partitioning requirements of the chosen join.

8.5 Windowing and Event-Time Processing

Many real-time calculations operate over a defined interval rather than the entire history of an event stream. Windowing divides events into logical time ranges for aggregation and correlation.

Window Type Behaviour Engineering Use Case
Tumbling Fixed, non-overlapping intervals Transactions per minute
Hopping Fixed-size intervals with configurable advance Five-minute metrics updated every minute
Sliding Time-relative windows based on record timestamps Correlating closely timed events
Session Activity grouped by inactivity gaps User sessions and behavioural analytics

Event time describes when an event occurred, whereas processing time describes when an application processes it. These timestamps can differ because of network delays, buffering, producer retries and consumer backlogs.

Kafka Streams uses record timestamps and stream-time progression for event-time window processing. Configurable grace periods determine how long eligible out-of-order records can update windowed results.

Production consideration — late events

An event arriving after its window has closed may be excluded from that aggregation. Grace periods must balance result completeness, state retention and the latency of final window results.

8.6 Kafka Connect and External Data Integration

Kafka Connect provides a framework for moving data between Kafka and external systems using reusable connectors. It addresses integration rather than general-purpose stream-processing computation.

INGRESS

Source Connectors

Import records from external systems such as relational databases, application logs, object storage and change data capture platforms into Kafka topics.

EGRESS

Sink Connectors

Consume Kafka records and deliver them to external destinations such as databases, search platforms, analytics systems and object storage.

Database | | Change Data Capture v Kafka Connect Source | v Kafka Input Topic | v Kafka Streams Application | v Kafka Output Topic | v Kafka Connect Sink | v Analytics Platform

In distributed mode, Kafka Connect workers coordinate connector and task execution. Connector configuration, status and applicable source offsets are maintained using Kafka-backed internal storage.

Engineers must monitor connector task health, serialization errors, schema compatibility, retries, external destination availability and the delivery guarantees supported by individual connectors.

8.7 Event-Driven Microservices

Kafka enables microservices to exchange events asynchronously instead of depending exclusively on synchronous service-to-service API calls. This reduces temporal coupling and allows services to evolve and scale independently.

01
Order Service

Publishes an OrderCreated event to the orders topic after reliably recording the order.

02
Inventory Service

Consumes the event, attempts to reserve inventory and publishes the reservation outcome.

03
Payment Service

Processes payment when the required workflow conditions are satisfied and publishes the payment outcome.

04
Fulfilment Service

Correlates the required successful reservation and payment outcomes before initiating shipment.

05
Notification and Analytics

Independently consume relevant events without introducing additional synchronous dependencies into the order workflow.

This architecture introduces eventual consistency and requires explicit handling of duplicate events, partial failures, compensating actions, correlation identifiers and workflow state.

Patterns such as the transactional outbox and saga-based coordination help address the reliability challenges associated with distributed business transactions.

8.8 Processing Guarantees and Exactly-Once Semantics

A stream-processing application may fail after consuming an event but before completing its processing or committing its input offset. The recovery behaviour determines whether events can be lost, replayed or duplicated.

Guarantee Failure Behaviour Trade-off
At-most-once Records may be lost Avoids processing retries
At-least-once Records may be processed again Requires duplicate-safe processing
Exactly-once Committed Kafka processing effects are atomic Additional transactional coordination

Kafka Streams supports exactly-once processing through the exactly_once_v2 processing guarantee. Kafka transactions coordinate output records, state-store changelog updates and consumed offsets within the transactional processing boundary.

processing.guarantee=exactly_once_v2
Exactly-once has a defined boundary

Kafka transactions do not automatically make arbitrary external API calls, database writes or payment operations exactly-once. External side effects require appropriate idempotency, transactional integration or deduplication mechanisms.

8.9 Backpressure, Consumer Lag and Processing Capacity

A real-time pipeline becomes unstable when events arrive faster than its processing applications can sustainably handle them. Kafka's durable log buffers the difference, allowing records to accumulate rather than requiring immediate synchronous processing.

INPUT RATE

10,000

Incoming events per second.

PROCESSING CAPACITY

7,500

Successfully processed events per second.

BACKLOG GROWTH

+2,500/s

Additional unprocessed events each second.

AFTER 60 SECONDS

150,000

Additional queued events, assuming constant rates and no initial backlog.

Increasing application instances may improve processing throughput, but useful parallelism is constrained by the available processing tasks, partition distribution and downstream dependencies.

A single heavily loaded partition can remain a bottleneck even when other processing instances have spare capacity. This is particularly important when partition keys produce uneven event distribution.

8.10 Troubleshooting a Real-Time Processing Pipeline

Consider a production incident in which transaction events continue arriving in Kafka, but the analytics platform stops receiving current results.

The existence of records in the input topic does not prove that the entire processing pipeline is functioning correctly. Engineers must investigate each architectural boundary independently.

Observation Possible Cause Evidence to Examine
Input topic grows continuously Processing capacity is insufficient Consumer lag and processing throughput
One partition has excessive lag Hot partition or uneven key distribution Per-partition lag and record rates
Processor repeatedly restarts Application failure or resource exhaustion Application logs, CPU, memory and exceptions
Output topic contains duplicate records Replay or application-level duplication Event IDs, offsets and transaction settings
State restoration takes excessive time Large state stores or slow changelog recovery Restore rates, disk performance and state size
Output topic is healthy but database is stale Sink connector or destination failure Connector task status and destination logs
Windowed results omit records Late events or timestamp problems Record timestamps, grace periods and dropped records
Engineering investigation principle

Follow the event from its source through the input partition, consumer task, processing topology, state store, output topic and final destination. Identify the first boundary where observed behaviour diverges from expected behaviour.

Interactive Engineering Lab 08

Real-Time Event Processing Pipeline

The interactive engineering widget accompanying this section allows you to investigate a simulated Kafka stream-processing architecture and observe how changes in processing behaviour affect the complete event pipeline.

  • Generate and observe incoming event streams.
  • Apply filtering and event transformations.
  • Explore KStream–KTable data enrichment.
  • Investigate tumbling-window aggregation.
  • Observe stateful processing and state stores.
  • Introduce processing and sink failures.
  • Investigate consumer lag and backpressure.
  • Compare replay and atomic processing models.
  • Identify the source of a pipeline incident using operational evidence.

Learning objective: Understand not only how events are processed under normal operating conditions, but how real-time distributed pipelines behave during congestion, application failure, replay and recovery.

Engineering Summary

Real-time stream processing transforms Kafka from a distributed event backbone into the foundation of continuously operating data applications.

Kafka Streams provides application-level processing capabilities, Kafka Connect integrates external systems, and Kafka topics provide durable communication boundaries between independent services.

Building reliable production pipelines requires careful engineering of partitioning, state management, processing guarantees, event-time semantics, application scalability and operational observability.

The objective is not simply to process events quickly. It is to process them correctly, recover predictably from failures and maintain sustainable performance as the distributed system evolves.

NETWORK INSIGHT / APACHE KAFKA / 08

Real-Time Event Processing Pipeline

Engineer an event-driven processing architecture with Kafka Streams, stateful transformations, windowed analytics and downstream integrations.

Input events 0
Processing attempts 0
Output records 0
Input lag 0
Filtered events 0
Revenue processed €0
STREAM PROCESSING CONFIGURATION

Configure the Processing Topology

Records below the threshold are consumed but excluded from downstream processing.
Adjust processing throughput to investigate input lag.
Compare non-atomic output and offset commits with a simplified transactional model.
Uses simulated event timestamps. Changing the window resets the laboratory.
Continuous input can exceed processing capacity.
Orders are enriched using the current customer reference table.
REAL-TIME EVENT PROCESSING FACTORY ● PIPELINE HEALTHY
EVENT INGESTION KAFKA STREAMS PROCESSING TOPOLOGY EVENT DELIVERY SOURCE → INPUT TOPIC → FILTER → ENRICH → AGGREGATE → OUTPUT TOPIC → SINK
KAFKA INPUT TOPIC

Incoming Event Log

Topic orders.created
Log end offset 0
Committed next offset 0
Uncommitted input records 0

Input lag is calculated as the log end offset minus the committed next offset.

DOWNSTREAM EVENT TOPIC

Processed Order Stream

Topic orders.enriched
Kafka output records 0
Duplicate output records 0
Sink backlog 0

Output records are retained independently of the downstream sink's availability.

INPUT EVENT INSPECTOR

Original Kafka Record

Generate an order to inspect its event payload.
TRANSFORMATION INSPECTOR

Enriched Output Record

Awaiting a successfully processed event.
KTABLE REFERENCE DATA

Customer State Store

Each incoming order can be joined against the latest customer reference data using its customer identifier.

KEY REGION TIER
Reference-table changes affect future lookups. Previously emitted order records are not automatically rewritten.
STATEFUL STREAM PROCESSING

Regional Revenue State

State-store updates 0
Unique accepted orders 0
Duplicate revenue contribution €0

Non-atomic replay can update state more than once. This laboratory makes the resulting overcount visible.

WINDOWED STREAM ANALYTICS

Tumbling-Window Revenue Aggregation

Simulated event clock 0 seconds

Events are grouped into non-overlapping windows using their original simulated timestamps. Delayed processing retains the original event-time window.

KAFKA CONNECT INTEGRATION

Source Connector

Connector orders-source
External system Order database
Connector state RUNNING
Published source events 0

Kafka Connect source connectors ingest records from external systems. Stream processors consume those records and apply application-specific logic.

DOWNSTREAM DELIVERY

Sink Connector and Analytics Database

Connector analytics-sink
Connector state RUNNING
Delivered records 0
Unique database orders 0
Database revenue €0

The simulated sink uses order-ID upserts, demonstrating how an idempotent destination can avoid duplicate database rows.

PROCESSING TELEMETRY

Event Processing and Delivery Statistics

PIPELINE STAGE RECORDS ENGINEERING INTERPRETATION
STREAM PROCESSING EVENT CONSOLE
GUIDED ENGINEERING INVESTIGATION / LAB 08

The Real-Time Analytics Incident

Investigate filtering, processing lag, downstream failure and duplicate revenue caused by event replay.

1 Generate and successfully process at least five orders.
2 Configure the €100 filter and generate orders until at least one event is filtered.
3 Fail the stream processor and generate at least 12 uncommitted input records.
4 Recover the processor and allow input lag to return to zero.
5 Disconnect the sink, generate accepted orders and observe the downstream backlog. Reconnect the sink and drain the backlog.
6 Select Accept all orders and at-least-once processing. Generate an order, use Crash Before Commit, then recover the processor to observe a duplicate output.
7 Switch to the atomic Kafka processing model, repeat the crash experiment and verify that the aborted operation does not produce a duplicate output.
Investigation ready
ENGINEERING PRINCIPLE 01

Stateful Versus Stateless Processing

Filtering and simple transformations can operate independently on each event. Aggregations, joins and deduplication require state that can be maintained and recovered across processing operations.

ENGINEERING PRINCIPLE 02

Exactly-Once Has a Boundary

Kafka Streams exactly-once processing coordinates Kafka output records, state-store changelogs and consumed offsets through transactions. External databases and APIs require their own delivery and idempotency guarantees.

☕
Support Network Insight
Help support the development of interactive networking labs, BGP simulations, and educational content.
Support the Project
Matt Conran
Tags: No tags

Comments are closed.