Interface ConsumerRebalanceListener


public interface ConsumerRebalanceListener
A callback interface that the user can implement to trigger custom actions when the set of partitions assigned to the consumer changes.

This is applicable when the consumer is having Kafka auto-manage group membership. If the consumer directly assigns partitions, those partitions will never be reassigned and this callback is not applicable.

When Kafka is managing the group membership, a partition re-assignment will be triggered any time the members of the group change or the subscription of the members changes. This can occur when processes die, new process instances are added or old instances come back to life after failure. Partition re-assignments can also be triggered by changes affecting the subscribed topics (e.g. when the number of partitions is administratively adjusted).

There are many uses for this functionality. One common use is saving offsets in a custom store. By saving offsets in the onPartitionsRevoked(Collection) call we can ensure that any time partition assignment changes the offset gets saved.

Another use is flushing out any kind of cache of intermediate results the consumer may be keeping. For example, consider a case where the consumer is subscribed to a topic containing user page views, and the goal is to count the number of page views per user for each five minute window. Let's say the topic is partitioned by the user id so that all events for a particular user go to a single consumer instance. The consumer can keep in memory a running tally of actions per user and only flush these out to a remote data store when its cache gets too big. However if a partition is reassigned it may want to automatically trigger a flush of this cache, before the new owner takes over consumption.

This callback will only execute in the user thread as part of the poll(long) call whenever partition assignment changes.

Under normal conditions, if a partition is reassigned from one consumer to another, then the old consumer will always invoke onPartitionsRevoked for that partition prior to the new consumer invoking onPartitionsAssigned for the same partition. So if offsets or other state is saved in the onPartitionsRevoked call by one consumer member, it will always be accessible by the time the other consumer member taking over that partition and triggering its onPartitionsAssigned callback to load the state.

You can think of revocation as a graceful way to give up ownership of a partition. In some cases, the consumer may not have an opportunity to do so. For example, if the session times out, then the partitions may be reassigned before we have a chance to revoke them gracefully. For this case, we have a third callback onPartitionsLost(Collection). The difference between this function and onPartitionsRevoked(Collection) is that upon invocation of onPartitionsLost(Collection), the partitions may already be owned by some other members in the group and therefore users would not be able to commit its consumed offsets for example. Users could implement these two functions differently (by default, onPartitionsLost(Collection) will be calling onPartitionsRevoked(Collection) directly); for example, in the onPartitionsLost(Collection) we should not need to store the offsets since we know these partitions are no longer owned by the consumer at that time.

During a rebalance event, the onPartitionsAssigned function will always be triggered exactly once when the rebalance completes. That is, even if there is no newly assigned partitions for a consumer member, its onPartitionsAssigned will still be triggered with an empty collection of partitions. As a result this function can be used also to notify when a rebalance event has happened. With eager rebalancing, onPartitionsRevoked(Collection) will always be called at the start of a rebalance. On the other hand, onPartitionsLost(Collection) will only be called when there were non-empty partitions that were lost. With cooperative rebalancing, onPartitionsRevoked(Collection) and onPartitionsLost(Collection) will only be triggered when there are non-empty partitions revoked or lost from this consumer member during a rebalance event.

It is possible for a WakeupException or InterruptException to be raised from one of these nested invocations. In this case, the exception will be propagated to the current invocation of KafkaConsumer.poll(java.time.Duration) in which this callback is being executed. This means it is not necessary to catch these exceptions and re-attempt to wakeup or interrupt the consumer thread. Also if the callback function implementation itself throws an exception, this exception will be propagated to the current invocation of KafkaConsumer.poll(java.time.Duration) as well.

Note that callbacks only serve as notification of an assignment change. They cannot be used to express acceptance of the change. Hence throwing an exception from a callback does not affect the assignment in any way, as it will be propagated all the way up to the KafkaConsumer.poll(java.time.Duration) call. If user captures the exception in the caller, the callback is still assumed successful and no further retries will be attempted.

Here is pseudo-code for a callback implementation for saving offsets:

 
   public class SaveOffsetsOnRebalance implements ConsumerRebalanceListener {
       private Consumer<?,?> consumer;

       public SaveOffsetsOnRebalance(Consumer<?,?> consumer) {
           this.consumer = consumer;
       }

       public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
           // save the offsets in an external store using some custom code not described here
           for(TopicPartition partition: partitions)
              saveOffsetInExternalStore(consumer.position(partition));
       }

       public void onPartitionsLost(Collection<TopicPartition> partitions) {
           // do not need to save the offsets since these partitions are probably owned by other consumers already
       }

       public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
           // read the offsets from an external store using some custom code not described here
           for(TopicPartition partition: partitions)
              consumer.seek(partition, readOffsetFromExternalStore(partition));
       }
   }
 
 
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    A callback method the user can implement to provide handling of customized offsets on completion of a successful partition re-assignment.
    default void
    A callback method you can implement to provide handling of cleaning up resources for partitions that have already been reassigned to other consumers.
    void
    A callback method the user can implement to provide handling of offset commits to a customized store.
  • Method Details

    • onPartitionsRevoked

      void onPartitionsRevoked(Collection<TopicPartition> partitions)
      A callback method the user can implement to provide handling of offset commits to a customized store. This method will be called during a rebalance operation when the consumer has to give up some partitions. The consumer may need to give up some partitions (thus this callback executed) under the following scenarios: It is recommended that offsets should be committed in this callback to either Kafka or a custom offset store to prevent duplicate data.

      This callback is always called before re-assigning the partitions. If the consumer is using the GroupProtocol.CLASSIC rebalance protocol:

      • In eager rebalancing, onPartitionsRevoked will be called with the full set of assigned partitions as a parameter (all partitions are revoked). It will be called even if there are no partitions to revoke.
      • In cooperative rebalancing, onPartitionsRevoked will be called with the set of partitions to revoke, iff the set is non-empty.
      If the consumer is using the GroupProtocol.CONSUMER rebalance protocol, this callback will be called with the set of partitions to revoke iff the set is non-empty (same behavior as the GroupProtocol.CLASSIC rebalance protocol with Cooperative mode).

      For examples on usage of this API, see Usage Examples section of KafkaConsumer.

      It is common for the revocation callback to use the consumer instance in order to commit offsets. It is possible for a WakeupException or InterruptException to be raised from one of these nested invocations. In this case, the exception will be propagated to the current invocation of KafkaConsumer.poll(java.time.Duration) in which this callback is being executed. This means it is not necessary to catch these exceptions and re-attempt to wakeup or interrupt the consumer thread.

      Parameters:
      partitions - The list of partitions that were assigned to the consumer and now need to be revoked. This will include the full assignment under the Classic/Eager protocol, given that it revokes all partitions. It will only include the subset to revoke under the Classic/Cooperative and Consumer protocols.
      Throws:
      WakeupException - If raised from a nested call to KafkaConsumer
      InterruptException - If raised from a nested call to KafkaConsumer
    • onPartitionsAssigned

      void onPartitionsAssigned(Collection<TopicPartition> partitions)
      A callback method the user can implement to provide handling of customized offsets on completion of a successful partition re-assignment. This method will be called after the partition re-assignment completes (even if no new partitions were assigned to the consumer), and before the consumer starts fetching data, and only as the result of a poll(long) call.

      It is guaranteed that under normal conditions all the processes in a consumer group will execute their onPartitionsRevoked(Collection) callback before any instance executes this onPartitionsAssigned callback. During exceptional scenarios, partitions may be migrated without the old owner being notified (i.e. their onPartitionsRevoked(Collection) callback not triggered), and later when the old owner consumer realized this event, the onPartitionsLost(Collection) callback will be triggered by the consumer then.

      It is common for the assignment callback to use the consumer instance in order to query offsets. It is possible for a WakeupException or InterruptException to be raised from one of these nested invocations. In this case, the exception will be propagated to the current invocation of KafkaConsumer.poll(java.time.Duration) in which this callback is being executed. This means it is not necessary to catch these exceptions and re-attempt to wakeup or interrupt the consumer thread.

      Parameters:
      partitions - Partitions that have been added to the assignment as a result of the rebalance. Note that partitions that were already owned by this consumer and remain assigned are not included in this list under the Classic/Cooperative or Consumer protocols. THe full assignment will be received under the Classic/Eager protocol.
      Throws:
      WakeupException - If raised from a nested call to KafkaConsumer
      InterruptException - If raised from a nested call to KafkaConsumer
    • onPartitionsLost

      default void onPartitionsLost(Collection<TopicPartition> partitions)
      A callback method you can implement to provide handling of cleaning up resources for partitions that have already been reassigned to other consumers. This method will not be called during normal execution as the owned partitions would first be revoked by calling the onPartitionsRevoked(java.util.Collection<org.apache.kafka.common.TopicPartition>), before being reassigned to other consumers during a rebalance event. However, during exceptional scenarios when the consumer realized that it does not own this partition any longer, i.e. not revoked via a normal rebalance event, then this method would be invoked.

      For example, this function is called if a consumer's session timeout has expired, or if a fatal error has been received indicating the consumer is no longer part of the group.

      By default it will just trigger onPartitionsRevoked(java.util.Collection<org.apache.kafka.common.TopicPartition>); for users who want to distinguish the handling logic of revoked partitions v.s. lost partitions, they can override the default implementation.

      It is possible for a WakeupException or InterruptException to be raised from one of these nested invocations. In this case, the exception will be propagated to the current invocation of KafkaConsumer.poll(java.time.Duration) in which this callback is being executed. This means it is not necessary to catch these exceptions and re-attempt to wakeup or interrupt the consumer thread.

      Parameters:
      partitions - The list of partitions that were assigned to the consumer and now have been reassigned to other consumers. With both, the Classic and Consumer protocols, this will always include all partitions that were previously assigned to the consumer.
      Throws:
      WakeupException - If raised from a nested call to KafkaConsumer
      InterruptException - If raised from a nested call to KafkaConsumer