Overview
Apache Kafka is a distributed, append-only event log. Producers write records to topics, which are split into partitions; each partition is an ordered, immutable sequence stored on disk and replicated across brokers. Consumers read by offset and track their own position, so many independent consumer groups can read the same data, and data can be replayed.
Kafka achieves very high throughput through sequential disk I/O, batching, compression, and zero-copy transfers. Ordering is guaranteed only within a partition, so records with the same key (such as a user ID) go to the same partition. It is used for event streaming, log aggregation, change data capture, and stream processing.
Every edition is printed and stored in order. Readers keep a bookmark of which edition they last read; different readers can be at different places, and anyone can go back and reread older editions within the retention period.
When to use it
- High-throughput event streams (clicks, logs, metrics, IoT).
- Multiple consumers need the same events, possibly replayed.
- Change data capture and data pipelines.
- Stream processing with Kafka Streams or Flink.
- Event sourcing and audit logs.
Where it shows up in interviews
Recognize it when: many services exchange high-volume events.
- Design Uber's event pipeline
- Design a real-time analytics system
Recognize it when: events for one entity must be processed in order.
- Design a payment event pipeline
- Design order state tracking
Recognize it when: stream DB changes to search and analytics.
- Keep Elasticsearch in sync with PostgreSQL
- Design a data lake ingestion
Where it is used in real software
Created Kafka and processes trillions of messages per day for activity streams and metrics.
Use Kafka as the central nervous system for events, logs, and real-time processing.
Managed Kafka services; Kafka Connect and Debezium stream data in and out.
Key terms
- Topic / partition
- Named stream / ordered shard of a topic.
- Offset
- Position of a record within a partition.
- Consumer group
- Consumers sharing work; each partition is read by one member.
- Replication factor / ISR
- Copies per partition / replicas that are caught up.
- Retention
- How long records are kept (time or size), or compacted by key.
How it works, step by step
- 1Producer chooses a partition
hash(key) mod partitions, so the same key goes to the same partition.
- 2Leader broker appends the record
Followers replicate; acks=all waits for in-sync replicas.
- 3Consumers poll
Each group member reads its assigned partitions from its offset.
- 4Consumers commit offsets
After processing, so they resume correctly after restarts.
- 5Retention cleans up
Delete after N days, or compact to keep the latest value per key.
STEP 1Records keyed by user-7 hash to partition P0, so all of user-7's events stay in order.
Kafka vs a traditional queue
Key differences
| Aspect | Kafka (log) | Queue (SQS, RabbitMQ) |
|---|---|---|
| After consumption | Retained until retention expires | Deleted after ack |
| Multiple consumers | Each group reads everything at its own offset | Messages split among consumers |
| Replay | Yes, reset offsets | No |
| Ordering | Per partition | None or FIFO per group |
| Throughput | Millions/s per cluster | High, lower per queue |
NOWAspect: After consumption | Kafka (log): Retained until retention expires | Queue (SQS, RabbitMQ): Deleted after ack
Use Kafka for event streams that several systems consume or replay; use queues for task distribution with per-message retries.
Implementation
import { Kafka } from "kafkajs"; const kafka = new Kafka({ clientId: "orders", brokers: process.env.KAFKA_BROKERS!.split(",") }); // Producer: idempotent, waits for all in-sync replicasconst producer = kafka.producer({ idempotent: true, maxInFlightRequests: 5 });await producer.connect();await producer.send({ topic: "order-events", acks: -1, messages: [{ key: "order-981", value: JSON.stringify({ type: "OrderPaid", orderId: "order-981" }) }],}); // Consumer group: partitions are shared among instances with the same groupIdconst consumer = kafka.consumer({ groupId: "shipping-service" });await consumer.connect();await consumer.subscribe({ topic: "order-events", fromBeginning: false });await consumer.run({ autoCommit: false, eachMessage: async ({ topic, partition, message }) => { await handleEvent(JSON.parse(message.value!.toString())); // idempotent handler await consumer.commitOffsets([{ topic, partition, offset: (BigInt(message.offset) + 1n).toString() }]); },});Complexity and performance
Sequential disk I/O.
Scale with partitions.
Per consumer group.
Trade-offs
Kafka is excellent for streams but lacks per-message delays, priorities, and individual acks that queues provide.
More partitions increase parallelism but add overhead and make ordering and rebalancing harder.
Variants and related techniques
Keep only the latest record per key, useful for state snapshots.
Stateful stream processing on Kafka topics.
Redpanda (Kafka API, C++), Pulsar (tiered storage), Kinesis (managed AWS).
Common mistakes
- Expecting global ordering.
Fix: Ordering holds only within a partition; key by the entity that needs order.
- Hot partitions from skewed keys.
Fix: Choose keys with even distribution; split heavy keys.
- Committing offsets before processing.
Fix: Commit after processing for at-least-once; make handlers idempotent.
Interview questions
How does Kafka guarantee ordering?
Only within a partition. Producers send all records with the same key to the same partition, and one consumer in a group reads a partition sequentially, so per-key order is preserved.
Why is Kafka so fast?
Append-only sequential writes, OS page cache, batching and compression, zero-copy transfer from disk to network, and horizontal scaling through partitions.
How many partitions should a topic have?
Enough for the target consumer parallelism and throughput (throughput / per-partition throughput), with room to grow, while avoiding thousands of unnecessary partitions per broker.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| Choose keys and partitions for an order events topic | Medium | Ordering. |
| Design a clickstream analytics pipeline | Hard | Kafka + stream processing. |