Skip to content

AxonOps — AI-Native Control Plane for Open Source Data Platforms

Kafka Topics

Topics are the fundamental unit of organization in Kafka. The topic architecture directly addresses the core problems Kafka was designed to solve: horizontal scalability through partitioning and high availability through replication.

A Kafka topic is a named, partitioned, append-only log that represents a logical stream of records. Producers write records to a topic, and consumers read records from a topic. A topic MUST provide:

  • A stable name used by producers and consumers to identify the stream.
  • Partitioned storage, where each partition is an ordered log.
  • Offset-based addressing, where each record has a unique offset within its partition.
  • Retention control, where records are retained for a configured time or size (or compacted by key).

Topics define the behavioral contract between producers and consumers: ordering is guaranteed within a partition, but not across partitions; durability and availability depend on replication configuration; and retention defines how long records remain readable.


Traditional message queues impose fundamental constraints: a single queue creates a throughput ceiling, and broker failure causes data loss or unavailability. Kafka's topic architecture eliminates both limitations.

ConstraintTraditional QueueKafka Topic
ThroughputSingle broker bottleneckPartitions distribute across brokers
AvailabilitySingle point of failureReplicas on multiple brokers
ScalingVertical onlyHorizontal via partition count
RetentionDeleted after consumptionConfigurable time/size-based retention

Partitions are the unit of parallelism in Kafka. A single log cannot scale beyond one broker's capacity—partitioning solves this by splitting a topic into independent segments that can be distributed across the cluster.

The partition count is specified when creating a topic and determines the topic's maximum parallelism. Each partition is an ordered, append-only sequence of records stored on a single broker. By distributing partitions across brokers:

  • Write throughput scales horizontally: Producers write to different partitions in parallel
  • Read throughput scales horizontally: Consumers in a group read from different partitions in parallel
  • Storage scales horizontally: Each broker stores only a subset of the topic's data
  • Failure isolation improves: A broker failure affects only its partitions, not the entire topic
GuaranteeScopeBehavior
OrderingWithin partitionRecords must be read in the order written
OrderingAcross partitionsUndefined—no ordering relationship exists between partitions
ImmutabilityRecordRecords must not be modified after being written
Offset assignmentPartitionOffsets must be sequential integers starting from 0
Offset uniquenessPartitionEach offset must be assigned to exactly one record

Undefined Behavior

The relative ordering of records across different partitions is undefined and must not be relied upon. A consumer reading from multiple partitions may observe records in any interleaving. Applications requiring total ordering must use a single partition.

When a record key is provided, the default partitioner guarantees:

partition = murmur2(keyBytes) & 0x7FFFFFFF % numPartitions
ConditionGuarantee
Same key, same partition countRecords must be assigned to the same partition
Same key, different partition countPartition assignment is undefined
Null key (Kafka 2.4+)Sticky partitioning—records batch to one partition until batch.size or linger.ms triggers send
Null key (pre-2.4)Round-robin distribution across available partitions

Partition Count Changes

Increasing partition count changes the key-to-partition mapping. Records with the same key may be assigned to different partitions before and after the change. Applications depending on key-based ordering must either:

  • Never increase partition count
  • Drain the topic before increasing partitions
  • Accept ordering discontinuity during transition

The partition count must be chosen at topic creation. It may be increased but must not be decreased without recreating the topic.

FactorGuidance
Consumer parallelismPartition count should be ≥ expected consumer count
ThroughputEach partition adds ~10 MB/s write capacity (rule-of-thumb; varies by hardware)
Ordering requirementsFewer partitions = broader ordering scope
Broker memoryEach partition consumes ~1-2 MB of broker heap (rule-of-thumb)
Recovery timeMore partitions increases leader election and rebalance time

Each partition may be replicated across multiple brokers. Replication provides fault tolerance—the cluster continues operating when brokers fail.

RoleBehavior
LeaderMust handle all produce and consume requests for the partition
FollowerMust replicate records from leader; serving client reads requires replica.selector.class
ISR memberFollower that has fully caught up with the leader within replica.lag.time.max.ms

Changed in Kafka 2.4 (KIP-392): Followers may serve read requests when replica.selector.class is configured.

ConstraintBehavior
MinimumReplication factor must be ≥ 1
MaximumReplication factor must be ≤ broker count
ModificationReplication factor may be changed via partition reassignment

Durability depends on the producer's acks setting and the topic's min.insync.replicas:

acksmin.insync.replicasGuarantee
0AnyNo durability—record may be lost before any broker persists it
1AnyLeader must persist before acknowledging; data lost if leader fails before replication
all1Leader must persist; equivalent to acks=1
all2At least 2 replicas (including leader) must persist before acknowledging
allNAt least N replicas must persist; produces fail if ISR < N

ISR Shrinkage

When ISR size falls below min.insync.replicas, producers with acks=all receive NotEnoughReplicasException. The topic remains readable but writes are blocked until ISR recovers.

Replication FactorTolerated FailuresProduction Suitability
10Development only—must not be used in production
21Minimal production; single failure causes unavailability during leader election
32Standard production; recommended minimum
54Critical data requiring extended failure tolerance

Kafka retains records based on time, size, or key-based compaction. Retention is configured per-topic and enforced per-partition.

Policycleanup.policyBehavior
DeletedeleteSegments older than retention.ms or exceeding retention.bytes are deleted
CompactcompactOnly the latest record per key is retained; older duplicates are removed
Bothdelete,compactCompaction runs first; then time/size-based deletion applies
ConfigurationDefaultGuarantee
retention.ms604800000 (7d)Records older than this value may be deleted
retention.bytes-1 (unlimited)Per-partition; oldest segments deleted when exceeded
segment.ms604800000 (7d)Active segment rolls after this interval
segment.bytes1073741824 (1GB)Active segment rolls when size exceeded

Retention Timing

Retention applies to closed segments only. The active segment is not eligible for deletion regardless of age or size until it rolls.

For topics with cleanup.policy=compact:

GuaranteeBehavior
Latest valueThe most recent record for each key must be retained
OrderingRecord order within a key must be preserved
Tombstone retentionTombstones (null values) must be retained for at least delete.retention.ms
Head of logRecords in the active segment are not eligible for compaction

Compaction Timing

Compaction is not immediate. Records may exist in duplicate until the log cleaner processes the segment. Applications must not assume instantaneous compaction.

ConfigurationDefaultPurpose
min.cleanable.dirty.ratio0.5Minimum dirty/total ratio before compaction eligible
min.compaction.lag.ms0Minimum time before record eligible for compaction
max.compaction.lag.msMaximum time before compaction is forced
delete.retention.ms86400000 (1d)Tombstone retention period

Topic names must conform to the following constraints:

ConstraintRule
LengthMust be 1-249 characters
CharactersMust contain only [a-zA-Z0-9._-]
Reserved prefixesNames starting with __ are reserved for internal topics
UniquenessMust be unique within the cluster

Period and Underscore Collision

Kafka uses . and _ interchangeably in some metric names. Topics my.topic and my_topic may collide in metrics. A cluster should use one convention consistently.


Kafka creates and manages internal topics for cluster operations. These topics must not be modified directly.

TopicPurposeCreated By
__consumer_offsetsConsumer group offset storageKafka (automatic)
__transaction_stateTransaction coordinator stateKafka (automatic)
_schemasSchema storageSchema Registry
connect-offsetsConnector offset trackingKafka Connect
connect-configsConnector configurationsKafka Connect
connect-statusConnector and task statusKafka Connect

When a partition leader fails:

  1. Controller detects failure via ZooKeeper session timeout (ZK mode) or heartbeat timeout (KRaft mode)
  2. Controller selects new leader from ISR
  3. New leader must have all committed records
  4. Producers receive NotLeaderOrFollowerException and must refresh metadata
  5. In-flight requests with acks=all may timeout; clients should retry (or see NotLeaderForPartition on older clients)
ScenarioOutcome
ISR contains eligible replicasNew leader elected; brief unavailability during election
ISR empty, unclean.leader.election.enable=falsePartition unavailable until replica recovers
ISR empty, unclean.leader.election.enable=trueData loss possible; out-of-sync replica becomes leader

Unclean Leader Election

Setting unclean.leader.election.enable=true allows data loss. An out-of-sync replica may become leader, discarding records not yet replicated. This setting should remain false for production topics.

Failure ModeImpact
Single broker, RF ≥ 2Affected partitions elect new leaders; cluster remains available
Multiple brokers, failures < RFCluster remains available if each partition has ≥ 1 ISR member
Failures ≥ RF for any partitionAffected partitions become unavailable

FeatureMinimum VersionNotes
Topic creation via Admin API0.10.1.0kafka-topics.sh available earlier
Log compaction0.8.1
Follower fetching (KIP-392)2.4.0Requires replica.selector.class configuration
Tiered storage (KIP-405)3.6.0Early access; production readiness varies
KRaft mode (no ZooKeeper)3.3.0Production-ready in 3.3+; recommended in 3.6+

ConfigurationDefaultDescription
partitions1Number of partitions
replication.factor-Number of replicas (broker default: default.replication.factor)
min.insync.replicas1Minimum ISR for acks=all produces
ConfigurationDefaultDescription
retention.ms604800000Time-based retention (ms)
retention.bytes-1Size-based retention per partition (-1 = unlimited)
cleanup.policydeletedelete, compact, or delete,compact
ConfigurationDefaultDescription
segment.bytes1073741824Segment file size
segment.ms604800000Time before rolling segment
segment.index.bytes10485760Index file size
ConfigurationDefaultDescription
min.cleanable.dirty.ratio0.5Dirty ratio threshold for compaction
min.compaction.lag.ms0Minimum age before compaction
max.compaction.lag.ms-Maximum age before forced compaction
delete.retention.ms86400000Tombstone retention