개요
Kafka를 처음 접한건 데이터 연합 동아리 BOAZ에서였다. 이벤트 스트리밍에 최적화된, producer와 consumer가 있는 메시징 큐라는 것을 배웠던 것 같다. 그때 Kafka를 배우기만 하고 따로 정리를 안하기도 했고, Kafka의 단편적인 모습만 배운 것 같아서 처음부터 정리하려고 한다.
우선 카프카는 라이브러리도, 프레임워크도 아닌 하나의 플랫폼이다. 여러 개의 컴포넌트들이 상호작용하면서 동작하는 플랫폼이다. Airflow랑 구조가 비슷하다고 보면 된다. 똑같이 여러 개의 컴포넌트를 사용해 서로 통신하면서 동작하니까.

Kafka가 탄생한 배경: Event Streaming
Kafka를 알기 위해 Apache Kafka 홈페이지에 들어가봤다. Kafka를 소개하는 페이지의 첫 번째 주제는 이벤트 스트리밍였다. Kafka를 소개하지 않고 이벤트 스트리밍부터 소개하는 걸로 보아 Kafka의 뼈대를 이루는 개념인 것 같았다.
💡 이벤트 스트리밍이란?
Event streaming is the digital equivalent of the human body's central nervous system. It is the technological foundation for the 'always-on' world where businesses are increasingly software-defined and automated, and where the user of software is more software.
Technically speaking, event streaming is the practice of capturing data in real-time from event sources like databases, sensors, mobile devices, cloud services, and software applications in the form of streams of events; storing these event streams durably for later retrieval; manipulating, processing, and reacting to the event streams in real-time as well as retrospectively; and routing the event streams to different destination technologies as needed. Event streaming thus ensures a continuous flow and interpretation of data so that the right information is at the right place, at the right time.
이벤트 스트리밍은 인간 신경계와 디지털적으로 같은 개념이다. 기업과 개인이 모두 자동화된 소프트웨어로 상호작용하는 오늘날의 지속하는 서비스의 기술적 기반이다.
기술적으로 얘기하자면, 이벤트 스트리밍은 데이터베이스와 같은 실시간으로(이벤트 스트림) 생성되는 데이터를 포착하는 일종의 방법이다. 실시간으로 데이터를 포착해 충분한 기간동안 저장하고 이를 원하는 목적으로 가공하며 필요한 목적지에 최종적으로 전달한다. 이벤트 스트리밍은 데이터의 지속적인 흐름과 가공을 가능하게 해, 원하는 시간과 공간에 데이터를 보냄을 보증한다.
실시간으로 생성되는 데이터를 가공해 원하는 곳에 전송한다. 이것이 이벤트 스트리밍의 핵심이다.
💡 Kafka를 활용할 수 있는 주제들

금융 시스템 거래, 스마트 팩토리에서 차량 추적, IoT 기기 센서들이 전송한 데이터 추합, 호텔과 여행 업계에서 실시간으로 고객에게 정보 전송, 병원 등 응급 상황에서의 정보 전송, 회사에 여러 부서에 실시간 데이터 전송, 데이터 플랫폼과 마이크로서비스의 구축 등 굉장히 다양한 방면에서 Kafka를 활용할 수 있다.
하긴 실시간이니까 실시간으로 하는 모든 작업들을 다 할 수 있겠다. 나 같은 경우 금융 거래 프로젝트에 Kafka를 활용하고 싶다는 생각이 들었다.
Kafka의 작동 원리
💡 Kafka의 핵심 key features

보낸 데이터를 쓰고 읽는 것, 데이터를 저장하는 것, 데이터를 가공하는 것을 담당한다.
실시간 이벤트 스트리밍에 꼭 필요한 요소들이다. 어떻게 이런 특성들을 충족하는지 세부적으로 살펴보자.
And all this functionality is provided in a distributed, highly scalable, elastic, fault-tolerant, and secure manner. Kafka can be deployed on bare-metal hardware, virtual machines, and containers, and on-premises as well as in the cloud. You can choose between self-managing your Kafka environments and using fully managed services offered by a variety of vendors.
카프카는 확장성이 있는 분산 환경에서도 사용할 수 있다. 심지어 bare-metal 하드웨어(어떤 소프트웨어도 설치되지 않은 하드웨어), 가상 머신, 컨테이너 환경에서 사용할 수 있다. 이래서 기업들이 좋아하는게 아닐까 싶다.
💡 카프카의 동작 원리 (Server & Client)
Kafka is a distributed system consisting of servers and clients that communicate via a high-performance TCP network protocol. It can be deployed on bare-metal hardware, virtual machines, and containers in on-premise as well as cloud environments.
위에서 카프카는 플랫폼이라고 했다. 카프카는 여러 개 서버가 모인 클러스터로 운영된다. 카프카는 프로그램이 아니고 다양한 서버에서 돌아가는 컴포넌트들이 서로 협력해서 동작한다.
Servers
: Kafka is run as a cluster of one or more servers that can span multiple datacenters or cloud regions. Some of these servers form the storage layer, called the brokers. Other servers run Kafka Connect to continuously import and export data as event streams to integrate Kafka with your existing systems such as relational databases as well as other Kafka clusters. To let you implement mission-critical use cases, a Kafka cluster is highly scalable and fault-tolerant: if any of its servers fails, the other servers will take over their work to ensure continuous operations without any data loss.
Kafka 서버는 데이터를 받고, 저장하고, 분산 관리하는 역할을 한다. Kafka 플랫폼은 여러 개의 서버들로 이루어지는데, 그 중 몇몇 서버는 데이터 저장소인 broker로서 동작한다. Producer(데이터 생성자)들이 보낸 데이터들을 저장하는 곳이 필요한데 broker가 이 역할을 담당한다. 다른 서버들은 데이터를 외부로 보내고 받는 역할을 하기 위해 Kafka Connect를 지속적으로 실행한다. Kafka cluster는 확장성이 있으며 가용성이 있다. 서버가 죽을 경우 다른 서버로 자동으로 대체함으로서 장애에 대응한다.
만약 Kafka가 로컬에서 실행되고 있으면 컨테이너로 나눠서 동작할 것이다. 플랫폼 내에 메세지를 담는 곳과 메세지를 보내고 받는 곳이 분리되어 있다는 것을 처음 알았다. BOAZ에서 실습할 때는 docker로 컨테이너로 띄워서 그런지 이러한 사실을 놓쳤던 것 같다.
Clients
: They allow you to write distributed applications and microservices that read, write, and process streams of events in parallel, at scale, and in a fault-tolerant manner even in the case of network problems or machine failures. Kafka ships with some such clients included, which are augmented by dozens of clients provided by the Kafka community: clients are available for Java and Scala including the higher-level Kafka Streams library, for Go, Python, C/C++, and many other programming languages as well as REST APIs.
Client 측은 Kafka를 사용하는 애플리케이션들이다. 잘 알고 있는 Producer, Consumer들이다. Kafka Client들은 하나의 ship으로서 동작할 수 있다. 안에 수많은 Client들이 동작하는 것이다. Kafka는 이를 위한 여러 Client API를 제공한다.
💡 카프카의 동작 원리 (Main Concept)
1️⃣ Kafka 내에서 활용되는 이벤트 형식

이벤트는 서비스 시간 동안 '무엇인가' 일어났음을 나타내는 데이터다. Kafka에 저장되는 데이터는 다 이런 형식이다. Kafka에 저장되는 이벤트는 key, value, timestamp를 가진다.
2️⃣ Prodcuer & Consumer
Kafka 플랫폼을 이용하는 Client에는 크게 Producer와 Consumer가 있다. Producer는 데이터를 발행하는 쪽, Consumer는 데이터를 소비하는 쪽이다. 두 클라이언트는 아예 관계가 없다.
두 클라이언트는 TCP 기반으로 Kafka와 통신하지만 서로의 상태를 기억할 필요가 없다. 이 점이 무한한 확장성을 가져다 준다. 통신할 때 key를 통일한다면, 원하는 데이터를 보내고 받는게 문제 없어진다.
Kafka provides various guarantees such as the ability to process events exactly-once.
Kafka는 기본적으로 exactly-once 형식으로 데이터를 보낸다. 한 번 보내는 대신 이 데이터가 제대로 들어왔음을 보장한다는 것이다. 내 생각으론 이건 TCP로 통신하기 때문에 가능한 것 같다.
Kafka의 핵심: Topic과 Partition
Events are organized and durably stored in topics . Very simplified, a topic is similar to a folder in a filesystem, and the events are the files in that folder. An example topic name could be "payments". Topics in Kafka are always multi-producer and multi-subscriber: a topic can have zero, one, or many producers that write events to it, as well as zero, one, or many consumers that subscribe to these events. Events in a topic can be read as often as needed—unlike traditional messaging systems, events are not deleted after consumption. Instead, you define for how long Kafka should retain your events through a per-topic configuration setting, after which old events will be discarded. Kafka's performance is effectively constant with respect to data size, so storing data for a long time is perfectly fine.
이벤트가 Kafka에 전송되면 이벤트는 토픽에 따라 분류돼 저장된다. 토픽은 파일 시스템에서 폴더와 비슷한 개념이다. 같은 묶음으로 분류되어야 하는 데이터들은 같은 토픽에 묶이게 된다. 마치 같은 주제를 묶는 느낌으로 토픽이란 이름을 사용한 것 같다.
한 토픽에 있어야 하는 Producer와 Consumer의 제한은 없다. 아예 없을 수 있고 엄청 많을 수 있다. 그리고 데이터를 가져가면 데이터가 없어지는 다른 큐들과는 달리 Kafka는 Consumer가 데이터를 가져갔다 하더라도 바로 삭제하지 않는다. 사용자가 직접 Kafka에서 데이터가 없어지는 시기를 설정할 수 있다.
Topics are partitioned, meaning a topic is spread over a number of "buckets" located on different Kafka brokers. This distributed placement of your data is very important for scalability because it allows client applications to both read and write the data from/to many brokers at the same time. When a new event is published to a topic, it is actually appended to one of the topic's partitions. Events with the same event key (e.g., a customer or vehicle ID) are written to the same partition, and Kafka guarantees that any consumer of a given topic-partition will always read that partition's events in exactly the same order as they were written.
토픽은 안에 여러 개의 파티션으로 이루어져 있다. 파티션은 데이터를 담는 버켓이다. 위에서 데이터를 저장하는 서버인 broker에 대해 말했었는데, 이 파티션이 바로 브로커다. 같은 key를 가진 이벤트는 같은 파티션이 저장되며 Kafka는 이들이 원래 작성된 순서대로 저장되게끔 알아서 조정한다.

그림과 같이 한 파티션에는 여러 개의 Consumer가 데이터를 전송할 수 있다. 데이터를 가져가는 Producer도 마찬가지다. 이런 파티션의 특성 덕분에 Kafka는 좋은 확장성을 가질 수 있게 됐다. 확장성을 가지며 장애에도 대응하고, 순서를 지켜주는 메시징 큐는 많은 기업들에게 매력적일 수밖에 없다.
파티션은 복제(replicate)를 통해 가용성을 가질 수 있는데, 이 부분은 좀 더 자세하게 다른 포스팅으로 적어보자.
출처
https://kafka.apache.org/intro
Apache Kafka
Apache Kafka: A Distributed Streaming Platform.
kafka.apache.org
'Data Engineering' 카테고리의 다른 글
| [데이터 파이프라인] 3. 데이터 수집 실습 (0) | 2025.07.10 |
|---|---|
| [Airflow] Slack을 이용한 Airflow 실습 - 3 (Slack Webhook) (0) | 2025.07.01 |
| [Airflow] Slack을 이용한 Airflow 실습 - 2 (Airflow와 DAG) (0) | 2025.06.25 |
| [Airflow] Slack을 이용한 Airflow 실습 - 1 (Docker와 Airflow 연동) (0) | 2025.06.24 |
| [데이터 파이프라인] 2. 일반적인 데이터 파이프라인 (0) | 2025.06.17 |