Skip to main content

Kafka Architecture

1. Executive Summary​

Apache Kafka is a distributed commit log used as a message broker, event backbone, and stream processing substrate. Its architecture centers on topics partitioned into append-only logs, replicated across brokers for durability, consumed by consumer groups that track offsets per partition. Unlike traditional queue systems that delete messages after consumption, Kafka retains messages for a configurable period—enabling replay, multiple independent consumer groups, and decoupled read scaling.

Understanding Kafka at principal level requires grasping the controller, partition leadership, In-Sync Replicas (ISR), producer acknowledgment modes, consumer group rebalancing, log compaction, and operational limits (disk, partition count, rebalance storms). Kafka provides strong ordering within a partition and at-least-once by default; exactly-once features apply within broker transaction boundaries.

This chapter covers Kafka's internal architecture, replication protocol, producer and consumer mechanics, stream processing integration, failure modes, tuning tradeoffs, and interview-level system design patterns.

2. Why This Topic Matters​

Kafka appears in nearly every principal-level system design interview involving event-driven microservices, real-time analytics, CDC pipelines, or log aggregation. Weak answers describe Kafka as "a fast queue."

Strong candidates explain:

  • Partitions bound parallelism and ordering—not topics alone.
  • Consumer groups provide scale-out consumption with partition assignment constraints.
  • ISR and min.insync.replicas define the durability/consistency tradeoff on write.
  • Rebalances cause duplicate processing and latency spikes if misconfigured.
  • Compaction enables changelog topics for stateful stream processing.

Production failures include under-replicated partitions, hot partitions, zombie consumers after long GC, disk full from retention misconfiguration, and broker overload from excessive partition counts. Architects who treat partition count as unlimited create operational nightmares.

3. Problems Being Solved​

ProblemTraditional MQKafka approach
Consumer scale-outCompeting consumers on one queuePartition-parallel consumers in group
Replay / auditMessages deleted after ackRetained log with offset seek
Multiple subscribersFan-out exchanges or duplicate queuesIndependent consumer groups per use case
High throughputOften broker-boundSequential disk writes, zero-copy transfer
OrderingGlobal or per-queuePer-partition strict ordering
DurabilityBroker-dependentReplicated distributed log

Kafka solves durable, ordered, replayable event streaming at scale. It does not solve arbitrary global ordering, unlimited retention without cost, or automatic schema governance without additional tooling (Schema Registry).

4. Assumptions and System Model​

Assume a cluster of brokers coordinated by a metadata controller (KRaft in modern Kafka or legacy ZooKeeper):

  • Each partition has one leader broker handling reads/writes; followers replicate.
  • Producers choose partition via key hash or explicit partition.
  • Consumers in a group coordinate partition assignment via group coordinator.
  • Failures: Broker crash, network partition, disk failure, slow follower.
  • Not Byzantine unless discussing encrypted inter-broker traffic separately.

Critical invariant: Messages within a partition have a monotonically increasing offset; cross-partition ordering is undefined.

5. Essential Terminology​

TermDefinition
TopicNamed stream of messages; divided into partitions.
PartitionOrdered, immutable sequence of messages (log segment files).
OffsetMonotonic position within a partition log.
BrokerKafka server storing partitions and serving clients.
ReplicaCopy of a partition on a broker; one leader, rest followers.
ISRIn-Sync Replicas—followers caught up within replica.lag.time.max.ms.
Consumer groupSet of consumers sharing work; one consumer per partition max.
Group coordinatorBroker managing consumer group membership and offsets.
High watermarkOffset up to which all ISR replicas have replicated.
Log compactionRetain latest record per key; tombstones delete keys.
KRaftKafka Raft metadata mode replacing ZooKeeper dependency.

Mnemonic: Topic splits into partitions; groups consume in parallel.

6. Core Mechanism​

Cluster and partition leadership​

Figure 1: Producers write to partition leaders; followers replicate; controller manages leadership; consumer group reads from leaders.

Producer acknowledgment modes​

Figure 2: acks trades latency vs durability; acks=all with min.insync.replicas=2 prevents commit on single broker.

Consumer group partition assignment​

Figure 3: Max parallelism = partition count; uneven key distribution creates hot partitions.

7. Step-by-Step Walkthrough​

Scenario: E-commerce order events topic with 12 partitions, replication factor 3, acks=all, min.insync.replicas=2.

StepComponentAction
1ProducerSerializes OrderCreated with key=order_id
2Partitionerhash(order_id) % 12 → partition 7
3Leader brokerAppends to log segment; updates high watermark after ISR ack
4FollowersFetch from leader; join ISR if within lag threshold
5Consumer groupMember assigned partition 7 via cooperative rebalance
6ConsumerPolls batch; processes; commits offset 15432
7RetentionSegments older than 7 days deleted (delete policy)

Leader failure:

EventSystem response
Leader broker diesController elects new leader from ISR
No ISR availablePartition offline—producers fail with NOT_ENOUGH_REPLICAS
Unclean leader election (if enabled)Data loss risk from out-of-sync replica—avoid in production

Rebalance trigger:

CauseEffect
New consumer joinsPartitions reassigned—stop-the-world with eager protocol
Consumer heartbeat timeoutPartitions reassigned to surviving members
Partition count increaseRebalance redistributes

Mitigation: Cooperative sticky assignor; max.poll.interval.ms tuned for processing time; static group membership.

Log segment and retention mechanics:

Kafka stores each partition as a sequence of log segment files on disk—not one unbounded file. When a segment reaches segment.bytes or segment.ms, a new segment is created; only the active segment accepts writes. Retention policies (retention.ms, retention.bytes) delete whole segments, not individual messages. This design enables efficient sequential I/O and cheap deletion.

PolicyBehaviorUse case
delete (default)Remove segments older than retentionEvent streams, metrics
compactKeep latest record per key per logChangelog, Kafka Streams state
Tiered storage (feature)Older segments to object storageCost reduction at scale

Compacted topics maintain the latest value for each key—critical for changelog topics where stream processors rebuild state. Tombstones (records with null value) delete keys after delete.retention.ms. Architects must size compaction lag and dirty ratio (min.cleanable.dirty.ratio) to avoid disk pressure during compaction cycles.

Consumer group coordinator internals:

When a consumer joins a group, the group coordinator broker (selected by hash of group.id) manages:

  1. Member registration and heartbeat monitoring.
  2. Partition assignment via pluggable assignor (range, round-robin, sticky, cooperative).
  3. Offset commits to internal __consumer_offsets topic (compacted).

The __consumer_offsets topic itself is a Kafka topic—its health affects all consumer groups. Platform teams monitor it like any production topic.

KRaft vs legacy ZooKeeper (operational shift):

Modern Kafka (3.3+) supports KRaft mode where metadata is stored in a Raft quorum of controller nodes, eliminating ZooKeeper dependency. Benefits include faster metadata propagation, simpler deployment topology, and improved scalability of partition counts. Migration from ZK to KRaft is a major operational project—architects planning greenfield clusters should default to KRaft per current Apache Kafka recommendations (verify version-specific maturity for your release).

8. Invariants and Guarantees​

PropertyTypeStatement
Per-partition orderingSafetyConsumers see messages in offset order
DurabilitySafetyWith acks=all and adequate ISR—survives broker loss
No message loss on leaderSafetyIf min ISR met before ack
AvailabilityLivenessSome partitions offline if ISR empty
Cross-partition orderNot guaranteedDesign keys accordingly
Consumer offset commitApplicationSeparate from broker durability

9. Failure Scenarios​

Scenario 1: Hot partition​

Setup: 90% of keys hash to partition 3.

Effect: Single broker disk and CPU saturated; consumer lag on one partition.

Mitigation: Custom partitioner; salt keys; increase partitions with rekey migration plan.

Scenario 2: ISR shrink during network blip​

Setup: Followers fall out of ISR; min.insync.replicas=2 but only leader in ISR.

Effect: Producers blocked—availability hit for durability.

Mitigation: Network redundancy; tune replica.lag.time.max.ms; monitor under-replicated partitions.

Scenario 3: Rebalance storm​

Setup: Frequent consumer restarts during deploy; eager rebalance revokes all partitions.

Effect: Processing pause; duplicate processing across generations.

Mitigation: Cooperative rebalance; rolling deploy with static membership; increase session.timeout.ms carefully.

Scenario 4: Disk full​

Setup: Retention unbounded; compacted topic misconfigured.

Effect: Broker rejects writes; cluster instability.

Mitigation: Disk alerts; retention.bytes; tiered storage (vendor/feature-dependent).

Scenario 5: Large message rejection​

Setup: message.max.bytes exceeded by fat JSON payloads.

Effect: Producer failures; partial pipeline stall.

Mitigation: Reference storage (S3) for blobs; Avro/Protobuf compression; raise limits coherently across cluster.

Scenario 6: ZooKeeper/KRaft metadata loss​

Setup: Metadata quorum lost (legacy ZK) or KRaft corruption.

Effect: Cluster administration impaired—catastrophic operational event.

Mitigation: KRaft with 3+ controllers; backup metadata; runbooks for recovery per Confluent/Apache docs.

10. Performance Characteristics​

FactorImpact
Batch size (linger.ms, batch.size)Higher throughput, higher latency
Compression (lz4, zstd)CPU vs network tradeoff
Partition countMore files, more memory per broker—avoid thousands per broker
Replication factorWrite amplification; 3 common for production
Fetch sizeConsumer throughput vs memory
Zero-copy (sendfile)Efficient broker-to-consumer transfer

Rule of thumb: Sequential disk append achieves high MB/s; random small messages still benefit from batching. Verify throughput targets with workload-specific benchmarks—do not rely on generic marketing numbers.

11. Scalability Limits​

  • Partitions per cluster: Operational guidance often cites low thousands per broker as practical upper bound—depends on hardware and version; monitor file descriptors and metadata size.
  • Consumer group members: Cannot exceed partition count for full utilization.
  • Retention storage: Linear with produce rate × retention time.
  • Controller load: Grows with partition and broker count—KRaft improves over ZK at scale.

12. Operational Considerations​

  • Monitor: under-replicated partitions, offline partitions, consumer lag, request latency, disk usage.
  • Rolling broker restarts with controlled leadership movement.
  • Topic configuration as code (Terraform, Strimzi, Confluent).
  • ACLs and quotas per tenant in multi-tenant clusters.
  • Upgrade strategy: Inter-broker protocol version compatibility matrix.
  • Backup: MirrorMaker 2 or cluster linking for DR—not a substitute for replication within cluster.

13. Security Considerations​

  • TLS for clients and inter-broker traffic.
  • SASL authentication (SCRAM, OAuth/OIDC in managed offerings).
  • ACLs: Topic produce/consume permissions per principal.
  • Encryption at rest: Broker disk encryption; KMS integration in cloud.
  • Audit logs: Track administrative actions.

14. Cost Considerations​

  • Storage dominates at long retention—tiered storage reduces cost (verify vendor pricing).
  • Cross-AZ replication doubles network egress charges in cloud.
  • Over-partitioning increases operational overhead without throughput gain.
  • Managed Kafka (MSK, Confluent Cloud) trades OpEx for reduced staffing.

15. Production Implementations​

Apache Kafka (self-managed)​

Full control; team owns upgrades, tuning, incidents. Common at scale with dedicated platform teams.

Confluent Platform / Cloud​

Schema Registry, ksqlDB, Connect ecosystem, tiered storage—implementation choices atop open-source Kafka.

Amazon MSK​

Managed brokers; IAM auth; integrates with AWS ecosystem.

Azure Event Hubs (Kafka protocol)​

Kafka-compatible API with different operational model—verify semantic differences.

Strimzi (Kubernetes)​

Operator-managed Kafka on K8s—popular for cloud-native deployments.

LinkedIn (origin)​

Kafka created at LinkedIn for activity stream pipeline—anecdotal origin for log-oriented messaging at scale.

16. Alternatives and Tradeoffs​

SystemStrengthWeakness vs Kafka
RabbitMQFlexible routing, low latency RPC-styleNo native long retention replay log
PulsarMulti-tenancy, tiered storage, geo-replicationSmaller ecosystem in some orgs
Amazon KinesisManaged shardsShard scaling model differs
Redis StreamsLow latency, simpleMemory-bound retention
NATS JetStreamLightweightDifferent durability model

Choose Kafka when replay, multiple consumer groups, and high sustained throughput on a durable log matter.

17. Common Misconceptions​

MisconceptionReality
"More consumers = unlimited scale"Capped by partition count.
"Kafka is a queue"It's a retained log; consumers track offsets.
"Replication factor = quorum reads"Consumers read from leader; ISR affects writes.
"Exactly-once everywhere"Transaction scope limited; external effects need idempotency.
"Keys always balance load"Skewed key distribution creates hot spots.

18. Principal Architect Perspective​

  1. Size partitions for target throughput and consumer parallelism—plan key distribution early.
  2. Set min.insync.replicas and acks=all for durability-critical topics.
  3. Treat rebalances as incidents waiting to happen—tune consumer and use cooperative assignors.
  4. Schema evolution policy before production—Registry with compatibility mode.
  5. Platform team owns cluster health; product teams own topic contracts.

Capacity planning: Model bytes/day = events/sec × avg size × 86400 × replication factor × retention days. Present disk and network budgets before approving new high-volume topics.

Stream processing integration (architectural context):

Kafka is frequently paired with stream processors (Kafka Streams, Apache Flink, ksqlDB) that consume topics, maintain state, and produce derived topics:

PatternInputOutputState store
FilteringRaw eventsFiltered streamStateless
AggregationClicksCounts per windowRocksDB changelog
JoinOrders + PaymentsEnriched ordersDual changelog
CDCDB binlogDomain eventsOffset tracking

Stream processors rely on changelog topics (compacted) for fault-tolerant state recovery. Architects must account for reprocessing cost when replaying from earliest offset after logic changes—version stream processing jobs with compatible state or plan state migration.

Inter-broker replication protocol (simplified):

Followers send Fetch requests to the leader specifying their current offset. The leader responds with new records up to the high watermark. A follower joins ISR when replica.lag.time.max.ms has not been exceeded—meaning it is "caught up enough." If a follower falls behind beyond this threshold, it exits ISR; with min.insync.replicas=2 and only one replica in ISR, producers with acks=all cannot commit new messages until ISR recovers.

Exactly-once stream processing scope:

Kafka Streams and similar frameworks offer exactly-once processing guarantees within the Kafka ecosystem—meaning output records and consumer offsets are written atomically via transactions. This reduces duplicate downstream Kafka messages but does not extend to side effects in external databases unless using transactional sinks or idempotent writes. Interview answers must scope the guarantee precisely.

19. Architecture Review Exercise​

Scenario: 50 microservices, each creates topics with RF=1, 3 partitions, no monitoring; consumers use auto-commit.

Review prompts:

  1. Durability on single broker loss?
  2. Can analytics team replay last month?
  3. Deploy-induced rebalance impact?
  4. Remediation roadmap?

Expected findings: RF=3, min.insync.replicas=2, increase partitions for hot topics, disable auto-commit, lag alerting, Schema Registry, topic naming standards.

20. Whiteboard Explanation​

90-second version:

"Kafka is a distributed commit log. Topics split into partitions for parallelism; each partition is an ordered log replicated across brokers. One replica is leader for writes; followers form the ISR. Producers pick partition by key hash for ordering per entity. Consumers join groups—the group coordinator assigns partitions so each partition has one consumer in the group. Offsets track read position; messages aren't deleted on consume—they expire by retention. acks=all with min ISR gives durability; acks=1 is faster but riskier. Rebalances happen when consumers join or die—tune timeouts and use cooperative assignor to reduce pain. Hot keys skew partitions. Kafka fits event sourcing backbones, CDC, and stream processing where replay and multiple readers matter."

21. Interview Questions​

  1. How does Kafka achieve ordering?

    • Signals: Per-partition only; key-based routing.
  2. What is ISR?

    • Signals: In-sync followers; write quorum for acks=all.
  3. Consumer group parallelism limit?

    • Signals: Partition count.
  4. acks=1 vs acks=all?

    • Signals: Leader-only vs ISR durability.
  5. What triggers rebalance?

    • Signals: Member join/leave, timeout, subscription change.
  6. Log compaction use case?

    • Signals: Changelog topics; latest value per key.
  7. Hot partition mitigation?

    • Signals: Key salting, more partitions, custom partitioner.
  8. Kafka vs RabbitMQ?

    • Signals: Retained log vs queue; replay; routing.
  9. Design order events topic.

    • Signals: Key=order_id, RF, retention, schema, consumer groups.
  10. KRaft vs ZooKeeper?

    • Signals: Metadata in Kafka Raft quorum; ZK deprecated path.

Scoring rubric:

DimensionStrongWeak
InternalsLeader, ISR, offsets"Distributed queue"
OpsRebalance, URP, diskIgnores failure modes
SizingPartition/key strategyRandom partition count

22. Interview Follow-Ups​

  1. Partition count increase live—impact?

    • Signals: Rebalance; only new keys to new partitions unless reprocess.
  2. Cross-region Kafka?

    • Signals: MirrorMaker, latency, active-active complexity.
  3. When not Kafka?

    • Signals: Low volume RPC tasks, simple work queues, sub-ms latency.

22A. Production Low-Level Design (Interview + Game Day)​

Regional Kafka + sized partitions for high ingest. Production LLD and Game Day Standard.

Topology LLD​

ConcernChoice
ClusterPer-region (not one global mega-cluster)
Partitionsthroughput / target_per_partition; key = order_id
ReplicationRF=3, min.insync.replicas=2, acks=all
ConsumersConsumer groups; lag SLO

Step-by-step consumer lag LLD:

StepActionNotes
1Measure lag by partitionoffset_lag / time lag
2Scale consumers ≤ partitionsMore consumers than parts idle
3Hot key?Re-key or local fan-out
4Poison messagePause / DLQ / skip policy

One SLO​

Publish success + end-to-end lag p99 (e.g. < 30s for order pipeline).


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Consumer lag spikeThrottle consumers / 10× produceLag alarmScale / pause noncriticalLag drains
GD-2Poison messageBad payload loopRetry storm / lagDLQ + skipGroup healthy
GD-3Broker / AZ lossKill brokerUnder-replicatedISR / replaceNo data loss with acks=all
GD-4Rebalance stormFlap membershipFrequent revokesSession timeout tuneStable assignment

GD-2 — Poison + rebalance​

23. Strong Answer Example​

Question: "Design Kafka for 100k orders/sec globally."

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—regional clusters + sized partitions, not "one huge global Kafka."

PRACTICE interview answer map for Kafka at 100k orders/sec globally

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"100k orders/sec globally is a sustained throughput + multi-region design problem. Kafka is a great backbone: durable log, per-partition order, many consumer groups, replay.

I would not put every region’s producers onto one global cluster for sync writes—cross-region RTT kills p99 and couples availability. I'd run regional Kafka clusters (US/EU/APAC), produce locally, and use MirrorMaker 2 / Cluster Linking asynchronously for DR and global analytics.

Short answer: Per-region orders topic, key=order_id, RF=3 / acks=all / min.insync.replicas=2, enough partitions for consumer parallelism, Schema Registry, lag/URP monitoring—and benchmark the numbers rather than inventing them."

R — Requirements​

RequirementDesign choice
100k orders/sec aggregateSize partitions + brokers; batch/compress producers
Per-order orderingPartition key = order_id
Durability (no silent loss)RF=3, acks=all, min.insync.replicas=2, 3 AZs
Multi-region UX latencyProduce to nearest region
Independent consumersSeparate groups: fulfillment, billing, search, analytics
Replay / auditRetention (e.g. 7–14d) + optional compacted state topic
Effectively-once billingAt-least-once + idempotent consumers (not broker EOS alone)

"I'd ask: average payload size? Peak vs average? Strict global order needed? (Usually no.)"

A — Assumptions (state aloud)​

AssumptionWhy it matters
~1 KB typical order event (ask!)100k msg/s ≈ 100 MB/s—comfortable if batched
Peak maybe 2–3× averageHeadroom in partitions and brokers
Order processing is regionalLocal cluster is source of truth for that region
Global analytics can lag seconds–minutesAsync mirror OK
KRaft-era cluster (greenfield)Prefer KRaft over ZK for new builds

"I'd state payload size assumptions aloud and offer to recalc if events are 10 KB."

C — Capacity (do the math on the whiteboard)​

Throughput: 100,000 msg/s × 1 KB ≈ 100 MB/s aggregate (plus replication × RF)
Per-partition sustain (example): ~1–5k msg/s depending on consumers/disk — BENCHMARK
Partitions (floor): 100k / 2k ≈ 50; plan ~128–256 with growth / consumer headroom
Brokers: enough to place leaders + RF=3 across AZs without hot disks
Producers: linger.ms + batch.size + lz4/zstd; idempotent producer
Consumers: parallelism ≤ partition count; scale groups independently

"Partition count is capped by ops cost—I'd start with headroom, not 10,000 partitions on day one. Increasing partitions later doesn't rebalance old keys."

Sizing partitions and producer tuning for 100k/sec

Figure B: Partition math for parallelism; key by order_id; avoid hot keys; tune batching/compression/acks=all.

T — Topology (draw this)​

Global Kafka topology for 100k orders/sec

Figure C: Regional clusters for local produce/consume; async mirror for DR/analytics—not sync cross-region writes.

ComponentChoice
Topicorders (and maybe order-state compacted)
Keyorder_id (not mega-tenant alone without salting)
ReplicationRF=3, min.insync.replicas=2, rack/AZ aware
Produceacks=all, idempotence, retries, Schema Registry (Avro/Protobuf)
ConsumeManual commit after idempotent write; cooperative sticky assignor
Cross-regionMirrorMaker 2 / Cluster Linking—async
QuotasProtect cluster from runaway producers/consumers

I — Invariants (safety)​

"Non-negotiable:

  1. Order only within a partition — key=order_id for per-order order.
  2. No ack before ISR durability — acks=all + adequate min.insync.replicas.
  3. No single global sync write path for 100k/s UX.
  4. Consumer lag SLO per group; under-replicated / offline partitions = page.
  5. Schema compatibility enforced—breaking events don't silently poison billing.
  6. Billing/fulfillment effectively-once via idempotency—not 'Kafka EOS' alone."

C — Constraints (second C)​

ConstraintDesign response
Hot keys / celebrity SKUsSalt keys; custom partitioner; monitor skew
Cross-region consistencyAccept async lag; don't require global total order
Rebalance storms on deployCooperative assignor; tune max.poll.interval.ms; rolling deploys
Disk / retention costTiered storage or shorter retention + archive; compact state topics
Too many partitionsOps/controller load; right-size then grow with migration plan
Multi-AZ network costBatch well; avoid chatty tiny messages

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1Regional cluster standards: RF, acks, racks, Schema Registry
M2orders topic sized + load test to ≥100k/s regional/aggregate targets
M3Consumer groups online with lag SLOs and idempotent handlers
M4MM2 to DR/analytics; failover runbook
M5Autoscale brokers/consumers; quotas; skew dashboards
M6Chaos: kill broker, shrink ISR, pause consumers—verify no loss / recover lag

Failure modes:

FailureMitigation
Hot partitionRekey/salt; more partitions (new keys); move leaders
ISR shrink → produce failsNetwork redundancy; tune lag; capacity
Consumer lag spikeScale consumers (≤ partitions); backpressure; alert
"One global cluster"Redesign to regional produce
Silent schema breakRegistry compatibility + contract tests

Observability: produce rate, byte rate, under-replicated partitions, offline partitions, request latency, per-partition lag, skew ratio, mirror lag.


Closing line (interview)​

"So for 100k orders/sec globally: regional Kafka clusters, produce locally, partition orders by order_id with enough partitions for consumer headroom (I'd ballpark 128–256 after stating assumptions—then benchmark). RF=3, acks=all, min.insync.replicas=2 across AZs. Idempotent producers, Schema Registry, separate consumer groups with manual commits and idempotent DB writes. Async mirror for DR/analytics—not sync cross-region writes. Monitor URP, lag, and skew, and prove it with a load test."

Scoring signals​

StrongWeak / red flag
Regional topology + async mirrorOne global sync cluster
Partition math + key=order_id"Add brokers when slow"
RF / acks / min ISRRF=1 or acks=0 for money path
Consumer group + lag SLOIgnore parallelism cap
Hot-key / rebalance awarenessNo ops story
Benchmark caveatBlind marketing throughput numbers

Compact outline (if time-boxed to 2 minutes)​

"Regional clusters, local produce. orders keyed by order_id, ~128+ partitions with headroom—benchmark. RF=3, acks=all, min ISR=2. Schema Registry. Separate consumer groups, idempotent handlers. MM2 async for DR/analytics. Watch lag, URP, skew."

24. Weak Answer Example​

Question: "Design Kafka for 100k orders/sec globally."

"Use Kafka, make it distributed, add more brokers when slow."

Why weak / red flags: No partitioning/key strategy, no replication/acks, no multi-region topology, no consumer design or lag/URP ops—hand-wavy scaling.

25. Hands-On Exercise​

Lab: labs/lab-006-kafka-stream-processing/ — stream pipeline on :8094

cd labs/lab-006-kafka-stream-processing
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pytest tests/ -v
docker compose -p lab006 -f docker/docker-compose.yml up --build -d
chmod +x scripts/demo_kafka.sh && ./scripts/demo_kafka.sh
StepEndpointWhat happens
1POST /v1/ordersProduce to orders (key = customer_id)
2POST /v1/enricher/runValidate + enrich → orders-enriched
3POST /v1/aggregator/run1-min tumbling windows → order-metrics
4POST /v1/poison/injectPoison message for DLT demo
5GET /v1/metricscount + revenue by region

Swagger: http://localhost:8094/docs

Engineer guide: how the local stack works​

  1. In-memory broker (src/broker.py) simulates Kafka topics with 4 partitions — hash partition by message key.
  2. Producer (POST /v1/orders) — idempotent within session by order_id; routes by customer_id for per-customer ordering.
  3. Enricher consumer — at-least-once safe via processed_ids set; invalid schema → DLT.
  4. Window aggregator — tumbling 1-minute windows: window_start = floor(event_time / 60) * 60.
  5. DLT + replay — GET /v1/dlt, POST /v1/dlt/replay for operational recovery pattern.

Pairs with Message Delivery Semantics §25 and Lab 009 outbox.

Build-from-scratch exercise (optional)​

  1. Start 3-broker Docker Compose Kafka with KRaft (--profile full).
  2. Create topic RF=3, produce with keyed messages.
  3. Kill leader broker; observe election and producer errors.
  4. Run 2 consumers in group; add third—watch rebalance.
  5. Enable compaction topic; produce updates same key.
  6. Measure throughput vs linger.ms settings.

26. Knowledge Check​

  1. Ordering guaranteed where? (Single partition.)
  2. Max consumers per group per topic? (Partition count.)
  3. ISR role in writes? (Acks=all waits for ISR.)
  4. Messages removed when? (Retention policy—not on consume.)
  5. Hot partition cause? (Skewed keys.)

27. Flashcards​

#FrontBack
1PartitionOrdered log shard of topic.
2OffsetPosition in partition log.
3ISRIn-sync replica set.
4Consumer groupCooperative partition consumers.
5acks=allWait for ISR persistence.
6Log compactionLatest record per key kept.
7High watermarkReplicated offset boundary.
8RebalancePartition reassignment event.
9KRaftKafka-native metadata quorum.
10LeaderHandles partition reads/writes.

28. Cheat Sheet​

STRUCTURE
Topic → N partitions → RF replicas each
1 leader + followers per partition

WRITE PATH
Producer → leader → ISR replicate → ack

READ PATH
Consumer group → assign partitions → poll → offset

DURABILITY
acks=all + min.insync.replicas≥2 + RF≥3

SCALE
Parallelism ≤ partitions
Key drives partition

OPS ALERTS
Under-replicated partitions
Offline partitions
Consumer lag (per partition)

30. References​

Primary sources​

  • Kreps, J., Narkhede, N., & Rao, J. (2011). "Kafka: A Distributed Messaging System for Log Processing." NetDB — original Kafka paper.
  • Apache Kafka Documentation — Design, Replication.

Engineering blogs​

  • Jay Kreps, "The Log" — log-oriented architecture philosophy.
  • Confluent Documentation — KRaft, producer/consumer tuning.

Distinction​

Claim typeSource
Log structure, replicationKafka design docs; Kreps et al.
Partition scaling guidanceOperational docs; benchmark-dependent
KRaft migrationApache Kafka / Confluent official docs