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.
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.
Direct request-response dependencies can propagate delays and failures between applications.
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.
Publish
Applications produce records representing business events, telemetry, transactions and infrastructure state changes.
Store
Distributed brokers retain records in partitioned logs, with configurable replication and durability characteristics.
Process
Independent consumers and stream-processing applications transform, analyse and react to available event streams.
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.
Microservices
Decouple order processing, inventory management, payments and notification systems through asynchronous business events.
Network Telemetry
Stream infrastructure measurements, security alerts and device events into monitoring and incident analysis pipelines.
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.
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.
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.
Sections
Explorers
Stages
Understanding Event-Driven Architecture
Events, asynchronous communication, distributed applications and loosely coupled services.
Apache Kafka Core Architecture
Brokers, clusters, clients, distributed event storage and the Kafka data plane.
Topics, Partitions and Distributed Logs
Partition keys, offsets, ordering, retention and the architecture of append-only event logs.
Kafka Producer Architecture
Serialization, batching, partition selection, acknowledgements, retries and idempotent publishing.
Consumers, Consumer Groups and Rebalancing
Consumer coordination, partition assignment, committed offsets, processing parallelism and lag.
Replication and Fault Tolerance
Leaders, followers, in-sync replicas, durability guarantees and partition failure recovery.
KRaft and Kafka Metadata Management
Controller quorums, metadata logs, Raft consensus, leader elections and control-plane resilience.
Real-Time Event Processing
Kafka Streams, Kafka Connect, stateful computation, windowing, stream joins and processing guarantees.
Production Kafka Architecture and Troubleshooting
Capacity planning, security, observability, disaster recovery and production incident investigation.
Understand event-driven systems, Kafka infrastructure and distributed logs.
Explore publishing, consumption, replication and metadata coordination.
Investigate real-time processing, infrastructure resilience and operational failures.
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.
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
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 requestAsynchronous Event Stream
Once the event has been successfully published, inventory processing can occur independently, subject to retention and recovery requirements.
Producer and consumer processing are decoupledAsynchronous 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.
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.
{
"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"
}
}
Identity
An event identifier distinguishes individual events and can help downstream applications detect duplicate processing.
Metadata
Event type, timestamp, schema version and correlation identifiers provide context for interpretation and distributed tracing.
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.
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.
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.
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.
Order Created
The order service records the new order in its application database.
Event Published
An outbox publisher or equivalent reliable publication mechanism sends the OrderCreated record to Kafka.
Record Acknowledged
The producer receives acknowledgement according to its configured durability and acknowledgement requirements.
Inventory Processing
The inventory consumer retrieves the event and attempts to reserve the required stock.
Payment Workflow
An independent payment consumer processes the event according to its business workflow. Additional coordination may be required before payment is authorised.
Analytics Updated
The analytics consumer incorporates the order event into operational reporting.
Notification Processed
The notification service sends an appropriate order acknowledgement to the customer.
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.
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.
Consumer Failure
The analytics application stops processing records. Its committed position stops advancing while producers continue publishing.
Lag Accumulates
The difference between the available log end and the consumer group's committed position increases as new events arrive.
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.
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
Event-Driven Architecture Explorer
Investigate asynchronous communication, service independence and the engineering value of retained event streams.
Downstream Applications
Order Event Stream
Select an event to inspect its JSON payload.
Waiting for an event...
Analytics Application
An analytics application can independently read historical events without removing them from the stream or changing another application's processing position.
The Unavailable Payment Service
Investigate whether asynchronous communication allows other applications to continue processing orders during a payment service outage.
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.
The producer publishes an event independently of downstream processing. Subscribers process at their own pace, while retained events support delayed consumption and replay.
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.
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.
Producer
A client application that publishes records to Kafka topics. Producers determine partition placement using explicit partition selection, partitioning logic or record keys.
Broker
A Kafka server that stores partition replicas, processes client requests and participates in distributed replication.
Topic
A named logical collection of related records. Topics provide an organisational boundary for event streams and configuration policies.
Partition
An independently ordered distributed log within a topic. Partitions provide the fundamental unit of Kafka parallelism.
Consumer
A client application that fetches records from Kafka and processes them according to application requirements.
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.
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.
Network Processing
Handles client connections, protocol requests, authentication, request queues and network responses.
Log Management
Maintains partition segment files, indexes, record offsets, retention policies and configured log compaction.
Replication
Coordinates partition leader and follower behaviour, replica progress and the replication of partition records.
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.
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.
# 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.
Bootstrap Connection
The Kafka client establishes a connection to an available configured bootstrap broker.
Protocol and Security Negotiation
The client establishes the required security context and negotiates supported protocol capabilities where applicable.
Metadata Discovery
The client retrieves information about available brokers, topic partitions and partition leadership.
Direct Broker Connections
The client connects to the appropriate advertised broker endpoints for producing records, fetching data or coordinating consumer group operations.
Metadata Refresh
The client periodically refreshes metadata and responds to relevant errors or leadership changes by updating its understanding of the cluster.
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.
# 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.
Incorrect DNS
The bootstrap address is reachable, but advertised broker hostnames cannot be resolved by the client.
Blocked Broker Ports
Firewall or network policy rules allow bootstrap connectivity but prevent access to individual partition leaders.
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.
Data Plane
Operated primarily by the Kafka brokers.
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.
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.
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.
Observe
Bootstrap connectivity succeeds, but subsequent connections to individual broker endpoints time out.
Investigate
Inspect returned broker metadata, advertised listeners, DNS resolution, routing and network security policies.
Resolve
Correct the advertised listener architecture and ensure every required broker endpoint is reachable and correctly authenticated.
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 Cluster Architecture Explorer
Explore how producers, brokers, distributed topic storage and consumer applications form an event-streaming platform.
Topics and Partition Placement
Each topic contains three partitions distributed across the physical brokers.
Consumer Applications
Disconnect an application and observe how its topic continues receiving events.
Broker 01 — Storage Inspector
| TOPIC | PARTITION | EVENTS | STATE |
|---|
Click any broker in the topology to inspect its local partition storage.
Recent Published Events
| EVENT | TOPIC | PARTITION | DESTINATION |
|---|---|---|---|
| Waiting for producer traffic... | |||
Discover the Distributed Cluster
Investigate the distinction between logical topics, physical brokers and independent consumer applications.
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.
*Conceptually growing offset sequences, subject to Kafka's numeric offset limits and operational constraints. Retained storage is finite.
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.
customer-orders
Business events representing order creation, modification, cancellation and fulfilment.
network-telemetry
Interface counters, device measurements, operational state changes and infrastructure performance observations.
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.
Independent Storage
Each partition maintains its own logical record sequence and physical log segments.
Independent Leadership
Each partition has a leader responsible for normal record production and coordinating its replica state.
Parallel Processing
Different partitions can be assigned to different members of a conventional consumer group, allowing concurrent processing.
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.
// 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.
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.
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.
| 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. |
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.
.log
Contains Kafka record batches and their associated encoded record data.
.index
Provides a sparse mapping from relative record offsets to positions within the segment data file.
.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
The records have an explicit order within the partition log.
Partition-level orderingAcross Multiple Partitions
These offsets belong to different logs. They do not establish a global event order.
No global offset orderingPartition-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.
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.
# 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.
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
Multiple historical values exist for keys A and B. Older superseded values may become eligible for compaction.
After Illustrative Compaction
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 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.
Example total: 100 MB/s across six partitions. Bar lengths represent each partition's share of total ingress.
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.
Low Key Cardinality
Too few distinct keys can prevent effective distribution across the available partitions.
Uneven Key Frequency
A small number of high-volume entities can dominate particular partition workloads.
Uneven Record Sizes
Similar record counts can conceal substantial differences in partition bandwidth and storage requirements.
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.
# 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.
Identify the Affected Partition
Examine consumer-group lag by topic and partition rather than relying exclusively on aggregate consumer lag.
Compare Partition Ingress Rates
Determine whether the affected partition receives substantially more records or bytes than the remaining partitions.
Investigate Consumer Processing
Compare fetch rates, processing latency, downstream service dependencies and application resource utilisation.
Inspect Record Key Distribution
Sample authorised record metadata or application instrumentation to identify dominant keys and workload skew.
Evaluate Architectural Remediation
Consider consumer processing optimisation, leader redistribution, revised partition keys or a controlled topic migration, depending on the verified bottleneck.
# 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
Kafka Partition & Offset Simulator
Explore deterministic key routing, append-only distributed logs, partition-level ordering and horizontal scalability.
Configure Event Routing
Kafka Event Payload
Select any stored record to inspect its partition, key, offset and event metadata.
No record selected.
Customer Key Routing Table
| KEY | HASH | PARTITION |
|---|
The mapping is calculated using Kafka-compatible Murmur2 hashing for the selected UTF-8 keys.
Read From a Partition
Choose a partition and starting offset. Reading records does not delete them from the log.
Partition Utilisation
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 |
|---|
The Hot Partition Investigation
Investigate how key selection influences partition distribution, ordering and scalability.
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.
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.
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.
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.
Application Submission
The application constructs a record containing a topic, optional key, value and optional metadata.
Local Preparation
The producer serialises data, selects a partition and appends the record to a partition-specific batch.
Network Delivery
The sender transmits produce requests, handles broker responses and reports delivery outcomes.
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.
JSON
Human-readable structured data with broad interoperability. Schema enforcement requires additional application or platform mechanisms.
Apache Avro
Schema-based binary serialisation commonly used with schema registries and controlled schema evolution.
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.
{
"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.
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
Sending each record independently can increase protocol overhead, request processing and network utilisation.
Batched Record Transmission
Grouping records can amortise request overhead and improve compression efficiency.
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.
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.
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.
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. |
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.
acks=0
The producer does not wait for a broker acknowledgement. It cannot confirm whether the broker successfully appended the record.
acks=1
The partition leader acknowledges the append without waiting for all current in-sync replicas to replicate the record.
acks=all
Successful acknowledgement requires the record to reach the current in-sync replica set, subject to minimum ISR requirements.
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.
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.
| 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.
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.
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.
At-Most-Once
An event may be lost, but the workflow avoids repeated delivery or processing within its defined guarantee boundary.
At-Least-Once
Events are retried or reprocessed as necessary under defined recovery assumptions. Duplicate processing remains possible.
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.
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.
Illustrative incident telemetry. Each bar represents utilisation relative to its own example capacity or operational threshold.
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.
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.
# 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.
// 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.
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.
Establish the Delivery Failure Boundary
Determine whether application submission, local record accumulation, network transmission or broker acknowledgement is experiencing delay.
Inspect Producer Metrics
Examine buffer availability, record queue time, request latency, retry activity and producer error rates.
Validate Network Reachability
Confirm DNS resolution, broker advertised addresses, TCP connectivity, TLS negotiation and relevant firewall policy.
Examine Broker and Replica Health
Inspect partition leadership, ISR membership, under-replicated partitions, broker request processing and storage performance.
Investigate Quota Enforcement
Determine whether client or user quotas are throttling produce requests and contributing to the ingestion deficit.
Apply Evidence-Based Remediation
Resolve the verified bottleneck, restore replica health, correct network connectivity, adjust appropriate quotas or reduce application production pressure.
# 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 Producer Delivery Simulator
Investigate batching, compression, acknowledgements, retry behaviour and reliable event delivery.
Configure the Delivery Pipeline
Producer Buffer
Waiting for application records.
In-Flight Batch
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.
Compression Telemetry
Each generated record represents 1 KiB of application data. Compression ratios are illustrative and include retry attempts, not actual measured network traffic.
Reliability 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.
The Lost Acknowledgement Incident
Investigate duplicate delivery and determine how idempotent production changes the outcome of a retry.
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.
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.
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.
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.
Fetch Manager
Retrieves record batches from the appropriate brokers and manages partition-specific fetching progress.
Group Membership
Coordinates membership, partition assignment and group lifecycle operations when using automatic group management.
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.
| 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.
Order Fulfilment
Processes incoming orders and initiates fulfilment operations.
Real-Time Analytics
Calculates business metrics from the same order event stream.
Fraud Detection
Independently evaluates transaction patterns and suspicious application behaviour.
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
Each consumer manages two partitions. All six partitions have active owners.
Eight Consumer Instances
Two consumers have no partition assignment. Adding further consumers does not increase partition-level ownership parallelism.
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.
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.
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.
Automatic Commit
The client periodically commits consumption positions. Correctness depends on how the application coordinates polling and processing.
Synchronous Commit
The application explicitly commits offsets and waits for the operation to complete or fail.
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.
// 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.
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.
5.10 — Eager and Cooperative Rebalancing
The way partitions are revoked and reassigned influences application availability during membership changes.
Eager Rebalancing
Consumers revoke their existing assignments before receiving new assignments, potentially creating a broad processing interruption.
Cooperative Rebalancing
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.
heartbeat.interval.ms
Controls heartbeat frequency for compatible classic-protocol consumers. Heartbeats communicate continued group membership.
session.timeout.ms
Establishes the classic-protocol membership expiration boundary when expected heartbeat activity is missing.
max.poll.interval.ms
Limits the permitted interval between application poll calls when using consumer group management.
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.
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.
*The ratio is illustrative only and is not a recommended general-purpose Kafka lag metric. Offset origins and retention boundaries vary.
Illustrative monitoring snapshot · order-processing consumer group · common scale of 0–60,000 offsets.
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.
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.
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.
earliest
Starts from the earliest available offset when no valid committed offset exists.
latest
Starts from the applicable end position when no valid committed offset exists.
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.
# 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
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.
5.18 — Production Consumer Configuration
Consumer configuration must balance processing latency, memory utilisation, failure recovery, partition assignment stability and application correctness.
# 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.
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.
Identify the Responsible Consumer
Map the affected partition to its current consumer instance. Examine application logs, CPU, memory, garbage collection and worker queue utilisation.
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.
Examine External Dependencies
Measure database query latency, connection pool utilisation, HTTP request duration and downstream service error rates.
Validate Group Stability
Inspect consumer restarts, membership changes, poll interval violations, heartbeat problems and rebalance frequency.
Validate Kafka and Network Performance
Compare fetch latency, broker resource usage, network throughput, TLS connectivity and transactional visibility boundaries.
Restore Processing Capacity
Correct the verified bottleneck and ensure processing capacity exceeds the incoming event rate until the backlog has recovered.
$ 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.
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
Consumer Group & Rebalancing Lab
Explore parallel event processing, partition ownership, committed offsets, consumer failures and workload redistribution.
Configure the Processing Environment
Consumer Application Instances
Crash or recover an individual consumer. The coordinator will initiate a new assignment for the remaining online members.
Rebalance Timeline
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.
Consumer Lag Monitor
Processing Capacity versus Ingestion
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.
The Consumer Scaling and Recovery Incident
Investigate parallel processing limits, offset recovery and the effect of scaling a consumer group.
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.
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.
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.
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.
Data Durability
Maintain redundant copies of important event records so that individual storage failures do not necessarily destroy the event history.
Service Availability
Allow eligible surviving replicas to assume leadership when the current partition leader becomes unavailable.
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.
| 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. |
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.
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.
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
ISR = {1, 2, 3}
All three assigned replicas currently participate in the in-sync replica set.
Degraded Replication State
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.
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.
Log End Offset
The next offset position at the end of an individual replica's local log.
High Watermark
The replicated visibility boundary used to prevent ordinary consumers from reading an uncommitted replication tail.
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.
acks=0
The producer does not wait for a broker acknowledgement. It cannot reliably determine whether the broker accepted the record.
acks=1
The leader acknowledges after accepting the write into its local log, without waiting for follower replication.
acks=all
The producer waits for the required replication acknowledgement condition across the current in-sync replica set.
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.
*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. |
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
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
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.
6.11 — The Leader Election Lifecycle
Broker Unavailability
A broker fails, loses connectivity or becomes fenced through the cluster's broker lifecycle mechanisms.
Partition Leadership Evaluation
The active controller identifies affected partitions and evaluates eligible surviving replicas according to the active election rules.
Metadata Update
New partition leadership and associated epoch information are recorded through the cluster metadata mechanisms.
Replica Role Transition
The selected broker becomes the new leader. Other surviving followers reconcile their replication state with the new leadership.
Client Metadata Refresh
Producers and consumers discover updated partition leadership through metadata refresh and error recovery mechanisms.
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.
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
Leadership transfers to an eligible replica expected to preserve the committed replication history under normal failure assumptions.
Unclean Leader Election
A stale replica may become leader to restore availability, potentially losing records that existed only on unavailable replicas.
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.
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.
# 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.
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.
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.
UnderReplicatedPartitions
Partitions whose ISR contains fewer replicas than their assigned replication factor.
UnderMinIsrPartitionCount
Partitions whose ISR size is below the configured minimum in-sync replica requirement.
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
| 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. |
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.
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
# 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.
Although every broker remains registered, some followers cannot replicate quickly enough to maintain synchronization. Producer applications begin reporting replication-related write errors.
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
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
Establish the Failure Scope
Identify affected topics, partitions, brokers and availability zones. Determine whether the incident affects leadership, replication or both.
Compare Assigned Replicas and ISR
Inspect topic metadata to identify replicas repeatedly disappearing from the ISR. Look for common broker or infrastructure placement patterns.
Inspect Network Connectivity
Examine inter-broker TCP connectivity, packet loss, retransmissions, interface errors, congestion and cross-zone latency.
Inspect Broker Storage
Compare disk latency, throughput, filesystem capacity, storage errors and log directory availability across affected brokers.
Evaluate Replica Fetch Performance
Inspect follower replication lag, fetcher activity, request processing delays, replication bandwidth and configured quotas.
Correlate Controller State
Examine broker registration, fencing, partition leadership changes and metadata quorum health to distinguish data-plane degradation from control-plane failure.
Restore the Verified Bottleneck
Correct the identified network, storage or broker resource problem. Allow replicas to reconcile their logs and recover synchronization.
Validate Durability Recovery
Confirm ISR restoration, stable leadership, successful producer acknowledgements and recovery of affected application workflows.
# 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.
Local Replication
Protects partition availability and data redundancy within the Kafka cluster.
Cross-Cluster Replication
Replicates selected event streams to another Kafka cluster using mechanisms such as MirrorMaker 2 or managed equivalents.
Independent Recovery
Uses appropriately designed archives, backups, restoration procedures and tested disaster recovery workflows.
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
Broker Failure & Recovery Simulator
Investigate distributed log replication, leader elections, in-sync replicas, storage durability and failure recovery.
Configure the Replication Environment
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.
Leader and Replica State
Write and Recovery Telemetry
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.
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.
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.
The Broker Failure and Recovery Incident
Demonstrate clean leader failover, minimum ISR enforcement and follower recovery without losing committed records.
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.
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.
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.
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.
Cluster Membership
Maintain broker registration, lifecycle information, fencing state and advertised network endpoints.
Partition Coordination
Maintain partition assignments, leader identities, replica membership and leadership generations.
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.
| 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.
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.
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.
| 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.
Leader Election
Voting members select an eligible leader for a particular leadership epoch.
Log Replication
Metadata records are replicated from the leader to follower voters through fetch requests and responses.
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.
Detect Leadership Loss
Followers detect that valid communication with the current leader has not been maintained within the applicable timeout.
Begin Election
An eligible candidate initiates a new election with an advanced epoch.
Evaluate Candidate State
Voters evaluate epoch information, previous voting state and candidate log freshness.
Establish Majority
A candidate receiving the required majority becomes the new quorum leader.
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.
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. |
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.
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
Majority = 2
Consensus = Raft-based
Coordinates authoritative cluster metadata through majority-based consensus.
Application Partition Replication
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.
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.
Registered and Fenced
The broker has registration information but is not yet eligible for normal cluster service.
Unfenced
The broker satisfies the applicable lifecycle requirements and can participate in normal cluster operations.
Fenced After Failure
The controller excludes the broker from eligible service because its lifecycle or liveness requirements are no longer met.
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.
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
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
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 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. |
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.
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
Required Majority = 2
Consensus = Available
Two Controller Failures
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.
Reliable Connectivity
Maintain stable controller-to-controller and broker-to-controller communication with predictable latency and packet loss.
Protected Listeners
Restrict controller listeners to required infrastructure participants and authorized administrative paths.
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
Remaining Voters = 1
Majority Lost
Losing one zone removes two voting members and prevents normal consensus.
Distributed Failure Domains
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
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
c101:9093,c102:9093,c103:9093
Supported dynamic quorum deployments maintain voting membership through quorum state and administrative 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.
# 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.
# 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 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.
# 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 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.
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.
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.
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.
Quorum Leadership
Monitor leader identity, current epoch, election frequency and the availability of voting members.
Metadata Replication
Monitor metadata log progress, high watermark advancement, follower lag and snapshot activity.
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.
# 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
Determine the Failure Domain
Establish whether the incident primarily affects metadata consensus, broker registration, application partitions or multiple architectural layers.
Inspect Quorum Leadership
Identify the current leader, leader epoch, voter membership and evidence of repeated controller elections.
Verify Majority Connectivity
Test the required controller communication paths. Confirm that an eligible majority can communicate, rather than relying on process uptime alone.
Compare Metadata Replication Positions
Inspect metadata log end offsets, follower lag and high watermark progress to identify replication or commit problems.
Investigate Controller Resources
Examine CPU saturation, garbage collection, memory pressure, disk latency, filesystem capacity and controller event processing.
Validate Identity and Security
Verify cluster identity, unique node IDs, listener configuration, quorum membership, certificate validity and authentication.
Correlate Broker Lifecycle State
Investigate broker registration, fencing, heartbeat behaviour and metadata application progress.
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
# 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
Dedicated Controllers
Isolate critical metadata operations from application partition resource contention.
Odd-Sized Quorums
Select an appropriate voting membership, commonly three or five controllers, based on failure tolerance requirements.
Failure Domain Diversity
Distribute voting members across independent infrastructure failure domains.
Reliable Metadata Storage
Use appropriately provisioned persistent storage with monitored latency and capacity.
Control Plane Security
Protect controller communication through authentication, encryption and restricted network access.
Independent Observability
Monitor quorum health separately from broker throughput and consumer lag.
Controlled Maintenance
Preserve a functioning majority during planned controller maintenance and validate recovery before proceeding.
Version Compatibility
Validate supported upgrade paths, metadata feature levels and quorum membership procedures.
Recovery Engineering
Test controller failures, network partitions and documented recovery procedures before production incidents.
Engineering Takeaways
KRaft Controller Quorum Simulator
Explore distributed metadata, majority consensus, controller elections and Kafka control-plane resilience.
Configure the Controller Quorum
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.
Majority Voting
A candidate requires a majority of configured voters, not merely a majority of currently reachable controllers.
Metadata Consensus State
Controller Metadata Log Inspector
Each controller maintains a replicated metadata log. Records become committed when the simulated consensus rules are satisfied.
Kafka Topic Registry
| TOPIC | PARTITIONS | STATE |
|---|
Only committed metadata operations modify this registry.
Broker Metadata Images
| BROKER | APPLIED RECORDS | METADATA LAG |
|---|
Brokers consume committed metadata independently of topic data replication.
Controller Failure Tolerance
| CONTROLLERS | MAJORITY | FAILURES TOLERATED | QUORUM LOST AT |
|---|---|---|---|
| 3 | 2 | 1 | 2 failures |
| 5 | 3 | 2 | 3 failures |
| 7 | 4 | 3 | 4 failures |
The Controller Quorum Incident
Investigate a metadata control-plane outage, demonstrate majority-based recovery and verify that committed metadata survives controller failures.
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.
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.
Real-Time Event Processing Pipeline
Engineer an event-driven processing architecture with Kafka Streams, stateful transformations, windowed analytics and downstream integrations.
Configure the Processing Topology
Incoming Event Log
Input lag is calculated as the log end offset minus the committed next offset.
Processed Order Stream
Output records are retained independently of the downstream sink's availability.
Original Kafka Record
Generate an order to inspect its event payload.
Enriched Output Record
Awaiting a successfully processed event.
Customer State Store
Each incoming order can be joined against the latest customer reference data using its customer identifier.
| KEY | REGION | TIER |
|---|
Regional Revenue State
Non-atomic replay can update state more than once. This laboratory makes the resulting overcount visible.
Tumbling-Window Revenue Aggregation
Events are grouped into non-overlapping windows using their original simulated timestamps. Delayed processing retains the original event-time window.
Source Connector
Kafka Connect source connectors ingest records from external systems. Stream processors consume those records and apply application-specific logic.
Sink Connector and Analytics Database
The simulated sink uses order-ID upserts, demonstrating how an idempotent destination can avoid duplicate database rows.
Event Processing and Delivery Statistics
| PIPELINE STAGE | RECORDS | ENGINEERING INTERPRETATION |
|---|
The Real-Time Analytics Incident
Investigate filtering, processing lag, downstream failure and duplicate revenue caused by event replay.
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.
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.
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.
8.1 From Event Streaming to Stream Processing
Event streaming and stream processing are closely related but represent different responsibilities within a distributed architecture.
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.
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.
Source Processors
Consume records from one or more Kafka topics and introduce those records into the processing topology.
Processing Nodes
Apply transformations, filtering, joins, aggregation and application-specific logic to incoming records.
State Stores
Maintain information required across multiple events, such as counters, historical values, windowed results and lookup tables.
Sink Processors
Publish the results of processing operations to Kafka output topics for consumption by downstream applications.
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.
KStream
Represents a sequence of individual events. Multiple records with the same key remain distinct events in the logical stream.
KTable
Represents changing keyed state. A new value updates the logical value associated with that key, while a tombstone represents deletion.
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.
Stream-Table Join
Enriches an incoming event using the corresponding table state available when the stream record is processed.
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.
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.
Source Connectors
Import records from external systems such as relational databases, application logs, object storage and change data capture platforms into Kafka topics.
Sink Connectors
Consume Kafka records and deliver them to external destinations such as databases, search platforms, analytics systems and object storage.
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.
Publishes an OrderCreated event to the orders topic after reliably recording the order.
Consumes the event, attempts to reserve inventory and publishes the reservation outcome.
Processes payment when the required workflow conditions are satisfied and publishes the payment outcome.
Correlates the required successful reservation and payment outcomes before initiating shipment.
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.
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.
10,000
Incoming events per second.
7,500
Successfully processed events per second.
+2,500/s
Additional unprocessed events each second.
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 |
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.
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.
Real-Time Event Processing Pipeline
Engineer an event-driven processing architecture with Kafka Streams, stateful transformations, windowed analytics and downstream integrations.
Configure the Processing Topology
Incoming Event Log
Input lag is calculated as the log end offset minus the committed next offset.
Processed Order Stream
Output records are retained independently of the downstream sink's availability.
Original Kafka Record
Generate an order to inspect its event payload.
Enriched Output Record
Awaiting a successfully processed event.
Customer State Store
Each incoming order can be joined against the latest customer reference data using its customer identifier.
| KEY | REGION | TIER |
|---|
Regional Revenue State
Non-atomic replay can update state more than once. This laboratory makes the resulting overcount visible.
Tumbling-Window Revenue Aggregation
Events are grouped into non-overlapping windows using their original simulated timestamps. Delayed processing retains the original event-time window.
Source Connector
Kafka Connect source connectors ingest records from external systems. Stream processors consume those records and apply application-specific logic.
Sink Connector and Analytics Database
The simulated sink uses order-ID upserts, demonstrating how an idempotent destination can avoid duplicate database rows.
Event Processing and Delivery Statistics
| PIPELINE STAGE | RECORDS | ENGINEERING INTERPRETATION |
|---|
The Real-Time Analytics Incident
Investigate filtering, processing lag, downstream failure and duplicate revenue caused by event replay.
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.
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.
- Kubernetes Multi-Cluster Networking Architecture Explained - November 24, 2026
- Post-Quantum Cryptography and Network Security - November 24, 2026
- Internet of Things (IoT) Access Technologies Explained - November 24, 2026
