0Pricing
Apache Kafka & Stream Processing Fundamentals · Урок

Понимание разделов и смещений

Разберитесь в важности разделов для масштабируемости и параллелизма, а также в том, как смещения отслеживают прогресс потребителей.

«Понимание разделов и смещений» — бесплатный урок Apache Kafka & Stream Processing Fundamentals на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Apache Kafka & Stream Processing Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Apache Kafka & Stream Processing Fundamentals содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are Kafka Partitions?

Imagine a Kafka topic as a category for messages. To handle lots of messages efficiently, Kafka divides a topic into smaller, ordered segments called partitions.

Think of each partition as its own mini-log. Messages are appended to the end of a partition in the order they arrive. Once written, messages in a partition are immutable.

Partitions: Ordered & Immutable

It's crucial to understand that while messages within a single partition are strictly ordered, there's no guaranteed order across different partitions of the same topic.

  • Ordered: Messages in one partition always have a clear sequence.
  • Immutable: Once a message is written to a partition, it cannot be changed.
  • Append-only: New messages are always added to the end.

Scalability Through Partitions

Partitions are the backbone of Kafka's scalability and parallelism. Here's why they matter:

  • Parallel Processing: Multiple consumers can read from different partitions of the same topic simultaneously.
  • Distributed Storage: Partitions can be spread across different Kafka brokers (servers) in a cluster. This allows topics to handle more data than a single server could.

How Messages Are Assigned

When a producer sends a message, Kafka needs to decide which partition it should go into. This is called partitioning strategy:

  • With a Key: If a message includes a key (e.g., a user ID), Kafka uses a hash of that key to consistently assign it to the same partition. This ensures all messages for a specific key are processed in order.
  • Without a Key: If no key is provided, Kafka typically uses a round-robin approach, distributing messages evenly across all partitions.

Producer with Message Keys

This Java example shows how a producer sends messages to a topic, explicitly providing a key. Messages with the same key will end up in the same partition.

import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

public class KeyedProducer {
  public static void main(String[] args) {
    Properties props = new Properties();
    props.put("bootstrap.servers", "localhost:9092");
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

    try (KafkaProducer<String, String> producer = new KafkaProducer<>(props)) {
      String topic = "my_keyed_topic";
      for (int i = 0; i < 4; i++) {
        String key = "user-" + (i % 2); // user-0, user-1, user-0, user-1
        String value = "Message " + i + " for " + key;
        producer.send(new ProducerRecord<>(topic, key, value));
        System.out.println("Sent: Key=" + key + ", Value=" + value);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Introducing Message Offsets

Every message within a Kafka partition has a unique, sequential identifier called an offset. Think of it as an index number for messages within that specific partition.

  • The first message in a partition has offset 0.
  • The next message has offset 1, and so on.
  • Offsets are local to each partition.

Offsets for Consumer Progress

Offsets are critical for consumers to track their progress. A consumer keeps a record of the offset of the last message it successfully processed in each partition.

This allows consumers to:

  • Resume processing exactly where they left off if they stop or crash.
  • Know which messages they still need to read.

Committing Offsets

After processing messages, consumers need to inform Kafka about their progress by committing their offsets. This means saving the current offset to a special Kafka topic (__consumer_offsets).

Committing can be:

  • Automatic: Kafka commits offsets periodically in the background.
  • Manual: The application explicitly tells Kafka when to commit offsets, offering more control over processing guarantees.

Check Your Understanding

Let's test your knowledge about Kafka partitions and offsets.

Recap: Partitions & Offsets

Today, we explored two core Kafka concepts:

  • Partitions: These segments divide a topic, enabling parallel processing, distributed storage, and ordered messages within each partition.
  • Offsets: These sequential IDs track the position of messages within a partition, allowing consumers to precisely manage their progress and resume reliably.

Understanding these concepts is key to building scalable and robust Kafka applications!

Часто задаваемые вопросы

Урок «Понимание разделов и смещений» бесплатный?

Да — полный текст урока «Понимание разделов и смещений» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Apache Kafka & Stream Processing Fundamentals, подпишись на CoddyKit PRO. Курс Apache Kafka & Stream Processing Fundamentals содержит 4 уроков всего.

Чему я научусь в уроке «Понимание разделов и смещений»?

Разберитесь в важности разделов для масштабируемости и параллелизма, а также в том, как смещения отслеживают прогресс потребителей. Ты практикуешь Apache Kafka & Stream Processing Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Apache Kafka & Stream Processing Fundamentals?

Предыдущий опыт не требуется. Apache Kafka & Stream Processing Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Понимание разделов и смещений»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Apache Kafka & Stream Processing Fundamentals?

Да. Каждый урок Apache Kafka & Stream Processing Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Отправка сообщений в Kafka
  2. Получение сообщений из Kafka
  3. Понимание разделов и смещений
  4. Ключи сообщений и стратегии распределения по разделам
← Назад к Apache Kafka & Stream Processing Fundamentals