Apache Kafka cheat sheet
175 commands from every lesson of Apache Kafka — Event Streaming from Basics to a Platform Service, on one page.
Which tool answers which question?
Is the service healthy? How many requests, how slow, how full? | Monitoring: Prometheus + Grafana (metrics) |
What exactly happened in this request? Show me the error | Logging: EFK or Loki (log lines) |
Where did this request spend its time across services? | Tracing: OpenTelemetry + Tempo/Jaeger |
Other systems must react to 'order placed' | Kafka (events) |
Several systems need the same data, now and later | Kafka (events, replay) |
How data gets in
Prometheus | Pulls: scrapes each app's /metrics endpoint every 15–30 s |
EFK | Pushed: Fluent Bit reads log files and sends them to Elasticsearch |
Kafka | Pushed by producers (your code, Fluent Bit, Debezium); consumers pull at their own pace |
Words to know
Event | A fact that happened: 'order 123 was placed'. Immutable once written |
Producer | A program that writes events |
Consumer | A program that reads events, at its own pace |
Topic | A named stream of events, such as orders |
Log | An append-only, ordered list of events kept for a retention period |
Replay | Reading old events again, from any point still retained |
Log or queue?
Many independent readers of the same data | Log (Kafka) |
Need to re-read history | Log (Kafka) |
Hand out tasks to workers, delete when done | Queue (RabbitMQ, SQS) |
Request needs an answer now | Neither: use an API call |
The pieces
Broker | One Kafka server; stores partitions and serves clients |
Cluster | Several brokers working together (3 or more in production) |
Topic | A named stream of records |
Partition | An ordered, append-only log; a topic has one or more |
Offset | A record's position number in its partition |
Consumer group | Consumers sharing the work; each partition goes to one member |
Replication factor | How many brokers hold a copy of each partition |
KRaft controller | Keeps the cluster's metadata; replaced ZooKeeper |
Rules worth memorising
Order | Guaranteed only within one partition |
Same key | Same partition (while the partition count is unchanged) |
Group parallelism | At most one active consumer per partition per group |
Reading | Never deletes data; retention does |
Run Kafka
docker run -d --name kafka -p 9092:9092 apache/kafka:4.1.0 | Single-node KRaft cluster (broker + controller) |
docker exec -it kafka bash | Shell inside; tools are in /opt/kafka/bin |
docker rm -f kafka | Remove it |
Topics
kafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders --partitions 3 --replication-factor 1 | Create a topic |
kafka-topics.sh --bootstrap-server localhost:9092 --list | List topics |
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders | Partitions, leaders, replicas, ISR |
kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name orders --alter --add-config retention.ms=86400000 | Change a topic setting |
kafka-get-offsets.sh --bootstrap-server localhost:9092 --topic orders | Latest offset per partition |
Produce and consume
kafka-console-producer.sh --bootstrap-server localhost:9092 --topic orders --property parse.key=true --property key.separator=: | Type key:value lines |
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders --from-beginning --group billing --property print.key=true --property print.partition=true --property print.offset=true | Read with a group, showing key, partition, offset |
Groups
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list | List groups |
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing | Offsets and lag per partition |
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group billing --topic orders --reset-offsets --to-earliest --execute | Replay from the start (group must be stopped) |
Install and create
helm repo add strimzi https://strimzi.io/charts/ | Add the Strimzi chart repository |
helm install strimzi strimzi/strimzi-kafka-operator --version 1.3.1 -n kafka --create-namespace | Install the operator |
kubectl apply -f kafka-lab.yaml | Create the KafkaNodePool and Kafka resources |
kubectl wait kafka/lab -n kafka --for=condition=Ready --timeout=10m | Wait until the cluster is ready |
kubectl get kafka,kafkanodepool,kafkatopic,pods,pvc,svc -n kafka | See everything Strimzi created |
Use it
k() { kubectl -n kafka exec -it lab-dual-role-0 -- "$@"; } | Helper: run a Kafka CLI tool inside a broker pod |
k bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic orders | Partitions, leaders and ISR |
k bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billing | Group offsets and lag |
lab-kafka-bootstrap.kafka.svc:9092 | The address applications use |
kubectl -n kafka delete pod lab-dual-role-2 | Simulate a broker failure |
Safety
acks=all | Wait until all in-sync replicas have the record (default since Kafka 3.0) |
enable.idempotence=true | No duplicates or reordering from retries (default since 3.0) |
delivery.timeout.ms=120000 | Total time allowed for a send, including retries |
retries (very large by default) | Bounded in practice by delivery.timeout.ms |
Throughput
linger.ms=5..20 | Wait a little to fill bigger batches |
batch.size=65536..262144 | Bytes per partition batch |
compression.type=lz4 or zstd | Smaller requests and disk use |
buffer.memory | Memory for unsent records; send blocks when full |
Test it
kafka-producer-perf-test.sh --topic t --num-records 200000 --record-size 200 --throughput -1 --producer-props bootstrap.servers=localhost:9092 acks=all linger.ms=5 compression.type=lz4 | Measure throughput and latency |
Inspect groups
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group g | Committed offset, end offset and lag per partition |
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group g --members | Members and how many partitions each has |
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group g --state | Coordinator, assignor, state (Stable, PreparingRebalance…) |
Key settings
enable.auto.commit=false + commit after processing | At-least-once you control |
auto.offset.reset=earliest | latest | Where a group with no committed offset starts (default latest) |
max.poll.records=500 | Records returned per poll |
max.poll.interval.ms=300000 | Max time between polls before the member is removed |
session.timeout.ms=45000 | Heartbeat timeout before a member is considered dead |
group.instance.id=pod-name | Static membership: restarts don't trigger rebalances |
group.protocol=consumer | Opt in to the new KIP-848 rebalance protocol (Kafka 4.0+) |
Inspect
kafka-topics.sh --bootstrap-server b:9092 --describe --topic t | Leader, replicas and ISR per partition |
kafka-topics.sh --bootstrap-server b:9092 --describe --under-replicated-partitions | Partitions missing a replica (should be empty) |
kafka-topics.sh --bootstrap-server b:9092 --describe --unavailable-partitions | Partitions with no leader (outage) |
kafka-metadata-quorum.sh --bootstrap-server b:9092 describe --status | KRaft controller leader and voters |
kafka-leader-election.sh --bootstrap-server b:9092 --election-type PREFERRED --all-topic-partitions | Move leadership back to preferred replicas |
The standard durable setup
replication.factor=3 | Three copies on three brokers (in three zones) |
min.insync.replicas=2 | A write needs at least two copies |
acks=all (producer) | Wait for all in-sync copies |
unclean.leader.election.enable=false | Never elect an out-of-date replica (default) |
broker.rack=<zone> | Spread replicas across zones |
Retention
retention.ms=604800000 | Keep 7 days (the default) |
retention.bytes=-1 | Size limit per partition (-1 = none) |
segment.bytes=1073741824 | Roll a new segment at 1 GiB |
segment.ms=604800000 | …or after 7 days |
kafka-configs.sh --bootstrap-server b:9092 --entity-type topics --entity-name t --alter --add-config retention.ms=86400000 | Change retention for one topic |
Compaction
cleanup.policy=compact | Keep the latest record per key |
cleanup.policy=compact,delete | Latest per key, and still drop very old data |
Record with a null value | Tombstone: deletes the key after compaction |
delete.retention.ms=86400000 | How long tombstones stay visible to consumers |
min.cleanable.dirty.ratio=0.5 | How much un-compacted data triggers cleaning |
Guarantees
At-most-once | Commit before processing; may lose, never duplicates |
At-least-once | Commit after processing; never loses, may duplicate (the usual default) |
Exactly-once inside Kafka | Transactions: consume, produce and commit offsets atomically |
Effectively-once end to end | At-least-once delivery + idempotent processing |
Settings
enable.idempotence=true | No duplicates from producer retries (default) |
transactional.id=<stable-name> | Enable transactions; one per producer instance |
isolation.level=read_committed | Consumers skip aborted and unfinished transactions |
processing.guarantee=exactly_once_v2 | Kafka Streams exactly-once |
Compatibility modes
BACKWARD (default) | New schema can read data written with the previous one: upgrade consumers first |
FORWARD | Old schema can read data written with the new one: upgrade producers first |
FULL | Both directions: upgrade in any order |
*_TRANSITIVE | Check against all previous versions, not just the last |
NONE | No checks: avoid for shared topics |
Safe changes (Avro, BACKWARD)
Add a field with a default | Safe |
Remove a field | Safe for BACKWARD (readers ignore it); breaks FORWARD unless it had a default |
Rename a field | Breaking (use an alias, or add new + deprecate old) |
Change a field's type | Breaking, except a few widening promotions such as int → long |
Registry API
GET /subjects | List subjects |
GET /subjects/orders-value/versions/latest | Latest schema for the orders value |
POST /compatibility/subjects/orders-value/versions/latest | Test a new schema before registering |
PUT /config/orders-value {"compatibility":"FULL"} | Set the mode for one subject |
Kafka Connect REST API (port 8083)
GET /connector-plugins | Installed connector types |
POST /connectors (JSON config) | Create a connector |
GET /connectors/<name>/status | Connector and task state (RUNNING, FAILED) |
POST /connectors/<name>/restart?includeTasks=true&onlyFailed=true | Restart failed tasks |
PUT /connectors/<name>/pause | Pause a connector |
Useful connector settings
tasks.max | Parallelism for this connector |
errors.tolerance=all | Don't stop on a bad record… |
errors.deadletterqueue.topic.name=<topic> | …send it here instead (sink connectors) |
transforms=… | Single message transforms: rename, mask, route |
Choosing a processor
Kafka Streams | A Java library inside your service; Kafka in, Kafka out |
Apache Flink | A separate cluster; large state, many sources, SQL, event time |
Plain consumer | Simple per-record logic |
Strimzi resources
Kafka | The cluster: version, listeners, authorization, config, operators |
KafkaNodePool | A group of nodes with roles (controller, broker), replicas, storage, resources |
KafkaTopic | A topic as a Kubernetes resource (Topic Operator) |
KafkaUser | A client identity, ACLs and quotas (User Operator) |
KafkaConnect / KafkaConnector | Connect cluster and connectors |
KafkaMirrorMaker2 | Replication between clusters |
KafkaRebalance | Cruise Control rebalancing proposal |
Everyday commands
kubectl get kafka,kafkanodepool -n kafka | Cluster status and pools |
kubectl get kafkatopic,kafkauser -n kafka | Topics and users with READY state |
kubectl describe kafkatopic orders.events -n kafka | Conditions explain why something is not ready |
kubectl -n kafka exec platform-dual-role-0 -- bin/kafka-topics.sh --bootstrap-server localhost:9092 --list | Run CLI tools inside a broker pod (needs a plain listener or a client config) |
kubectl annotate kafka platform strimzi.io/manual-rolling-update=true -n kafka | Ask the operator for a safe rolling restart |
Client security settings
security.protocol=SSL + ssl.keystore.* + ssl.truststore.* | TLS with a client certificate (mTLS) |
security.protocol=SASL_SSL + sasl.mechanism=SCRAM-SHA-512 | Username and password over TLS |
security.protocol=SASL_SSL + sasl.mechanism=OAUTHBEARER | OAuth/OIDC tokens over TLS |
kafka-topics.sh --command-config client.properties … | Use those settings with admin tools |
ACLs
kafka-acls.sh --bootstrap-server b:9093 --command-config admin.properties --list | List ACLs |
kafka-acls.sh … --add --allow-principal User:orders-svc --operation Write --operation Describe --topic orders. --resource-pattern-type prefixed | Let a service write to its own prefix |
kafka-acls.sh … --add --allow-principal User:billing-svc --operation Read --group billing. --resource-pattern-type prefixed | Let a service use its own consumer groups |
Quotas
kafka-configs.sh … --alter --add-config producer_byte_rate=1048576,consumer_byte_rate=2097152 --entity-type users --entity-name orders-svc | Per-user byte-rate limits |
kafka-configs.sh … --describe --entity-type users --entity-name orders-svc | Show a user's quotas |
Alerts that matter
OfflinePartitionsCount > 0 | Partitions with no leader: data unavailable (page) |
UnderMinIsrPartitionCount > 0 | Writes with acks=all are being refused (page) |
ActiveControllerCount: sum != 1 | No (or split) controller (page) |
UnderReplicatedPartitions > 0 for 5–10 min | One failure away from trouble |
Consumer lag in time > SLO | A consumer group is falling behind |
Disk used > 75–80% on any broker | Brokers stop when the disk fills |
RequestHandlerAvgIdlePercent < 30% | Brokers are saturated |
Diagnose
kafka-topics.sh --bootstrap-server b:9092 --describe --under-replicated-partitions | Which partitions are missing replicas |
kafka-topics.sh --bootstrap-server b:9092 --describe --unavailable-partitions | Partitions with no leader |
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group g | Lag per partition, and which member owns it |
kafka-log-dirs.sh --bootstrap-server b:9092 --describe --topic-list t | Partition sizes per broker and disk |
kafka-metadata-quorum.sh --bootstrap-server b:9092 describe --status | Controller quorum health |
kafka-broker-api-versions.sh --bootstrap-server b:9092 | Can I reach every broker? What versions? |
Sizing formulas
Storage = write MB/s × retention seconds × RF × (1 + headroom) | Disk across the cluster |
Network in = write MB/s × RF | Produce plus replication into brokers |
Network out = write MB/s × (RF − 1 + consumer groups) | Replication plus consumer fan-out |
Partitions ≥ max(target MB/s ÷ per-partition MB/s, consumers needed) | Partition count for a topic |
Benchmark
kafka-producer-perf-test.sh --topic t --num-records 1000000 --record-size 1000 --throughput -1 --producer-props bootstrap.servers=b:9092 acks=all | Maximum producer throughput |
kafka-consumer-perf-test.sh --bootstrap-server b:9092 --topic t --messages 1000000 | Consumer throughput |
DR
KafkaMirrorMaker2 (Strimzi) / connect-mirror-maker.sh | Replicate topics, configs and offsets between clusters |
replication.policy.class=IdentityReplicationPolicy | Keep topic names (no 'source.' prefix) for active-passive |
RPO ≈ replication lag; RTO ≈ time to switch clients | What you can promise |
The platform contract
Naming: <domain>.<team>.<event>.v<N> | Drives prefix ACLs, ownership and dashboards |
Topic request = a pull request (KafkaTopic / Terraform) | Reviewed, audited, repeatable |
One identity per service (KafkaUser / IAM role) | ACLs and quotas per service |
Guardrails at CI and admission | RF 3, min ISR 2, partition and retention limits, owner label |
Schema required, compatibility checked in CI | No breaking changes reach consumers |
Golden-path template | Producer/consumer with retries, DLQ, idempotence, tracing, dashboards |
Showback per team | Bytes in, bytes out, storage, partitions |