Kafka Study Notes: knowledge point sorting and kafka Study Notes
Reading directory
1. Why message system is required 2. kafka architecture 2.1 topology structure 2.2 related concepts 2.3 zookeeper Node 3. producer publish message 3.1 write mode 3.2 message route 3.3 write process
3.4 producer delivery guarantee4.broker stores messages 4.1 storage mode 4.2 Storage Policy
4.3 topic creation and deletion 5. kafka HA 5.1 replication 5.2 leader failover 5.3 broker failover 5.4 controller failover 6. consumer consumption message 6.1 consumer API 6.2 consumer group
6.3 consumption Method
6.4 consumer delivery guarantee
6.5 consumer rebalance7. note 8. References
I. Why do I need a message system?
1. Decoupling:
Allows you to independently expand or modify the processing processes on both sides, as long as they comply with the same interface constraints.2. redundancy:Message Queues persist data until they are completely processed. This avoids the risk of data loss. In many message queues, before a message is deleted from the queue, your processing system must explicitly state that the message has been processed, so that your data is saved securely until you have used it.3. Scalability:Because the Message Queue decouples your processing process, it is easy to increase the frequency of Message Queuing and processing, as long as the processing process is added.4. Flexibility & peak processing capabilities:In the case of a sharp increase in traffic, applications still need to play a role, but such sudden traffic spikes are not common. It would be a waste of resources to be put on standby based on the ability to handle such peak access requests. The use of Message Queue allows key components to withstand sudden access pressure, without a complete crash due to sudden overload of requests.5. Recoverability:When some components of the system become invalid, the entire system is not affected. Message Queue reduces the coupling between processes. Even if a process that processes messages fails, messages added to the queue can still be processed after the system recovers.6. Sequence assurance:In most use cases, the order of data processing is very important. Most message queues are originally ordered, and data can be processed in a specific order. (Kafka ensures the order of messages in a Partition)7. Buffer:It helps to control and optimize the speed at which data streams pass through the system and solve the inconsistency between the processing speed of messages produced and consumed.8. asynchronous communication:In many cases, users do not want or need to process messages immediately. The message queue provides an asynchronous processing mechanism that allows you to put a message into the queue but does not process it immediately. Messages that you want to put into the queue are then processed as needed.
Ii. kafka Architecture
2.1 Topology
For example:
Figure. 1
2.2 concepts
In. 1, kafka terms are explained as follows:
1. producer:The message producer publishes a message to the terminal or service of the kafka cluster.2. broker:Servers contained in the kafka cluster.3. topic:The category of each message that is published to the kafka cluster. That is, kafka is topic-oriented.4. partition:Partition is a physical concept. Each topic contains one or more partitions. The Unit allocated by kafka is partition.5. consumer:A terminal or service that consumes messages from a kafka cluster.6. Consumer group:In the high-level consumer API, each consumer belongs to a consumer group. Each message can only be consumed by one consumer in the Consumer group, but can be consumed by multiple consumer groups.7. replica:A copy of the partition to ensure high availability of the partition.8. leader:A role in replica. producer and consumer only interact with leader.9. follower:A role in replica that copies data from the leader.10. controller:One server in the kafka cluster is used for leader election and various failovers.12. zookeeper:Kafka uses zookeeper to store the meta information of the cluster.
2.3 zookeeper Node
Shows the storage structure of kafka in zookeeper:
Figure 2
3. The producer publishes a message.
3.1 write mode
The producer publishes messages to the broker in the push mode. Each message is appended to the patition, which is a sequential write disk (sequential write disk is more efficient than random write memory, ensure kafka throughput ).
3.2 message routing
When the producer sends a message to the broker, it selects the partition to which the message is stored Based on the partition algorithm. The routing mechanism is as follows:
1. if patition is specified, it will be used directly; 2. if patition is not specified but the key is specified, a patition3. patition and key are not specified by hash of the key value, and a patition is selected by polling.
The source code of the java client partition is included, which is clear at a glance:
// Create a message instance public ProducerRecord (String topic, Integer partition, Long timestamp, K key, V value) {if (topic = null) throw new IllegalArgumentException ("Topic cannot be null"); if (timestamp! = Null & timestamp <0) throw new IllegalArgumentException ("Invalid timestamp" + timestamp); this. topic = topic; this. partition = partition; this. key = key; this. value = value; this. timestamp = timestamp;} // calculate patition. If patition is specified, use it directly. Otherwise, use the key to calculate private int partition (ProducerRecord <K, V> record, byte [] serializedKey, byte [] serializedValue, Cluster cluster) {Integer partition = record. part Ition (); if (partition! = Null) {List <PartitionInfo> partitions = cluster. partitionsForTopic (record. topic (); int lastPartition = partitions. size ()-1; if (partition <0 | partition> lastPartition) {throw new IllegalArgumentException (String. format ("Invalid partition given with record: % d is not in the range [0... % d]. ", partition, lastPartition);} return partition;} return this. partitioner. partition (record. topic (), record. key (), serializedKey, record. value (), serializedValue, cluster);} // use the key to select patitionpublic int partition (String topic, Object key, byte [] keyBytes, Object value, byte [] valueBytes, cluster cluster) {List <PartitionInfo> partitions = cluster. partitionsForTopic (topic); int numPartitions = partitions. size (); if (keyBytes = null) {int nextValue = counter. getAndIncrement (); List <PartitionInfo> availablePartitions = cluster. availablePartitionsForTopic (topic); if (availablePartitions. size ()> 0) {int part = DefaultPartitioner. toPositive (nextValue) % availablePartitions. size (); return availablePartitions. get (part ). partition ();} else {return defaparpartitioner. toPositive (nextValue) % numPartitions;} else {// hash keyBytes to select a patition return DefaultPartitioner. toPositive (Utils. murmur2 (keyBytes) % numPartitions ;}}
3.3 write process
The following figure shows the sequence of messages written by producer:
Figure 3
Process description:
1. producer first from zookeeper's "/brokers /... the/state node finds the leader2. producer of the partition and sends the message to the leader3. leader to write the message to the local log4. followers pull message from the leader, after the local log is written, the leader sends ACK5. leader receives the ACK of replica in all ISR, adds HW (high watermark, final commit offset), and sends ACK to the producer.
3.4 producer delivery guarantee
Generally, there are three situations:
1. at most once messages may be lost, but will never be transmitted again. at least one messages will never be lost, but may be transmitted again. exactly once each message is certainly transmitted once and only once
When the producer sends a message to the broker, once the message is committed, it will not be lost because of the existence of replication. However, if the communication is interrupted due to network problems after the producer sends data to the broker, the Producer cannot determine whether the message has been committed. Although Kafka cannot determine what happened during a network failure, the producer can generate something similar to a primary key. In the event of a failure, the power is equivalent to multiple retries, so that Exactly once is achieved, but not yet. Therefore, by default, At least once is ensured for the next message from producer to broker. You can implement At most once by setting the asynchronous sending of producer.
4. The broker saves the message.
4.1 Storage Method
Physically, topics are divided into one or more patition (corresponding to server. num. partitions = 3 configuration), each patition physically corresponds to a folder (this folder stores all messages and index files of the patition), as follows:
Figure 4
4.2 Storage Policy
No matter whether the message is consumed or not, kafka retains all messages. There are two policies to delete old data:
1. Based on Time: log. retention. hours = 1682. Based on Size: log. retention. bytes = 1073741824
It should be noted that because the time complexity for Kafka to read a specific message is O (1), that is, it has nothing to do with the file size. Therefore, deleting an expired file here is irrelevant to improving the Kafka performance.
4.3 topic creation and Deletion
4.3.1 create a topic
The sequence diagram for creating a topic is as follows:
Figure 5
Process description:
1. The controller registers watcher on the/brokers/topics node of ZooKeeper. When a topic is created, the controller obtains the partition/replica allocation of the topic through watch. 2. the controller reads the list of all available brokers from/brokers/ids. For each partition in set_p: 2.1, all replica (called AR) allocated to the partition) select an available broker as the new leader, set AR to ISR2.2 to write the new leader and ISR to/brokers/topics/[topic]/partitions/[partition]/state3. the controller sends the LeaderAndISRRequest to the relevant broker through RPC.
4.3.2 delete a topic
The sequence diagram for deleting a topic is as follows:
Figure 6
Process description:
1. The controller registers watcher on the/brokers/topics node of zooKeeper. When the topic is deleted, the controller obtains the partition/replica allocation of the topic through watch. 2. If delete. topic. enable = false, the process ends. Otherwise, the watch registered by the controller on/admin/delete_topics is fired, and the controller sends StopReplicaRequest to the corresponding broker through callback.
5. kafka HA
5.1 replication
As shown in. 1, the same partition may have multiple replica (corresponding to default. replication. factor = N in server. properties configuration ). In the absence of replica, once the broker goes down, all the patition data on the broker cannot be consumed, and the producer cannot store the data on the patition. After replication is introduced, the same partition may have multiple replica. In this case, you need to select a leader between these replica. The producer and consumer only interact with this leader, the other replica copies data from the leader as the follower.
The algorithm for allocating Replica to Kafka is as follows:
1. sort all brokers (n brokers in total) and the partitions to be allocated. 2. allocate the I-th partition to the (I mod n) broker. allocate the j replica of the I partition to the (I + j) mode n) broker.
5.2 leader failover
When the leader corresponding to partition goes down, you need to select a new leader from follower. When a new leader is elected, a basic principle is that the new leader must have all the messages that the old leader commit.
Kafka is in zookeeper (/brokers /... /state) dynamically maintains an ISR (in-sync replicas). From the write process in section 3.3, we can see that all replica in the ISR keep up with the leader, only members in ISR can be selected as the leader. For f + 1 replica, a partition can ensure that messages are not lost when the failure of f replica is tolerated.
When no replica works, there are two feasible solutions:
1. Wait for any replica in the ISR to survive and select it as the leader. Data is not lost, but the time may be relatively long. 2. Select the first active replica (not necessarily an ISR member) as the leader. It is impossible to ensure that data is not lost, but the relative unavailable time is short.
Kafka 0. 8. * uses the second method.
Kafka uses the Controller to elect the leader. For the process, see section 5.3.
5.3 broker failover
The following figure shows the kafka broker failover sequence:
Figure. 7
Process description:
1. the controller registers Watcher on the/brokers/ids/[brokerId] node of zookeeper. When the broker goes down, zookeeper will fire watch2. the controller reads data from/brokers/ids and can use broker3. the controller determines set_p, this set contains all partition4. for every partition 4.1 In set_p, read ISR 4.2 From/brokers/topics/[topic]/partitions/[partition]/state node, and decide the new leader. (as described in section 4.3) 4.3 write information such as new leader, ISR, controller_epoch, and leader_epoch to the state node. send the leaderAndISRRequest command to the broker through RPC.
5.4 controller failover
When the controller goes down, the controller failover is triggered. Every broker registers watcher on the "/controller" node of zookeeper. When the controller is down, the temporary node in zookeeper disappears, and all the surviving brokers receive the fire notification, each broker tries to create a new controller path. Only one broker is successfully elected as the controller.
When a new controller is selected, the KafkaController. onControllerFailover method is triggered. Complete the following operations in this method:
1. Read and add the Controller Epoch. 2. Register watcher on the reassignedPartitions Patch (/admin/reassign_partitions. 3. Register watcher on preferredReplicaElection Path (/admin/preferred_replica_election. 4. Register watcher on the broker Topics Patch (/brokers/topics) through partitionStateMachine. 5. If delete. topic. enable = true (the default value is false), partitionStateMachine registers watcher on the Delete Topic Patch (/admin/delete_topics. 6. Use replicaStateMachine to register Watch on the Broker Ids Patch (/brokers/ids. 7. initialize the ControllerContext object and set the list of currently all topics, "active" brokers, and the leader and ISR of all partition. 8. Start replicaStateMachine and partitionStateMachine. 9. Set the brokerState status to RunningAsController. 10. Send the Leadership information of each partition to all "active" brokers. 11. If auto. leader. rebalance. enable = true (default value: true), start the partition-rebalance thread. 12. If delete. topic. enable = true and Delete Topic Patch (/admin/delete_topics) has a value, delete the corresponding Topic.
6. consumer consumes messages
6.1 consumer API
Kafka provides two sets of consumer APIs:
1. The high-level Consumer API2. The SimpleConsumer API
The high-level consumer API provides a high-level abstraction for consuming data from kafka, while SimpleConsumer API requires developers to pay more attention to details.
6.1.1 The high-level consumer API
The high-level consumer API provides the consumer group semantics. A message can only be consumed by one consumer in the group, and the consumer does not pay attention to offset when consuming the message. The last offset is saved by zookeeper.
The high-level consumer API can be a multi-threaded application. Note the following:
1. if the number of consumption threads is greater than the number of patition, some threads will not receive messages 2. if the number of patition messages is greater than the number of threads, some threads receive messages with multiple patition messages. if a thread consumes multiple patition messages, the order of the messages you receive is not guaranteed, and the messages in a patition are ordered.
6.1.2 The SimpleConsumer API
If you want to have more control over patition, you should use SimpleConsumer API, such:
1. Read one message multiple times. 2. Only consume some messages in one patition. 3. Use transactions to ensure that one message is consumed only once.
However, when using this API, partition, offset, broker, and leader are no longer transparent to you and need to be managed by yourself. You need to do a lot of extra work:
1. You must track the offset in the application to determine which message should be consumed next. 2. The application needs to know who the leader of each Partition is through the program. 3. You need to process the leader change.
The general process of using SimpleConsumer API is as follows:
1. find a "alive" broker and find leader2. for each partition. Find follower3. define the request for each partition. The request should be able to describe what data the application needs. 4. fetch data 5. identify leader changes and make necessary responses
The following describes the high-level Consumer API.
6.2 consumer group
As mentioned in section 2.2, the distribution unit of kafka is patition. Each consumer belongs to a group, and a partition can only be consumed by one consumer in the same group (this ensures that a message can only be consumed by one consuemr in the group ), however, multiple groups can consume this partition at the same time.
One of kafka's design goals is to achieve both offline processing and real-time processing. Based on this feature, real-time processing systems such as spark and Storm can be used to process messages online, at the same time, you can use the Hadoop Batch Processing System for offline processing and back up data to another data center. You only need to ensure that these three belong to different consumer groups. As shown in:
Figure 8
6.3 consumption Method
Consumer uses the pull mode to read data from the broker.
The push mode is difficult to adapt to consumers with different consumption rates, because the message sending rate is determined by the broker. Its goal is to transmit messages as quickly as possible, but this can easily cause consumer to have no time to process the messages. A typical manifestation is denial of service and network congestion. The pull mode can consume messages at an appropriate rate based on the Consumption capability of the consumer.
For Kafka, the pull mode is more suitable. It simplifies the design of the broker, and the consumer can independently control the message consumption rate, at the same time, the consumer can control the consumption method by itself-Batch consumption can also be consumed one by one, and different submission methods can be selected to achieve different transmission semantics.
6.4 consumer delivery guarantee
If you set consumer to autocommit, consumer automatically commit once it reads data. If you only discuss the process of reading the message, Kafka ensures Exactly once.
However, in actual use, the application does not end when the consumer reads data, but needs to be further processed. The order of data processing and commit determines to a large extent the consumer delivery guarantee:
1. After reading the message, commit the message before processing the message.In this mode, if the consumer has not had time to process the message after the commit, the crash will fail to read the message that has just been submitted but not processed after the next restart, this corresponds to At most once2. After reading the message, process it and then commit it.In this mode, if the consumer crash is completed before the commit is completed after the message is processed, the message that has not been commit will be processed the next time you start to work. In fact, the message has already been processed. This corresponds to At least once.3. If Exactly once is required, it is necessary to coordinate the offset and the output of the actual operation.The typical practice is to introduce two-phase commit. If the offset and operation input can exist in the same place, it is more concise and common. This method may be better because many output systems may not support two-phase commit. For example, after the consumer obtains the data, it may put the data in HDFS. If the latest offset is written to HDFS together with the data itself, the data output and offset update can be ensured to be completed either, either not, or indirectly implement Exactly once. (Currently, for the high-level API, offset is stored in Zookeeper and cannot be stored in HDFS. The offset of SimpleConsuemr API is maintained by itself and can be stored in HDFS)
In short, Kafka guarantees At least once by default, and allows At most once by setting the producer asynchronous commit (see kafka consumer to prevent data loss). Exactly once requires collaboration with external storage systems. Fortunately, the offset provided by kafka can be very direct and easy to use.