⚡ Apache Kafka – Architecture, Opérations & Bonnes Pratiques
Clusters KRaft, Producers/Consumers, Streams, Connect, Registry, sécurité, monitoring & troubleshooting.
Vue d’ensemble
Concepts, flux, comparatif RabbitMQ.
TopicPartitionOffsetArchitecture
Brokers, Controller, ISR, KRaft.
ReplicationISRKRaftInstallation
Linux, Docker, KRaft single/cluster.
apt/yumdockerkraftProducteurs
Idempotence, acks, débit, exemples.
acks=alllinger.msConsommateurs
Groupes, commit, rebalance.
group.idcooperative-stickySémantiques & Ordre
At‑least/most, EoS, keys.
EoSorderingKafka Streams
DSL, Processor API, windows.
DSLRocksDBKafka Connect
Sources/Sinks, SMT, REST.
ConnectSchéma & Sérialisation
Avro/JSON/Protobuf, Registry.
SchemaSécurité
TLS, SASL, ACL, quotas.
TLSSASLMonitoring
JMX/Prometheus, lags.
JMXPrometheusPerformance & Tuning
Disque, réseau, brokers.
I/ObatchTroubleshooting
URP, rebalances, segments.
URPLagCas d’usage
EDA, ETL, log, IoT.
EDAETLRéférences
Docs officielles & liens.
docCheat‑sheet
CLI, configs, recettes.
kafka‑*- Topic : bus logique d’événements. Partition : journal ordonné append‑only.
- Producer écrit en batches (compression, linger, batch.size).
- Consumer Group lit en parallèle ; un seul consumer par partition.
- ISR : in‑sync replicas. URP : under‑replicated partitions.
- Retention par durée/taille ; compactage conserve la dernière valeur par clé.
- Exactly‑Once (EoS) via idempotence + transactions.
Objets clés
| Objet | Rôle | CLI |
|---|---|---|
| Topic | Flux partitionné | kafka-topics.sh |
| ACL | Sécurité ressource | kafka-acls.sh |
| Group | Conso parallèle | kafka-consumer-groups.sh |
| Connector | Ingestion/egestion | REST Connect |
[Producer] --batch--> [Broker/Leader] --replicate--> [Followers] [Segments .log] <= retention/compactage [Consumer Group] --fetch--> [Partition 0..n] --commit--> __consumer_offsets
Le débit provient du séquencement disque + envoi séquentiel réseau, et du batching.
| Critère | Kafka | RabbitMQ | Quand l’utiliser ? |
|---|---|---|---|
| Modèle | Log/Offset | Queue/Ack | Kafka pour analytics/ETL, RabbitMQ pour RPC/Work Queues |
| Routage | Key → partition | Exchange (direct/topic/…) | RabbitMQ pour routes riches |
| Retours | Pas de DLQ natif (pattern) | DLX/DLQ intégrés | RabbitMQ pour retries structurés |
| Replay | Offsets repositionnables | Non (sauf requeue) | Kafka pour relecture massive |
Règles de pouce (rough sizing)
- Partitions : ~ (10 × nb. consommateurs parallèles visés).
- Stockage : débit_journalier × rétention_jours × réplication (×1.2 marge).
- RF : 3 pour prod. min.insync.replicas = 2 + acks=all.
| Composant | Rôle | Points d’attention |
|---|---|---|
| Broker | Stockage partitions, API réseau | page cache, I/O séquentiel |
| Controller | Métadonnées cluster | stabilité quorum |
| Log | Segments .log/.index | retention.ms / bytes, cleanup.policy |
| Group Coordinator | Rebalance, commits | timeouts, cooperative‑sticky |
min.insync.replicas=2
acks=all # requiert ≥2 ISR pour l’ack
unclean.leader.election.enable=false
Surveiller UnderReplicatedPartitions; déclencher un reassignment si nécessaire.
process.roles=broker,controller
controller.listener.names=CONTROLLER
controller.quorum.voters=1@node1:9093,2@node2:9093,3@node3:9093
- Pas de ZooKeeper : bootstrapping via cluster.id.
- 3 voters min. Production : 3 ou 5 selon SLA.
kafka-reassign-partitions.sh --generate --topics-to-move-json-file topics.json --broker-list "1,2,3" --bootstrap-server :9092
kafka-reassign-partitions.sh --execute --reassignment-json-file map.json --bootstrap-server :9092
Utiliser --verify et surveiller le throttle pour limiter l’impact.
+ Controller Quorum (KRaft)
| voters: node1,node2,node3
+-----v----+ replicate +-----------+
| Broker 1 |<------------->| Broker 2 |
+----------+ +-----------+
# User, Java, déballage
sudo useradd -m -s /bin/bash kafka && sudo su - kafka
curl -O https://downloads.apache.org/kafka/3.7.0/kafka_2.13-3.7.0.tgz
mkdir -p ~/kafka && tar xzf kafka_2.13-3.7.0.tgz -C ~/kafka --strip-components=1
# Unit systemd (extrait)
[Service]
ExecStart=/opt/kafka/bin/kafka-server-start.sh /etc/kafka/server.properties
docker‑compose.yml
version: '3.8'
services:
kafka:
image: bitnami/kafka:3.7
environment:
- KAFKA_ENABLE_KRAFT=yes
- KAFKA_CFG_PROCESS_ROLES=broker,controller
- KAFKA_CFG_NODE_ID=1
- KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093
- KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER
- KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093
- ALLOW_PLAINTEXT_LISTENER=yes
ports: ["9092:9092","9093:9093"]
volumes: ["kdata:/bitnami/kafka"]
volumes: { kdata: {} }
# KRaft cluster (3 voters)
CLUSTER_ID=$(bin/kafka-storage.sh random-uuid)
# init + format + start (node1..node3)
- Configurer advertised.listeners pour clients distants.
- RAID1/10 conseillé, XFS/ext4.
- kcat (ancien kafkacat) : production/consommation rapide.
- jmx_exporter + Prometheus + Grafana.
- Cruise Control : rebalancing automatisé.
| Propriété | Effet | Valeur type | Notes |
|---|---|---|---|
| acks | Durabilité | all | avec min.insync.replicas≥2 |
| enable.idempotence | Dé‑doublonnage | true | active retry+acks automatiques |
| linger.ms | Batching | 5–50 | + batch.size 64–256 KB |
| compression.type | Débit/réseau | lz4/zstd | gagne 2‑5× |
Properties p=new Properties();
p.put("bootstrap.servers","broker:9092");
p.put("acks","all");
p.put("enable.idempotence",true);
p.put("linger.ms",10);
Producer prod=new KafkaProducer<>(p,new StringSerializer(), new ByteArraySerializer());
prod.send(new ProducerRecord<>("orders","k1", payload));
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers=['broker:9092'],
acks='all', linger_ms=10, value_serializer=lambda v: v)
producer.send('orders', key=b'k1', value=b'{...}')
producer.flush()
# Conseils débit
- Favoriser des messages 1–10 KB, mais batcher jusqu'à 128–512 KB.
- Multi‑threads producteurs (1 conn / plusieurs threads ok).
- Eviter l'ACK local (acks=1) en prod; préférer acks=all.
enable.auto.commit=false
# traiter -> commitSync() (ou commitAsync avec callbacks)
max.poll.interval.ms=300000 # éviter les rebalances pendant des traitements longs
session.timeout.ms=45000
partition.assignment.strategy=cooperative-sticky
# réduit les pauses; nécessite clients récents
kafka-consumer-groups.sh --bootstrap-server :9092 --describe --group g1 # Exporter le lag vers Prometheus (burrow, kafka-lag-exporter)
| Type | Garanties | Mise en œuvre |
|---|---|---|
| At‑most‑once | 0/N | commit avant traitement |
| At‑least‑once | ≥1 | traiter puis commit |
| Exactly‑Once | 1 | Idempotence + transactions |
partitioner: key -> hash(key) % partitions # pour l’ordre par clé, réutiliser la même clé (ex: userId)
enable.idempotence=true transactional.id=service-A # côté consumer: read-process-produce-commit transactionnel
builder.stream("orders").mapValues(enrich).to("orders.enriched")State local (RocksDB) + changelog Kafka. Sauvegarde compacte, rééquilibrage en cas de rebalance.
orders.join(payments, joiner, JoinWindows.ofSeconds(30))
- Workers, Tasks, Connectors, Converters, Transforms.
bootstrap.servers=broker:9092
config.storage.topic=connect-configs
status.storage.topic=connect-status
offset.storage.topic=connect-offsets
errors.tolerance=all
errors.deadletterqueue.topic.name=_connect_dlq
transforms=unwrap
transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState
- Confluent Schema Registry ou Apicurio.
- Sujets
topic-value/topic-key.
| Format | Avantages | Notes |
|---|---|---|
| Avro | Compact + évolutif | Très courant |
| JSON‑Schema | Lisible | Validation stricte |
| Protobuf | Perf/gRPC | Types riches |
compatibility.level=BACKWARD # Process d’évolution: add fields with default, éviter les breaks
listeners=SSL://:9093 ssl.keystore.location=/etc/kafka/keystore.jks ssl.truststore.location=/etc/kafka/truststore.jks
sasl.enabled.mechanisms=SCRAM-SHA-512 sasl.mechanism.inter.broker.protocol=SCRAM-SHA-512 listener.name.sasl_ssl.scram-sha-512.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required ...;
kafka-acls.sh --bootstrap-server :9092 --add --allow-principal User:alice --operation READ --topic orders
Métriques essentielles
| Métrique | Signification | Seuils/Alertes |
|---|---|---|
| UnderReplicatedPartitions | Partitions hors ISR | >0 = alerte |
| OfflinePartitionsCount | Indisponibles | doit = 0 |
| RequestHandlerAvgIdlePercent | Idle broker | <0.2 = saturation |
| NetworkProcessorAvgIdlePercent | Idle réseau | <0.2 = saturation |
| Lag par group | Retard conso | seuils métier |
Dashboards
Exporter JMX -> Prometheus (jmx_exporter) Dashboards: Kafka/Broker, Kafka/Connect, Kafka/Streams, Lag (Burrow)
log.retention.hours=168
log.segment.bytes=1GB
num.recovery.threads.per.data.dir=8
Disques SSD NVMe recommandés, pas de RAID5.
socket.send.buffer.bytes=1048576
socket.receive.buffer.bytes=1048576
num.network.threads=8
num.io.threads=16
queued.max.requests=1000
replica.fetch.max.bytes=1048576
kafka-topics.sh --describe --topic orders --bootstrap-server :9092 # Vérifier leader/ISR; réparer via reassign/throttle
# Symptômes: pauses longues, throughput en dents de scie
- Activer cooperative-sticky
- Réduire max.poll.interval.ms si trop grand
- Augmenter partitions (scaling horizontal)
du -sh /kafka-logs/* # Purges manuelles contrôlées, vérifier retention/segment
Event‑Driven & Micro‑services
- Event sourcing, CQRS, audit trail.
- Anti‑corruption layer vers systèmes legacy.
Data/ETL temps réel
- CDC (Debezium) → Kafka → DWH/Lake (Iceberg/Delta).
- Enrichissement via Streams/ksqlDB.
IoT & Logs
- Ingestion télémétrie massive, partitions par device/site.
- Centralisation logs (Filebeat → Kafka → OpenSearch).
Finances & Paiement
- Transactions, détection de fraude en streaming.
- Apache Kafka : Docs, KIPs, Quickstarts.
- Kafka Streams : guide, Topology Test Driver.
- Kafka Connect : REST API, SMT catalogue, Debezium.
- Schema Registry : stratégies de compatibilité.
- Observabilité : jmx_exporter, Burrow, Grafana dashboards.
- Outils : kcat, kafka-tools, Cruise Control.
CLI essentiels
kafka-topics.sh --create --topic orders --partitions 12 --replication-factor 3 --bootstrap-server :9092
kafka-configs.sh --alter --entity-type topics --entity-name orders --add-config cleanup.policy=compact
kafka-consumer-groups.sh --describe --group g1 --bootstrap-server :9092
kafka-reassign-partitions.sh --generate ...
Recettes rapides
# Topic compacté pour vues matérielles
cleanup.policy=compact
min.cleanable.dirty.ratio=0.2
# Topic retention 7j
retention.ms=604800000
# Producteur haut débit
acks=all, linger.ms=20, compression.type=zstd
