Apache Kafka
Apache Kafka is a distributed event streaming platform designed for high-throughput, durable, ordered message delivery — used for real-time data pipelines, event sourcing at scale, and decoupling services in large systems.
Overview
Kafka stores messages as immutable, ordered logs partitioned across a cluster of brokers. Producers append events to topics; consumers read from specific offsets and commit their progress independently, enabling multiple consumer groups to process the same stream at their own pace. Unlike traditional message queues, messages are retained for a configurable period regardless of consumption — allowing replay, late subscribers, and event sourcing. In .NET, Confluent.Kafka provides the low-level client; MassTransit wraps it with familiar consumer and saga patterns. Azure Event Hubs is a fully managed Kafka-compatible service requiring no infrastructure management.
What you will learn
- Explain topics, partitions, offsets, keys, retention, compaction, and replication.
- Design keys and partitions from ordering, throughput, skew, and growth.
- Configure safe producers and consumer groups.
- Operate commits, rebalances, retries, and poison records.
- Evolve schemas and scope exactly-once guarantees.
- Monitor lag, age, ISR health, storage, and recovery.
Prerequisites
- Distributed logs, serialization, workers, and eventual consistency.
- Networking, storage, replication, security, and capacity basics.
- A real cluster for production verification.
When to use Apache Kafka
Good fit
- Retained high-throughput streams need replay and independent groups.
- Per-key ordering matters.
- The team can operate partitions, schemas, lag, and storage.
Choose another approach when
- A task queue needs flexible routing.
- Global order is mandatory at high parallelism.
- Distributed-log operations are unavailable.
Key concepts
Topics are partitioned append-only logs; offsets identify records and enable independent replay.
Each partition is assigned to one member per group while different groups consume independently.
Time or size retention preserves history; compaction retains the latest record for each key.
Offset timing controls loss or replay; transactions cover Kafka read-process-write but not arbitrary external effects.
Keys select partitions, and ordering is guaranteed only within a partition.
Replication, in-sync replicas, acknowledgements, and leader failover determine durability.
Membership changes reassign partitions and require safe pause, revocation, commit, and resume behavior.
Registries and compatibility policy allow independent producer and consumer evolution.
Architecture
Producers append events to partitioned topics on the Kafka cluster; each consumer group reads independently at its own offset, enabling multiple downstream services to process the same stream without coordination.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The partition lab makes key placement, offsets, group positions, redelivery, and commits executable without claiming to replace a cluster.
- 01Define contracts
Choose schema, key, retention, replay, and ownership.
- 02Size partitions
Estimate throughput, parallelism, skew, and growth.
- 03Configure producers
Set acknowledgements, idempotence, batching, compression, and timeouts.
- 04Build consumers
Bound work, process idempotently, and commit after effects.
- 05Handle failure
Classify retries and isolate poison records.
- 06Evolve schemas
Enforce compatibility and stage consumers first.
- 07Operate recovery
Monitor lag and rehearse rebalance, loss, replay, and restore.
Code example
MassTransit wraps Confluent.Kafka so Kafka consumers use the same IConsumer interface as Service Bus and RabbitMQ consumers — the infrastructure concern is in registration, not in the handler.
using Confluent.Kafka;
using MassTransit;
builder.Services.AddMassTransit(x =>
{
// Kafka is configured as a rider alongside a primary bus.
x.UsingInMemory();
x.AddRider(rider =>
{
rider.AddConsumer<OrderPlacedConsumer>();
rider.UsingKafka((context, kafka) =>
{
kafka.Host("kafka:9092");
kafka.TopicEndpoint<OrderPlaced>(
"order-events",
"orders-consumer-group",
endpoint =>
{
endpoint.AutoOffsetReset = AutoOffsetReset.Earliest;
endpoint.CheckpointMessageCount = 100;
endpoint.CheckpointInterval = TimeSpan.FromSeconds(30);
endpoint.EnableErrorTopic();
endpoint.ConfigureConsumer<OrderPlacedConsumer>(context);
});
});
});
});
public sealed class OrderPlacedConsumer(
ILogger<OrderPlacedConsumer> logger,
IOrderRepository repository)
: IConsumer<OrderPlaced>
{
public async Task Consume(ConsumeContext<OrderPlaced> context)
{
logger.LogInformation("Processing order {OrderId}", context.Message.OrderId);
await repository.MarkAsProcessingAsync(
context.Message.OrderId,
context.CancellationToken);
}
}
public sealed record OrderPlaced(
Guid OrderId,
Guid CustomerId,
DateTime OccurredAt);Testing strategy
Production claims require a real multi-broker environment.
- Prove same-key order and parallelism.
- Crash around effects and commits.
- Trigger rebalances.
- Contract-test schemas.
- Test poison isolation.
- Load-test skew, loss, lag recovery, and storage.
Security considerations
Kafka retains replayable business history.
- Use TLS, identity, networking, and ACLs.
- Authorize and tenant-scope consumers.
- Validate schemas and size.
- Minimize sensitive data.
- Protect registries and admin APIs.
Performance and scalability
Partitioning, batching, and downstream work determine performance.
- Measure per partition.
- Batch and compress.
- Avoid hot keys.
- Keep poll loops responsive.
- Track lag and event age.
Deployment and operations
Clients, schemas, topics, and settings coexist during rollouts.
- Provision topology as code.
- Deploy compatible consumers first.
- Use stable group IDs.
- Stop cooperatively.
- Rehearse loss and restore.
Common problems and fixes
A partition is hot.
Likely cause: Keys are skewed.
Fix: Redesign the key.
Lag rises after scaling.
Likely cause: Consumers exceed partitions or rebalance.
Fix: Inspect assignments.
Records duplicate.
Likely cause: Effects preceded commit.
Fix: Make effects idempotent.
Records disappear.
Likely cause: Commit was early.
Fix: Commit after effects.
Deserialization fails.
Likely cause: Schema is incompatible.
Fix: Enforce compatibility.
Disk fills.
Likely cause: Retention assumptions are wrong.
Fix: Inspect bytes and headroom.
Best practices
- Choose keys from order and skew evidence.
- Commit after idempotent processing.
- Use stable group IDs.
- Enable producer idempotence.
- Enforce schema compatibility.
- Bound consumer work.
- Monitor per partition.
- Test on a real cluster.
Production checklist
- Keys, partitions, order, retention, and replay are documented.
- Producer durability is tested.
- Consumers commit after idempotent effects.
- Rebalances and poison records are handled.
- Schemas are compatible.
- Security and retention meet policy.
- Lag, age, skew, ISR, and storage alert.
- Loss, replay, and restore are rehearsed.
Common interview questions
What limits group parallelism?
The partition count.
What ordering exists?
Only within one partition.
Why redelivery?
The next offset was not committed.
What does exactly-once cover?
Kafka transactions, not arbitrary external effects.
Retention versus compaction?
History removal versus latest record per key.
What is a rebalance?
Partition reassignment among group members.
Why a schema registry?
To enforce compatibility.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Kafka Partition Lab
A deterministic .NET 10 simulator of partitioned append-only logs, key ordering, consumer-group offsets, redelivery, and commit advancement.
- Run
dotnet run --project src/KafkaPartitionLab- Test
dotnet test KafkaPartitionLab.slnx