What the log guarantees, and what it does not
Kafka is an append-only, partitioned, replicated log. Producers append records, each partition orders them with a monotonically increasing offset, and consumers read at their own pace from a cursor they control. Nothing is deleted when it is consumed, which is the property that separates Kafka from a classic message broker: retention is a time or size policy, not a delivery acknowledgement, and any consumer can rewind and replay history that other consumers already read.
That freedom comes with a boundary worth stating precisely. Kafka guarantees ordering within one partition and says nothing about ordering across partitions. Durability is a replication question, not a message-acknowledgement question: a write is durable when enough in-sync replicas have flushed it. And "exactly once" is not a magic switch â it is a combination of idempotent producer writes, transactional commits, and consumers that only read committed offsets. Get one of the three wrong and you are back to at-least-once with extra steps.
By the end of this lesson you should be able to size a topic, pick a partition key from an ordering requirement rather than a guess, and explain to a teammate exactly which failures your chosen acks setting does and does not cover.
Partition keys decide who sees what, in what order
The partitioner is where architecture meets data shape. With a null key, records round-robin across partitions, which spreads load evenly but scatters every entity's history. With a key, a hash of the key picks the partition, so every record for a given user, order, or device lands in the same partition and is read in write order by a single consumer. The trade-off is skew: a hot key funnels an entire workload through one partition while two others sit idle.
| Requirement | Key choice | Result | Risk to watch |
|---|---|---|---|
| Per-entity ordering | Entity id | All records for one entity share a partition | Hot keys concentrate load |
| Even throughput, no ordering | None | Round-robin distribution | Global order is lost |
| Geographic locality | Region code | Records cluster by region | Uneven regional volume |
| Downstream co-partitioning | Same key as join partner | Joins work without a repartition | Key changes break the layout |
| Compacted state topic | Entity id | Latest value per key survives compaction | Retention must allow compaction |
Two operational rules follow from this design. Partition count can be increased but never safely decreased, because consumers hold positions relative to existing partitions and a shrink strands data. Increasing the count also re-hashes key â partition assignments, which quietly breaks per-key ordering for existing topics. Decide the count from peak throughput and desired consumer parallelism, then treat it as frozen.
Consumer groups and the rebalance arithmetic
A consumer group is a set of instances that share one offset log per partition, and Kafka assigns each partition to exactly one member. If a topic has eight partitions and the group has three consumers, the assignment comes out 3/3/2, so throughput is capped at three concurrent readers no matter how many instances you add. More consumers than partitions buys nothing except rebalance churn: extra members sit idle, and every join or leave stops the world briefly while ownership is redistributed.
Rebalances are the operational cost of elasticity. During one, all members pause until the protocol completes, so long-running batches inside poll() extend the pause and risk a session timeout, which triggers yet another rebalance. Static group membership mitigates the common case: give each instance a stable group.instance.id and a temporary network blip no longer forces a full redistribution.
from kafka import KafkaConsumer
import json
consumer = KafkaConsumer(
"orders.events",
bootstrap_servers=["broker-1:9092", "broker-2:9092"],
group_id="order-enrichment",
auto_offset_reset="earliest",
enable_auto_commit=False, # commit only after the work is done
max_poll_records=300,
max_poll_interval_ms=300000, # batch must finish inside this window
session_timeout_ms=10000,
group_instance_id="order-enrichment-01",
value_deserializer=lambda b: json.loads(b.decode("utf-8")),
)
for record in consumer:
enrich(record.value) # raises on failure: offsets stay put
consumer.commit() # acknowledged only after success
Notice what enable_auto_commit=False buys. Auto-commit records positions on a timer regardless of whether your handler finished, so a crash between commit and completion loses the record. Manual commit after the handler gives at-least-once: the window where a crash duplicates work is far smaller than the window where it loses work, and deduplication downstream is cheap.
Producing for durability without destroying throughput
Producer configuration is a negotiation between latency, throughput, and durability. acks=0 fires and forgets. acks=1 waits for the partition leader only, so a leader failure after acknowledgement loses the record. acks=all waits for every in-sync replica, and combined with min.insync.replicas=2 the write fails unless at least two replicas hold it â which is what survives a broker dying mid-write.
| Setting | Durability | Latency | When it fits |
|---|---|---|---|
acks=0 | None | Lowest | Metrics where loss is acceptable |
acks=1 | Leader only | Low | High-volume telemetry with tolerant consumers |
acks=all, min.insync.replicas=1 | Whole ISR, but ISR of 1 | Medium | Dev clusters |
acks=all, min.insync.replicas=2 | At least two replicas | Medium-high | Default for production events |
| Idempotent producer on top | No duplicates on retry | Small overhead | Any at-least-once pipeline |
Idempotence deserves its own note. With enable_idempotence=True, the broker deduplicates producer retries using a sequence number per partition, so a retried batch cannot double-write. It also constrains you: acks are forced to all and in-flight requests are bounded, which is a feature rather than a limitation for anything that feeds a ledger.
from kafka import KafkaProducer
import json, time, uuid
def build_event(order_id, amount):
return {
"event_id": str(uuid.uuid4()),
"event_type": "order_created",
"order_id": order_id,
"amount": amount,
"emitted_at": time.time(),
}
producer = KafkaProducer(
bootstrap_servers=["broker-1:9092", "broker-2:9092"],
acks="all",
enable_idempotence=True,
compression_type="snappy",
linger_ms=20,
batch_size=32768,
retries=10,
retry_backoff_ms=100,
value_serializer=lambda v: json.dumps(v).encode("utf-8"),
key_serializer=lambda k: k.encode("utf-8") if k else None,
)
future = producer.send(
"orders.events",
key="ORD-78421", # ordering per order
value=build_event("ORD-78421", 249.99),
)
metadata = future.get(timeout=10) # blocks until ISR acks arrive
print(f"{metadata.topic}[{metadata.partition}]@{metadata.offset}")
producer.flush()
linger_ms and batch_size are the throughput levers: waiting twenty milliseconds lets the producer fill a 32 KB batch, which amortises the round trip across hundreds of records. For a payments topic you would push linger down and rely on idempotence; for clickstream you would push it up and ride the batch.
Consumer lag, retention, and the data-loss window
Lag is the distance between the log head and a consumer's committed position, summed across partitions. It is the health metric that matters, because lag interacts with retention in a way nobody notices until it is too late: if lag exceeds the retention window, records are deleted before the slow consumer reaches them and the loss is permanent and silent. Alerting on "lag is high" is therefore not enough; alert when projected lag approaches retention time.
Practical mitigation is a combination of capacity and discipline. Add partitions or instances when lag trends upward under steady load, cap max_poll_records so a single batch always finishes inside max.poll.interval.ms, and push heavy work out of the poll loop into a bounded worker pool. A consumer that spends two seconds per record inside the loop will trip the interval, get kicked from the group, and hand its partitions to a peer that now has to replay them.
When Kafka is the wrong tool
Kafka shines when you have multiple independent consumers, need replay, or are building an event-sourced system where the log is the source of truth. It is the wrong choice for a simple request-response handoff, for workloads where every message must be processed exactly once by exactly one consumer with no idempotency story, or for small teams that cannot operate a cluster â a managed queue with a day of setup beats a bespoke cluster nobody monitors.
Retention policy closes the loop. Time-based retention suits analytics topics where consumers are expected to keep up; size-based retention suits state topics where only the current picture matters; log compaction retains the latest value per key and turns a topic into a rebuildable materialised view. Choose deliberately, because retention is the deadline against which every consumer outage is measured.
đĄA quick durability check
Ask three questions about any topic: how many replicas must acknowledge a write, what happens to ordering if the partition leader moves, and how long a consumer may fall behind before records expire. If any answer is unclear, the topic is not production-ready.
Common Mistakes
Choosing a partition count from today's throughput and expecting to shrink it later
Fix: Size from peak plus consumer parallelism, then treat the count as append-only
Relying on auto-commit so offsets advance before processing finishes
Fix: Commit manually after the handler succeeds and deduplicate with event ids
Using a random key while still promising per-customer ordering
Fix: Key on the entity whose order you promised; accept the skew or shard the hot key
Never checking lag against retention
Fix: Alert when projected time-to-loss approaches the retention window, not just on absolute lag
Best Practices
- Run acks=all with min.insync.replicas=2 for anything that feeds a ledger or bill
- Enable idempotent producers so retries cannot duplicate writes
- Give every topic an owner and document its key, retention, and schema
- Use static group membership to survive blips without a full rebalance
- Register schemas with a registry and evolve them compatibly rather than reparsing free-form JSON
Interview Questions
Q1: Does Kafka guarantee global ordering?
No. Ordering is guaranteed only within a partition. Global order requires a single partition, which caps throughput to one reader.
Q2: What does min.insync.replicas actually protect against?
It forces a write to be held by at least that many replicas before acking, so the loss of one broker cannot lose a record that was reported as durable.
Q3: Why can more consumers than partitions hurt?
Extra members own no partitions, sit idle, and add rebalance work every time the group changes.
Q4: At-least-once versus exactly-once in practice?
At-least-once duplicates on retry or rebalance; exactly-once adds idempotent writes plus transactional offset commits so an input record produces one output record.
Key Takeaways
- Ordering exists per partition, so the key choice is an ordering decision before it is a performance one
- acks=all with min.insync.replicas=2 and an idempotent producer is the durable production baseline
- Manual offset commits after successful processing give at-least-once with a small duplication window
- Consumer throughput is capped by partition count, and lag must be read against retention to spot real loss risk
- Retention and compaction are policies per topic: choose them from the consumer contract, not by default