Apache Kafka¶
Scope: designing topics, producers and consumers for Apache Kafka 4.x, which runs only in KRaft mode (ZooKeeper mode was removed in Kafka 4.0). Shared messaging rules aren't repeated here: publish events together with database changes through a transactional outbox (DATA-4, general/data.md), make operations safe to retry and evolve contracts compatibly (API-1, API-2, general/api-design.md), retry with backoff (OPS-3, general/operations-reliability.md), and say which event-driven pattern you mean (STYLE-8 to STYLE-10, general/architecture-styles.md). For a queue-based broker, see RabbitMQ. Features that only Confluent's products provide are marked as such.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 Apache Kafka documentation (Apache Kafka 4.4): the baseline. The Design chapter, the producer, consumer and topic configuration references, Operations and Security matter most for application work.
- 8 Design (Apache Kafka docs): how producers, consumers, delivery semantics, transactions, share groups, replication and log compaction work, and the guarantees each gives.
- 7 Security (Apache Kafka docs): encryption and authentication with TLS, SASL mechanisms, and authorization with ACLs.
- 7 Basic Kafka Operations (Apache Kafka docs): creating and changing topics, consumer groups, expanding clusters and increasing the replication factor.
- 7 Schema Evolution and Compatibility (Confluent docs): the compatibility types of Confluent Schema Registry, the changes each allows for Avro, Protobuf and JSON Schema, and the order in which to upgrade clients. Schema Registry is a Confluent product under the Confluent Community License.
Key rules¶
Topics and partitions¶
- 8
KAFKA-1Choose each record's key by the ordering you need: records with the same key go to the same partition, and Kafka keeps order only within a partition. Use the ID of the entity whose events must stay in order, such as a customer or order ID. (Apache Kafka, Introduction, Design: load balancing, Confluent, Partitioned Parallelism) - 7
KAFKA-2Choose a topic's partition count when you create it, from the throughput and consumer parallelism you need, with room for growth. A consumer group can't use more consumers than there are partitions, adding partitions sends existing keys to different partitions, and Kafka can't reduce the count. (Apache Kafka, Modifying topics, Confluent, Choose and Change the Partition Count) - 7
KAFKA-3Create topics explicitly with their partition count, replication factor and retention, and turn off automatic topic creation on the brokers. Auto-created topics get the broker defaults, and the default replication factor is 1. (Apache Kafka, Adding and removing topics, Broker configs: auto.create.topics.enable, default.replication.factor) - 6
KAFKA-4Set each topic's cleanup policy and retention on purpose: keep records at least as long as consumers may lag behind or need to replay them, and use compaction (cleanup.policy=compact) for topics where only the latest value per key matters.retention.msdefaults to seven days. On a compacted topic, delete a key with a tombstone: a record with that key and a null value. (Topic configs: retention.ms, cleanup.policy, Design: log compaction)
Producers and durability¶
- 8
KAFKA-5For data you can't afford to lose, use a replication factor of 3,min.insync.replicas=2and produceracks=all, and leave unclean leader election off.min.insync.replicasdefaults to 1, so anacks=allwrite can succeed when only one replica is in sync, and is lost if that replica then fails. (Topic configs: min.insync.replicas, Design: availability and durability guarantees) - 7
KAFKA-6Keep producer idempotence on, and setenable.idempotence=trueexplicitly, so that conflicting settings fail when the producer is created instead of silently turning it off. Idempotence, on by default, stops retries from writing duplicates; it needsacks=all,retriesabove 0 and at most 5 in-flight requests per connection. (Producer configs: enable.idempotence, acks)
Consumers¶
- 8
KAFKA-7Commit offsets only after the records are processed, and make processing idempotent, because after a failure Kafka redelivers the records since the last commit. With automatic commits, finish every record returned by onepollbefore the next; if other threads process the records, turn offenable.auto.commitand commit the offsets they have finished. (Design: message delivery semantics, KafkaConsumer API: manual offset control, microservices.io, Idempotent Consumer) - 7
KAFKA-8Don't let a record that can't be processed block its partition: after a bounded number of retries, write it with the error details to a dead-letter topic and move on. Kafka Connect and Kafka Streams have dead-letter settings built in. Retry topics delay records that may succeed later, but lose per-key ordering, so use them only where order doesn't matter. (Confluent, Error Handling Patterns in Kafka, Apache Kafka, Kafka Connect error reporting, Kafka Streams configs: errors.dead.letter.queue.topic.name, Spring for Apache Kafka, Non-blocking retries) - 6
KAFKA-9Keep the work for eachpollwell withinmax.poll.interval.ms, and lowermax.poll.recordswhen processing is slow. A consumer that doesn't poll in time leaves the group, its partitions are reassigned, and its offset commits fail. (KafkaConsumer API: detecting consumer failures) - 5
KAFKA-10For consume-transform-produce flows between Kafka topics, get exactly-once processing from Kafka Streams or a transactional producer, and read the results withisolation.level=read_committed. Transactions cover only writes to Kafka; when the output goes to another system, store the offsets with the output or rely on idempotent processing. (Design: using transactions, Design: message delivery semantics) - 5
KAFKA-11For queue-style work whose records are independent and need no ordering, consider a share group (production-ready since Kafka 4.2) instead of a consumer group. A share group can have more consumers than partitions, acknowledges each record, and stops delivering a record after a limited number of attempts (5 by default). (Design: the share consumer, Upgrading: notable changes in 4.2.0, Broker configs: group.share.delivery.count.limit)
Schemas¶
- 8
KAFKA-12Give every topic a schema (Avro, Protobuf or JSON Schema) in a schema registry, and enforce a compatibility type for each subject. Confluent Schema Registry defaults toBACKWARD, which lets consumers re-read old records; with it, upgrade consumers before producers. Apicurio Registry, under the Apache License, offers the same compatibility rules. (Confluent, Schema Evolution and Compatibility, Apicurio Registry, Content rule reference) - 7
KAFKA-13Register schemas from CI after a compatibility check, and setauto.register.schemas=falseon producers in production. Producers register new schemas themselves by default, which suits development but lets an untested schema reach production. (Confluent, Schema Registry Best Practices, Schema Registry Maven plugin: test-compatibility)
Security¶
- 8
KAFKA-14Authenticate every connection to the brokers with TLS client certificates or SASL over TLS, turn on theStandardAuthorizer, and give each application its own principal with only the ACLs it needs. Kafka accepts unauthenticated, unencrypted clients unless you configure security, and SASL/PLAIN and SCRAM should only be used over TLS. Don't setallow.everyone.if.no.acl.found=true. (Apache Kafka, Security overview, Authentication using SASL, Authorization and ACLs)
Operations¶
- 7
KAFKA-15Run production clusters with dedicated KRaft controller nodes, usually three or five, rather than nodes that are both broker and controller. Combined mode should be avoided in critical environments. Clusters still on ZooKeeper must migrate to KRaft, using Kafka 3.9 as the bridge release, before they can upgrade to 4.x. (Apache Kafka, KRaft: deploying considerations, KRaft: controllers, Upgrading to 4.0) - 7
KAFKA-16Monitor consumer lag for every consumer group, and the brokers' under-replicated and under-min-ISR partition counts, and alert when lag keeps growing or those counts aren't 0. (Apache Kafka, Monitoring, Checking consumer position)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 Schema Registry Maven plugin (Confluent): in CI,
test-compatibilitychecks the project's schemas against a Schema Registry,test-local-compatibilitychecks them against earlier local versions without a registry, andregisterregisters them. ChecksKAFKA-12, and partlyKAFKA-13. - 7 buf breaking: for Protobuf schemas kept in the repository, compares them in CI with a previous version, such as the main branch, and reports changes that break the wire format or generated code. Partly checks
KAFKA-12. - 5 CreateTopicPolicy (Apache Kafka): a policy class you write and set in
create.topic.policy.class.name; the controller runs it for every topic creation and rejects topics whose replication factor,min.insync.replicasor retention is outside the range you allow. Partly checksKAFKA-3,KAFKA-4andKAFKA-5.
Tutorials and further reading¶
- 6 Apache Kafka 101 (Confluent Developer): a free video course on events, topics, partitions, brokers, replication, producers and consumers.
- 6 Event Streaming Patterns (Confluent Developer): a catalogue of patterns such as Dead Letter Stream, Idempotent Reader and Schema Compatibility, with Kafka examples.
- 6 Quick Start (Apache Kafka docs): start a local Kafka server from the download or the Docker image, create a topic, write and read events, and process them with Kafka Connect and Kafka Streams.