Kafka
아키텍처

용어 설명
- Producer : 이벤트를 보내는 주체
- Consumer: 토픽의 파티션에 저장되어 있는 메시지를 소비(consume)하는 역할.
- Consumer Group : 하나의 Topic의 모든 파티션들을 구독하는 consumer 그룹.
- Partition : Producer로부터 전달받은 메세지를 저장하는 공간
- Leader Partition : 실질적으로 Producer/Consumer와 통신하는 파티션
- Follower Partition : Leader Partition의 데이터를 복제하여 저장하는 파티션. 그래서 Leader Partition에 장애가 생겼을 때, Follower Partition이 리더로 승격가능.
- Broker = 카프카 서버 : 토픽과 파티션들을 관리하는 역할.
- Controller : 하나의 브로커가 이 역할을 맡는다. 리더 파티션이 문제 있을 때, Follow Partition을 Leader로 승격시켜주는 역할을 수행한다.
- Coordinator : 하나의 브로커가 이 역할을 맡는다. 장애로 인해 특정 파티션의 메세지가 소비되지 않을 때, 다른 Consumer에 매칭시키는 역할을 수행한다.
- Topic : 메세지의 주제
- Offset : 파티션 내 메세지 위치.
- Kafka Cluster : = Kafka 서버(Broker)의 모임
- Event : = Message
- Zookeeper : 카프카 메타데이터 저장 및 관리 서버. [How Kafka and ZooKeeper Work Together]
- Broker 관리
- Broker 생성/삭제/장애감지
- Broker Controller/Coordinator 선정
- Topic 관리
- Topic 별 권한 설정
- 요청 쿼터 관리
- Broker 관리
- Replication Factor : Topic별로 처리하는 Broker 개수를 정하는 계수.
3대의 Broker로 처리하도록 하면, Broker이 장애 시 다른 Broker가 처리 가능하도록 도와준다. Topic의 중요도에 따라 Broker 설정해야함.
동작 방식
- 클라이언트가 메세지를 Producer에게 전송
- Producer가 메세지를 batch size 만큼 토픽의 특정 파티션의 리더에 저장한다.
- 이 때, 파티션의 리더/팔로우 들은 ISR(In Sync Replica)로 묶여 있으며, 서로 데이터 싱크를 맞추게 된다.
- 각각의 브로커와 연결된 Consumer가 이를 필요할 때 읽으면서 이벤트를 핸들링한다. 이 때, Broker은 전달된 이벤트의 메타 데이터를 기록한다.
기타 용어
- batching : Producer/Consumer이 여러개의 메세지를 묶어서 Kafka에 전송/수신하는 기능.
- 이를 이용하면 요청별로 발생하는 오버헤드를 방지할 수 있다.
- request quota(요청 쿼터) : Broker별로 특정 클라이언트가 전송/수신받을 수 있는 자원양을 설정할 수 있는 기능. 하나의 사용자로 인한 서버 부하 방지 가능.
- 데이터 영속성 보장 : 메시지를 기본적으로 메모리에 저장하는 기본 메시징 시스템과는 달리 메시지를 파일 시스템에 저장한다. 그래서 데이터 영속성이 보장된다.
- Consumer pull 방식 : 기존의 메시징 시스템에서는 Broker가 Consumer에게 메시지를 Push해주는 방식인데 반해, Kafka는 Consumer가 Broker로부터 직접 메시지를 가지고 가는 pull방식으로 동작한다.
- 이를 이용하면 Consumer은 자신의 메세지 처리 성능에 따라 최적으로 메세지를 가져올 수 있게된다.
장점
- Leader/Follow 덕에 안정적으로 서버 운영 가능. SPOF 방지.
예시 시나리오 - 만약 파티션이나 Controller 브로커가 다운된다면?!
- Zookeeper에서 Controller Broker 장애 감지. 새로운 Controller Broker 선출.
- 선출 된 Controller Broker은 Zookeeper내 state변화(장애발생 Broker에 할당된 Leader Partition 상태 변화) 감지.
- 다른 Broker들에게 장애발생된 Leader Partition의 Follow Partition들을 받아와서 이 중 하나를 Leader로 승격. [Controller Broker]
- Topic 별 데이터를 묶어서 처리하기에 오버헤드를 줄일 수 있음.
예시 : 온라인 상품 구매 프로세스에서 재고 수량은 실시간으로 업데이트 되나(Producer
Remain.batch_size = 0), 구매 로그(ProducerRemain.batch_size = 50)는 실시간 처리 보다는 배치 처리한다.
메세지 처리 전략 3가지
- Exaclty Once : 메세지가 정확히 한번 전달되고 처리되는 전략.
- 오버헤드가 매우 크다. 은행과 같이 정확한 데이터 처리가 필요한 곳에서 사용.
- At Least Once : 메세지가 최소 한번 전달/처리 되는 전략.
- Producer/Consumer 둘 다 메세지를 여러번 읽을 수 있기 때문에, 멱등성을 고려해야한다.
- At Most Once : 메세지가 최대 한번 전달/처리 되는 전략.
- 메세지 손실이 발생할 수 있음. 모니터링 데이터 처리에 좋음.
주의사항
- Consumer은 브로커의 메세지를 여러번 읽을 수 있기 때문에, 멱등성을 고려해야한다. Producer 또한 마찬가지.
Reference
- https://velog.io/@jwpark06/Kafka-시스템-구조-알아보기
- Setting client quotas - IBM Event Streams
- https://jhleed.tistory.com/180
- https://engineering.linecorp.com/ko/blog/how-to-use-kafka-in-line-1/
- https://galid1.tistory.com/793
- https://goyunji.tistory.com/125
- https://jaceklaskowski.gitbooks.io/apache-kafka/content/kafka-brokers.html
Kafka
Architecture

Terms
- Producer: sends events.
- Consumer: consumes messages stored in topic partitions.
- Consumer Group: a group of consumers that subscribe to all partitions of one topic.
- Partition: storage for messages received from Producers.
- Leader Partition: the partition that actually communicates with Producer/Consumer.
- Follower Partition: replicates and stores data from the Leader Partition. If the Leader fails, a Follower can be promoted.
- Broker = Kafka server: manages topics and partitions.
- Controller: one broker takes this role and promotes a follower partition when a leader partition has a problem.
- Coordinator: one broker takes this role and matches partitions to other Consumers when messages are not consumed due to failure.
- Topic: the subject of messages.
- Offset: message position inside a partition.
- Kafka Cluster: a group of Kafka Brokers.
- Event: same as Message.
Zookeeper: server that stores and manages Kafka metadata.
- Replication Factor: determines how many Brokers process each Topic.
If three Brokers are configured, another Broker can process work when one Broker fails. Broker settings should depend on topic importance.
How it works
- The client sends a message to the Producer.
- The Producer stores messages up to the batch size in the leader of a specific topic partition.
- The partition leader and followers are grouped as ISR, In Sync Replica, and synchronize data.
- Consumers connected to each broker read messages when needed and handle events. The Broker records metadata for delivered events.
Advantages and strategies
- Leader/Follower replication helps stable operation and prevents SPOF.
- Processing data by Topic can reduce overhead.
- Exactly Once delivers and processes a message exactly once, but overhead is high.
- At Least Once delivers/processes at least once, so idempotency is required.
- At Most Once delivers/processes at most once, so message loss can occur.
Notes
Since Consumers can read Broker messages multiple times, idempotency must be considered. The same applies to Producers.
Reference
- https://velog.io/@jwpark06/Kafka-시스템-구조-알아보기
- Setting client quotas - IBM Event Streams
- https://jhleed.tistory.com/180
- https://engineering.linecorp.com/ko/blog/how-to-use-kafka-in-line-1/
- https://galid1.tistory.com/793
- https://goyunji.tistory.com/125
- https://jaceklaskowski.gitbooks.io/apache-kafka/content/kafka-brokers.html