Message Brokers. Основы Kafka. Часть 1

NextWay
19 Feb 202409:05

Summary

TLDRThis video explores the foundational principles of Kafka, a distributed event-driven log system, crucial to our course. It begins by explaining the consumption model where messages, once published, remain accessible to multiple consumers without being deleted, akin to balls in a sealed tube that can only be observed, not removed. The discussion moves to Kafka's architecture, highlighting partitions as atomic storage units preserving message order. It introduces the concept of topics as logical groupings of partitions for efficient message distribution and consumer access. The video concludes by examining how Kafka ensures parallel reading through partition and topic management, setting the stage for future discussions on consumer groups and advanced Kafka functionalities.

Takeaways

  • 😀 Kafka is a distributed, event-driven log system covered extensively in the course.
  • 😃 The consumption model in Kafka allows multiple consumers to receive the same message without it disappearing after being read.
  • 😉 Kafka uses a metaphor of a sealed glass tube where producers drop balls (messages) that consumers can't remove but can read sequentially.
  • 😊 Partitions in Kafka are atomic units of storage, ensuring the order of messages is maintained for reading by consumers.
  • 😍 Multiple business services can read from the same partition without issue, independently accessing messages.
  • 😎 To handle consumer overload and enhance performance, Kafka allows partitioning messages across multiple instances.
  • 😝 A topic in Kafka acts as a logical grouping or container for partitions, organizing messages of the same type.
  • 😳 Producers write to topics, not directly to partitions, with Kafka distributing messages among partitions based on a default algorithm.
  • 😱 Consumers read from specific partitions within a topic, with Kafka assigning which partition(s) a consumer reads from.
  • 🙏 The key concept is that while topics logically group messages, partitions physically separate them for parallel processing and reading.

Q & A

  • What is Kafka in the context of the provided script?

    -Kafka is described as a distributed, event-oriented log system that plays a crucial role in the course being discussed.

  • What analogy is used to explain Kafka's message handling mechanism?

    -The script uses the analogy of a sealed glass tube into which producers drop balls (messages), which can't be removed but can be read by consumers.

  • How does Kafka ensure that a message is accessible to multiple consumers without being deleted after being read?

    -Kafka stores messages in a broker, allowing multiple consumers to access the same message without it being removed upon reading.

  • What is a partition in Kafka, according to the script?

    -A partition in Kafka is described as an atomic unit of storage, essentially an atomic log where messages are stored and maintained in order.

  • How do consumers read messages from Kafka?

    -Consumers read messages from Kafka sequentially, using a pointer-like mechanism to move from one message to the next within a partition.

  • What happens if multiple business services want to read from the same partition?

    -The script suggests that multiple services can independently read from the same partition without issues, each receiving the same messages.

  • What is a topic in Kafka and how does it relate to partitions?

    -A topic in Kafka is a logical grouping or container for partitions, which helps organize messages of the same type but doesn't affect the mechanical function of message distribution across partitions.

  • How do producers write messages in Kafka?

    -Producers send messages to a topic, and Kafka internally handles the distribution of these messages across the available partitions.

  • How does Kafka maintain the order of messages?

    -Kafka maintains message order within each partition, ensuring that messages are stored and read in the order they were received.

  • What is the default algorithm Kafka uses to distribute messages across partitions?

    -The default algorithm is round-robin, where Kafka distributes messages evenly across all available partitions.

Outlines

00:00

📚 Introduction to Kafka's Fundamentals

This paragraph serves as an introduction to Kafka, emphasizing its significance in the course. Kafka is described as a distributed, event-oriented log, a model where multiple consumers can receive the same message without it disappearing after being read. The analogy of a glass tube with sealed ends is used to explain how producers add messages to the log, while consumers read these messages in order without the ability to remove them. The persistence and order of messages are highlighted, indicating that they are stored in the order received from the producer and are not deleted after reading. The concept of partitions in Kafka is introduced as atomic storage units, maintaining the order of messages, which are read by consumers.

05:01

🌐 Kafka's Partition and Topic Mechanics

The second paragraph delves deeper into Kafka's architecture, focusing on the roles of partitions and topics. It clarifies that a producer writes to a topic, not directly to partitions, and Kafka itself handles the distribution of messages across partitions. This distribution is based on a round-robin algorithm, ensuring equal distribution among available partitions. Consumers, in contrast, read messages from specific partitions. The ordering of messages within each partition is maintained, but across multiple partitions, the overall order isn't guaranteed. The concept of a topic is explained as a logical grouping or container for partitions, which helps in the organization and categorization of messages. The essence of this design allows for parallel processing and reading of messages, enhancing performance and scalability. The discussion indicates that in Kafka, producers write to topics (not knowing the exact number of partitions), while consumers read from specific partitions, ensuring efficient and parallel message processing.

Mindmap

Keywords

💡Kafka

Kafka is introduced as a distributed, event-driven log system, playing a central role in the video's discussion. It is designed for handling high throughput and scalable data streaming applications. Kafka allows multiple consumers to read the same message without it being deleted, emphasizing its immutable log nature where data is stored and accessed by consumers in real-time or later.

💡Producer

In the Kafka ecosystem, a producer is an entity that publishes data to Kafka topics. The video describes producers as the sources of data, akin to inserting balls into a sealed tube, representing Kafka's data storage model. Producers play a crucial role in Kafka's architecture by generating and sending messages to be stored in topics and subsequently processed or consumed by consumers.

💡Consumer

Consumers in Kafka are entities that subscribe to topics and read messages from them. The video illustrates consumers as reading messages from a Kafka log without removing them, ensuring that messages remain available for other consumers. This mechanism supports Kafka's event-driven architecture by allowing multiple consumers to independently process the same data.

💡Log

The log in Kafka is a fundamental concept discussed in the video, representing an append-only, ordered sequence of records that are stored across multiple brokers. The analogy of a sealed glass tube filled with balls is used to describe the immutability and sequential nature of Kafka logs, where messages are consumed in the order they are produced.

💡Partition

Partitions are a core component of Kafka's scalability and fault tolerance, described in the video as atomic units of storage within a topic. Each partition is an independent log sequence, allowing Kafka to distribute data across the cluster for load balancing and parallel processing. The video explains how partitions enable multiple consumers to read from the same topic simultaneously without interfering with each other.

💡Topic

A topic in Kafka serves as a category or feed name to which records are published. The video defines a topic as a logical grouping or container for partitions, allowing producers to send messages that are then distributed across partitions within the topic. This facilitates organized data streaming and categorization in Kafka's architecture.

💡Consumer Group

Although briefly mentioned at the end of the script, a consumer group is an important concept in Kafka for managing and scaling consumption. Consumer groups consist of multiple consumers that work together to consume a topic; each consumer within the group reads from exclusive partitions, enhancing parallel processing and ensuring efficient data consumption.

💡Throughput

While not explicitly defined in the script, throughput is an underlying theme when discussing Kafka's capabilities. It refers to the amount of data processed in a given time frame. Kafka's design, including its use of partitions and consumer groups, aims to maximize throughput, allowing for high-volume, real-time data processing.

💡Event-Driven Architecture

The event-driven architecture is a central theme in Kafka's design, highlighted throughout the video. It refers to a system where producers generate events (messages) that are asynchronously consumed by consumers. This architecture facilitates decoupled systems where components communicate through events, making Kafka suitable for complex data pipelines and microservices.

💡Scalability

Scalability is a key aspect of Kafka discussed in the video, particularly in the context of handling increasing workloads by adding more consumers or partitions. Kafka's architecture supports horizontal scaling, allowing systems to handle more messages by distributing the load across multiple consumers and partitions, thereby maintaining performance as demand grows.

Highlights

Introduction to Kafka and its significance in the course.

Definition of Kafka as a distributed, event-oriented log.

Overview of the consumer model in Kafka, where multiple consumers can receive the same message.

Explanation of message persistence in Kafka; messages are not deleted after being read.

Use of a glass tube metaphor to illustrate how Kafka stores and handles messages.

Description of how consumers interact with the message log in Kafka.

Introduction to Kafka partitions as atomic units of storage.

Explanation of how partitions maintain the order and storage of messages.

Discussion on handling multiple consumers from the same partition.

The concept of topics in Kafka for logical grouping of partitions.

How producers interact with topics instead of individual partitions.

Kafka's default message distribution mechanism across partitions.

Understanding the consumer's role and how it reads from specific partitions.

The role of consumer offsets in tracking message consumption in partitions.

Overview of Kafka's architecture enabling parallel consumption of messages.

Preview of upcoming discussions on working with multiple partitions and consumer groups.

Transcripts

play00:00

всем привет сегодня мы поговорим Об

play00:03

основах Кафки который мы уделим много

play00:06

времени на нашем курсе а что это такое

play00:10

Ну если говорить формальным сухим языком

play00:12

кавка - это такой распределённый

play00:14

событийно-ориентированная

play00:21

Log которую мы обсуждали уже Давайте

play00:24

немножко вспомним Что же это такая за

play00:27

модель Мы говорили о том что с точки

play00:29

зрения

play00:31

классификации модели потреблении это

play00:33

такая модель в которой одно и то же

play00:35

сообщение могут получить сразу несколько

play00:38

потребителей при этом После прочтения

play00:42

Что первым что вторым что любым другим

play00:44

потребителем само по себе сообщение оно

play00:47

никуда не исчезает Оно не удаляется оно

play00:49

хранится в брокере в качестве бытовой

play00:52

метафоры мы здесь приводили такую

play00:55

стеклянную трубку с запаян концом в

play00:57

которую мячики можно скидывать продюсеры

play00:59

их накидывает но э к счастью или к

play01:03

сожалению их никак нельзя вытащить

play01:05

поэтому всё что остаётся консьюмер это

play01:08

вот подойти так к трубке пальцем условно

play01:10

указать сначала на первый элемент

play01:13

посмотреть что на нём написано и дальше

play01:15

Вот так вот двигая пальцем как

play01:16

указателем а соответственно по очереди

play01:19

читать одно за другим сообщением таким

play01:21

образом каждый консьюмер получается

play01:24

прочитывает все сообщения в этом логе а

play01:27

При этом они хранятся в том порядке в

play01:30

котором были записаны то есть в которым

play01:32

поступили от продюсера Ну и сами по себе

play01:35

за счёт прочтения никуда не удаляются

play01:38

А как же эта модель реализована в кафке

play01:43

когда мы говорим про кафку мы

play01:45

встречаемся с таким понятием как

play01:48

партиции Что такое партиции по факту это

play01:51

тот самый Лог о которым мы сейчас

play01:54

говорили то есть в кафке это такая

play01:56

скажем так атомарная единица хранения

play01:59

сообщени это вот такой атомарный Лог в

play02:01

котором соблюдается порядок записи и

play02:04

хранения сообщений и из которого

play02:07

консьюмер вот так вот могут их читать то

play02:10

есть в целом тот же самый Лог в случае

play02:13

если мы имеем ра дело с одной партиции

play02:17

всё здорово у нас продюсер пишет туда

play02:19

сообщение кон сюр читает А если

play02:22

несколько разных бизнес-сервис захотят

play02:24

читать из одной партиции тоже ничего

play02:27

страшного как и на схеме

play02:31

они будут Независимо друг от друга

play02:32

читать эти сообщения ВС нормально

play02:35

допустим вот в нашем случае сюда

play02:38

поступают продюсер присылают информацию

play02:41

о новых вышедших фильмах в кинотеатре Но

play02:45

что же будет Что же нам делать если

play02:48

консьюмер например не справляется с

play02:50

нагрузкой и мы хотим увеличить его

play02:52

производительность развернуть экземпляра

play02:55

получается В таком случае

play02:58

коню они будут жить если они будут

play03:01

читать оба из одной партиции они

play03:03

получается будут получать одни и те же

play03:05

сообщения а нас это совершенно не

play03:08

устраивает Зачем нам двойная обработка

play03:11

Вот для этого в кафке появляется уже

play03:13

такая как-то механика логика Когда у нас

play03:17

для того чтобы получать события одного и

play03:20

того же типа в данном случае информацию

play03:22

о новых фильмах мы используем две

play03:24

партиции соответственно один коню читает

play03:27

из партиции номер о в комер читает из

play03:31

партиции номер

play03:33

д при этом продюсер что получается

play03:37

продюсеру приходится писать в две

play03:39

партиции и с появлением с каждой но

play03:41

новой партиции продюсеру придётся ещё в

play03:44

Новую партиции писать кажется что такая

play03:47

схема не очень удобна потому что вот мы

play03:50

много боролись с понятием сильной

play03:53

связано както свы чтобы с

play03:58

св экземпляр сервиса продюсеру

play04:01

приходится писать новую партиции Ну

play04:03

как-то неудобно и вот Чтобы

play04:06

избежать этой проблемы в кафке

play04:09

соответственно Ну не то чтобы ввели

play04:11

существует такая концепция как топик Что

play04:14

такое топик топик - это некоторая такая

play04:18

логическая группировка такой контейнер

play04:21

для

play04:22

партиции В каком смысле логическо В том

play04:25

смысле что в топик летят мы присылаем

play04:28

сообщения Ну скажем так

play04:30

э одного и того же типа например да

play04:33

информацию о том что вышел новый фильм

play04:36

при этом партиции выполняют сугубо такую

play04:38

механическую функцию это распределение

play04:41

сообщений Ну например можно это

play04:44

представить как опять же если посмотреть

play04:46

какой-нибудь провод дома взять его и

play04:48

разрезать то с одной стороны провод -

play04:50

это некоторая цельная штука по которой

play04:53

передаётся сигнал с другой стороны если

play04:55

мы разрежем то увидим на срезе несколько

play04:57

таких жилок вот в данном случае топик

play05:00

является вот этом вот общим контейнером

play05:02

партиции и теми самыми жилками А как это

play05:05

происходит в кафке здесь вот сразу в

play05:08

очень важный момент обращаю внимание что

play05:11

продюсер В общем случае пишет именно не

play05:14

в партиции а в топик то есть продюсер не

play05:17

знает сколько партиции мы поместили в

play05:20

топик и когда продюсер пишет сообщение

play05:23

Он пишет сообщение в топик отправляет

play05:26

эту в кафку и дальше сама уже кавка

play05:28

распределяет сообщение между партиции

play05:31

опять же по дефолту дефолтный алгоритм

play05:33

распределения это Рон то есть первое

play05:35

сообщение попадёт в партиции номер один

play05:39

второе следующую если партиции

play05:42

закончились то третье сообщение опять

play05:44

попадёт в первую партиции четвёртое

play05:46

сообщение попадёт в вторую

play05:48

партиционирование

play05:59

партиции сохраняется То есть если первое

play06:01

пришло первым то оно вот будет на первом

play06:03

месте дальше Обратите внимание в

play06:05

партиции номер один а пришло третье

play06:08

сообщение поэтому будет лежать третье

play06:10

сообщение То есть если у нас в топике

play06:13

несколько партиции то вот уже общий

play06:17

порядок 1 2 3 4 в рамках одной партиции

play06:21

соблюдаться не будет но в рамках одной

play06:25

партиции будет соблюдаться тот Порядок в

play06:27

котором сообщения пришли если мы так

play06:29

будем продолжать например отправим пятое

play06:31

сообщение то опять же оно ляжет в

play06:33

партиции номер один если мы отправим

play06:36

шестое сообщение то оно уже окажется в

play06:38

партиции номер два то есть порядок то в

play06:42

рамках партиции будет соблюдаться но мы

play06:44

должны понимать что они будут

play06:46

распределяться

play06:48

равномерно что же происходит с консьюмер

play06:51

в консьюмер в отличие от продюсер Они

play06:54

читают уже не из топика Они читают

play06:56

сообщения Уже именно из конкретной

play06:58

партиции когда консьюмер подключается к

play07:02

кафке к конкретному топику кавка сама

play07:05

определяет Из каких партий ему читать то

play07:07

есть в данном случае консьюмер вот этот

play07:10

номер один верхний экземпляр будет

play07:12

читать из первой партиции как он читает

play07:15

он получает некоторый указатель в случае

play07:17

Кафки это называется

play07:19

Осе который сначала указывает на первый

play07:21

элемент в партиции дальше когда он его

play07:25

прочитал сдвигается указывает на второй

play07:27

элемент партиции дальше сдвигает

play07:30

ре Эмен партиции Ну и так далее в свою

play07:32

очередь комер второй Независимо читает

play07:35

партию

play07:37

свою Если бы у нас был для двух партий

play07:41

ровно один кон сюр то соответственно он

play07:43

бы получил указатели от

play07:46

каки сразу на две партиции

play07:49

соответственно он бы читал параллельно

play07:51

бы из двух партий есть вот это вот есть

play07:55

концепция то и партиции в

play07:58

ка формулировать это строго то вот

play08:00

партиции - это такой такой атомарный Лог

play08:04

сообщений в кафке в котором они хранятся

play08:07

в том порядке в котором поступили именно

play08:10

в партиции не удаляются прочтения то

play08:13

есть вот та самая модель Лога в то время

play08:15

как топик - это вот некоторая логическая

play08:18

группа которая объединяет несколько

play08:20

партиции с точки зрения того ну с точки

play08:23

зрение того какие сообщения туда

play08:24

поступают и что очень важно ещё раз

play08:27

подчеркну продюсер по дефолту пишет

play08:31

именно в топик не в конкретные партиции

play08:33

А в топик В общем случае он не знает

play08:35

сколько там даже партиции какие они есть

play08:37

А В то время как консьюмер читают именно

play08:41

из партиции Таким образом у нас кавка

play08:45

позволяет обеспечивать параллельно а

play08:48

параллельное чтение А в следующем

play08:51

видосики мы посмотрим уже как именно

play08:55

происходит работа скажем

play08:58

так с несколькими партиции с несколькими

play09:01

топика и что такое коню группа

Rate This

5.0 / 5 (0 votes)

相关标签
KafkaEvent-DrivenData ProcessingDistributed SystemsMessage BrokeringConsumersProducersPartitionsTopicsParallel Processing
您是否需要英文摘要?