Skip to content

Apache Kafka: complete learning guide

A practical, end-to-end guide to Apache Kafka — core architecture, storage and delivery, replication, performance (including zero-copy), producer/consumer internals, ecosystem, enterprise use cases, event-driven patterns, and production operations with KRaft.

35 MIN READUPDATED 2026-11-18Data streaming & event platforms
ORIGINAL DIAGRAM · EVENT STREAMPRODUCERSwrite eventsTOPICPARTITION 1PARTITION 2PARTITION 3CONSUMER Agroup 1CONSUMER Bgroup 2REPLAY FROM OFFSET ↺

Original stream diagram — not a copied image

§ 00Notes & rules
Ordering guarantee
Kafka guarantees ordering within a partition, not across all partitions of a topic. Use event keys for entities that require ordered processing. (see Visual 3)
Modern clusters use KRaft
New Kafka 4.x architecture should be taught around KRaft (brokers + controller quorum). Kafka 4.0 removed ZooKeeper mode, so ZooKeeper is not a required component for modern deployments.
Replication is not backup
Replication improves availability and fault tolerance, but it does not replace backups, disaster recovery, or appropriate retention policies. (see Visual 4, Visual 10)
Exactly-once has boundaries
Kafka transactions can provide atomicity for Kafka reads/writes in supported designs, but they do not automatically make external side effects (databases, APIs) exactly-once. Use idempotency or coordination for external systems.
Zero-copy nuance
Zero copy reduces unnecessary user/kernel memory copies on eligible paths (e.g. page cache/sendfile), improving efficiency — but DMA still moves data and TLS/compression or other processing can affect the optimization. (see Visual 5)
Producer/consumer clarifications
A producer can publish to multiple topics. Within a consumer group a partition is assigned to at most one consumer at a time, while different groups can consume the same events independently. Consumers fetch records from brokers. (see Visual 2–3, Visual 6)
§ 01Key concepts
Event / recordAn immutable fact that something happened, published to Kafka with an optional key, value, headers and timestamp.
ProducerAn application that publishes events to Kafka topics (a producer can publish to one or multiple topics).
ConsumerAn application that fetches and processes events from Kafka topics.
TopicA logical, named stream/category of events.
PartitionAn ordered, append-only log within a topic; the unit of parallelism and ordering (ordering is guaranteed per partition, not across partitions).
OffsetA partition-specific position of a record within that partition's log.
BrokerA Kafka server that stores partition replicas and serves client requests.
ClusterA group of Kafka brokers and controllers working together.
Controller (KRaft)A node role managing cluster metadata and coordination via the KRaft quorum (modern Kafka; ZooKeeper mode removed in Kafka 4.0).
Consumer groupA set of consumers cooperating to process a topic; within a group, a partition is assigned to at most one consumer at a time (other groups can read the same data independently).
Replica / leader / followerCopies of a partition for fault tolerance: the leader handles writes and serves reads in the normal model, followers fetch from the leader.
ISR (in-sync replicas)Replicas sufficiently caught up to be eligible for relevant leadership/ack guarantees.
Retention / log compactionRetention keeps records for configured time/size; compaction retains the latest value per key (useful for latest-state topics).
Zero copyAn optimization (e.g. sendfile/page cache) that reduces unnecessary user/kernel memory copies on eligible transfer paths; it does not eliminate all data movement (DMA, TLS/compression can affect it).
§ 02When to use
  • Decoupling producers and consumers so services evolve and scale independently (event-driven architectures). (see Visual 1, Visual 8)
  • High-throughput, durable event streams: logs/telemetry, activity streams, metrics, CDC, and real-time pipelines. (see Visual 8)
  • Multiple independent consumers need the same events (fan-out) with replay within retention/compaction policies. (see Visual 3, Visual 8)
  • Building streaming analytics, recommendations, monitoring/alerting, or feeding data platforms/ML feature pipelines. (see Visual 7–8)
  • System migration or strangler patterns where old and new systems run in parallel consuming the same events. (see Visual 8–9)
§ 03How it works
  1. 01Publish: a producer serializes an event, the partitioner selects a partition (by key/hash or strategy), records are batched in the accumulator and sent to the partition leader broker; the broker appends to the log and acknowledges per acks config. (see Visual 1–2, Visual 6)
  2. 02Store & replicate: each partition is an append-only log segmented on disk; leader writes are replicated to follower replicas, and the cluster tracks in-sync replicas (ISR) for durability and failover. (see Visual 3–4)
  3. 03Consume: consumers in a group subscribe to topics, partitions are assigned, records are fetched in batches, processed by the application, and offsets are committed (enabling resume/replay semantics per group). (see Visual 2–3, Visual 6)
  4. 04Fault tolerance: with replication, if a leader fails an eligible in-sync replica can be elected leader (subject to config and cluster state); replication improves availability but does not replace backups/DR/retention planning. (see Visual 4, Visual 9)
  5. 05Performance path: sequential appends, OS page cache, batching/compression and kernel-assisted transfers (e.g. sendfile on eligible paths) reduce overhead and improve throughput for producers and consumers. (see Visual 5)
  6. 06Ecosystem & processing: Kafka Connect moves data to/from external systems (source/sink), Kafka Streams and engines like Flink process streams, and schema management (e.g. Schema Registry) governs compatibility. (see Visual 7)
  7. 07Operate: run on KRaft (brokers + controller quorum), secure with TLS/SASL/ACLs, monitor lag/health/ISR/latency, and plan scaling, retention and disaster recovery. (see Visual 10)
§ 04Use cases & scenarios

Order events fan out to two systems

Context
An order service publishes events consumed by fulfilment and analytics.
Problem
Both consumers need the same events but must scale independently.
Approach
Key events by order ID for per-partition ordering and use separate consumer groups.
Outcome
Each service processes events at its own pace without coupling.

Inventory state with log compaction

Context
A warehouse needs the latest stock position per SKU.
Problem
A full event history would grow without bound and replay would be slow.
Approach
Use a compacted topic keyed by SKU and let new consumers rebuild latest state from it.
Outcome
Fast state recovery with a bounded topic footprint.
§ 05Examples

Example domain event (JSON)

json
{
  "event_id": "evt-1001",
  "event_type": "OrderCreated",
  "customer_id": "C101",
  "order_id": "ORD5001",
  "amount": 25000,
  "currency": "INR",
  "timestamp": "2026-11-19T08:00:00Z"
}

Use a stable key (e.g. customer_id/order_id) when consumers must process related events in order within a partition.

Illustrative producer reliability settings

properties
acks=all
enable.idempotence=true
retries=10
delivery.timeout.ms=120000
linger.ms=5
batch.size=65536
compression.type=lz4

Illustrative tuning values — benchmark against your latency, durability and broker/cluster capacity. Pair acks=all with an appropriate min.insync.replicas. (see Visual 4–6, Visual 10)

Illustrative consumer baseline

properties
group.id=orders-service
enable.auto.commit=false
auto.offset.reset=earliest
max.poll.records=500
# process records, then commit offsets after successful/idempotent handling

Commit strategy depends on semantics; design handlers to be safe under retries/duplicates (at-least-once is common). (see Visual 3, Visual 6, Visual 9)

Learning lab roadmap (hands-on)

text
1) Run Kafka (KRaft) locally and create topics
2) Produce and consume events; inspect offsets
3) Add partitions and multiple consumers (observe group assignment)
4) Configure replication; simulate broker failure/leader changes
5) Test retries, idempotent producers, and idempotent consumers
6) Add Kafka Connect/CDC pipeline to/from a database
7) Build a simple stream aggregation (Kafka Streams or Flink)
8) Add DLQ/error handling and monitor consumer lag & health

Progress from fundamentals to reliability, integration, processing and production observability. (see Visual 1–10)

§ 06Trade-offs

Kafka (event log) vs traditional queue

Up: Durable replay, multi-consumer fan-out, high throughput

Down: More concepts/operational overhead than simple point-to-point queues

More partitions

Up: Higher parallelism and throughput potential

Down: More overhead, rebalances, and ordering only within a partition

acks=all + min.insync.replicas

Up: Stronger write durability (given healthy ISR)

Down: Higher latency and writes can fail when ISR is insufficient

At-least-once processing

Up: Simple and resilient to crashes

Down: Duplicates possible; consumers/external effects must be idempotent

Transactions / exactly-once (Kafka scope)

Up: Atomic read-process-write within Kafka under supported designs

Down: Added complexity; does not make arbitrary external side effects exactly-once

Log compaction vs time/size retention

Up: Keeps latest state per key

Down: Not a full event history; requires good key design

§ 07Implementation checklist
  • Model events clearly (type, key, schema, timestamps) and choose keys deliberately to preserve required per-entity ordering.
  • Size partitions for parallelism and growth; remember ordering guarantees are per partition.
  • Configure durability explicitly (replication factor, acks, min.insync.replicas) and test failure scenarios.
  • Make consumers idempotent and handle retries/DLQs; commit offsets according to your processing semantics.
  • Use batching/compression and benchmark (linger.ms, batch.size, compression.type) against latency/throughput goals.
  • Plan schema evolution/compatibility and access control (authn/authz, TLS, secrets).
  • Monitor consumer lag, under-replicated/offline partitions, ISR changes, throughput/latency, disk usage and rebalances.
  • For production, deploy KRaft-based clusters, document retention/DR, and avoid treating replication as a backup.
§ 08Configuration reference
KeyTypical valueNote
acksall (durable), 1, 0With acks=all, writes wait for required in-sync replicas (combine with min.insync.replicas).
min.insync.replicas2 (common with RF=3)Minimum ISR for acks=all writes; tune for durability vs availability.
enable.idempotencetruePrevents duplicate writes from producer retries within supported guarantees.
retries / delivery.timeout.msboundedHandle transient failures without unbounded retry loops.
linger.ms0–10+ ms (example 5)Trade small latency for batching/throughput; benchmark per workload.
batch.sizee.g. 16–64 KiB+Larger batches improve throughput; balance memory and latency.
compression.typelz4 / snappy / zstd / gzipReduces network/storage; CPU trade-off varies by codec and data.
replication.factor3 (common)Partition replicas across brokers/racks where possible.
num.partitionsworkload-drivenControls parallelism; harder to reduce later, so plan capacity.
retention.ms / retention.bytespolicy-drivenTime/size retention; independent of consumer read state.
cleanup.policydelete / compact / compact,deleteUse compaction for latest-value-per-key topics.
auto.offset.resetearliest / latestBehavior when no committed offset exists for a group.
§ 09Troubleshooting
SymptomCauseFix
Consumer lag growingInsufficient consumers/partitions, slow processing, or throttlingScale consumers (up to partition count), optimize processing/fetching, check broker and network health.
Frequent rebalances / processing pausesUnstable consumers, long polls/GC, session/heartbeat issues, or membership churnTune timeouts/heartbeats, use cooperative assignment where appropriate, and stabilize deployments.
Duplicate processing / side effectsAt-least-once delivery, retries, or reprocessing after failuresMake handlers idempotent (dedupe keys), commit offsets deliberately, and isolate side effects.
Messages out of expected orderAssuming global ordering across partitions or key changesUse consistent keys for entities needing order, and rely on per-partition ordering only.
Produce fails with not-enough-replicasISR below min.insync.replicas or broker issuesRestore broker/replica health, verify replication/ISR, and balance durability vs availability settings.
Data not readable by new consumersRetention expired or unexpected compaction/tombstonesAlign retention/compaction with replay needs and communicate topic contracts.
Low throughput despite KafkaSmall batches, no compression, too few partitions, or client/broker bottlenecksEnable batching/compression, right-size partitions, and profile network/disk/CPU and page cache.
§ 10Frequently asked questions

Is Kafka just a message queue?

No. Kafka combines durable, append-only event storage (log) with pub/sub distribution and stream processing/replay within retention policies.

Does Kafka guarantee ordering?

Yes, within a single partition. There is no global ordering across all partitions of a topic.

Can a producer send to multiple topics?

Yes. A producer is not limited to one topic.

How many consumers can read a partition?

Within a consumer group, at most one consumer reads a partition at a time. Different consumer groups can read the same partition independently.

Do consumers 'pull' from Kafka?

Consumers fetch records from brokers (often described as pull/fetch), which lets them control pace and batching.

Is replication the same as backup?

No. Replication improves availability/fault tolerance, but you still need appropriate retention, backups and disaster-recovery planning.

Does zero copy mean no data movement?

No. It reduces unnecessary user-space/kernel copies on eligible paths (e.g. page cache/sendfile), but DMA and factors like TLS/compression still involve data movement/processing.

Does Kafka provide exactly-once processing everywhere?

Kafka transactions support atomicity for Kafka reads/writes in supported designs, but external side effects (databases/APIs) require idempotency or coordination.

Do I need ZooKeeper for new Kafka clusters?

Modern Kafka uses KRaft for metadata/coordination and Kafka 4.0 removed ZooKeeper mode; new 4.x deployments should be designed around KRaft (brokers + controller quorum).

Where should I start learning hands-on?

Spin up Kafka (e.g. Docker/KRaft), create topics, build a producer/consumer, experiment with partitions/consumer groups, then add replication, failure tests, idempotent processing, and observability (lag/metrics).

§ 11Diagrams & visuals
Visual 1kafka-learning-1.png
Kafka learning visual 1 — architecture overview
Visual 1 (architecture overview): end-to-end Kafka concepts and platform context. Referenced in Key concepts and How it works.
Visual 2kafka-learning-2.png
Kafka learning visual 2 — core components and message flow
Visual 2 (components & message flow): producers, topics, brokers and consumers. Referenced in How it works.
Visual 3kafka-learning-3.png
Kafka learning visual 3 — topics, partitions and consumer groups
Visual 3 (topics, partitions & consumer groups): partitioned logs, offsets and group assignment. Referenced in Key concepts and How it works.
Visual 4kafka-learning-4.png
Kafka learning visual 4 — replication and durability
Visual 4 (replication & durability): leaders/followers, ISR and failover behavior. Referenced in How it works and Notes.
Visual 5kafka-learning-5.png
Kafka learning visual 5 — performance and zero-copy
Visual 5 (performance & zero-copy): page cache, batching/compression and efficient data transfer. Referenced in How it works, Examples and Notes.
Visual 6kafka-learning-6.png
Kafka learning visual 6 — producer and consumer internals
Visual 6 (producer/consumer internals): batching, delivery, fetch and offset handling. Referenced in How it works and Examples.
Visual 7kafka-learning-7.png
Kafka learning visual 7 — ecosystem and stream processing
Visual 7 (ecosystem & stream processing): Connect, Streams/Flink and integration patterns. Referenced in How it works.
Visual 8kafka-learning-8.png
Kafka learning visual 8 — enterprise use cases
Visual 8 (enterprise use cases): log analytics, CDC, monitoring, recommendations and event-driven flows. Referenced in When to use and How it works.
Visual 9kafka-learning-9.png
Kafka learning visual 9 — architecture patterns and reliability
Visual 9 (patterns & reliability): event-driven architecture, delivery semantics and resilience patterns. Referenced in How it works, Trade-offs and Notes.
Visual 10kafka-learning-10.png
Kafka learning visual 10 — production operations
Visual 10 (production operations): KRaft, security, observability, scaling and DR. Referenced in Checklist, Configuration and Troubleshooting.