Kafka
Apache Kafka
A distributed streaming platform. Real-time data pipelines and event streaming. High throughput.
Apache Kafka
A distributed streaming platform. Real-time data pipelines and event streaming. High throughput.
Apache Kafka is an open-source distributed event streaming platform developed at LinkedIn and donated to the Apache Software Foundation. It provides high throughput, capable of handling millions of events per second, along with fault tolerance, and has become a core infrastructure for building real-time data pipelines and streaming applications.
Kafka's core concepts consist of Topic (message category), Partition (unit of parallel processing), Producer (message publisher), and Consumer (message subscriber). Messages are stored sequentially on disk to achieve high I/O performance, and horizontal scaling is possible through Consumer Groups.
Operational complexity has decreased significantly with the transition from the previous ZooKeeper-based cluster management to KRaft (Kafka Raft) mode. Kafka Connect provides connectors for a variety of data sources and sinks, and Kafka Streams provides a real-time stream processing library.
It is used as the standard for event-driven communication in microservice architectures and is essential for implementing log aggregation, real-time analytics, CDC (Change Data Capture), and event sourcing patterns. Confluent Platform additionally provides enterprise features such as Schema Registry and ksqlDB on top of Kafka.
# Kafka Producer/Consumer Python ์์ (kafka-python)
from kafka import KafkaProducer, KafkaConsumer
from kafka.errors import KafkaError
import json
from datetime import datetime
# ========== Producer ์ค์ ==========
producer = KafkaProducer(
bootstrap_servers=['kafka1:9092', 'kafka2:9092', 'kafka3:9092'],
value_serializer=lambda v: json.dumps(v).encode('utf-8'),
key_serializer=lambda k: k.encode('utf-8') if k else None,
acks='all', # ๋ชจ๋ ๋ณต์ ๋ณธ ํ์ธ
retries=3, # ์ฌ์๋ ํ์
compression_type='snappy', # ์์ถ ๋ฐฉ์
batch_size=16384, # ๋ฐฐ์น ํฌ๊ธฐ (bytes)
linger_ms=10 # ๋ฐฐ์น ๋๊ธฐ ์๊ฐ
)
def send_event(topic: str, key: str, event: dict):
"""์ด๋ฒคํธ๋ฅผ Kafka ํ ํฝ์ผ๋ก ์ ์ก"""
try:
future = producer.send(topic, key=key, value=event)
record_metadata = future.get(timeout=10)
print(f"์ ์ก ์ฑ๊ณต: partition={record_metadata.partition}, "
f"offset={record_metadata.offset}")
return True
except KafkaError as e:
print(f"์ ์ก ์คํจ: {e}")
return False
# ์ด๋ฒคํธ ๋ฐํ
order_event = {
'event_id': 'evt_12345',
'order_id': 'ORD-2024-001',
'customer_id': 'cust_001',
'event_type': 'order_created',
'total_amount': 150000,
'timestamp': datetime.utcnow().isoformat()
}
send_event('order-events', key=order_event['customer_id'], event=order_event)
producer.flush()
# ========== Consumer ์ค์ ==========
consumer = KafkaConsumer(
'order-events',
bootstrap_servers=['kafka1:9092', 'kafka2:9092'],
group_id='order-processor-group',
auto_offset_reset='earliest',
enable_auto_commit=False, # ์๋ ์คํ์
์ปค๋ฐ
value_deserializer=lambda m: json.loads(m.decode('utf-8'))
)
# ๋ฉ์์ง ์๋น
for message in consumer:
print(f"์์ : partition={message.partition}, offset={message.offset}")
print(f"๋ฐ์ดํฐ: {message.value}")
# ๋น์ฆ๋์ค ๋ก์ง ์ฒ๋ฆฌ ํ ์ปค๋ฐ
consumer.commit()
break # ์์ ์ฉ
consumer.close()
Senior: "Let's create a single Kafka topic between the order service and the payment service and connect them asynchronously. Since we need ordering guarantees, use customer_id as the key so messages go to the same partition."
Junior: "How do I decide the number of partitions? Does it need to match the number of Consumer instances?"
Senior: "The number of partitions must be greater than or equal to the number of Consumers. Start with 6 for now, and you can increase it as you watch throughput, but you can't decrease it."
Interviewer: "What do you need to do to guarantee message ordering in Kafka?"
Candidate: "Messages with the same key are sent to the same partition, and ordering is guaranteed within a partition. If you need global ordering, you must limit the topic to 1 partition, but throughput drops."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Senior: "You're using auto.commit. If the commit happens before the message is processed, data can be lost. Switch to manual commit and commit after processing is complete."
Junior: "Okay, I'll change it to enable_auto_commit=False and call consumer.commit()."