MESSAGING & EVENT-DRIVEN ARCHITECTURE / SYSTEM CONCEPT BRIEF

Kafka

Apache Kafka is a distributed, append-only event log.

IntermediatePhase 06 / Topic 3 of 18RequirementsTrade-offsFailure modes
01

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.

A newspaper archive

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.

02

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.
03

Where it shows up in interviews

Event streaming backbone

Recognize it when: many services exchange high-volume events.

  • Design Uber's event pipeline
  • Design a real-time analytics system
Ordering per key

Recognize it when: events for one entity must be processed in order.

  • Design a payment event pipeline
  • Design order state tracking
CDC and pipelines

Recognize it when: stream DB changes to search and analytics.

  • Keep Elasticsearch in sync with PostgreSQL
  • Design a data lake ingestion
04

Where it is used in real software

LinkedIn

Created Kafka and processes trillions of messages per day for activity streams and metrics.

Netflix and Uber

Use Kafka as the central nervous system for events, logs, and real-time processing.

Confluent and Amazon MSK

Managed Kafka services; Kafka Connect and Debezium stream data in and out.

05

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.
06

How it works, step by step

  1. 1
    Producer chooses a partition

    hash(key) mod partitions, so the same key goes to the same partition.

  2. 2
    Leader broker appends the record

    Followers replicate; acks=all waits for in-sync replicas.

  3. 3
    Consumers poll

    Each group member reads its assigned partitions from its offset.

  4. 4
    Consumers commit offsets

    After processing, so they resume correctly after restarts.

  5. 5
    Retention cleans up

    Delete after N days, or compact to keep the latest value per key.

Topic with 3 partitions and one consumer group
Step 1 / 4
Producer
P0
P1
P2
Consumer A
Consumer B

STEP 1Records keyed by user-7 hash to partition P0, so all of user-7's events stay in order.

07

Kafka vs a traditional queue

Key differences

Step 1 / 5
AspectKafka (log)Queue (SQS, RabbitMQ)
After consumptionRetained until retention expiresDeleted after ack
Multiple consumersEach group reads everything at its own offsetMessages split among consumers
ReplayYes, reset offsetsNo
OrderingPer partitionNone or FIFO per group
ThroughputMillions/s per clusterHigh, 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.

08

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() }]);  },});
09

Complexity and performance

Append / sequential readO(1)

Sequential disk I/O.

Throughput per partition~10s of MB/s

Scale with partitions.

Max consumer parallelism= partitions

Per consumer group.

10

Trade-offs

Throughput vs per-message features

Kafka is excellent for streams but lacks per-message delays, priorities, and individual acks that queues provide.

Partition count

More partitions increase parallelism but add overhead and make ordering and rebalancing harder.

11

Variants and related techniques

Log compaction

Keep only the latest record per key, useful for state snapshots.

Kafka Streams / Flink

Stateful stream processing on Kafka topics.

Alternatives

Redpanda (Kafka API, C++), Pulsar (tiered storage), Kinesis (managed AWS).

12

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.

13

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.

14

Practice problems

ProblemDifficultyWhat it trains
Choose keys and partitions for an order events topicMediumOrdering.
Design a clickstream analytics pipelineHardKafka + stream processing.