Apache Kafka Distributed Event Streaming Master Interview Bank
Distributed commit log architecture, Topics, Partitions, Consumer Groups, rebalancing protocols, KRaft consensus, exact-once semantics (EOS), and Kafka Streams.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Basic & Foundational Concepts (Junior / Entry-Level)
12 QuestionsWhat is Apache Kafka and how does it fundamentally differ from traditional message brokers (like RabbitMQ)?
Traditional Message Brokers (RabbitMQ, ActiveMQ) • Built on the Smart Broker / Dumb Consumer model • The broker tracks which consumer has read which message, deletes messages immediately upon consumer acknowledgment, and routes via queues • Designed for discrete, transactional task processing.
What are Topics, Partitions, and Offsets in Kafka?
Topic: A logical category or stream name to which records are published (e.g., orders, user-signups) • Partition: A topic is divided into one or more partitions • Offset: A unique, sequential integer assigned to each record within a partition (e.g., 0, 1, 2...).
How does Kafka achieve massive write and read throughput?
Kafka achieves millions of messages per second per node through three core architectural choices: Sequential Disk I/O: Kafka writes data strictly by appending to the end of segment files • Heavy Utilization of OS Page Cache: Kafka delegates memory caching entirely to the Linux OS Page Cache instead of caching objects in JVM heap memory.
What is a Producer, and how does message partitioning work (Keys vs. Round-Robin)?
A Producer publishes records to Kafka topics. How Kafka decides which partition receives a message: Message has a Key (e.g., userId: "usr1001") • Kafka hashes the key: MurmurHash2(key) % totalpartitions.
What is a Consumer and a Consumer Group? How does group rebalancing work?
Consumer: A client application that subscribes to topics and processes records • Consumer Group: A collection of consumers cooperating to read from a topic • Each partition in a topic is assigned to exactly one consumer within a group • If a topic has 4 partitions and a consumer group has 2 consumers, each consumer processes 2 partitions.
What are the three Message Delivery Semantics?
At-Most-Once: Messages may be lost, but are never duplicated • Consumer commits offset before processing message: Fetch -> Commit Offset -> Process • At-Least-Once (Default & Most Common): Messages are never lost, but may be duplicated • Consumer commits offset after successfully processing message: Fetch -> Process -> Commit Offset.
How does Kafka manage data retention (Time-based vs. Size-based)?
Kafka does not retain data indefinitely by default; it cleans up old log segments based on topic configuration: Time-Based Retention (log.retention.hours / log.retention.ms): Deletes log segments older than a specific duration (default is 7 days / 168 hours).
What is the difference between Log Retention (Delete) and Log Compaction?
Log Retention (cleanup.policy=delete): Purges records based strictly on age or total partition size • Log Compaction (cleanup.policy=compact): Retains at least the most recent value for every key within a partition log • Older records with the same key are deleted during background cleaning.
What are Replicas, Leaders, and Followers in Kafka partition replication?
To survive server crashes, Kafka replicates each partition across multiple brokers (determined by replication.factor, typically 3 in production).: Partition Leader: One broker node is elected leader for a specific partition • Partition Followers: The other replica brokers act as followers.
What is the In-Sync Replicas (ISR) list and how does `min.insync.replicas` prevent data loss?
ISR (In-Sync Replicas): The subset of partition replicas that are actively caught up with the leader's commit log (within • min.insync.replicas: A topic-level setting that defines the minimum number of replicas that must acknowledge a write when producer acks=all • The Production Golden Standard for Zero Data Loss.
What is Producer `acks` (`acks=0`, `acks=1`, `acks=all`)?
Controls the level of durability acknowledgment the producer demands from the broker before considering a write successful: acks=0 (Fire-and-Forget): Producer never waits for any broker response • acks=1 (Leader Ack - Legacy Default): Producer waits until the partition leader has written the record to its local log.
What are the essential Kafka CLI tools for cluster operations?
```bash # 1. Create a Topic with 6 partitions and 3 replicas kafka-topics.sh --bootstrap-server localhost:9092 --create \ --topic customer-orders --partitions 6 --replication-factor 3 # 2.
Part 2: Core Architecture & Implementation (Mid-Level)
12 QuestionsHow does Kafka's Zero-Copy optimization work using the Linux `sendfile()` system call?
In traditional network file transfer.
What is KRaft Mode (Kafka Raft Metadata Mode), and why was ZooKeeper eliminated?
Historically, Kafka relied on Apache ZooKeeper to manage cluster metadata, leader elections, and topic configurations.: ZooKeeper Limitations: Dual-system operational overhead, metadata duplication in memory, slow cluster startup, and a practical limit of ~200,000 • KRaft Mode (KIP-500 - Production standard since Kafka 3.3+).
What is the Consumer Rebalance Protocol (Eager vs. Incremental Cooperative Rebalancing)?
Eager Rebalancing (Legacy) • When any consumer joins or leaves, all consumers in the group stop processing, revoke all their partition assignments, and rejoin the group • Causes "stop-the-world" latency spikes across entire consumer fleets for seconds or minutes • Cooperative Sticky Rebalance (Modern Default).
How does Consumer Offset Management work, and what are the trade-offs of Auto-Commit vs. Manual Commit?
Kafka consumers store their current progress as offsets in an internal compacted topic named consumeroffsets.: Auto-Commit (enable.auto.commit=true) • Commits offsets periodically (default every 5s via auto.commit.interval.ms).
What is the Confluent Schema Registry, and how does it enforce schema evolution?
In microservices, producers and consumers communicate via binary formats like Apache Avro or Protobuf. If a producer removes a required field or renames an attribute without warning, downstream consumer applications crash with deserialization errors.: Schema Registry is a standalone HTTP server that stores and versions schemas.
What is Kafka Connect, and how does Change Data Capture (CDC) with Debezium work?
Kafka Connect is a distributed, fault-tolerant framework for streaming data between Kafka and external datastores without writing custom boilerplate code.: Debezium CDC Source Connector • Hooks directly into database transaction logs (PostgreSQL WAL, MySQL binlog, SQL Server CDC).
Kafka Streams vs. Apache Flink: Stream Processing Paradigms.
Kafka Streams • A lightweight Java/JVM client library embedded directly into your standard microservice application • Requires zero external cluster infrastructure (no separate cluster to manage; runs inside your Docker/Kubernetes container) • Features local state stores powered by RocksDB backed by Kafka changelog topics.
How do you handle Poison Pill Messages in Kafka using Dead Letter Topics (DLT)?
A Poison Pill is a corrupted, unparseable, or schema-violating message that causes the consumer deserializer to throw an unhandled exception. If the consumer crashes and restarts, it fetches the exact same offset again and crashes in an infinite loop!: Wrap message deserialization and processing in a strict try-catch block.
What are Idempotent Producers (`enable.idempotence=true`) and how do they eliminate duplicates?
When a producer sends a batch of records, the broker may successfully write them to disk, but the network ACK packet drops before reaching the producer. The producer assumes a failure and retries, creating duplicate records in the partition log.: The broker assigns each producer a unique 64-bit Producer ID (PID) via InitProducerId.
How do Kafka Transactions work to achieve Exactly-Once Semantics (EOS)?
In a Consume-Transform-Produce loop (read from Topic A, compute result, write to Topic B, commit offset to consumeroffsets): If the app crashes after writing to Topic B but before committing the offset, the record is processed twice.: Wraps the outgoing message and the consumer offset commit into an atomic transaction.
What is Kafka MirrorMaker 2 (MM2), and how does it support Active-Passive vs. Active-Active Disaster Recovery?
MirrorMaker 2 (MM2) is a Kafka Connect-based replication engine that synchronizes topics, topic configurations, and consumer group offsets between separate Kafka clusters across cloud regions.: Active-Passive DR • Region A (Primary) handles 100% of production traffic.
How do you optimize Kafka batching parameters (`batch.size`, `linger.ms`, `compression.type`)?
By default, producers send records almost immediately, resulting in thousands of tiny network packets. Tuning batching improves throughput by up to 10x with negligible latency addition: linger.ms=20: Tells the producer to wait up to 20 milliseconds before sending, allowing incoming records to accumulate into a single batch.
Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)
26 QuestionsKafka Storage Internals: How Segment Files (`.log`), Index Files (`.index`), and Time Indexes (`.timeindex`) work.
Each partition directory on a broker disk contains segment files.
Deep Dive into KRaft Consensus: Leader Elections and Metadata Quorum.
In KRaft, metadata is managed by a small quorum of controller nodes (typically 3 or 5 controllers) running a specialized Raft consensus state machine: Unlike ZooKeeper, which required periodic snapshot syncs and full metadata tree watches, KRaft controllers write metadata records directly to an.
Handling Consumer Lag: Detection, Diagnosing Root Causes, and Autoscaling Consumer Pods.
Consumer Lag = Log End Offset (LEO) - Current Consumer Committed Offset. It measures how many records are sitting in the broker unread.: Uneven Lag across Partitions: Caused by a hot partition key (e.g. 80% of traffic using the same customer ID).
Mitigating Hot Partitions and Data Skew.
If 1 partition receives 100,000 messages/sec while 9 other partitions receive 1,000 messages/sec, the broker hosting that partition experiences disk and CPU saturation, and the assigned consumer falls behind.: Key Salting (Compound Keys) • Custom Partitioner.
Tuning JVM Garbage Collection (G1GC) and Linux Kernel Parameters for Kafka Brokers.
Brokers require optimized OS kernel memory and disk flushing parameters: vm.dirtybackgroundratio = 5: Begins background flushing of dirty page cache pages to disk when dirty memory reaches 5% of RAM • vm.dirty_ratio = 10: Blocks incoming writes if dirty memory reaches 10% until disk flushes catch up.
Disaster Recovery and Split-Brain Prevention: `unclean.leader.election.enable`.
What happens if the partition leader crashes, and none of the remaining available replicas are in the ISR list (all followers are out of sync)?: unclean.leader.election.enable=false (Default & Safe) • Kafka refuses to elect an out-of-sync follower as leader.
End-to-End Kafka Security Architecture: mTLS, SASL/SCRAM, and ACLs.
Enterprise production clusters must enforce security at three distinct layers: Wire Encryption & Mutual Authentication (mTLS) • Uses X.509 SSL certificates to encrypt network traffic between clients and brokers and between brokers • Brokers authenticate client identity via client certificate subjects.
Tiered Storage in Apache Kafka (KIP-405).
Historically, retaining months or years of Kafka data required attaching petabytes of expensive NVMe SSD storage directly to broker instances. Tiered Storage separates compute from storage: Local Tier (Hot Storage): Brokers store the most recent log segments on local high-speed SSDs (e.g. 24 hours of data).
Kafka Cluster Sizing and Network Bottlenecks.
When sizing a production Kafka cluster: Network Bandwidth is almost always the first bottleneck, not CPU or disk • Total Inbound = \text{Write MB/s} \times \text{Replication Factor} • Total Outbound = \text{Write MB/s} \times \text{Follower Replicas} + \text{Read MB/s} \times \text{Number of Consumer Groups}.
Real-World Architecture: The Transactional Outbox Pattern with Kafka and Debezium CDC.
A microservice must save an order to PostgreSQL and publish an OrderCreated event to Kafka.: If you save to DB first and the app crashes before publishing to Kafka -> Inconsistent state! • If you publish to Kafka first and DB commit fails -> Ghost event!.
Zero-Downtime Migration from ZooKeeper to KRaft in Production.
Migrating an existing enterprise Kafka cluster from ZooKeeper to KRaft without interrupting live producers or consumers: Deploy KRaft Controller Quorum: Spin up dedicated KRaft controller nodes running Kafka 3.6+.
Kafka Streams vs Apache Flink vs Spark Streaming: Architecture, state management (RocksDB), and stream-table duality.
Kafka Streams: A lightweight client Java library that runs directly inside your application microservice • Apache Flink: True event-driven, distributed stream processing cluster with native support for complex event processing, out-of-order.
Consumer Rebalance Protocols: Eager Rebalance vs Cooperative Sticky Assignor (Incremental Cooperative Rebalance).
When a consumer joins or leaves a consumer group: Eager Rebalance (Legacy): Every single consumer in the group revokes all its assigned partitions and stops consuming ("stop-the-world" pause) • Cooperative Sticky Rebalance (CooperativeStickyAssignor) • Rebalances happen incrementally across multiple rounds.
Kafka Log Compaction Deep Dive: Cleaner threads, dirty ratio, compaction tombstone records, and `min.compaction.lag.ms`.
For key-value topics (e.g. user account profiles), log compaction guarantees that Kafka retains at least the last known value for each record key indefinitely: Log Cleaner Threads: Background threads that scan log segments, building an in-memory hash map of the latest key offsets, and rewrite clean.
Producer Partitioning Strategies: DefaultPartitioner (Murmur2 hash), RoundRobin, sticky partitioning, and custom key partitioners.
How Kafka determines which partition an event lands in: Explicit Partition Specified: Message is routed directly to that partition index • Key Provided (Default): Kafka calculates murmur2(key) % totalpartitions.
Kafka MirrorMaker 2 (MM2) Architecture: Active-Active vs Active-Passive geo-replication and offset translation.
MirrorMaker 2 leverages the Kafka Connect framework to replicate topics between distinct physical data centers or cloud regions: Active-Passive (DR): Replicates all topics from Region A to Region B • Active-Active: Producers in both US-East and EU-Central write locally.
Exactly-Once Semantics (EOS) in Kafka Streams: Two-phase commit with transaction coordinator and marker messages.
Kafka's "Read-Process-Write" loop achieves transactional Exactly-Once processing across multiple topics and state stores: Producer Transaction Coordinator: Allocates a unique transactional.id • Transaction Log (transactionstate): Records transaction state transitions (Ongoing, PrepareCommit, Committed).
Schema Evolution in Confluent Schema Registry: Backward, Forward, Full, and None compatibility modes with Avro/Protobuf.
Schema Registry enforces data governance at the broker boundary, preventing downstream consumers from crashing due to unexpected field removals or type changes: BACKWARD (Default): Consumers using the new schema can read data written with the previous schema.
Consumer Lag Monitoring and Mitigation: Prometheus JMX exporter, Burrow, and scaling partition-to-consumer mapping.
Consumer Lag is the delta between the latest offset written to a partition (Log End Offset) and the latest offset committed by a consumer group: Monitoring Tools: Export metrics via Kafka Exporter or Burrow (kafkaconsumergrouplag) • Mitigation Strategies • If lag is isolated to one partition -> Check for hot key skew.
Handling Head-of-Line Blocking: Concurrency patterns with worker thread pools and out-of-order acknowledgment in consumers.
If message 5 in a partition takes 30 seconds to process (e.g. slow external API call), standard single-threaded consumers cannot process messages 6, 7, 8 behind it, stalling the entire partition.: Worker Pool Pattern: The Kafka consumer thread only fetches messages and dispatches them into an internal in-memory bounded...
Kafka Connect Architecture: Source vs Sink connectors, tasks distribution, converters, and Single Message Transforms (SMTs).
Kafka Connect is a distributed, fault-tolerant framework for streaming data between Kafka and external datastores: Source Connectors: Pull data from datastores into Kafka (e.g., Debezium CDC from MySQL/PostgreSQL, Salesforce events).
Kafka Broker Socket Request Handlers: Acceptor thread, network processor threads, and I/O worker threads.
Understanding Kafka's low-level multi-threaded network model: Acceptor Thread (1 per port): Accepts new incoming TCP connections from clients and delegates the socket to a Network Thread in a round-robin pool.
Multi-DC Stretching vs Cluster Federation: Latency boundaries and witness nodes in quorum configurations.
Stretched Cluster (Single Cluster across 2-3 Availability Zones) • Synchronous replication via ISR • Requires RTT latency < 15ms between data centers • Place brokers evenly across 3 AZs.
Zero-Copy Architecture Deep Dive: Linux `sendfile()` syscall, DMA transfer, and kernel page cache direct routing.
Traditional file transfer requires 4 context switches and 3 data copies between kernel memory and user space. Kafka's Zero-Copy Optimization with sendfile(): Kafka instructs the Linux kernel to transfer data directly from the OS Page Cache to the NIC Network Socket Buffer via Direct Memory Access (DMA).
Debugging Stalled Consumers: Diagnosing `CommitFailedException`, `poll()` timeout (`max.poll.interval.ms`), and heartbeat threads.
When consumers crash with.
High-Throughput Producer Tuning: `linger.ms`, `batch.size`, compression algorithms (zstd vs lz4 vs snappy), and buffer memory exhaustion.
Maximizing Kafka producer throughput (achieving 100MB+/sec per node).