Apache Kafka: Distributed Streaming Platform

Learn Kafka topics, partitions, consumer groups, delivery guarantees, Kafka transactions, and the boundary between stream processing and external effects.

published: reading time: 45 min read author: Geek Workbench updated: November 2, 2026
Quick Summary

Kafka stores events in partitioned logs, so consumer groups can read the same stream and replay retained records. This post covers key-based ordering, consumer parallelism, replication, and offset management. Kafka transactions coordinate Kafka records and offsets, while database and webhook effects need destination-side retry protection. Later sections cover rebalancing, backpressure, security, and monitoring.

Apache Kafka: Distributed Streaming Platform

Introduction

Apache Kafka is a distributed event-streaming platform. Producers append records to topics, and consumer groups read those records independently. Because Kafka retains records, a consumer can replay them while they remain within the topic’s retention window.

This guide starts with Kafka’s core model and processing guarantees, then moves to production operations such as replication, rebalancing, backpressure, and monitoring. Its transactional examples target the Apache Kafka 4.4 Java client. See the versioned Kafka design documentation and producer configuration reference when adapting examples to a deployment.

Core concepts: Topics, partitions, consumer groups, and offsets, followed by processing guarantees and transaction scope.

Production operations: Replication, consumer coordination, failure scenarios, and observability.

Core concepts

Topics and partitions

Kafka organizes data into topics. Unlike a queue where messages are consumed and deleted, Kafka topics are logs. Messages are appended and kept for a configurable retention period: hours, days, or indefinitely.

Topic: order-events
Partition 0: [msg1, msg2, msg3, msg5, msg8]
Partition 1: [msg4, msg6, msg7, msg9]
Partition 2: [msg10, msg11, msg12]

Each topic splits into partitions for parallelism. Partitions distribute across brokers. Within a partition, messages have a monotonically increasing offset that uniquely identifies each one.

Message keying

Producers can specify a key when publishing:

producer.send(new ProducerRecord("order-events", orderId, orderJson));

Kafka hashes the key to determine the partition. With a stable partition count and partitioner, records with the same key go to the same partition, which preserves per-key ordering. Increasing the partition count can change that mapping.

Partition assignment

Partitions assign to brokers at topic creation time:

Broker 1: Partition 0, Partition 3
Broker 2: Partition 1, Partition 4
Broker 3: Partition 2, Partition 5

The leader broker for each partition handles reads and writes. Followers replicate for fault tolerance.

Consumer groups

Kafka consumers belong to consumer groups. Each message in a topic delivers to one consumer within each group.

graph LR
    Producer -->|publish| Topic[Topic with 3 Partitions]
    Topic -->|P0| CG1[Consumer Group A]
    Topic -->|P1| CG1
    Topic -->|P2| CG1
    Topic -->|P0| CG2[Consumer Group B]
    Topic -->|P1| CG2
    Topic -->|P2| CG2

Group A might have one consumer processing all partitions. Group B might have three consumers, each owning one partition. Both groups receive all messages independently.

Rebalancing

When a consumer joins or leaves a group, Kafka triggers a rebalance. The group coordinator redistributes partition assignments. An eager rebalance revokes all assignments; a cooperative rebalance moves only the partitions that need to change owners.

The pause and recovery time depend on the group protocol, assignment strategy, workload, and cluster state:

Protocol What happens Processing impact
Eager rebalance All consumers revoke their assignments before partitions are reassigned The group pauses while assignments are replaced
Cooperative rebalance Only partitions changing owners are revoked; others can keep processing The pause is limited to partitions being transferred

The cooperative protocol uses a cooperative assignor such as CooperativeStickyAssignor, covered below. Check the configured group protocol and assignment strategy instead of assuming a rebalance mode from a single client setting.

What causes unwanted rebalances

Most unwanted rebalances start with a simple mismatch: the consumer takes longer to process a batch than the broker’s timeout allows.

Kafka 4.4’s Java consumer default for max.poll.interval.ms is 300000 ms. Confirm defaults for the group protocol and client version in the versioned consumer configuration reference before changing timeout settings.

config.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 300000); // Kafka 4.4 Java client default

If consumer.poll() isn’t called within max.poll.interval.ms because the previous batch took too long, the broker marks the consumer dead, kicks it from the group, and triggers a rebalance. The typical fix is to lower max.poll.records so each batch fits inside your processing window, or raise max.poll.interval.ms to match reality.

Other common triggers:

  • Garbage collection pauses — a stop-the-world GC that lasts longer than session.timeout.ms looks like a crashed consumer to the broker
  • Network blips — missed heartbeats during transient network issues cause false-positive failures
  • Slow consumer.commitSync() — if offset commits block on a downstream system, the poll interval timer keeps ticking

Static group membership

Introduced in Kafka 2.3, static group membership lets a consumer survive restarts without triggering a rebalance. A consumer configured with a group.instance.id holds its partition assignment for session.timeout.ms while it’s offline, then reconnects and resumes from where it left off:

config.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG, "consumer-1");

With a stable group.instance.id, rolling restarts can avoid triggering a rebalance if the consumer returns before its session timeout.

Spotting problematic rebalances

A healthy group rebalances only when consumers are intentionally added or removed. If you see rebalances at odd hours or during low traffic, look at broker and consumer logs for:

  • Consumer crashes or OOM kills
  • Member [...] has left group without a clean leave request — suggests an unplanned disconnect
  • Rebalancing events with no corresponding consumer join — a consumer timed out
  • Repeated rebalance cycles without stable intervals — the group can never settle, often called a “rebalance storm”

Graph rebalance events alongside consumer heap usage and network latency. That often makes the cause easier to spot than reading through configs.

Offset management

Kafka tracks consumption progress via offsets. Consumers commit offsets to mark what they have processed:

while (true) {
    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
    for (ConsumerRecord<String, String> record : records) {
        process(record);
    }
    consumer.commitSync();
}

If a consumer crashes after processing but before committing, it receives the same messages on restart. This is at-least-once delivery. With idempotent processing, duplicates are harmless.

Processing guarantees and transactions

Kafka transactions commit output records and consumed offsets together, which gives Kafka-to-Kafka processing an exactly-once guarantee. They do not include a write to an external database, webhook, or other service. The Kafka design docs describe this boundary; the Kafka 4.4 Java producer API lists the transactional calls.

With a transactional producer, an application can send records to one or more Kafka partitions and commit the consumed offsets in the same Kafka transaction. A read_committed consumer sees only committed transactional records. On abort, the transaction’s output is not committed, and its input offsets are not advanced.

For example, this Kafka 4.4 Java client pattern coordinates Kafka output with consumed offsets:

producer.initTransactions();
producer.beginTransaction();
producer.send(outputRecord);
producer.sendOffsetsToTransaction(offsetsForRecordsSentToKafka, consumer.groupMetadata());
producer.commitTransaction();

Here, offsetsForRecordsSentToKafka represents the offsets for input records whose Kafka output was added to this transaction. Give each logical producer a unique transactional.id and keep it stable across restarts. Set downstream Kafka consumers to isolation.level=read_committed when they should ignore aborted output. See the versioned producer configuration and Kafka Streams processing guarantee references.

External database and webhook effects

Suppose the database commits, then the consumer crashes before Kafka commits the input offset. Kafka replays the input. Store an event ID under a unique constraint in the same database transaction as the business update so the retry does not repeat the update.

If a webhook accepts a request and the consumer crashes before committing its offset, the replay can send that request again. Use a destination-supported idempotency key where available, and make retries safe. A Kafka transaction cannot roll back a request the remote service has accepted. If using Kafka Connect, exactly-once behavior for a sink depends on the connector’s documented support and configuration; see the Kafka Connect guide.

flowchart LR
    subgraph kafka_tx["Kafka transaction"]
        input[Input record] --> processor[Consumer or processor]
        processor --> output[Kafka output record]
        processor --> offset[Consumed offset commit]
    end
    processor -. "outside this transaction" .-> database[External database]
    processor -. "outside this transaction" .-> webhook[Webhook or API]

Broker replication and fault tolerance

Replication and ISR

Kafka replicates partitions across brokers for fault tolerance. Each partition has a leader and multiple followers. Followers replicate messages from the leader, staying in sync.

graph LR
    subgraph Broker-1
        L1[Partition 0 Leader]
    end
    subgraph Broker-2
        F1[Partition 0 Follower - ISR]
    end
    subgraph Broker-3
        F2[Partition 0 Follower - ISR]
    end
    Producer -->|writes| L1
    L1 -->|replicate| F1
    L1 -->|replicate| F2
    L1 -->|consume| Consumer

In-Sync Replicas (ISR) are replicas that have fully caught up with the leader. With unclean leader election disabled, only ISR members can become leaders after a failure. The replication.factor setting controls how many replicas exist, and min.insync.replicas defines the minimum ISR size for acknowledging writes.

For example, with replication.factor=3, min.insync.replicas=2, and producer acks=all, the broker accepts writes only while at least two replicas are in sync. Each accepted write waits for every replica in the current ISR; if all three replicas are in sync, all three must acknowledge. This is an example configuration, not a universal recommendation. See the Kafka 4.4 broker configuration reference for the interaction between these settings.

Kafka 4.4 configuration defaults

These are documented Kafka 4.4 defaults, not production recommendations. They were checked on 2026-11-02 against the versioned broker, topic, producer, and consumer references.

Setting Kafka 4.4 default Scope and note
default.replication.factor 1 Broker default for topic creation paths that use this setting; set topic replication for availability.
min.insync.replicas 1 Broker default; applies with producer acks=all.
retention.ms 604800000 (7 days) Topic default when using time-based deletion; select retention for replay and storage needs.
compression.type producer Broker/topic default; retains the producer’s chosen codec.
Producer acks all Waits for the current in-sync replicas, not necessarily every configured replica.
Producer enable.idempotence true Enabled unless conflicting producer settings are supplied.
Producer max.in.flight.requests.per.connection 5 Idempotence requires a value no greater than 5.
Producer buffer.memory 33554432 bytes (32 MiB) Buffer size for records waiting to be sent; this is not a hard bound on producer memory.
Producer batch.size 16384 bytes (16 KiB) Default batch size per partition.
Producer linger.ms 5 ms Kafka 4.0 changed the default from zero to 5 ms.
Consumer max.poll.interval.ms 300000 ms (5 min) Maximum delay between poll() calls with consumer group management.
Consumer max.poll.records 500 Maximum records returned by one poll() call.

Dead letter queues

When processing fails and you cannot retry, messages need somewhere to go. Dead letter queues (DLQs) catch messages that consumer processing repeatedly fails on.

This Spring Kafka example uses an illustrative fixed delay of one second for three retries. Choose a retry policy that fits the downstream system and recovery objective.

@Bean
public DeadLetterPublishingPostProcessor deadLetterPublishingPostProcessor(
        ConcurrentKafkaListenerContainerFactory<String, String> factory) {

    DefaultErrorHandler errorHandler = new DefaultErrorHandler(
        new FixedBackOff(1000L, 3)  // 3 retries, 1 second apart
    );

    // Send to DLQ after retries exhausted
    factory.setCommonErrorHandler(errorHandler);

    return new DeadLetterPublishingPostProcessor(
        factory.getKafkaTemplate(),
        (record, exception) -> new TopicPartition(
            record.topic() + ".DLQ",  // convention: topic.DLQ
            record.partition()
        )
    );
}

This sends failed messages to order-events.DLQ after 3 retry attempts. The DLQ preserves the original topic, partition, and key so you can investigate without losing context.

DLQ design considerations

  • Monitoring: Alert when the DLQ is nonempty; a growing backlog often points to a processing or upstream issue
  • Retention: DLQ retention is often shorter than main topic; set a TTL or explicit cleanup job
  • Reprocessing: DLQ messages can be reprocessed by a debugging consumer or manually re-published to the original topic after fixing the issue
  • Causality tracking: Include the original exception stack trace or error code in the message value for debugging

Backpressure handling

Kafka producers send messages faster than consumers can process them. Backpressure management prevents unbounded lag growth.

Consumer-side backpressure

max.poll.records limits how many messages a consumer fetches per poll:

The value of 100 below is an example cap, not a default. Kafka 4.4 defaults max.poll.records to 500 and max.poll.interval.ms to 300000 ms; see the versioned consumer configuration reference.

config.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 100);  // example cap
config.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 300000);  // Kafka 4.4 default, in milliseconds

fetch.min.bytes and fetch.max.wait.ms control how much data the consumer waits for. This example overrides the minimum fetch size; the wait value matches the Kafka 4.4 default:

config.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1024 * 1024);  // example override: 1 MiB
config.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 500);  // Kafka 4.4 default, in milliseconds

Producer-side backpressure

Producer buffer memory (buffer.memory) and batch.size interact to create natural backpressure. If the broker is slow and the send buffer fills, send() blocks or throws an exception:

The following values match Kafka 4.4 Java producer defaults. They are reference points, not tuning recommendations; measure the workload before changing them.

config.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 32 * 1024 * 1024);  // 32 MiB
config.put(ProducerConfig.BATCH_SIZE_CONFIG, 16 * 1024);  // 16 KiB
config.put(ProducerConfig.LINGER_MS_CONFIG, 5);  // 5 ms

Backpressure signals to watch

Signal Meaning Action
Consumer lag growing Producers outpacing consumers Add consumers or optimize processing
Producer send() blocking Producer buffer pressure or broker backpressure Check buffer use, broker load, network, and quotas
Under-replicated partitions > 0 Followers falling behind leader Check disk I/O, network, or broker load
Request timeout exceptions Brokers too slow to respond Increase request.timeout.ms or scale

Delivery guarantees

Kafka provides three delivery guarantee levels. Understanding when each applies matters for system design.

At-most-once delivery

Messages may be lost but are never duplicated. This happens when consumers commit offsets before processing:

consumer.commitAsync();  // commit before processing
process(record);  // if crash here, message is lost

Use at-most-once when:

  • Duplicate messages cost more than missed messages (sensor data aggregation, metrics)
  • You need lowest possible latency and can tolerate gaps

At-least-once delivery (default)

Messages are never lost but may be duplicated. Consumer commits after processing:

process(record);  // do work first
consumer.commitSync();  // then commit offset

If the consumer crashes after processing but before committing, the same messages reprocess on restart. With idempotent operations (writes with unique keys), duplicates are safe.

Use at-least-once when:

  • Missing messages is worse than duplicates (inventory updates, payment processing)
  • Your consumers are idempotent

Kafka-to-Kafka exactly-once processing

A Kafka transaction can atomically commit Kafka output records and the consumed offsets for their input. This guarantee covers records and offsets managed by Kafka. It does not make a database write, payment, or webhook happen exactly once. For those effects, use destination-side transaction coordination or idempotency.

Processing pattern Kafka behavior External effect
At-most-once Commit offsets before processing; a crash can skip unprocessed records May be skipped
At-least-once Process before committing offsets; a crash can replay records Make retries safe
Kafka-to-Kafka exactly-once Commit Kafka output records and consumed offsets in one Kafka transaction Not included

Consumer group coordination

Consumer group behavior depends on partition assignment strategy and coordination needs.

Sticky assignor

The default sticky assignor minimizes partition movement during rebalances. When a consumer leaves, its partitions stay together when reassigned rather than being scattered across remaining consumers.

config.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
    StickyAssignor.class.getName());

Benefit: fewer message reorderings during rebalance since partitions that were together stay together.

Cooperative sticky assignor

For minimal disruption during rebalances, use cooperative sticky assignor. It allows incremental rebalancing without stopping consumption entirely:

config.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,
    CooperativeStickyAssignor.class.getName());

The consumer continues processing while partition ownership shifts incrementally.

Standalone consumers

Sometimes you need a single consumer not part of a group:

consumer.subscribe(List.of("topic"));  // group-based
// vs
consumer.assign(List.of(new TopicPartition("topic", 0)));  // standalone, manual assignment

Standalone consumers manually assign partitions and manage their own offsets. Useful for:

  • One-off administrative tasks (consuming from beginning to rebuild state)
  • Specialized processing pipelines that should not interfere with normal consumers
  • Debugging and testing

Maximum parallelism calculation

For a given topic, maximum consumer parallelism equals partition count:

Topic with 12 partitions
  → Up to 12 consumers in the group (each gets 1 partition)
  → Adding more consumers does nothing (no extra partitions)

If you need 20 consumers for parallel processing:
  → Topic must have at least 20 partitions

Kafka lets you increase a topic’s partition count, but not decrease it. Increasing it can change key-to-partition mapping; see the Kafka 4.4 topic operations guidance before changing a live topic.

Kafka Streams example

Kafka Streams is a client library for building real-time stream processing applications. The word count example is the canonical demonstration. It counts occurrences of words across an infinite stream of text events:

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Materialized;

import java.util.Arrays;
import java.util.Properties;

public class WordCountApplication {
    public static void main(String[] args) {
        Properties config = new Properties();
        config.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-app");
        config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();

        // Source: read from input topic
        KStream<String, String> textLines = builder.stream("text-lines-topic");

        // Process: split into words, group, count
        textLines
            .flatMapValues(textLine -> Arrays.asList(textLine.toLowerCase().split("\\W+")))
            .groupBy((key, word) -> word)
            .count(Materialized.as("word-counts-store"))
            .toStream()
            .to("word-counts-output-topic");

        KafkaStreams streams = new KafkaStreams(builder.build(), config);
        streams.start();
    }
}

How it works:

  1. flatMapValues splits each input line into lowercase words
  2. groupBy groups by word, discarding the message key
  3. count maintains a running count per word in a state store
  4. toStream.to writes results to the output topic

Scaling behavior: each partition processes words independently. The word “kafka” appearing in partitions 0 and 1 produces two separate counts that must be aggregated downstream if you need a global count. For true global word count, either use a single partition or aggregate in a subsequent step.

Fault tolerance: Kafka Streams checkpointing persists state to Kafka topics. If a stream processor crashes, it resumes from the last checkpointed position without data loss.

Topic-specific guidance

Advanced partition sizing

Partition count caps consumer parallelism within a group: one consumer in a group owns a partition at a time. It does not guarantee a specific throughput. Throughput depends on record size, key distribution, producer settings, replication, broker resources, and consumer work.

Start with the concurrency a consumer group needs, then benchmark the expected workload on the intended Kafka version and cluster configuration. Include representative keys and record sizes. Watch per-partition traffic, producer latency, broker disk and network use, consumer lag, and rebalance behavior. A hot key can concentrate traffic on one partition even when the topic has many partitions.

Partition count sizing

Use the concurrency target as a lower bound: a group that needs twenty consumers processing different partitions at once needs at least twenty partitions. Then test the producer and broker workload; there is no universal bytes-per-partition or partitions-per-broker limit that applies across hardware and configurations.

Kafka lets you increase a topic’s partition count, but not decrease it. Increasing the count can change key-to-partition mapping, so existing keys may no longer stay on the same partition after expansion. Review the versioned Kafka topic operations guidance before changing a production topic. If the key mapping or ordering change is unacceptable, plan a new topic and migration instead.

When to use and avoid Kafka

Kafka fits systems that need a durable event log, high write throughput, replay, or independent consumer groups. It works well when several services need the same events at different speeds, or when a consumer may need to rebuild state from retained history.

Choose a simpler queue or direct service call when one worker should take each task, messages can be deleted after processing, and replay is not useful. Kafka also adds operational cost: brokers, partitions, retention, and consumer lag need ongoing attention. For low-volume request/response traffic, that cost can outweigh the value of a shared event log. If the design requires a single total order across all events, Kafka’s per-partition ordering also needs careful consideration.

Kafka use cases

Kafka fits these workloads:

Event streaming

Capture events from many sources and distribute to multiple consumers:

Clickstream -> Kafka -> Analytics
                     -> Personalization
                     -> Fraud Detection
                     -> Audit Log

Message bus replacement

Consider Kafka when consumers need replayable logs or independent reads at different rates. If each task should be delivered to one worker and removed after acknowledgment, a traditional queue may fit better.

Data integration

Connect different systems without point-to-point coupling:

Database CDC -> Kafka -> Search Index
                     -> Cache
                     -> Data Warehouse
                     -> ML Pipeline

Change Data Capture from databases fits this pattern well. Any system can consume the stream without touching the source database.

Kafka vs traditional queues

Aspect Kafka Traditional Queue
Retention Configured by topic Until consumed or expired by policy
Replay Yes No (usually)
Ordering Per partition Per queue
Throughput Built for event streams Depends on the queue and workload
Consumer groups Independent per group Shared or exclusive

Kafka retains records independently of consumer progress, so consumers can replay them while they remain within the retention window. That makes it possible to rerun historical events after changing processing logic.

For broader event-driven patterns, see our post on event-driven architecture. For pub/sub patterns that overlap with Kafka’s topic model, see pub/sub patterns.

Trade-off analysis

Kafka’s main operational trade-offs are durability, partition overhead, and retention cost.

Throughput vs durability

Producer acknowledgments control when a write is reported as successful. Kafka 4.4 defaults producer acks to all; that waits for the current in-sync replicas. With min.insync.replicas, a broker can reject writes when the ISR falls below the configured minimum. The versioned broker configuration reference describes this interaction.

With acks=1, the leader can acknowledge before followers replicate the record, so a leader failure in that gap can lose the acknowledged record. With acks=all, every replica in the current ISR must acknowledge. For example, with replication factor 3 and min.insync.replicas=2, writes fail if fewer than two replicas are in sync; if all three are in the ISR, all three acknowledge an acks=all write.

Kafka transactions add coordination and commit markers for Kafka-managed output and offsets. Their effect on latency and throughput depends on the workload and configuration. Measure it on the target cluster rather than applying a fixed percentage.

Setting Kafka behavior What to measure or decide
acks=1 Leader acknowledgment can precede follower replication Whether the failure window is acceptable for this data
acks=all with min.insync.replicas=2 Requires acknowledgments from the current ISR and rejects writes when ISR size is below two Availability and data-loss tolerance during replica failures
Kafka transaction Coordinates Kafka output records with consumed offsets Latency, throughput, and lag under the target workload

Partition count vs overhead

Partition replicas use log segments and indexes, and they add metadata, replication work, and consumer assignment state. The resource cost depends on traffic, retention, segment settings, replication, and hardware; Kafka does not define a universal partition ceiling for a broker.

Test with the expected topic count, partition distribution, replication, and traffic. During the test, watch file descriptor use, broker heap and garbage collection, disk and network utilization, under-replicated partitions, and controller or leader-election metrics. Set operational limits from the tested cluster and its recovery goals rather than from a generic partition-count table.

Retention vs storage cost

Choose retention to meet replay, recovery, and policy requirements. Kafka 4.4 documents a default retention.ms of 604800000 milliseconds (7 days), but that default is not a recommendation for every topic. Check the versioned topic configuration reference when setting retention.

Assuming a roughly steady write rate and time-based retention, multiply the average bytes written to the log per second after compression by the retention duration to estimate per-replica log bytes. Multiply by the replication factor for cluster-wide copies, then add measured index, segment, and headroom needs. Treat this as an estimate: compaction, segment boundaries, size-based retention, and local versus remote retention change disk use. Validate against observed growth on representative data.

Longer retention increases the amount of data available for replay and can increase storage and recovery work. For Kafka 4.4 tiered storage, a remote storage implementation must be configured; it is not a universal storage multiplier. See the versioned tiered storage documentation before using it.

For compacted topics, Kafka retains the latest value per key as old segments are compacted. Consider compaction when consumers need current state by key rather than every historical value; it does not replace a time-based replay policy in every design.

Consumer scaling constraints

Consumer lag grows when producers write faster than consumers can process. Before adding resources, diagnose which constraint is actually binding. Applying the wrong fix wastes effort and can make things worse.

The first check is partition count versus consumer count. For example, a topic with twelve partitions and four consumers has eight unassigned partitions in that group. If lag is growing, adding consumers may help until each partition is assigned. This does not help if the bottleneck is downstream processing.

If every partition is assigned and lag is still growing, adding consumers to that group will not add partition-level parallelism. Optimize processing or evaluate increasing the partition count. Increasing it can change key-to-partition mapping; review the topic operations guidance before changing a live topic.

Sometimes lag grows despite having spare partitions and efficient consumers. This points to a processing bottleneck in the consumer itself — a slow database write, a rate-limited downstream API, or a consumer that is doing too much work per message. Profile the consumer code directly: instrument processing time per message batch, check database connection pool utilization, and look for anything that blocks or serializes where parallelism could help.

Frequent rebalances cause a distinct pattern. Throughput drops in cycles rather than growing gradually. Each rebalance pauses consumption while partitions are revoked and reassigned. If your consumers restart often (rolling deploys, OOM kills, GC pauses triggering broker timeouts), the group never settles and achieves steady-state throughput. Switching to the cooperative sticky assignor reduces the scope of each rebalance to only the partitions being transferred, rather than stopping the world.

Scenario Limiting Factor Solution
Lag growing, spare partitions Consumer count < partitions Add consumers up to partition count
Lag growing, no spare partitions Partition count limits parallelism Optimize processing or evaluate a partition increase
Lag growing, many consumers but still behind Processing bottleneck Optimize logic, scale horizontally with more partitions
Rebalances causing throughput drops Frequent consumer restarts Use sticky/cooperative sticky assignor

Exactly-once vs at-least-once decision matrix

Factor At-least-once Kafka-to-Kafka exactly-once
Processing behavior Input may be replayed after a failure Kafka output and consumed offsets commit together
External database or webhook Use idempotent handling for retries Still needs destination-side coordination or idempotency
Operational complexity Simpler when duplicate handling is safe Requires Kafka transactions and read_committed consumers

Production failure scenarios

Understanding how Kafka fails in production helps you design more resilient systems.

Scenario 1: broker network partition

When a broker loses network connectivity but doesn’t crash:

Broker-2 becomes unreachable
  → Partition 0 leader (on Broker-2) stops responding
  → Followers on Broker-1 and Broker-3 detect leader timeout
  → Kafka controller triggers leader election
  → ISR shrinks to exclude unreachable broker
  → min.insync.replicas check: if remaining < min.insync.replicas, writes fail
  → Producer receives NotEnoughReplicasException

Impact: Temporary unavailability of the partition. If unclean.leader.election=true and no ISR available, potential message loss.

Scenario 2: zombie consumer problem

Consumer crashes but doesn’t leave group gracefully:

Consumer-1 processes messages and writes to database
Consumer-1 crashes AFTER database write but BEFORE offset commit
  → Consumer-1's partition sits unassigned
  → No consumer processes those messages (lag grows)
  → After session.timeout expires, Kafka triggers rebalance
  → New consumer picks up partition, replays same messages
  → Without idempotent processing: duplicate writes occur

The fix: use an idempotent database operation, such as recording a unique event ID with the business update in one database transaction. Kafka transactions can coordinate Kafka output and offsets, but they do not make the database write atomic with the offset commit.

Scenario 3: Schema Registry mismatch

Producer and consumer evolve schemas independently:

Producer v1: { "userId": "string", "action": "string" }
Producer v2: { "userId": "string", "action": "string", "metadata": { "source": "string" } }
Consumer still expects v1 schema
  → Deserialization fails
  → Message goes to DLQ (if configured) or consumer crashes
  → Backlog of unprocessed messages accumulates

The fix: use Schema Registry with compatibility checking. Never evolve schemas in incompatible ways.

Scenario 4: clock skew in clustered deployment

Kafka’s auto.offset.reset=by_duration uses the client clock to choose a timestamp and compares it with broker-side record timestamps. If clocks are out of sync, a consumer can start too far forward and skip records, or too far back and replay more history. The Kafka 4.4 operations guide calls for accurate clock synchronization when using this reset mode. Keep client and broker clocks synchronized and monitor drift.

Scenario 5: partition reassignment during peak load

Operations team rebalances partitions while producers are at full throughput:

Original: Broker-1 has partitions 0,1,2; Broker-2 has 3,4,5
Reassignment triggered:
  → New replicas start copying from leaders (network spike)
  → ISR temporarily expands (old + new replicas receiving)
  → Controller overwhelmed by metadata updates
  → Request latency can rise while replicas copy data and controller metadata changes
  → Producer buffers fill, send() blocks
  → Consumer lag grows as brokers struggle to keep up

The impact depends on traffic, disk, network, and reassignment throttles. Plan and monitor reassignments against the cluster’s normal workload; use a tool such as Cruise Control only with settings that fit the deployment.

Failure Impact Mitigation
Broker goes down Partition leader election; temporary unavailability Choose replication and ISR settings for the failure tolerance you need; monitor ISR
Controller failure Controller quorum re-election or unavailable operations Run a healthy KRaft controller quorum and test failover behavior
Network partition Followers fall out of ISR; potential data loss Monitor ISR size; alert when replicas fall behind
Producer retry storm Duplicate messages after transient failures Enable idempotent producer; design idempotent consumers
Consumer rebalance storm Throughput drops during rebalancing Use sticky partition assignment; avoid frequent consumer restarts
Offset commit failure Messages reprocessed or skipped Use Kafka transactions for Kafka output plus offsets; make external effects idempotent
Partition imbalance Some brokers overloaded while others idle Monitor partition distribution; use Cruise Control for rebalancing
Data loss on leader change Under-replicated partitions may lose acknowledged data Set producer acknowledgments and the minimum ISR for the failure tolerance you need

Common pitfalls and anti-patterns

Pitfall 1: too many partitions

Each partition replica adds log, index, metadata, and replication work. The impact depends on the data directories, traffic, retention, cluster resources, and failure-recovery goals, so use representative load tests and monitor broker file descriptors, heap, disk and network use, and controller behavior.

Changing the partition count

Partition counts can be increased, but Kafka does not support decreasing them. An increase can change the partition selected for a key and affect ordering for that key. Plan expansion with the documented topic-operation considerations or migrate to a new topic when the mapping must remain stable.

Pitfall 2: ignoring consumer lag

Consumer lag is the gap between the latest offset in a partition and the offset your consumer has committed. A small amount of lag is normal during traffic spikes, but lag that grows over time signals a real mismatch between how fast producers write and how fast consumers can process.

Lag hides in plain sight because Kafka keeps working while it grows. Producers keep writing, consumers keep reading older messages, and nobody notices until the backlog reaches a point where consumers can never fully catch up without downtime.

To stay ahead of it:

  • Check lag via kafka-consumer-groups — run kafka-consumer-groups --bootstrap-server localhost:9092 --group my-group --describe to see per-partition lag
  • Alert on persistent growth — sustained lag growth matters more than a single high spike
  • Add consumers first — if your topic has spare partitions, adding consumers is the quickest fix
  • Optimize processing if consumers are maxed out — profile consumer code, batch database writes, or move slow operations to async handlers
  • Evaluate partition changes carefully — increasing partitions can change key mapping; Kafka does not support decreasing the count

Before scaling, check whether lag is evenly distributed. A much larger backlog on one partition can point to a hot key concentrating writes there. That may call for a data-model change rather than more consumer capacity.

Pitfall 3: not using compression

Text-based formats like JSON have a lot of redundancy. Without compression, Kafka producers send raw payloads across the network, consuming more bandwidth and filling broker disks faster than needed.

Compression codecs trade off CPU use, latency, and compressed size. Their results depend on the data, batch size, codec settings, and hardware. Benchmark with representative records and measure CPU use and storage or network reduction before choosing a codec.

Enable compression at the producer level with one config line:

config.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4");

Brokers and consumers decompress transparently, so the read side needs no codec-specific changes. Compression trades producer CPU for reduced network and disk use; benchmark representative records before deciding whether that trade works for the workload.

Pitfall 4: auto.offset.reset = earliest without understanding consequences

auto.offset.reset controls what happens when a consumer group has no committed offset — either because the group is brand new or its offset expired from the __consumer_offsets topic. The three options are:

  • earliest — start from the beginning of the log
  • latest — start from the newest message (skip all existing data)
  • none — fail immediately if no offset is found

Starting at earliest can create a large replay workload when a group has no committed offset and the topic has retained history. How long catch-up takes depends on the retained volume, consumer capacity, and downstream rate limits. Before a backfill or group reset, estimate the replay work and plan how to protect downstream systems.

The safer pattern:

  • Choose latest when a new group should read only new records; choose earliest when it must process retained history
  • Use earliest explicitly when you need to backfill or rebuild state, and scope the operation to a separate consumer group with its own offset tracking
  • Set none during development to catch offset issues early — the consumer fails fast instead of silently reprocessing old data

Pitfall 5: sending sensitive data unencrypted

Kafka sends data in plaintext by default — no encryption in transit, no encryption at rest. If your messages contain PII, credentials, financial data, or anything with compliance requirements, the default configuration is a liability.

Production Kafka security has several layers:

  • Encryption in transit — enable SSL/TLS on brokers and configure clients with ssl.truststore.location and ssl.keystore.location. This prevents eavesdropping on the wire between producers, brokers, and consumers
  • Authentication — SASL/SCRAM or mTLS verifies that clients are who they claim to be before they can connect
  • Authorization — ACLs on topics restrict which clients can read or write. Without ACLs, any authenticated client can access any topic
  • Encryption at rest — broker-side disk encryption or Kafka’s Secret API protects data stored in log segments

A minimal TLS setup on the producer:

config.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL");
config.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, "/path/to/truststore.jks");
config.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, "/path/to/keystore.jks");
config.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, "password");

If compliance or data governance policies prevent sensitive data from touching Kafka at all, consider a sidecar or pre-processing service that scrubs sensitive fields before publishing.

Quick recap checklist

  • Choose a partition count that fits expected throughput and consumer parallelism; partitions are costly to change later.
  • Use message keys when events for the same entity must stay ordered.
  • Set replication, min.insync.replicas, and producer acknowledgments to match the cost of losing an event.
  • Prefer at-least-once delivery with idempotent consumers; use Kafka transactions to coordinate Kafka output records and consumed offsets.
  • Watch consumer lag, under-replicated partitions, and rebalance frequency before adding capacity.
  • Set retention to cover replay and recovery needs, then account for the storage cost.
  • Configure retries and a dead letter topic for records that keep failing, and monitor the DLQ.

Observability checklist

Metrics to monitor

  • Consumer lag: difference between latest offset and consumer position (critical for SLAs)
  • Under-replicated partitions: partitions without full replication
  • ISR size: In-Sync Replicas count per partition
  • Message throughput: messages and bytes per second per topic
  • Request latency: P99 producer and consumer request latencies
  • Disk usage: broker disk utilization and growth rate
  • Consumer group status: active members and partition assignments
  • Controller status: leader elections and controller changes

Logs to capture

  • Broker startup and shutdown events
  • Partition leader election events
  • Consumer group rebalancing events
  • Producer acknowledgment failures and retries
  • Controller changes and election events
  • Under-replicated partition events
  • Disk space warnings

Alerts to configure

  • Consumer lag or lag age exceeds the service’s recovery and freshness objective
  • Under-replicated partitions greater than 0
  • Broker disk headroom falls below the reserve set for the workload
  • Producer error rate exceeds the service’s error budget
  • Consumer group has no active members
  • Controller is unavailable
  • Messages per second exceeds capacity threshold
  • Request latency P99 exceeds threshold

KRaft metadata storage in Kafka 4.4

Kafka 4.4 uses KRaft; ZooKeeper mode was removed in Kafka 4.0. The KRaft controller quorum stores cluster metadata in a metadata log and snapshots. Consumer group offsets are stored in Kafka’s __consumer_offsets topic, not in a generic ZooKeeper/KRaft storage pool.

Kafka 4.4’s metadata.max.retention.bytes default is 104857600 bytes (100 MiB). It is a soft limit on the combined metadata log and snapshots, not an estimate of total cluster metadata storage. See the versioned broker configuration and upgrade guide for the metadata settings and ZooKeeper migration path.

Deployment readiness

Pre-deployment checklist

Kafka’s 4.4 operations guide discusses replication factors of 2 or 3 for availability. Choose topic replication and min.insync.replicas for the failure tolerance you need; see the operations guidance.

- [ ] Replication factor and `min.insync.replicas` chosen for each critical topic's failure tolerance
- [ ] Consumer lag monitoring configured and alerts set
- [ ] Producer retries and idempotency configured
- [ ] Compression enabled on producers
- [ ] Schema Registry deployed for schema validation
- [ ] ACLs configured for topic access control
- [ ] TLS/SSL encryption enabled for all connections
- [ ] Partition count planned based on throughput requirements
- [ ] Retention policy configured (hours, days, weeks)
- [ ] Dead letter topic configured for failed messages
- [ ] Consumer group offset reset policy defined
- [ ] Backup and disaster recovery plan documented

Security and compliance notes

  • SASL/SCRAM or mTLS configured for authentication
  • ACLs configured for topic access control
  • TLS/SSL encryption enabled for all connections
  • Sensitive data encryption configured

Security checklist

  • Authentication: use SASL/PLAIN or SCRAM for client authentication; mTLS for certificate-based auth
  • Authorization: implement ACLs to restrict topic access; principle of least privilege
  • Encryption in transit: enable SSL/TLS for all broker and client connections
  • Encryption at rest: use disk encryption or Kafka’s Secret API for sensitive data
  • Schema validation: validate message schemas with Confluent Schema Registry
  • Data sanitization: sanitize message keys and values to prevent injection
  • Audit logging: enable Kafka’s audit logging for admin operations
  • Network segmentation: place brokers in private networks; restrict inter-broker communication

For regulated data, document which topics contain sensitive fields, who can read them, and how long they remain available. Match topic retention and deletion procedures to your data retention policy, including replicas and backups. Keep audit records for privileged access and ACL changes so reviews can show who accessed or changed a topic and when.

Interview questions

1. What is the fundamental difference between Kafka and a traditional message queue?

Expected answer points:

  • Kafka is a distributed streaming platform built around the concept of a durable log, not a queue
  • Messages in Kafka topics are retained for a configurable period (hours, days, indefinitely) rather than being deleted upon consumption
  • This retention enables replay capability: consumers can re-read historical data from any point in the log
  • Traditional queues typically delete messages after consumption and do not support replay
  • Kafka's topic model supports multiple independent consumer groups, each reading the same data independently
2. How does Kafka guarantee ordering within a partition?

Expected answer points:

  • Within a partition, messages have monotonically increasing offsets that define total order
  • Producers can specify a message key; Kafka hashes the key to determine partition assignment
  • With a stable partition count and partitioner, messages with the same key go to the same partition and retain per-key order
  • Consumers read messages in offset order from their assigned partitions
  • Cross-partition ordering is not guaranteed; only per-partition ordering is maintained
3. Explain the difference between at-least-once, at-most-once, and exactly-once delivery semantics in Kafka.

Expected answer points:

  • At-most-once: consumer commits offsets before processing; messages may be lost but never duplicated (lowest latency)
  • At-least-once (default): consumer processes messages then commits offsets; messages may be duplicated but never lost
  • Kafka-to-Kafka exactly-once: a transaction atomically commits Kafka output records and consumed offsets; external database or webhook effects need destination-side coordination or idempotency
  • The choice depends on use case: at-least-once with idempotent consumers handles most scenarios well
  • Use Kafka transactions when Kafka output and consumed offsets must commit together; handle external effects separately
4. What is a Consumer Group and how does it affect message consumption?

Expected answer points:

  • A consumer group is a set of consumers cooperating to consume messages from a topic
  • Each partition is delivered to exactly one consumer within a group (ensuring parallelism)
  • Different consumer groups each receive all messages independently
  • When a consumer joins or leaves, Kafka rebalances partition assignments across the group
  • Rebalancing temporarily pauses consumption; frequent rebalances hurt throughput
5. What is ISR (In-Sync Replicas) and why does it matter for durability?

Expected answer points:

  • ISR are replicas that have fully caught up with the partition leader
  • With unclean leader election disabled, only ISR members can become leader after a failure
  • The min.insync.replicas setting determines the minimum ISR size for acknowledging writes
  • With producer acks=all, all replicas in the current ISR must acknowledge; min.insync.replicas sets the minimum ISR size for accepting writes
  • If all in-sync replicas fall behind or fail, the partition becomes unavailable for writes
6. How do you handle messages that fail processing repeatedly in Kafka?

Expected answer points:

  • Dead Letter Queues (DLQs) catch messages that exhaust retries
  • Configure a DefaultErrorHandler with FixedBackOff for retry behavior (e.g., 3 retries, 1 second apart)
  • DLQ preserves original topic, partition, and key for debugging
  • Monitor DLQ depth — messages piling up indicate upstream issues
  • DLQ messages can be reprocessed after fixing the underlying issue
7. What are the key configuration parameters for ensuring durability in Kafka?

Expected answer points:

  • Choose replication factor and min.insync.replicas for the failure tolerance and availability the topic needs; Kafka's operations guide discusses replication factors of 2 or 3
  • Use acks=all when a write should wait for every replica in the current ISR; the broker rejects writes if the ISR falls below min.insync.replicas
  • retention.ms configured based on replay requirements (hours, days, or indefinite)
  • Enable producer idempotency to prevent duplicates during retries
8. How does the partition count affect Kafka performance and scalability?

Expected answer points:

  • Partition count determines maximum consumer parallelism (one consumer per partition per group)
  • There is no universal throughput per partition or partition limit per broker; benchmark the target workload and cluster
  • More partitions add file, metadata, replication, and assignment work; monitor broker resources and recovery behavior
  • Partitions can be added but not removed, and increasing the count can change key-to-partition mapping
9. What is the difference between ZooKeeper and KRaft modes in Kafka?

Expected answer points:

  • ZooKeeper: traditional metadata management (partition leadership, ISR, consumer offsets, ACLs)
  • KRaft: Kafka's built-in metadata quorum; Kafka 4.4 runs in KRaft mode
  • Kafka 4.0 and later do not support ZooKeeper; existing ZooKeeper clusters must migrate before upgrading
  • KRaft removes the ZooKeeper dependency; plan controller quorum and failure handling for the cluster
  • Use the versioned upgrade guide to plan a ZooKeeper-to-KRaft migration for an older cluster
10. How would you design a Kafka-based system to handle backpressure?

Expected answer points:

  • Consumer-side: limit max.poll.records and configure fetch.min.bytes/fetch.max.wait.ms
  • Producer-side: buffer.memory and batch.size create natural backpressure when broker is slow
  • Monitor consumer lag — growing lag signals producers outpacing consumers
  • Watch for under-replicated partitions, producer send() blocking, and request timeout exceptions
  • Scale consumers horizontally (if partitions allow) or optimize processing logic
  • Scale brokers if broker throughput is the bottleneck
11. What is log compaction in Kafka and when would you use it?

Expected answer points:

  • Log compaction retains the latest message for each key within a partition, discarding older messages with the same key
  • Unlike time-based retention, compaction removes older values for a key as segments are cleaned; it does not preserve every historical update
  • Use cases: maintaining a lookup table or changelog where only the latest state matters (e.g., customer profile updates)
  • Enables Kafka as a key-value store or database for event sourcing where you need the current state, not full history
  • Compaction runs in the background and does not block normal writes
12. How does Kafka handle schema evolution with Schema Registry?

Expected answer points:

  • Schema Registry stores and validates message schemas (Avro or JSON Schema) separately from Kafka
  • Producers and consumers register and retrieve schemas by subject name, enabling schema validation at publish time
  • Schema compatibility modes control evolution: BACKWARD, FORWARD, FULL, NONE
  • BACKWARD compatibility allows consumers reading new data to work with old schemas (most common)
  • Without Schema Registry, incompatible schema changes cause deserialization errors or silent data corruption
  • Schema Registry also compresses message payloads by storing schema IDs instead of full schemas in each message
13. What is Kafka Connect and what are the key components?

Expected answer points:

  • Kafka Connect is a framework for scalably and reliably streaming data between Kafka and external systems
  • Connectors are plugins that define how to interact with source systems (databases, S3, JDBC) or sink systems
  • Workers are the processes that execute connectors; they can run in standalone or distributed mode
  • Converters handle serialization/deserialization of record keys and values (Avro, JSON, Parquet)
  • Transforms are optional lightweight modifications to records (e.g., filtering, adding fields)
  • Offset storage: Connect manages offset tracking internally, typically in a Kafka topic
14. Explain the role of the Transaction Coordinator in Kafka exactly-once semantics.

Expected answer points:

  • The transaction coordinator tracks Kafka producer transactions and records their outcome in Kafka
  • The producer sends Kafka records and consumed offsets as part of a transaction, then commits or aborts it
  • Consumers configured with isolation.level=read_committed do not expose aborted transactional records
  • A transactional.id lets Kafka identify and fence a producer instance across restarts
  • The guarantee covers Kafka records and offsets in the transaction; a database or webhook still needs its own idempotency or coordination
15. How does the consumer partition assignment strategy affect performance?

Expected answer points:

  • Range assignor: assigns partitions contiguously per topic; can cause imbalance if topic partition counts differ
  • RoundRobin assignor: distributes partitions evenly across consumers regardless of topic; better balance
  • Sticky assignor: minimizes partition movement during rebalances, reducing reprocessing overhead
  • Cooperative sticky assignor: allows incremental rebalancing without full stop-the-world pauses
  • Choice affects rebalance duration, message ordering during rebalance, and consumer CPU utilization
  • For stateful consumers, sticky assignment prevents costly state migration
16. What are the trade-offs between increasing partitions versus adding consumers?

Expected answer points:

  • Adding consumers only helps if there are spare partitions; max parallelism equals partition count
  • Increasing partitions may add consumer parallelism, but can change key routing; Kafka does not support decreasing the count
  • The effect of partition count on throughput, latency, and recovery depends on the workload and cluster; benchmark and monitor it
  • If the existing key mapping must remain unchanged, consider moving to a new topic instead of increasing partitions in place
17. How do you monitor Kafka consumer lag and what are acceptable thresholds?

Expected answer points:

  • Consumer lag is the difference between the latest offset and the consumer's committed offset
  • Kafka exposes lag per partition via KafkaConsumer.metrics() or tools like kafka-consumer-groups
  • JMX metrics: ConsumerLag and FetchManager metrics in the kafka.consumer group
  • Monitoring tools: Confluent Control Center, Kafka Manager, Prometheus with JMX exporter, Datadog
  • Set alert thresholds against the freshness or recovery objective; offset lag is a record count, so do not treat it as elapsed time without measuring record age
  • Growing lag signals producers outpacing consumers; investigate processing bottlenecks or scale consumers
18. What is the purpose of Kafka's retention policy and how do you choose the right setting?

Expected answer points:

  • Retention policy determines how long messages are kept before being eligible for deletion
  • Configured via retention.ms (time-based) or retention.bytes (size-based) per topic
  • Choose based on use case: event sourcing needs long retention for replay, real-time analytics may need shorter
  • Consider downstream consumers needing to reprocess historical data if processing logic changes
  • Longer retention increases storage costs; balance between replay window and cost
  • For compliance or audit requirements, retention may need to be days or weeks
19. How does Kafka achieve fault tolerance at the broker level?

Expected answer points:

  • Partition replication: each partition has a leader and ISR followers on different brokers
  • If a broker fails, Kafka automatically elects a new leader from ISR members
  • min.insync.replicas ensures writes persist to multiple replicas before acknowledgment
  • Controller broker manages partition leadership and cluster coordination (backed by ZooKeeper or KRaft)
  • unclean.leader.election setting controls behavior when no ISR is available: can lose messages if set to true
  • racks configuration allows placing replicas in different physical locations for rack-aware failure handling
20. What are the key differences between Kafka and other streaming platforms like Apache Pulsar or RabbitMQ?

Expected answer points:

  • Kafka uses partition-centric model with consumer groups; Pulsar uses subscription types (exclusive, failover, shared, key-shared)
  • Pulsar separates storage into tiered storage (BookKeeper for real-time, Apache Tiered Storage for historical)
  • RabbitMQ is a traditional broker with exchanges and queues, not a log-based system; no native replay
  • Pulsar supports geo-replication out-of-the-box; Kafka requires MirrorMaker
  • Kafka has a larger ecosystem and community; Pulsar offers better multi-tenancy and geo-replication
  • Compare queue delivery and acknowledgment needs with Kafka's replayable log and consumer-group model; benchmark the workload before making throughput claims
## Further reading

Conclusion

Kafka stores events in partitioned logs, so multiple consumer groups can read the same stream and replay retained data. Partition count sets the ceiling for consumer parallelism, while replication and acknowledgments determine how writes behave during broker failures. For most applications, at-least-once delivery with idempotent processing keeps the design simpler. Kafka transactions coordinate Kafka output records and consumed offsets; external side effects need destination-side coordination or idempotency.

Category

Related Posts

Exactly-Once Delivery: The Elusive Guarantee

Explore exactly-once semantics in distributed messaging - why it's hard, how Kafka and SQS approach it, and practical patterns for deduplication.

#distributed-systems #messaging #kafka

Ordering Guarantees in Distributed Messaging

Understand how message brokers provide ordering guarantees, from FIFO queues to causal ordering across partitions, and the trade-offs in distributed systems.

#distributed-systems #messaging #kafka

Event Envelopes and Metadata for Reliable EDA

Learn how event envelopes separate transport context from payload, apply CloudEvents attributes, propagate correlation IDs, and validate messages safely.

#event-driven-architecture #cloudevents #messaging