Apache Kafka
medium 34 minApache Kafka is a distributed log for events.
A tiny Kafka
Read it, run it, change a line and run it again.
Loading editor…
A model, not a client: partitions, in-sync copies, the minimum, duplicate detection and group positions. The variants show real clients and commands for Kafka 4.4; they need a running cluster.
The same in Java
import java.time.Duration;import java.util.*;import org.apache.kafka.clients.admin.*;import org.apache.kafka.clients.consumer.*;import org.apache.kafka.clients.producer.*;import org.apache.kafka.common.TopicPartition;import org.apache.kafka.common.config.ConfigResource;/** Needs kafka-clients 4.x and a cluster. */public class KafkaExamples { static final String SERVERS = "kafka1:9092,kafka2:9092,kafka3:9092"; static Properties producerConfig(String transactionalId) { Properties p = new Properties(); p.put("bootstrap.servers", SERVERS); p.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); p.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); p.put("acks", "all"); // default, written down on purpose p.put("enable.idempotence", "true"); // default p.put("batch.size", "32768"); p.put("linger.ms", "20"); p.put("compression.type", "lz4"); p.put("delivery.timeout.ms", "120000"); if (transactionalId != null) p.put("transactional.id", transactionalId); return p; } static Properties consumerConfig(String group) { Properties p = new Properties(); p.put("bootstrap.servers", SERVERS); p.put("group.id", group); p.put("group.protocol", "consumer"); // classic is the default in 4.4 p.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); p.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); p.put("enable.auto.commit", "false"); p.put("auto.offset.reset", "earliest"); p.put("max.poll.records", "500"); p.put("isolation.level", "read_committed"); // p.put("group.instance.id", "orders-0"); // static member return p; } static void produce() { try (Producer<String, String> producer = new KafkaProducer<>(producerConfig(null))) { producer.send(new ProducerRecord<>("orders", "user-123", "{\"orderId\":\"abc\"}"), (meta, error) -> { if (error != null) System.err.println("failed: " + error.getMessage()); else System.out.printf("partition %d offset %d%n", meta.partition(), meta.offset()); }); } // close() sends what is left } static void consumeAtLeastOnce() { try (Consumer<String, String> consumer = new KafkaConsumer<>(consumerConfig("billing"))) { consumer.subscribe(List.of("orders")); while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500)); for (ConsumerRecord<String, String> r : records) handle(r.value()); if (!records.isEmpty()) consumer.commitSync(); // after the work } } } static void readProcessWrite() { Producer<String, String> producer = new KafkaProducer<>(producerConfig("order-processor-1")); Consumer<String, String> consumer = new KafkaConsumer<>(consumerConfig("processor")); producer.initTransactions(); // fences an older copy of this processor consumer.subscribe(List.of("orders-input")); while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500)); if (records.isEmpty()) continue; try { producer.beginTransaction(); Map<TopicPartition, OffsetAndMetadata> next = new HashMap<>(); for (ConsumerRecord<String, String> r : records) { producer.send(new ProducerRecord<>("orders-output", r.key(), handle(r.value()))); next.put(new TopicPartition(r.topic(), r.partition()), new OffsetAndMetadata(r.offset() + 1)); } producer.sendOffsetsToTransaction(next, consumer.groupMetadata()); producer.commitTransaction(); } catch (org.apache.kafka.common.errors.ProducerFencedException fenced) { throw fenced; // a newer copy took over: stop } catch (RuntimeException e) { producer.abortTransaction(); rewind(consumer); // without this the batch is skipped } } } static void rewind(Consumer<String, String> consumer) { Map<TopicPartition, OffsetAndMetadata> saved = consumer.committed(consumer.assignment()); for (TopicPartition tp : consumer.assignment()) { OffsetAndMetadata at = saved.get(tp); if (at != null) consumer.seek(tp, at.offset()); else consumer.seekToBeginning(List.of(tp)); } } static void admin() throws Exception { Properties p = new Properties(); p.put("bootstrap.servers", SERVERS); try (Admin admin = Admin.create(p)) { NewTopic topic = new NewTopic("orders", 12, (short) 3).configs(Map.of( "retention.ms", "604800000", "min.insync.replicas", "2", "cleanup.policy", "delete")); admin.createTopics(List.of(topic)).all().get(); admin.describeTopics(List.of("orders")).allTopicNames().get().get("orders") .partitions().forEach(System.out::println); ConfigResource res = new ConfigResource(ConfigResource.Type.TOPIC, "orders"); admin.incrementalAlterConfigs(Map.of(res, List.of(new AlterConfigOp( new ConfigEntry("retention.ms", "259200000"), AlterConfigOp.OpType.SET)))).all().get(); // lag of one group Map<TopicPartition, OffsetAndMetadata> done = admin.listConsumerGroupOffsets("billing").partitionsToOffsetAndMetadata().get(); Map<TopicPartition, OffsetSpec> ask = new HashMap<>(); done.keySet().forEach(tp -> ask.put(tp, OffsetSpec.latest())); var ends = admin.listOffsets(ask).all().get(); done.forEach((tp, at) -> System.out.println(tp + " lag " + (ends.get(tp).offset() - at.offset()))); } } static String handle(String v) { return "processed: " + v; }}/* Kafka Streams word count, exactly once: props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, StreamsConfig.EXACTLY_ONCE_V2); StreamsBuilder b = new StreamsBuilder(); b.<String, String>stream("text-input") .flatMapValues(line -> Arrays.asList(line.toLowerCase().split("\\W+"))) .groupBy((key, word) -> word) .count(Materialized.as("word-counts-store")) .toStream().to("word-counts", Produced.with(Serdes.String(), Serdes.Long())); Other steps: filter, mapValues, stream.join(other, fn, JoinWindows...), leftJoin(table, fn), groupByKey().windowedBy(TimeWindows.ofSizeWithNoGrace(Duration.ofMinutes(5))).count()*/The same in Python
# pip install confluent-kafka (needs a running cluster)from confluent_kafka import Consumer, OFFSET_BEGINNING, Producer, TopicPartitionSERVERS = "kafka1:9092,kafka2:9092,kafka3:9092"def produce(): producer = Producer({"bootstrap.servers": SERVERS, "acks": "all", "enable.idempotence": True, "linger.ms": 20, "compression.type": "lz4"}) def report(err, msg): print("failed:" if err else "stored:", err or (msg.partition(), msg.offset())) producer.produce("orders", key="user-123", value='{"orderId": "abc"}', on_delivery=report) producer.flush()def consumer(group): return Consumer({"bootstrap.servers": SERVERS, "group.id": group, "enable.auto.commit": False, "auto.offset.reset": "earliest", "isolation.level": "read_committed"})def consume_at_least_once(handle): c = consumer("billing") c.subscribe(["orders"]) try: while True: msg = c.poll(1.0) if msg is None: continue if msg.error(): print(msg.error()) continue handle(msg.value()) c.commit(msg, asynchronous=False) # after the work finally: c.close()def rewind(c): for tp in c.committed(c.assignment()): at = tp.offset if tp.offset >= 0 else OFFSET_BEGINNING c.seek(TopicPartition(tp.topic, tp.partition, at))def read_process_write(handle): p = Producer({"bootstrap.servers": SERVERS, "transactional.id": "order-processor-1"}) c = consumer("processor") p.init_transactions() c.subscribe(["orders-input"]) while True: msgs = [m for m in c.consume(500, 1.0) if not m.error()] if not msgs: continue p.begin_transaction() try: for m in msgs: p.produce("orders-output", key=m.key(), value=handle(m.value())) p.send_offsets_to_transaction(c.position(c.assignment()), c.consumer_group_metadata()) p.commit_transaction() except Exception as e: p.abort_transaction() rewind(c) # or the batch is skipped print("aborted:", e)def lag(c, topic, partitions): total = 0 for tp in c.committed([TopicPartition(topic, p) for p in range(partitions)]): low, high = c.get_watermark_offsets(tp) total += high - (tp.offset if tp.offset >= 0 else low) return totalThe same in Shell
B=kafka1:9092# topicskafka-topics.sh --bootstrap-server $B --create --topic orders \ --partitions 12 --replication-factor 3 \ --config retention.ms=604800000 --config min.insync.replicas=2kafka-topics.sh --bootstrap-server $B --listkafka-topics.sh --bootstrap-server $B --describe --topic orderskafka-topics.sh --bootstrap-server $B --alter --topic orders --partitions 24 # only upwardskafka-configs.sh --bootstrap-server $B --alter --entity-type topics \ --entity-name orders --add-config retention.ms=259200000kafka-configs.sh --bootstrap-server $B --describe --entity-type topics --entity-name orders# try it by hand (4.2 and later: --reader-property, --formatter-property)kafka-console-producer.sh --bootstrap-server $B --topic orders \ --reader-property parse.key=true --reader-property key.separator=:kafka-console-consumer.sh --bootstrap-server $B --topic orders --from-beginning \ --formatter-property print.key=truekafka-console-consumer.sh --bootstrap-server $B --topic orders --group billingkafka-producer-perf-test.sh --topic orders --num-records 1000000 --record-size 1000 \ --throughput -1 --command-property bootstrap.servers=$B --command-property acks=all# groups and lag; stop the group before a reset, and look at --dry-run firstkafka-consumer-groups.sh --bootstrap-server $B --listkafka-consumer-groups.sh --bootstrap-server $B --describe --group billingkafka-consumer-groups.sh --bootstrap-server $B --describe --all-groups --statekafka-consumer-groups.sh --bootstrap-server $B --group billing --topic orders \ --reset-offsets --to-earliest --dry-runkafka-consumer-groups.sh --bootstrap-server $B --group billing --topic orders \ --reset-offsets --to-datetime 2026-01-15T00:00:00.000 --execute# healthkafka-topics.sh --bootstrap-server $B --describe --under-replicated-partitionskafka-topics.sh --bootstrap-server $B --describe --under-min-isr-partitionskafka-topics.sh --bootstrap-server $B --describe --unavailable-partitionskafka-get-offsets.sh --bootstrap-server $B --topic orders --time latestkafka-metadata-quorum.sh --bootstrap-server $B describe --status# balancekafka-leader-election.sh --bootstrap-server $B --election-type preferred --all-topic-partitionskafka-reassign-partitions.sh --bootstrap-server $B \ --reassignment-json-file reassignment.json --execute# transactionskafka-transactions.sh --bootstrap-server $B listkafka-transactions.sh --bootstrap-server $B describe --transactional-id order-processor-1# look inside one segment file, on the brokerkafka-dump-log.sh --files /var/kafka-logs/orders-0/00000000000000000000.log --print-data-log# JMX names to collect# kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions# kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount# kafka.server:type=ReplicaManager,name=IsrShrinksPerSec# kafka.controller:type=KafkaController,name=ActiveControllerCount# kafka.network:type=RequestMetrics,name=TotalTimeMs,request=Produce# kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec# kafka.server:type=BrokerTopicMetrics,name=BytesOutPerSec# producer: record-send-rate, request-latency-avg, batch-size-avg, records-per-request-avg# consumer: records-lag-max, fetch-rate, commit-latency-avgThe same in SQL
-- ksqlDB: a separate product that runs SQL over Kafka topics.CREATE STREAM orders_stream ( order_id VARCHAR KEY, user_id VARCHAR, amount DECIMAL(10,2), ordered_at VARCHAR) WITH ( KAFKA_TOPIC = 'orders', VALUE_FORMAT = 'JSON', TIMESTAMP = 'ordered_at', TIMESTAMP_FORMAT = 'yyyy-MM-dd HH:mm:ss');CREATE TABLE order_counts AS SELECT user_id, COUNT(*) AS order_count, SUM(amount) AS total_amount FROM orders_stream WINDOW TUMBLING (SIZE 1 HOUR) GROUP BY user_id EMIT CHANGES;CREATE TABLE users (user_id VARCHAR PRIMARY KEY, name VARCHAR) WITH (KAFKA_TOPIC = 'users', VALUE_FORMAT = 'JSON');CREATE STREAM enriched_orders AS SELECT o.order_id, o.user_id, u.name, o.amount FROM orders_stream o LEFT JOIN users u ON o.user_id = u.user_id EMIT CHANGES;SELECT * FROM order_counts WHERE user_id = 'user-123'; -- pull: the value nowSELECT * FROM order_counts EMIT CHANGES; -- push: every change