Java Code Examples for org.apache.kafka.clients.consumer.OffsetOutOfRangeException

The following examples show how to use org.apache.kafka.clients.consumer.OffsetOutOfRangeException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
 * Calling nextRecord calls fillBuffer() which has special handling for OutOfRangeExceptions.  There is some
 * recursion in this method, but it should not go on forever and yield a StackOverflow exception.  This test verifies
 * that when the KafkaConsumer is relentlessly throwing OutOfRangeExceptions that we stop trying to fill the buffer
 * after five attempts and do not have any other errors.
public void testNextRecordWithRecursiveOutOfRangeException() {
    // Create mock KafkaConsumer instance
    final KafkaConsumer<byte[], byte[]> mockKafkaConsumer = (KafkaConsumer<byte[], byte[]>) mock(KafkaConsumer.class);

        Stream.of(new TopicPartition("Foobar", 0)).collect(Collectors.toSet())
        new PartitionInfo(topicName, 0, null, null, null)
        new OffsetOutOfRangeException(new HashMap<>())

    final PersistenceAdapter persistenceAdapter = new InMemoryPersistenceAdapter(); HashMap<>());

    // Create our consumer
    final Consumer consumer = new Consumer(mockKafkaConsumer);
        new LogRecorder(),

    final Record record = consumer.nextRecord();


    Mockito.verify(mockKafkaConsumer, Mockito.times(5)).poll(300);

Example 2
private long positionMain(TopicPartition partition, Duration timeout) {
  // Not handling large message here. The position will be actual position.
  while (true) { // In kafka 0.10.x we can get an unbounded number of invalid offset exception
    try {
      if (timeout == null) {
        return _kafkaConsumer.position(partition);
      } else {
        return _kafkaConsumer.position(partition, timeout);
    } catch (OffsetOutOfRangeException | NoOffsetForPartitionException oe) {
Example 3
 * Internal method used to fill internal message buffer from kafka.
 * Limited by the number of trips made. This should only be called from {@link #fillBuffer()}.
private void fillBuffer(final int trips) {
    // If our buffer is null, or our iterator is at the end
    if (buffer == null || !bufferIterator.hasNext()) {

        // If we have no assigned partitions to consume from, then don't call poll()
        // The underlying consumer call here does NOT make an API call, so this is safe to call within this loop.
        if (getKafkaConsumer().assignment().isEmpty()) {
            // No assigned partitions, nothing to consume :)

        // Time to refill the buffer
        try {
            buffer = getKafkaConsumer().poll(300);
        } catch (OffsetOutOfRangeException outOfRangeException) {
            // Handle it

            // Clear out so we can attempt next time.
            buffer = null;
            bufferIterator = null;

            // Why 5? Because it's less than 6.
            if (trips >= 5) {
                    "Attempted to fill the buffer after an OffsetOutOfRangeException, but this was my fifth attempt so I'm bailing."
                // nextRecord() will get called by the VirtualSpout instance soon so we're not giving up, just avoiding a StackOverflow
                // exception on this current run of checks.

            fillBuffer(trips + 1);

        // Create new iterator
        bufferIterator = buffer.iterator();
Example 4
 * This method handles when a partition seek/retrieve request was out of bounds.
 * This happens in two scenarios:
 *  1 - The offset is too old and was cleaned up / removed by the broker.
 *  2 - The offset just plain does not exist.
 * This is particularly nasty in that if the poll() was able to pull SOME messages from
 * SOME partitions before the exception was thrown, those messages are considered "consumed"
 * by KafkaClient, and there's no way to get them w/o seeking back to them for those partitions.
 * This means when we roll back, we may replay some messages :/
 * @param outOfRangeException The exception that was raised by the consumer.
private void handleOffsetOutOfRange(final OffsetOutOfRangeException outOfRangeException) {
    final Set<TopicPartition> resetPartitions = new HashSet<>();

    // Loop over all the partitions in this exception
    for (final TopicPartition topicPartition : outOfRangeException.offsetOutOfRangePartitions().keySet()) {
        // The offset that was in the error
        final long exceptionOffset = outOfRangeException.offsetOutOfRangePartitions().get(topicPartition);
        // What kafka says the last offset is
        final long endingOffset = getKafkaConsumer().endOffsets(Collections.singletonList(topicPartition))

        logger.warn("Offset Out of Range for partition {} at offset {}, kafka says last offset in partition is {}",
            topicPartition.partition(), exceptionOffset, endingOffset);

        // We have a hypothesis that the consumer can actually seek past the last message of the topic,
        // this yields this error and we want to catch it and try to back it up just a bit to a place that
        // we can work from.
        if (exceptionOffset >= endingOffset) {
                "OutOfRangeException yielded offset {}, which is past our ending offset of {} for {}",

            // Seek to the end we found above.  The end may have moved since we last asked, which is why we are not doing seekToEnd()

                new ConsumerPartition(topicPartition.topic(), topicPartition.partition()),
        } else {

    // All of the error'd partitions we need to seek to earliest available position.
Example 5
@Test(dataProvider = "offsetResetStrategies")
public void testOffsetOutOfRangeForStrategy(LiOffsetResetStrategy strategy) throws Exception {
  Properties props = new Properties();
  props.setProperty("", "testOffsetOutOfRange");

  TopicPartition tp = new TopicPartition(TOPIC1, 0);
  try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
    ConsumerRecords<String, String> consumerRecords = ConsumerRecords.empty();, 0);
    while (consumerRecords.isEmpty()) {
      consumerRecords = consumer.poll(1000);
    }, 100000L);
    assertEquals(consumer.position(tp), 100000L);
    switch (strategy) {
      case EARLIEST:
        long expectedEarliestOffset = consumerRecords.iterator().next().offset();
        consumerRecords = ConsumerRecords.empty();
        while (consumerRecords.isEmpty()) {
          consumerRecords = consumer.poll(1000);
        assertEquals(consumerRecords.iterator().next().offset(), expectedEarliestOffset,
            "The offset should have been reset to the earliest offset");
      case LATEST:
        long expectedLatestOffset = consumer.endOffsets(Collections.singleton(tp)).get(tp);
        assertEquals(consumer.position(tp), expectedLatestOffset,
            "The offset should have been reset to the latest offset");
      case LICLOSEST:
        long expectedEndOffset = consumer.endOffsets(Collections.singleton(tp)).get(tp);
        long currentPosition = consumer.position(tp);
        assertTrue(currentPosition == expectedEndOffset);
      case NONE:
        try {
          fail("OffsetOutOfRangeException should have been thrown.");
        } catch (OffsetOutOfRangeException oore) {
          // Expected
        fail("Unknown reset strategy " + strategy);
Example 6
private ConsumerRecords<K, V> poll(long timeout, boolean includeMetadataInTimeout) {
  ConsumerRecords<K, V> processedRecords;
  // We will keep polling until timeout.
  long now = System.currentTimeMillis();
  long deadline = now + timeout;
  do {
    ConsumerRecordsProcessingException crpe;

    // throw exception to user if the current active (un-paused) topic-partitions has exceptions
    Set<TopicPartition> unPausedTopicPartitions = new HashSet<>(_kafkaConsumer.assignment());
    crpe = handleRecordProcessingException(unPausedTopicPartitions);
    if (crpe != null) {
      throw crpe;

    if (_autoCommitEnabled && now > _lastAutoCommitMs + _autoCommitInterval) {
      _lastAutoCommitMs = now;
    ConsumerRecords<byte[], byte[]> rawRecords = ConsumerRecords.empty();
    try {
      if (includeMetadataInTimeout) {
        rawRecords = _kafkaConsumer.poll(Duration.ofMillis(deadline - now));
      } else {
        rawRecords = _kafkaConsumer.poll(deadline - now);
    } catch (OffsetOutOfRangeException | NoOffsetForPartitionException oe) {

    _lastProcessedResult = _consumerRecordsProcessor.process(rawRecords);
    processedRecords = _lastProcessedResult.consumerRecords();
    // Clear the internal reference.
    // Rewind offset if there are processing exceptions.

    // this is an optimization
    // if no records were processed try to throw exception in current poll()
    if (processedRecords.isEmpty()) {
      crpe = handleRecordProcessingException(null);
      if (crpe != null) {
        throw crpe;
    now = System.currentTimeMillis();
  } while (processedRecords.isEmpty() && now < deadline);
  return processedRecords;
Example 7
 * This method handles the OffsetResetStrategy="LICLOSEST" offset reset strategy.
 * The semantics of this strategy is defined as follows:
 * Consumer will {@link #seekToBeginning(Collection)} when InvalidOffsetException occurs due to:
 * 1. New Consumer / Expired Commit Offset
 * 2. Fall-off Start (fetch offset < LSO)
 * Consumer will {@link #seekToEnd(Collection)} when InvalidOffsetException occurs due to:
 * 3a. Fall-off End (fetch offset > LEO): Consumer will seek to the end
 * 3b. Fall-off End (fetch offset <= LEO): Consumer will seek to the fetched offset
 * Note: Offset to which we reset may not necessarily be a safe offset. This method invokes 2 blocking calls and does
 * ignore large-message tracking metadata. If we are unable to calculate the bounds, it will throw an
 * IllegalStateException.
 * Design details can be found here -
 * @param oe InvalidOffsetException
private void handleLiClosestResetStrategy(InvalidOffsetException oe) {
  if (oe instanceof NoOffsetForPartitionException) {  // Case 1"No valid offsets found. Rewinding to the earliest");
  } else if (oe instanceof OffsetOutOfRangeException) {
    Map<TopicPartition, Long> seekBeginningPartitions = new HashMap<>();
    Map<TopicPartition, Long> seekEndPartitions = new HashMap<>();
    Map<TopicPartition, Long> seekFetchedOffsetPartitions = new HashMap<>();
    Set<TopicPartition> boundsUnknownPartitions = new HashSet<>();

    Map<TopicPartition, Long> beginningOffsets = beginningOffsets(oe.partitions());
    Map<TopicPartition, Long> endOffsets = endOffsets(oe.partitions());

    ((OffsetOutOfRangeException) oe).offsetOutOfRangePartitions().forEach((tp, fetchedOffset) -> {
      long beginningOffset = beginningOffsets.getOrDefault(tp, -1L);
      long endOffset = endOffsets.getOrDefault(tp, -1L);
      if (beginningOffset != -1L && endOffset != -1L) {
        if (beginningOffset > fetchedOffset) {  // Case 2
          seekBeginningPartitions.put(tp, beginningOffset);
        if (endOffset < fetchedOffset) {  // Case 3a
          LOG.debug("Closest offset computed for topic partition {} is the log end offset {}. ", tp, fetchedOffset);
          seekEndPartitions.put(tp, endOffset);
        } else {  // Case 3b: endOffset >= fetchedOffset
          LOG.debug("Closest offset computed for topic partition {} is the fetched offset {}. ", tp, fetchedOffset);
          seekFetchedOffsetPartitions.put(tp, fetchedOffset);
      } else {
        // can't handle reset if the either bound values are not known
        // ideally, this should never happen since the listoffsets protocol always returns all requested offset or none

    if (!boundsUnknownPartitions.isEmpty()) {
      throw new IllegalStateException("Couldn't figure out the closest offset for these topic partitions " +
          boundsUnknownPartitions + "Aborting..");

    if (!seekBeginningPartitions.isEmpty()) {"Offsets are out of range for partitions {}. Seeking to the beginning offsets returned", seekBeginningPartitions);
    if (!seekEndPartitions.isEmpty()) {"Offsets are out of range for partitions {}. Seeking to the end offsets returned", seekEndPartitions);
    if (!seekFetchedOffsetPartitions.isEmpty()) {"Seeking to fetched offsets for topic partitions {}. This may indicate a potential loss of data.",
  } else {
    throw oe;
Example 8
 * Handle when Kafka consumer throws OffsetOutOfRangeException. The base behavior is no-op.
 * @param e the Exception
protected void handleOffsetOutOfRangeException(OffsetOutOfRangeException e) {