Cheat Sheets / Data & Event Streaming

Apache Kafka cheat sheet

175 commands from every lesson of Apache Kafka — Event Streaming from Basics to a Platform Service, on one page.

01 · Kafka, EFK and monitoring: who does what

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 errorLogging: 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 laterKafka (events, replay)

How data gets in

PrometheusPulls: scrapes each app's /metrics endpoint every 15–30 s
EFKPushed: Fluent Bit reads log files and sends them to Elasticsearch
KafkaPushed by producers (your code, Fluent Bit, Debezium); consumers pull at their own pace

02 · Why event streaming

Words to know

EventA fact that happened: 'order 123 was placed'. Immutable once written
ProducerA program that writes events
ConsumerA program that reads events, at its own pace
TopicA named stream of events, such as orders
LogAn append-only, ordered list of events kept for a retention period
ReplayReading old events again, from any point still retained

Log or queue?

Many independent readers of the same dataLog (Kafka)
Need to re-read historyLog (Kafka)
Hand out tasks to workers, delete when doneQueue (RabbitMQ, SQS)
Request needs an answer nowNeither: use an API call

03 · Core concepts

The pieces

BrokerOne Kafka server; stores partitions and serves clients
ClusterSeveral brokers working together (3 or more in production)
TopicA named stream of records
PartitionAn ordered, append-only log; a topic has one or more
OffsetA record's position number in its partition
Consumer groupConsumers sharing the work; each partition goes to one member
Replication factorHow many brokers hold a copy of each partition
KRaft controllerKeeps the cluster's metadata; replaced ZooKeeper

Rules worth memorising

OrderGuaranteed only within one partition
Same keySame partition (while the partition count is unchanged)
Group parallelismAt most one active consumer per partition per group
ReadingNever deletes data; retention does

04 · Lab: your first Kafka cluster

Run Kafka

docker run -d --name kafka -p 9092:9092 apache/kafka:4.1.0Single-node KRaft cluster (broker + controller)
docker exec -it kafka bashShell inside; tools are in /opt/kafka/bin
docker rm -f kafkaRemove it

Topics

kafka-topics.sh --bootstrap-server localhost:9092 --create --topic orders --partitions 3 --replication-factor 1Create a topic
kafka-topics.sh --bootstrap-server localhost:9092 --listList topics
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic ordersPartitions, leaders, replicas, ISR
kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name orders --alter --add-config retention.ms=86400000Change a topic setting
kafka-get-offsets.sh --bootstrap-server localhost:9092 --topic ordersLatest 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=trueRead with a group, showing key, partition, offset

Groups

kafka-consumer-groups.sh --bootstrap-server localhost:9092 --listList groups
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billingOffsets and lag per partition
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group billing --topic orders --reset-offsets --to-earliest --executeReplay from the start (group must be stopped)

05 · Lab: Kafka on your Kubernetes cluster

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-namespaceInstall the operator
kubectl apply -f kafka-lab.yamlCreate the KafkaNodePool and Kafka resources
kubectl wait kafka/lab -n kafka --for=condition=Ready --timeout=10mWait until the cluster is ready
kubectl get kafka,kafkanodepool,kafkatopic,pods,pvc,svc -n kafkaSee 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 ordersPartitions, leaders and ISR
k bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group billingGroup offsets and lag
lab-kafka-bootstrap.kafka.svc:9092The address applications use
kubectl -n kafka delete pod lab-dual-role-2Simulate a broker failure

06 · Producers in depth

Safety

acks=allWait until all in-sync replicas have the record (default since Kafka 3.0)
enable.idempotence=trueNo duplicates or reordering from retries (default since 3.0)
delivery.timeout.ms=120000Total time allowed for a send, including retries
retries (very large by default)Bounded in practice by delivery.timeout.ms

Throughput

linger.ms=5..20Wait a little to fill bigger batches
batch.size=65536..262144Bytes per partition batch
compression.type=lz4 or zstdSmaller requests and disk use
buffer.memoryMemory 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=lz4Measure throughput and latency

07 · Consumers and consumer groups

Inspect groups

kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group gCommitted offset, end offset and lag per partition
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group g --membersMembers and how many partitions each has
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group g --stateCoordinator, assignor, state (Stable, PreparingRebalance…)

Key settings

enable.auto.commit=false + commit after processingAt-least-once you control
auto.offset.reset=earliest | latestWhere a group with no committed offset starts (default latest)
max.poll.records=500Records returned per poll
max.poll.interval.ms=300000Max time between polls before the member is removed
session.timeout.ms=45000Heartbeat timeout before a member is considered dead
group.instance.id=pod-nameStatic membership: restarts don't trigger rebalances
group.protocol=consumerOpt in to the new KIP-848 rebalance protocol (Kafka 4.0+)

08 · Replication and durability

Inspect

kafka-topics.sh --bootstrap-server b:9092 --describe --topic tLeader, replicas and ISR per partition
kafka-topics.sh --bootstrap-server b:9092 --describe --under-replicated-partitionsPartitions missing a replica (should be empty)
kafka-topics.sh --bootstrap-server b:9092 --describe --unavailable-partitionsPartitions with no leader (outage)
kafka-metadata-quorum.sh --bootstrap-server b:9092 describe --statusKRaft controller leader and voters
kafka-leader-election.sh --bootstrap-server b:9092 --election-type PREFERRED --all-topic-partitionsMove leadership back to preferred replicas

The standard durable setup

replication.factor=3Three copies on three brokers (in three zones)
min.insync.replicas=2A write needs at least two copies
acks=all (producer)Wait for all in-sync copies
unclean.leader.election.enable=falseNever elect an out-of-date replica (default)
broker.rack=<zone>Spread replicas across zones

09 · Storage, retention and compaction

Retention

retention.ms=604800000Keep 7 days (the default)
retention.bytes=-1Size limit per partition (-1 = none)
segment.bytes=1073741824Roll 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=86400000Change retention for one topic

Compaction

cleanup.policy=compactKeep the latest record per key
cleanup.policy=compact,deleteLatest per key, and still drop very old data
Record with a null valueTombstone: deletes the key after compaction
delete.retention.ms=86400000How long tombstones stay visible to consumers
min.cleanable.dirty.ratio=0.5How much un-compacted data triggers cleaning

10 · Delivery guarantees and exactly-once

Guarantees

At-most-onceCommit before processing; may lose, never duplicates
At-least-onceCommit after processing; never loses, may duplicate (the usual default)
Exactly-once inside KafkaTransactions: consume, produce and commit offsets atomically
Effectively-once end to endAt-least-once delivery + idempotent processing

Settings

enable.idempotence=trueNo duplicates from producer retries (default)
transactional.id=<stable-name>Enable transactions; one per producer instance
isolation.level=read_committedConsumers skip aborted and unfinished transactions
processing.guarantee=exactly_once_v2Kafka Streams exactly-once

11 · Schemas and Schema Registry

Compatibility modes

BACKWARD (default)New schema can read data written with the previous one: upgrade consumers first
FORWARDOld schema can read data written with the new one: upgrade producers first
FULLBoth directions: upgrade in any order
*_TRANSITIVECheck against all previous versions, not just the last
NONENo checks: avoid for shared topics

Safe changes (Avro, BACKWARD)

Add a field with a defaultSafe
Remove a fieldSafe for BACKWARD (readers ignore it); breaks FORWARD unless it had a default
Rename a fieldBreaking (use an alias, or add new + deprecate old)
Change a field's typeBreaking, except a few widening promotions such as int → long

Registry API

GET /subjectsList subjects
GET /subjects/orders-value/versions/latestLatest schema for the orders value
POST /compatibility/subjects/orders-value/versions/latestTest a new schema before registering
PUT /config/orders-value {"compatibility":"FULL"}Set the mode for one subject

12 · Kafka Connect, CDC and stream processing

Kafka Connect REST API (port 8083)

GET /connector-pluginsInstalled connector types
POST /connectors (JSON config)Create a connector
GET /connectors/<name>/statusConnector and task state (RUNNING, FAILED)
POST /connectors/<name>/restart?includeTasks=true&onlyFailed=trueRestart failed tasks
PUT /connectors/<name>/pausePause a connector

Useful connector settings

tasks.maxParallelism for this connector
errors.tolerance=allDon'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 StreamsA Java library inside your service; Kafka in, Kafka out
Apache FlinkA separate cluster; large state, many sources, SQL, event time
Plain consumerSimple per-record logic

13 · Kafka on Kubernetes and managed Kafka

Strimzi resources

KafkaThe cluster: version, listeners, authorization, config, operators
KafkaNodePoolA group of nodes with roles (controller, broker), replicas, storage, resources
KafkaTopicA topic as a Kubernetes resource (Topic Operator)
KafkaUserA client identity, ACLs and quotas (User Operator)
KafkaConnect / KafkaConnectorConnect cluster and connectors
KafkaMirrorMaker2Replication between clusters
KafkaRebalanceCruise Control rebalancing proposal

Everyday commands

kubectl get kafka,kafkanodepool -n kafkaCluster status and pools
kubectl get kafkatopic,kafkauser -n kafkaTopics and users with READY state
kubectl describe kafkatopic orders.events -n kafkaConditions explain why something is not ready
kubectl -n kafka exec platform-dual-role-0 -- bin/kafka-topics.sh --bootstrap-server localhost:9092 --listRun 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 kafkaAsk the operator for a safe rolling restart

14 · Security: TLS, authentication, ACLs and quotas

Client security settings

security.protocol=SSL + ssl.keystore.* + ssl.truststore.*TLS with a client certificate (mTLS)
security.protocol=SASL_SSL + sasl.mechanism=SCRAM-SHA-512Username and password over TLS
security.protocol=SASL_SSL + sasl.mechanism=OAUTHBEAREROAuth/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 --listList ACLs
kafka-acls.sh … --add --allow-principal User:orders-svc --operation Write --operation Describe --topic orders. --resource-pattern-type prefixedLet a service write to its own prefix
kafka-acls.sh … --add --allow-principal User:billing-svc --operation Read --group billing. --resource-pattern-type prefixedLet 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-svcPer-user byte-rate limits
kafka-configs.sh … --describe --entity-type users --entity-name orders-svcShow a user's quotas

15 · Monitoring and troubleshooting

Alerts that matter

OfflinePartitionsCount > 0Partitions with no leader: data unavailable (page)
UnderMinIsrPartitionCount > 0Writes with acks=all are being refused (page)
ActiveControllerCount: sum != 1No (or split) controller (page)
UnderReplicatedPartitions > 0 for 5–10 minOne failure away from trouble
Consumer lag in time > SLOA consumer group is falling behind
Disk used > 75–80% on any brokerBrokers stop when the disk fills
RequestHandlerAvgIdlePercent < 30%Brokers are saturated

Diagnose

kafka-topics.sh --bootstrap-server b:9092 --describe --under-replicated-partitionsWhich partitions are missing replicas
kafka-topics.sh --bootstrap-server b:9092 --describe --unavailable-partitionsPartitions with no leader
kafka-consumer-groups.sh --bootstrap-server b:9092 --describe --group gLag per partition, and which member owns it
kafka-log-dirs.sh --bootstrap-server b:9092 --describe --topic-list tPartition sizes per broker and disk
kafka-metadata-quorum.sh --bootstrap-server b:9092 describe --statusController quorum health
kafka-broker-api-versions.sh --bootstrap-server b:9092Can I reach every broker? What versions?

16 · Capacity, performance and disaster recovery

Sizing formulas

Storage = write MB/s × retention seconds × RF × (1 + headroom)Disk across the cluster
Network in = write MB/s × RFProduce 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=allMaximum producer throughput
kafka-consumer-perf-test.sh --bootstrap-server b:9092 --topic t --messages 1000000Consumer throughput

DR

KafkaMirrorMaker2 (Strimzi) / connect-mirror-maker.shReplicate topics, configs and offsets between clusters
replication.policy.class=IdentityReplicationPolicyKeep topic names (no 'source.' prefix) for active-passive
RPO ≈ replication lag; RTO ≈ time to switch clientsWhat you can promise

17 · Capstone: Kafka as a self-service platform

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 admissionRF 3, min ISR 2, partition and retention limits, owner label
Schema required, compatibility checked in CINo breaking changes reach consumers
Golden-path templateProducer/consumer with retries, DLQ, idempotence, tracing, dashboards
Showback per teamBytes in, bytes out, storage, partitions