This is an automated email from the ASF dual-hosted git repository.

KKcorps pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 5bd5627d8ba Let stream decoders ask the consumer to retry a message 
instead of dropping it (#20137)
5bd5627d8ba is described below

commit 5bd5627d8baf0afa6f848680372a0a3352c13da7
Author: Anshul Singh <[email protected]>
AuthorDate: Tue Nov 17 09:41:09 2026 +0530

    Let stream decoders ask the consumer to retry a message instead of dropping 
it (#20137)
    
    * Let stream decoders ask the consumer to retry a message instead of 
dropping it
    
    A StreamMessageDecoder had no way to say that a message may decode later: 
returning null or throwing
    dropped the message, or stopped consumption with stopOnDecodeError. A 
decoder whose schema registry was
    briefly slow or throttling therefore lost messages permanently.
    
    Add RetriableDecodeException to pinot-spi and document the decoder failure 
contract on
    StreamMessageDecoder. StreamDataDecoderImpl passes it through 
StreamDataDecoderResult (isRetriable())
    without logging every attempt.
    
    RealtimeSegmentDataManager stops the batch at such a message without moving 
_currentOffset, backs off and
    fetches again from the same offset. The backoff starts at 100 ms and 
doubles up to the stream config
    decodeRetryMaxBackoffMillis (10 s by default). Stopping and end criteria 
are checked between attempts and
    the backoff ends at the consumption deadline, so a segment that has to end 
while a message is stuck ends
    before it and the next segment starts from it. After a force commit, which 
pausing also sends, the backoff
    is skipped. stop() interrupts the backoff. A batch fetched again for a 
retry is charged to the rate
    limiters and the fetched-rows meter only for the messages it processes. 
Retries are counted in the
    REALTIME_DECODE_RETRIES meter. The first failure of an outage is logged at 
WARN with its cause and recorded
    as a segment error, later ones at most once a minute; a failure a minute 
after the previous one, with no
    message being retried, is reported afresh. While a message is stuck, the 
ingestion delay is computed from
    the last consumed message.
    
    decodeRetryMaxDurationMillis bounds an outage: retriable failures less than 
that duration apart belong to
    one outage, and once it has lasted that long they are handled like any 
other decode failure until none
    happens for that long. There is no limit by default, and 0 restores the 
previous behaviour.
    
    StatelessRealtimeSegmentWriter (re-ingestion) retries the same way, also 
bounded by the re-ingestion
    timeout, instead of leaving the message out of the re-ingested segment.
    
    * Wake the decode retry backoff when a force commit arrives
    
    A force commit that arrived while the consumer slept before retrying a 
decode waited out the sleep (up to
    decodeRetryMaxBackoffMillis, 10 s by default) before the segment could end. 
forceCommit() now wakes the
    backoff, which sleeps on a monitor instead of Thread.sleep, so the segment 
ends at the message being
    retried at once. Only a force commit that ends the segment 
(INITIAL_CONSUMING) wakes it; stop() still
    interrupts it.
    
    * Shorten comments
    
    Trim the comments this change adds to the essentials.
    
    * Use a ReentrantLock for the decode retry backoff wake
    
    The force-commit wake now signals a Condition instead of notifying an 
Object monitor.
    
    * Share the decode retry outage logic between the consumer and the 
stateless writer
    
    DecodeRetryTracker holds the outage window, retry count, backoff and 
reporting cadence; the stateless writer now also reminds once a minute. 
Document that the retry limit is per segment.
---
 .../etc/jmx_prometheus_javaagent/configs/pinot.yml |   2 +-
 .../apache/pinot/common/metrics/ServerMeter.java   |   2 +
 .../prometheus/ServerPrometheusMetricsTest.java    |   5 +-
 .../realtime/RealtimeSegmentDataManager.java       | 218 ++++++-
 .../realtime/RealtimeSegmentDataManagerTest.java   | 638 ++++++++++++++++++++-
 .../core/realtime/stream/StreamConfigTest.java     |  39 ++
 .../segment/local/realtime/DecodeRetryTracker.java | 139 +++++
 .../writer/StatelessRealtimeSegmentWriter.java     |  52 ++
 .../local/realtime/DecodeRetryTrackerTest.java     |  79 +++
 .../writer/StatelessRealtimeSegmentWriterTest.java | 261 ++++++++-
 .../pinot/spi/stream/RetriableDecodeException.java |  47 ++
 .../org/apache/pinot/spi/stream/StreamConfig.java  |  67 ++-
 .../pinot/spi/stream/StreamConfigProperties.java   |  12 +
 .../apache/pinot/spi/stream/StreamDataDecoder.java |   1 +
 .../pinot/spi/stream/StreamDataDecoderImpl.java    |   3 +
 .../pinot/spi/stream/StreamDataDecoderResult.java  |   5 +
 .../pinot/spi/stream/StreamMessageDecoder.java     |  10 +
 .../spi/stream/StreamDataDecoderImplTest.java      |  59 +-
 18 files changed, 1611 insertions(+), 28 deletions(-)

diff --git a/docker/images/pinot/etc/jmx_prometheus_javaagent/configs/pinot.yml 
b/docker/images/pinot/etc/jmx_prometheus_javaagent/configs/pinot.yml
index 5bd1d623633..77a88f09c3f 100644
--- a/docker/images/pinot/etc/jmx_prometheus_javaagent/configs/pinot.yml
+++ b/docker/images/pinot/etc/jmx_prometheus_javaagent/configs/pinot.yml
@@ -448,7 +448,7 @@ rules:
     database: "$2"
     table: "$1$3"
     tableType: "$4"
-- pattern: 
"\"org\\.apache\\.pinot\\.common\\.metrics\"<type=\"ServerMetrics\", 
name=\"pinot\\.server\\.(([^.]+)\\.)?([^.]*)_(OFFLINE|REALTIME)\\-(.+)\\-(\\w+)\\.(invalidRealtimeRowsDropped|incompleteRealtimeRowsConsumed|rowsWithErrors|realtimeRowsConsumed|realtimeRowsFetched|realtimeBytesConsumed|streamConsumerCreateExceptions)\"><>(\\w+)"
+- pattern: 
"\"org\\.apache\\.pinot\\.common\\.metrics\"<type=\"ServerMetrics\", 
name=\"pinot\\.server\\.(([^.]+)\\.)?([^.]*)_(OFFLINE|REALTIME)\\-(.+)\\-(\\w+)\\.(invalidRealtimeRowsDropped|realtimeDecodeRetries|incompleteRealtimeRowsConsumed|rowsWithErrors|realtimeRowsConsumed|realtimeRowsFetched|realtimeBytesConsumed|streamConsumerCreateExceptions)\"><>(\\w+)"
   name: "pinot_server_$7_$8"
   cache: true
   labels:
diff --git 
a/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java 
b/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java
index c58d1a95ef8..ce06bec98f9 100644
--- 
a/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java
+++ 
b/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java
@@ -48,6 +48,8 @@ public enum ServerMeter implements AbstractMetrics.Meter {
   REALTIME_ROWS_FETCHED("rows", false),
   REALTIME_ROWS_FILTERED("rows", false),
   INVALID_REALTIME_ROWS_DROPPED("rows", false),
+  // Messages fetched again after their decoder threw RetriableDecodeException
+  REALTIME_DECODE_RETRIES("retries", false),
   INCOMPLETE_REALTIME_ROWS_CONSUMED("rows", false),
   REALTIME_CLP_TOO_MANY_ENCODED_VARS("rows", false),
   REALTIME_CLP_UNENCODABLE("rows", false),
diff --git 
a/pinot-common/src/test/java/org/apache/pinot/common/metrics/prometheus/ServerPrometheusMetricsTest.java
 
b/pinot-common/src/test/java/org/apache/pinot/common/metrics/prometheus/ServerPrometheusMetricsTest.java
index 5eb006e4d38..fdf34b55264 100644
--- 
a/pinot-common/src/test/java/org/apache/pinot/common/metrics/prometheus/ServerPrometheusMetricsTest.java
+++ 
b/pinot-common/src/test/java/org/apache/pinot/common/metrics/prometheus/ServerPrometheusMetricsTest.java
@@ -41,8 +41,9 @@ public abstract class ServerPrometheusMetricsTest extends 
PinotPrometheusMetrics
   private static final List<ServerMeter> METERS_ACCEPTING_CLIENT_ID =
       List.of(ServerMeter.REALTIME_ROWS_CONSUMED, 
ServerMeter.REALTIME_ROWS_SANITIZED,
           ServerMeter.REALTIME_ROWS_FETCHED, 
ServerMeter.REALTIME_ROWS_FILTERED,
-          ServerMeter.INVALID_REALTIME_ROWS_DROPPED, 
ServerMeter.INCOMPLETE_REALTIME_ROWS_CONSUMED,
-          ServerMeter.STREAM_CONSUMER_CREATE_EXCEPTIONS, 
ServerMeter.ROWS_WITH_ERRORS);
+          ServerMeter.INVALID_REALTIME_ROWS_DROPPED, 
ServerMeter.REALTIME_DECODE_RETRIES,
+          ServerMeter.INCOMPLETE_REALTIME_ROWS_CONSUMED, 
ServerMeter.STREAM_CONSUMER_CREATE_EXCEPTIONS,
+          ServerMeter.ROWS_WITH_ERRORS);
 
   private static final List<ServerMeter> METERS_ACCEPTING_RAW_TABLE_NAMES =
       List.of(ServerMeter.SEGMENT_UPLOAD_FAILURE, 
ServerMeter.SEGMENT_UPLOAD_SUCCESS,
diff --git 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
index 36a0e513352..a6631fb0f74 100644
--- 
a/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
+++ 
b/pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManager.java
@@ -37,7 +37,9 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 import java.util.function.BooleanSupplier;
 import javax.annotation.Nullable;
 import org.apache.commons.configuration2.ex.ConfigurationException;
@@ -63,6 +65,7 @@ import 
org.apache.pinot.segment.local.dedup.PartitionDedupMetadataManager;
 import org.apache.pinot.segment.local.indexsegment.mutable.MutableSegmentImpl;
 import org.apache.pinot.segment.local.io.writer.impl.DirectMemoryManager;
 import org.apache.pinot.segment.local.io.writer.impl.MmapMemoryManager;
+import org.apache.pinot.segment.local.realtime.DecodeRetryTracker;
 import 
org.apache.pinot.segment.local.realtime.converter.RealtimeSegmentConverter;
 import org.apache.pinot.segment.local.realtime.impl.RealtimeSegmentConfig;
 import org.apache.pinot.segment.local.segment.creator.TransformPipeline;
@@ -286,6 +289,9 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
   private volatile long _numBytesDropped = 0;
   private volatile int _consecutiveErrorCount = 0;
   private volatile boolean _firstDecodeErrorLogged = false;
+  // Decode retry state, used by the consumer thread, or by the Helix thread 
catching up in CONSUMING_TO_ONLINE after
+  // the consumer thread has stopped
+  private final DecodeRetryTracker _decodeRetryTracker;
 
   // Configuration constants
   private static final String STOP_ON_DECODE_ERROR_CONFIG = 
"stopOnDecodeError";
@@ -307,6 +313,9 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
   private volatile boolean _hasMessagesFetched = false;
   private volatile boolean _endOfPartitionGroup = false;
   private volatile boolean _forceCommitMessageReceived = false;
+  // Signalled by forceCommit() to wake a decode retry backoff, so the segment 
ends without waiting it out
+  private final Lock _decodeRetryBackoffLock = new ReentrantLock();
+  private final Condition _forceCommitReceived = 
_decodeRetryBackoffLock.newCondition();
   private volatile StreamPartitionMsgOffset _finalOffset; // Exclusive, used 
when we want to catch up to this one
   private volatile boolean _shouldStop = false;
 
@@ -372,6 +381,54 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
 
   private volatile boolean _stopReasonPrinted = false;
 
+  /// Outcome of [#processStreamEvents].
+  private enum BatchOutcome {
+    PROCESSED,
+    /// Stopped early because consumption is stopping or an end criterion was 
reached.
+    STOPPED_EARLY,
+    /// Stopped at a message to decode again, without moving [#_currentOffset] 
past it.
+    DECODE_RETRY_NEEDED
+  }
+
+  /// The first messages of a batch fetched again to retry a decode, to charge 
the rate limiters for those processed.
+  /// Sized like stream batches: by serialized record size when known, 
otherwise by value size.
+  private static final class ProcessedMessages<T> implements MessageBatch<T> {
+    private final MessageBatch<T> _messageBatch;
+    private final int _numMessages;
+
+    ProcessedMessages(MessageBatch<T> messageBatch, int numMessages) {
+      _messageBatch = messageBatch;
+      _numMessages = numMessages;
+    }
+
+    @Override
+    public int getMessageCount() {
+      return _numMessages;
+    }
+
+    @Override
+    public StreamMessage<T> getStreamMessage(int index) {
+      Preconditions.checkElementIndex(index, _numMessages);
+      return _messageBatch.getStreamMessage(index);
+    }
+
+    @Override
+    public StreamPartitionMsgOffset getOffsetOfNextBatch() {
+      return getStreamMessage(_numMessages - 1).getMetadata().getNextOffset();
+    }
+
+    @Override
+    public long getSizeInBytes() {
+      long sizeInBytes = 0;
+      for (int i = 0; i < _numMessages; i++) {
+        StreamMessage<T> streamMessage = _messageBatch.getStreamMessage(i);
+        int recordSerializedSize = 
streamMessage.getMetadata().getRecordSerializedSize();
+        sizeInBytes += recordSerializedSize > 0 ? recordSerializedSize : 
streamMessage.getLength();
+      }
+      return sizeInBytes;
+    }
+  }
+
   private boolean endCriteriaReached() {
     Preconditions.checkState(_state.shouldConsume(), "Incorrect state %s", 
_state);
     long now = now();
@@ -539,11 +596,16 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
       // Consume for the next readTime ms, or we get to final offset, 
whichever happens earlier,
       // Update _currentOffset upon return from this method
       MessageBatch messageBatch;
+      // A batch fetched again to retry a decode is charged to the rate 
limiters and fetched rows meter after
+      // processing, for the processed messages only: the rest are fetched 
again later
+      boolean decodeRetryFetch = _decodeRetryTracker.isRetrying();
       try {
         messageBatch = _partitionGroupConsumer.fetchMessages(_currentOffset, 
_streamConfig.getFetchTimeoutMillis());
         //track realtime rows fetched on a table level. This included valid + 
invalid rows
-        _serverMetrics.addMeteredTableValue(_clientId, 
ServerMeter.REALTIME_ROWS_FETCHED,
-            messageBatch.getUnfilteredMessageCount());
+        if (!decodeRetryFetch) {
+          _serverMetrics.addMeteredTableValue(_clientId, 
ServerMeter.REALTIME_ROWS_FETCHED,
+              messageBatch.getUnfilteredMessageCount());
+        }
         if (_segmentLogger.isDebugEnabled()) {
           _segmentLogger.debug("message batch received. filtered={} 
unfiltered={} endOfPartitionGroup={}",
               messageBatch.getMessageCount(), 
messageBatch.getUnfilteredMessageCount(),
@@ -575,7 +637,9 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
 
       reportDataLoss(messageBatch);
 
-      boolean endCriteriaReached = processStreamEvents(messageBatch, 
idlePipeSleepTimeMillis);
+      BatchOutcome batchOutcome = processStreamEvents(messageBatch, 
idlePipeSleepTimeMillis, decodeRetryFetch);
+      boolean endCriteriaReached = batchOutcome == BatchOutcome.STOPPED_EARLY;
+      boolean decodeRetryNeeded = batchOutcome == 
BatchOutcome.DECODE_RETRY_NEEDED;
 
       if (_currentOffset.compareTo(lastUpdatedOffset) != 0) {
         _idleTimer.markEventConsumed();
@@ -590,6 +654,12 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
               _currentOffset);
         }
         // We check this flag again further down
+      } else if (decodeRetryNeeded) {
+        // Unlike an all-filtered batch, don't skip it: its first message is 
fetched again after the backoff below
+        if (_segmentLogger.isDebugEnabled()) {
+          _segmentLogger.debug("No messages processed before a retriable 
decode error. Staying at offset {}",
+              _currentOffset);
+        }
       } else if (messageBatch.getUnfilteredMessageCount() > 0) {
         _idleTimer.markEventConsumed();
         // we consumed something from the stream but filtered all the content 
out,
@@ -619,6 +689,10 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
         // check this flag to avoid calling endCriteriaReached() at the 
beginning of the loop
         break;
       }
+      if (decodeRetryNeeded) {
+        // The loop condition checks stopping and end criteria again before 
the next fetch
+        backOffBeforeDecodeRetry();
+      }
     }
 
     if (_numRowsErrored > 0) {
@@ -675,12 +749,14 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
 
   /// @param messageBatch batch of messages to process
   /// @param idlePipeSleepTimeMillis wait time in case no messages were read
-  /// @return returns `true` if the process loop ended before processing the 
batch, `false`
-  /// otherwise
-  private boolean processStreamEvents(MessageBatch messageBatch, long 
idlePipeSleepTimeMillis) {
+  /// @param decodeRetryFetch whether the batch was fetched again to retry a 
decode; it is then charged after processing
+  /// @return how processing of the batch ended
+  private BatchOutcome processStreamEvents(MessageBatch<?> messageBatch, long 
idlePipeSleepTimeMillis,
+      boolean decodeRetryFetch) {
     int messageCount = messageBatch.getMessageCount();
-    _partitionRateLimiter.throttle(messageBatch);
-    _serverRateLimiter.throttle(messageBatch);
+    if (!decodeRetryFetch) {
+      throttle(messageBatch);
+    }
 
     // One local per meter: addMeteredTableValue() marks the reused meter it 
is passed, whichever meter is named
     PinotMeter realtimeBytesIngestedMeter = null;
@@ -694,6 +770,8 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
     int streamMessageCount = 0;
     boolean canTakeMore = true;
     boolean prematureExit = false;
+    boolean decodeRetryNeeded = false;
+    StreamMessageMetadata lastProcessedMetadata = null;
 
     for (int index = 0; index < messageCount; index++) {
       prematureExit = _shouldStop || endCriteriaReached();
@@ -732,6 +810,16 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
       StreamPartitionMsgOffset offset = metadata.getOffset();
       StreamPartitionMsgOffset nextOffset = metadata.getNextOffset();
       int rowSizeInBytes = metadata.getRecordSerializedSize();
+      if (decodedRow.isRetriable() && shouldRetryDecode(offset, 
decodedRow.getException())) {
+        // Stop without moving _currentOffset past the message, so that 
consumeLoop() backs off and fetches it again
+        decodeRetryNeeded = true;
+        break;
+      }
+      int numDecodeRetries = _decodeRetryTracker.onMessageDone();
+      if (numDecodeRetries > 0) {
+        _segmentLogger.info("Resumed decoding at offset: {} after {} retriable 
decode failures", offset,
+            numDecodeRetries);
+      }
       if (decodedRow.getException() != null) {
         String errorMessage = "Stopping consumption due to decode error at 
offset: " + offset;
         if (_stopOnDecodeError) {
@@ -818,11 +906,26 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
       _numRowsIndexed = _realtimeSegment.getNumDocsIndexed();
       _numRowsConsumed++;
       streamMessageCount++;
+      lastProcessedMetadata = metadata;
     }
 
+    if (decodeRetryFetch) {
+      if (decodeRetryNeeded || prematureExit) {
+        // The message to decode again counts as processed
+        chargeProcessedMessages(messageBatch, decodeRetryNeeded ? 
streamMessageCount + 1 : streamMessageCount);
+      } else {
+        throttle(messageBatch);
+        _serverMetrics.addMeteredTableValue(_clientId, 
ServerMeter.REALTIME_ROWS_FETCHED,
+            messageBatch.getUnfilteredMessageCount());
+      }
+    }
     updateCurrentDocumentCountMetrics();
-    if (messageBatch.getUnfilteredMessageCount() > 0) {
-      StreamMessageMetadata lastMetadata = 
messageBatch.getLastMessageMetadata();
+    // On a decode retry, the ingestion delay comes from the last consumed 
message, so it grows while retrying
+    boolean consumedFromStream =
+        decodeRetryNeeded ? streamMessageCount > 0 : 
messageBatch.getUnfilteredMessageCount() > 0;
+    if (consumedFromStream) {
+      StreamMessageMetadata lastMetadata =
+          decodeRetryNeeded ? lastProcessedMetadata : 
messageBatch.getLastMessageMetadata();
       updateIngestionMetrics(lastMetadata);
       _hasMessagesFetched = true;
       // When messages were consumed from the stream but all were filtered 
out, we update
@@ -836,7 +939,7 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
         _segmentLogger.debug("Indexed {} messages ({} messages read from 
stream) current offset {}",
             indexedMessageCount, streamMessageCount, _currentOffset);
       }
-    } else if (!prematureExit) {
+    } else if (!prematureExit && !decodeRetryNeeded) {
       // Record Pinot ingestion delay as zero since we are up-to-date and no 
new events
       setIngestionDelayToZero();
       if (_segmentLogger.isDebugEnabled()) {
@@ -845,7 +948,91 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
       // If there were no messages to be fetched from stream, wait for a 
little bit as to avoid hammering the stream
       Uninterruptibles.sleepUninterruptibly(idlePipeSleepTimeMillis, 
TimeUnit.MILLISECONDS);
     }
-    return prematureExit;
+    if (decodeRetryNeeded) {
+      return BatchOutcome.DECODE_RETRY_NEEDED;
+    }
+    return prematureExit ? BatchOutcome.STOPPED_EARLY : BatchOutcome.PROCESSED;
+  }
+
+  @VisibleForTesting
+  void throttle(MessageBatch<?> messageBatch) {
+    _partitionRateLimiter.throttle(messageBatch);
+    _serverRateLimiter.throttle(messageBatch);
+  }
+
+  /// Charges the rate limiters and fetched rows meter for the first 
`numMessages` messages of a batch fetched again to
+  /// retry a decode. Charging after processing still holds the rate: the rate 
limiters let a caller take permits ahead
+  /// of the rate and make the next caller wait. Filtered messages (e.g. 
tombstones) are not counted, as the batch does
+  /// not tell where they are.
+  private void chargeProcessedMessages(MessageBatch<?> messageBatch, int 
numMessages) {
+    if (numMessages > 0) {
+      throttle(new ProcessedMessages<>(messageBatch, numMessages));
+      _serverMetrics.addMeteredTableValue(_clientId, 
ServerMeter.REALTIME_ROWS_FETCHED, numMessages);
+    }
+  }
+
+  /// Returns whether to fetch and decode the message at `offset` again after 
a retriable decode failure (see
+  /// [DecodeRetryTracker]); if not, it is handled like any other decode 
failure.
+  private boolean shouldRetryDecode(StreamPartitionMsgOffset offset, Exception 
cause) {
+    long nowMs = now();
+    DecodeRetryTracker.Outcome outcome = 
_decodeRetryTracker.onRetriableFailure(nowMs);
+    if (!outcome.isRetry()) {
+      if (outcome == DecodeRetryTracker.Outcome.GIVE_UP_AND_REPORT) {
+        _segmentLogger.warn("Retriable decode errors have lasted {}ms, giving 
up retrying the message at offset: {}. "
+                + "Until none happens for {}ms, retriable decode errors are 
handled like any other decode error",
+            _decodeRetryTracker.getOutageDurationMs(nowMs), offset, 
_decodeRetryTracker.getMaxDurationMs());
+      }
+      return false;
+    }
+    _serverMetrics.addMeteredTableValue(_clientId, 
ServerMeter.REALTIME_DECODE_RETRIES, 1L);
+    if (outcome == DecodeRetryTracker.Outcome.RETRY_AND_REPORT) {
+      String message = "Retriable decode error at offset: " + offset + ". 
Fetching and decoding it again";
+      _segmentLogger.warn(message, cause);
+      _realtimeTableDataManager.addSegmentError(_segmentNameStr, new 
SegmentErrorInfo(nowMs, message, cause));
+    } else if (outcome == DecodeRetryTracker.Outcome.RETRY_AND_REMIND) {
+      _segmentLogger.warn("Still retrying: retriable decode error at offset: 
{}, {}ms into the outage", offset,
+          _decodeRetryTracker.getOutageDurationMs(nowMs), cause);
+    } else if (_segmentLogger.isDebugEnabled()) {
+      _segmentLogger.debug("Retriable decode error at offset: {} (failure {} 
of the message)", offset,
+          _decodeRetryTracker.getNumRetries(), cause);
+    }
+    return true;
+  }
+
+  /// Sleeps the decode retry backoff, then doubles it up to the cap. The 
sleep ends at the consumption deadline, if
+  /// any, so that [#endCriteriaReached()] ends the segment (or gives up 
catching up) on time, at the message being
+  /// retried. A force commit, also sent on pause, skips or wakes the sleep; 
[#stop()] interrupts it.
+  private void backOffBeforeDecodeRetry()
+      throws InterruptedException {
+    if (_shouldStop || forceCommitEndsSegment()) {
+      return;
+    }
+    long backoffMs = _decodeRetryTracker.nextBackoffMs();
+    if (_state == State.INITIAL_CONSUMING || _state == 
State.CONSUMING_TO_ONLINE) {
+      backoffMs = Math.min(backoffMs, Math.max(_consumeEndTime - now(), 0));
+    }
+    if (backoffMs > 0) {
+      sleepBeforeDecodeRetry(backoffMs);
+    }
+  }
+
+  @VisibleForTesting
+  void sleepBeforeDecodeRetry(long backoffMs)
+      throws InterruptedException {
+    long remainingNs = TimeUnit.MILLISECONDS.toNanos(backoffMs);
+    _decodeRetryBackoffLock.lock();
+    try {
+      while (remainingNs > 0 && !forceCommitEndsSegment()) {
+        remainingNs = _forceCommitReceived.awaitNanos(remainingNs);
+      }
+    } finally {
+      _decodeRetryBackoffLock.unlock();
+    }
+  }
+
+  /// Whether a force commit ends the segment at the next end criteria check 
(only in INITIAL_CONSUMING).
+  private boolean forceCommitEndsSegment() {
+    return _state == State.INITIAL_CONSUMING && _forceCommitMessageReceived;
   }
 
   @VisibleForTesting
@@ -2094,6 +2281,7 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
           _tableNameWithType);
       _streamConfig = new StreamConfig(_tableNameWithType, 
streamConfigMaps.get(index));
     }
+    _decodeRetryTracker = new DecodeRetryTracker(_streamConfig);
     _streamConsumerFactory = 
StreamConsumerFactoryProvider.create(_streamConfig);
     _streamPartitionMsgOffsetFactory = 
_streamConsumerFactory.createStreamMsgOffsetFactory();
     String streamTopic = _streamConfig.getTopicName();
@@ -2511,6 +2699,12 @@ public class RealtimeSegmentDataManager extends 
SegmentDataManager {
 
   public void forceCommit() {
     _forceCommitMessageReceived = true;
+    _decodeRetryBackoffLock.lock();
+    try {
+      _forceCommitReceived.signalAll();
+    } finally {
+      _decodeRetryBackoffLock.unlock();
+    }
   }
 
   @VisibleForTesting
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManagerTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManagerTest.java
index f0850a4f531..936cb94022b 100644
--- 
a/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManagerTest.java
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/data/manager/realtime/RealtimeSegmentDataManagerTest.java
@@ -24,6 +24,7 @@ import java.io.IOException;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
+import java.net.SocketTimeoutException;
 import java.nio.charset.StandardCharsets;
 import java.time.Instant;
 import java.util.ArrayList;
@@ -33,10 +34,13 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.Lock;
 import java.util.function.BooleanSupplier;
 import java.util.function.Supplier;
@@ -86,12 +90,14 @@ import org.apache.pinot.spi.stream.MessageBatch;
 import org.apache.pinot.spi.stream.PartitionGroupConsumer;
 import org.apache.pinot.spi.stream.PartitionGroupConsumptionStatus;
 import org.apache.pinot.spi.stream.PermanentConsumerException;
+import org.apache.pinot.spi.stream.RetriableDecodeException;
 import org.apache.pinot.spi.stream.StreamConfigProperties;
 import org.apache.pinot.spi.stream.StreamMessage;
 import org.apache.pinot.spi.stream.StreamMessageDecoder;
 import org.apache.pinot.spi.stream.StreamMessageMetadata;
 import org.apache.pinot.spi.stream.StreamPartitionMsgOffset;
 import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.IngestionConfigUtils;
 import org.apache.pinot.spi.utils.builder.TableNameBuilder;
 import org.mockito.ArgumentCaptor;
 import org.mockito.InOrder;
@@ -100,14 +106,17 @@ import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
+import org.testng.asserts.SoftAssert;
 
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.same;
 import static org.mockito.Mockito.anyString;
 import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.inOrder;
@@ -2013,6 +2022,516 @@ public class RealtimeSegmentDataManagerTest {
     }
   }
 
+  @DataProvider
+  public Object[][] decodeRetryModes() {
+    return new Object[][]{
+        // fetchAfterStartOffset, stopOnDecodeError
+        {false, false}, {false, true}, {true, false}, {true, true}
+    };
+  }
+
+  @Test(dataProvider = "decodeRetryModes")
+  public void 
testRetriableDecodeErrorFetchesTheMessageAgainInsteadOfDroppingIt(boolean 
fetchAfterStartOffset,
+      boolean stopOnDecodeError)
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    
OffsetPayloadConsumerFactory.FETCH_AFTER_START_OFFSET.set(fetchAfterStartOffset);
+    long firstFailingOffset = START_OFFSET_VALUE + 5;
+    long secondFailingOffset = START_OFFSET_VALUE + 12;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(firstFailingOffset, new 
AtomicInteger(3));
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(secondFailingOffset, new 
AtomicInteger(1));
+    // A stream that fetches from after the given offset stands at the 
previous message
+    long fetchOffsetDelta = fetchAfterStartOffset ? 1 : 0;
+    long firstFetchOffset = firstFailingOffset - fetchOffsetDelta;
+    long secondFetchOffset = secondFailingOffset - fetchOffsetDelta;
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        new TimeSupplier(), 
Map.of(StreamConfigProperties.DECODE_RETRY_MAX_BACKOFF_MILLIS, "250",
+            "stopOnDecodeError", String.valueOf(stopOnDecodeError)))) {
+      List<Long> offsetsWhileFailing = new CopyOnWriteArrayList<>();
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(
+          () -> offsetsWhileFailing.add(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset()));
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      long retriesBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES);
+
+      consumeToRowLimitAndCommit(segmentDataManager);
+
+      SoftAssert softAssert = new SoftAssert();
+      softAssert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          0, "rows dropped");
+      softAssert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS,
+          List.of(firstFailingOffset, firstFailingOffset, firstFailingOffset, 
secondFailingOffset),
+          "offsets of the retriable decode failures");
+      softAssert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES) - retriesBefore, 4,
+          "decode retries");
+      softAssert.assertEquals(offsetsWhileFailing,
+          List.of(firstFetchOffset, firstFetchOffset, firstFetchOffset, 
secondFetchOffset),
+          "current offset during the retriable decode failures");
+      softAssert.assertEquals(OffsetPayloadConsumerFactory.FETCH_START_OFFSETS,
+          List.of(START_OFFSET_VALUE, firstFetchOffset, firstFetchOffset, 
firstFetchOffset, secondFetchOffset),
+          "fetch start offsets");
+      
softAssert.assertEquals(OffsetPayloadDecoder.getFirstDecodeAttemptAfterEachRetriableFailure(),
+          OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS, "first decode 
attempt after each retriable decode failure");
+      // Doubles up to the cap, and starts over for the second failing message
+      softAssert.assertEquals(segmentDataManager._decodeRetrySleeps, 
List.of(100L, 200L, 250L, 100L),
+          "decode retry backoffs");
+      
softAssert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
OFFSET_STREAM_SEGMENT_ROWS,
+          "rows indexed");
+      softAssert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(),
+          START_OFFSET_VALUE + OFFSET_STREAM_SEGMENT_ROWS, "current offset at 
the end of the segment");
+      
softAssert.assertEquals(segmentDataManager._state.get(segmentDataManager),
+          RealtimeSegmentDataManager.State.COMMITTED, "state");
+      softAssert.assertAll();
+      // Both failures belong to one outage, reported once
+      verify(segmentDataManager.getTableDataManager(), 
times(1)).addSegmentError(eq(SEGMENT_NAME_STR), any());
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testStopWhileRetryingDecodeExitsWithoutMovingPastTheMessage()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics)) {
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> {
+        if (OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size() == 3) {
+          segmentDataManager.stop();
+        }
+      });
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+
+      segmentDataManager.createPartitionConsumer().run();
+
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS,
+          List.of(failingOffset, failingOffset, failingOffset));
+      // No backoff once stopping
+      Assert.assertEquals(segmentDataManager._decodeRetrySleeps, List.of(100L, 
200L));
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          0);
+      // Clean exit: no ERROR state and no stoppedConsuming message
+      Assert.assertEquals(segmentDataManager._state.get(segmentDataManager),
+          RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+      Assert.assertFalse(segmentDataManager._postConsumeStoppedCalled);
+      // The ingestion delay comes from the last consumed message, not the 
batch end, and is not reset to zero
+      RealtimeTableDataManager tableDataManager = 
segmentDataManager.getTableDataManager();
+      verify(tableDataManager, 
atLeastOnce()).updateIngestionMetrics(eq(SEGMENT_NAME_STR), anyInt(), anyLong(),
+          anyLong(), argThat(offset -> isLongOffset(offset, failingOffset - 
1)));
+      verify(tableDataManager, 
never()).updateIngestionMetrics(eq(SEGMENT_NAME_STR), anyInt(), anyLong(), 
anyLong(),
+          argThat(offset -> offset == null || isLongOffset(offset, 
START_OFFSET_VALUE + OFFSET_STREAM_BATCH_SIZE - 1)));
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testStopInterruptsTheDecodeRetryBackoff()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(
+        new ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry()))) {
+      // The backoff sleeps until interrupted
+      segmentDataManager._decodeRetrySleepStarted = new CountDownLatch(1);
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+      Thread consumerThread = new 
Thread(segmentDataManager.createPartitionConsumer());
+      consumerThread.start();
+      Assert.assertTrue(segmentDataManager._decodeRetrySleepStarted.await(10, 
TimeUnit.SECONDS));
+
+      // The real stop() interrupts the consumer thread and waits for it
+      segmentDataManager.setConsumerThread(consumerThread);
+      segmentDataManager.invokeRealStop();
+
+      Assert.assertFalse(consumerThread.isAlive());
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+      Assert.assertEquals(segmentDataManager._state.get(segmentDataManager),
+          RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+      Assert.assertFalse(segmentDataManager._postConsumeStoppedCalled);
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testTimeLimitWhileRetryingDecodeEndsTheSegmentAtTheMessage()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    TimeSupplier timeSupplier = new TimeSupplier();
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        timeSupplier, Map.of())) {
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> {
+        if (OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size() == 2) {
+          timeSupplier.set(segmentDataManager.getConsumeEndTime());
+        }
+      });
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+      LongMsgOffset failingMsgOffset = new LongMsgOffset(failingOffset);
+      segmentDataManager._consumeOffsets.add(failingMsgOffset);
+      segmentDataManager._responses.add(new SegmentCompletionProtocol.Response(
+          new SegmentCompletionProtocol.Response.Params().withStatus(
+              
SegmentCompletionProtocol.ControllerResponseStatus.COMMIT).withStreamPartitionMsgOffset(
+              failingMsgOffset.toString())));
+
+      segmentDataManager.createPartitionConsumer().run();
+
+      Assert.assertEquals(segmentDataManager.getStopReason(), 
SegmentCompletionProtocol.REASON_TIME_LIMIT);
+      Assert.assertTrue(segmentDataManager._commitSegmentCalled);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS, 
List.of(failingOffset, failingOffset));
+      // No backoff past the consumption deadline
+      Assert.assertEquals(segmentDataManager._decodeRetrySleeps, 
List.of(100L));
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          0);
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testForceCommitWhileRetryingDecodeEndsTheSegmentAtTheMessage()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    TimeSupplier timeSupplier = new TimeSupplier();
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        timeSupplier, Map.of())) {
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> {
+        if (OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size() == 2) {
+          segmentDataManager.forceCommit();
+        }
+      });
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+      LongMsgOffset failingMsgOffset = new LongMsgOffset(failingOffset);
+      segmentDataManager._consumeOffsets.add(failingMsgOffset);
+      segmentDataManager._responses.add(new SegmentCompletionProtocol.Response(
+          new SegmentCompletionProtocol.Response.Params().withStatus(
+              
SegmentCompletionProtocol.ControllerResponseStatus.COMMIT).withStreamPartitionMsgOffset(
+              failingMsgOffset.toString())));
+
+      segmentDataManager.createPartitionConsumer().run();
+
+      Assert.assertEquals(segmentDataManager.getStopReason(),
+          SegmentCompletionProtocol.REASON_FORCE_COMMIT_MESSAGE_RECEIVED);
+      Assert.assertTrue(segmentDataManager._commitSegmentCalled);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS, 
List.of(failingOffset, failingOffset));
+      // Only the backoff before the force commit arrived
+      Assert.assertEquals(segmentDataManager._decodeRetrySleeps, 
List.of(100L));
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          0);
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testForceCommitWakesTheDecodeRetryBackoff()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        new TimeSupplier(), Map.of())) {
+      // The backoff sleeps until woken
+      segmentDataManager._decodeRetrySleepStarted = new CountDownLatch(1);
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.INITIAL_CONSUMING);
+      LongMsgOffset failingMsgOffset = new LongMsgOffset(failingOffset);
+      segmentDataManager._consumeOffsets.add(failingMsgOffset);
+      segmentDataManager._responses.add(new SegmentCompletionProtocol.Response(
+          new SegmentCompletionProtocol.Response.Params().withStatus(
+              
SegmentCompletionProtocol.ControllerResponseStatus.COMMIT).withStreamPartitionMsgOffset(
+              failingMsgOffset.toString())));
+      Thread consumerThread = new 
Thread(segmentDataManager.createPartitionConsumer());
+      consumerThread.start();
+      Assert.assertTrue(segmentDataManager._decodeRetrySleepStarted.await(10, 
TimeUnit.SECONDS));
+
+      segmentDataManager.forceCommit();
+      consumerThread.join(10_000);
+
+      Assert.assertFalse(consumerThread.isAlive());
+      Assert.assertEquals(segmentDataManager.getStopReason(),
+          SegmentCompletionProtocol.REASON_FORCE_COMMIT_MESSAGE_RECEIVED);
+      Assert.assertTrue(segmentDataManager._commitSegmentCalled);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+    }
+  }
+
+  /// The catch-up deadline caps the backoff; at the deadline, the segment is 
downloaded instead.
+  @Test(timeOut = 30_000)
+  public void 
testCatchUpForOnlineTransitionGivesUpAtTheDeadlineWhileRetryingDecode()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    TimeSupplier timeSupplier = new TimeSupplier();
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        timeSupplier, Map.of())) {
+      // The second backoff starts 50ms before the deadline, and the third 
failure happens at it
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> {
+        int numFailures = 
OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size();
+        if (numFailures == 2) {
+          timeSupplier.set(segmentDataManager.getConsumeEndTime() - 50);
+        } else if (numFailures == 3) {
+          timeSupplier.set(segmentDataManager.getConsumeEndTime());
+        }
+      });
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      segmentDataManager.getConsumerSemaphoreAcquired().set(true);
+      segmentDataManager._stopWaitTimeMs = 0;
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.HOLDING);
+      SegmentZKMetadata committedSegmentZKMetadata = createZkMetadata();
+      committedSegmentZKMetadata.setEndOffset(new 
LongMsgOffset(START_OFFSET_VALUE + 10).toString());
+
+      segmentDataManager.goOnlineFromConsuming(committedSegmentZKMetadata);
+
+      Assert.assertEquals(segmentDataManager._state.get(segmentDataManager),
+          RealtimeSegmentDataManager.State.CONSUMING_TO_ONLINE);
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS,
+          List.of(failingOffset, failingOffset, failingOffset));
+      Assert.assertEquals(segmentDataManager._decodeRetrySleeps, List.of(100L, 
50L));
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          0);
+      Assert.assertTrue(segmentDataManager._downloadAndReplaceCalled);
+      Assert.assertFalse(segmentDataManager._buildAndReplaceCalled);
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testCatchingUpRetriesDecodeWithoutDeadlineUntilStopped()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    TimeSupplier timeSupplier = new TimeSupplier();
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(
+        new ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry()), 
timeSupplier, Map.of())) {
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(
+          () -> timeSupplier.set(segmentDataManager.getConsumeEndTime() + 
TimeUnit.HOURS.toMillis(1)));
+      // The fifth backoff sleeps until interrupted
+      segmentDataManager._blockOnDecodeRetrySleep = 5;
+      segmentDataManager._decodeRetrySleepStarted = new CountDownLatch(1);
+      segmentDataManager._stubConsumeLoop = false;
+      segmentDataManager._state.set(segmentDataManager, 
RealtimeSegmentDataManager.State.CATCHING_UP);
+      segmentDataManager.setFinalOffset(START_OFFSET_VALUE + 10);
+      Thread consumerThread = new 
Thread(segmentDataManager.createPartitionConsumer());
+      consumerThread.start();
+      Assert.assertTrue(segmentDataManager._decodeRetrySleepStarted.await(10, 
TimeUnit.SECONDS));
+
+      segmentDataManager.setConsumerThread(consumerThread);
+      segmentDataManager.invokeRealStop();
+
+      Assert.assertFalse(consumerThread.isAlive());
+      Assert.assertEquals(segmentDataManager._decodeRetrySleeps, List.of(100L, 
200L, 400L, 800L, 1600L));
+      
Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size(), 5);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(), failingOffset);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
5);
+      Assert.assertEquals(segmentDataManager._state.get(segmentDataManager),
+          RealtimeSegmentDataManager.State.CATCHING_UP);
+      Assert.assertFalse(segmentDataManager._postConsumeStoppedCalled);
+    }
+  }
+
+  @Test
+  public void 
testDecodeRetryMaxDurationHandlesTheMessageLikeAnyOtherDecodeError()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    TimeSupplier timeSupplier = new TimeSupplier();
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        timeSupplier, 
Map.of(StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS, "1000"))) {
+      // The second failure comes after the 1s limit
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> 
timeSupplier.add(1000));
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      long retriesBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES);
+
+      consumeToRowLimitAndCommit(segmentDataManager);
+
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS, 
List.of(failingOffset, failingOffset));
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES) - retriesBefore, 1);
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          1);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
OFFSET_STREAM_SEGMENT_ROWS);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(),
+          START_OFFSET_VALUE + OFFSET_STREAM_SEGMENT_ROWS + 1);
+    }
+  }
+
+  @Test
+  public void testDecodeRetryMaxDurationBoundsAnOutageOfInterleavedFailures()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    // Failures less than the limit apart, with messages decoding in between, 
then one after a quiet period
+    List<Long> outageOffsets = List.of(START_OFFSET_VALUE + 5, 
START_OFFSET_VALUE + 7, START_OFFSET_VALUE + 9);
+    for (long offset : outageOffsets) {
+      OffsetPayloadDecoder.RETRIABLE_FAILURES.put(offset, new 
AtomicInteger(Integer.MAX_VALUE));
+    }
+    long nextOutageOffset = START_OFFSET_VALUE + 17;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(nextOutageOffset, new 
AtomicInteger(1));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    TimeSupplier timeSupplier = new TimeSupplier();
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        timeSupplier, 
Map.of(StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS, "1000"))) {
+      // Failures happen 600ms apart, except the last one, 2s after the 
previous one
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> timeSupplier.add(
+          
OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.get(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size()
 - 1)
+              == nextOutageOffset ? 2000 : 600));
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      long retriesBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES);
+
+      consumeToRowLimitAndCommit(segmentDataManager);
+
+      // The first message is retried until the outage has lasted 1s, then 
dropped; later failures of that outage are
+      // dropped at once. The failure 2s later starts a new outage and is 
retried.
+      long firstOffset = outageOffsets.get(0);
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS,
+          List.of(firstOffset, firstOffset, firstOffset, outageOffsets.get(1), 
outageOffsets.get(2), nextOutageOffset));
+      Assert.assertEquals(OffsetPayloadConsumerFactory.FETCH_START_OFFSETS,
+          List.of(START_OFFSET_VALUE, firstOffset, firstOffset, 
START_OFFSET_VALUE + 15, nextOutageOffset));
+      Assert.assertEquals(segmentDataManager._decodeRetrySleeps, List.of(100L, 
200L, 100L));
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          3);
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES) - retriesBefore, 3);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
OFFSET_STREAM_SEGMENT_ROWS);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(),
+          START_OFFSET_VALUE + OFFSET_STREAM_SEGMENT_ROWS + 3);
+      // One segment error per outage
+      verify(segmentDataManager.getTableDataManager(), 
times(2)).addSegmentError(eq(SEGMENT_NAME_STR), any());
+    }
+  }
+
+  @Test
+  public void 
testFailureLongAfterThePreviousOneIsReportedAgainWithNoRetryLimit()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long firstOffset = START_OFFSET_VALUE + 3;
+    long laterOffset = START_OFFSET_VALUE + 10;
+    long soonAfterOffset = START_OFFSET_VALUE + 12;
+    for (long offset : List.of(firstOffset, laterOffset, soonAfterOffset)) {
+      OffsetPayloadDecoder.RETRIABLE_FAILURES.put(offset, new 
AtomicInteger(1));
+    }
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    TimeSupplier timeSupplier = new TimeSupplier();
+    // No retry limit, so the outage that starts at the first failure never 
ends
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        timeSupplier, Map.of())) {
+      // The second failure comes 5 minutes after the first, and the third 10 
seconds after the second
+      OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> {
+        List<Long> failingOffsets = 
OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS;
+        long failingOffset = failingOffsets.get(failingOffsets.size() - 1);
+        if (failingOffset == laterOffset) {
+          timeSupplier.add(TimeUnit.MINUTES.toMillis(5));
+        } else if (failingOffset == soonAfterOffset) {
+          timeSupplier.add(TimeUnit.SECONDS.toMillis(10));
+        }
+      });
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+      long retriesBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES);
+
+      consumeToRowLimitAndCommit(segmentDataManager);
+
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS,
+          List.of(firstOffset, laterOffset, soonAfterOffset));
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_DECODE_RETRIES) - retriesBefore, 3);
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          0);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
OFFSET_STREAM_SEGMENT_ROWS);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(),
+          START_OFFSET_VALUE + OFFSET_STREAM_SEGMENT_ROWS);
+      // Reported: the first failure and the one 5 minutes later, not the one 
10 seconds after that
+      verify(segmentDataManager.getTableDataManager(), 
times(2)).addSegmentError(eq(SEGMENT_NAME_STR), any());
+    }
+  }
+
+  @Test
+  public void testBatchesFetchedAgainChargeOnlyTheMessagesTheyProcess()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(2));
+    // In the first batch and in the batch fetched again for the failing 
message
+    OffsetPayloadConsumerFactory.TOMBSTONE_OFFSETS.add(START_OFFSET_VALUE + 8);
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics)) {
+      long fetchedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_ROWS_FETCHED);
+
+      consumeToRowLimitAndCommit(segmentDataManager);
+
+      Assert.assertEquals(OffsetPayloadConsumerFactory.FETCH_START_OFFSETS,
+          List.of(START_OFFSET_VALUE, failingOffset, failingOffset, 
failingOffset + OFFSET_STREAM_BATCH_SIZE));
+      // Charged: the first batch (9 messages and a tombstone) when fetched, 
the refetch stopped at the failing message
+      // for that message only, the refetch processed in full like any batch, 
and the next batch when fetched
+      int recordSizeInBytes = 3 + 
OffsetPayloadConsumerFactory.RECORD_OVERHEAD_IN_BYTES;
+      Assert.assertEquals(segmentDataManager._throttledMessageCounts, 
List.of(9, 1, 9, 10));
+      Assert.assertEquals(segmentDataManager._throttledSizesInBytes,
+          List.of(9L * recordSizeInBytes, (long) recordSizeInBytes, 9L * 
recordSizeInBytes, 10L * recordSizeInBytes));
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.REALTIME_ROWS_FETCHED) - fetchedBefore,
+          10 + 1 + 10 + 10);
+      Assert.assertEquals(segmentDataManager.getSegment().getNumDocsIndexed(), 
OFFSET_STREAM_SEGMENT_ROWS);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(),
+          START_OFFSET_VALUE + OFFSET_STREAM_SEGMENT_ROWS + 1);
+    }
+  }
+
+  @Test
+  public void testZeroDecodeRetryMaxDurationNeverRetries()
+      throws Exception {
+    OffsetPayloadDecoder.reset();
+    long failingOffset = START_OFFSET_VALUE + 5;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(failingOffset, new 
AtomicInteger(Integer.MAX_VALUE));
+    ServerMetrics serverMetrics = new 
ServerMetrics(PinotMetricUtils.getPinotMetricsRegistry());
+    try (FakeRealtimeSegmentDataManager segmentDataManager = 
createOffsetPayloadSegmentManager(serverMetrics,
+        new TimeSupplier(), 
Map.of(StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS, "0"))) {
+      long droppedBefore = getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED);
+
+      consumeToRowLimitAndCommit(segmentDataManager);
+
+      Assert.assertEquals(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS, 
List.of(failingOffset));
+      Assert.assertTrue(segmentDataManager._decodeRetrySleeps.isEmpty());
+      Assert.assertEquals(
+          getMeterCount(serverMetrics, segmentDataManager, 
ServerMeter.INVALID_REALTIME_ROWS_DROPPED) - droppedBefore,
+          1);
+      Assert.assertEquals(((LongMsgOffset) 
segmentDataManager.getCurrentOffset()).getOffset(),
+          START_OFFSET_VALUE + OFFSET_STREAM_SEGMENT_ROWS + 1);
+    }
+  }
+
+  private static boolean isLongOffset(@Nullable StreamPartitionMsgOffset 
offset, long expectedOffset) {
+    return offset instanceof LongMsgOffset && ((LongMsgOffset) 
offset).getOffset() == expectedOffset;
+  }
+
   @Test
   public void testFilteredAndDroppedRowsInOneBatchAreCountedOnTheirOwnMeters()
       throws Exception {
@@ -2042,9 +2561,17 @@ public class RealtimeSegmentDataManagerTest {
 
   private FakeRealtimeSegmentDataManager 
createOffsetPayloadSegmentManager(ServerMetrics serverMetrics)
       throws Exception {
+    return createOffsetPayloadSegmentManager(serverMetrics, new 
TimeSupplier(), Map.of());
+  }
+
+  private FakeRealtimeSegmentDataManager 
createOffsetPayloadSegmentManager(ServerMetrics serverMetrics,
+      TimeSupplier timeSupplier, Map<String, String> streamConfigs)
+      throws Exception {
     TableConfig tableConfig = 
Fixtures.createTableConfig(OffsetPayloadConsumerFactory.class.getName(),
         OffsetPayloadDecoder.class.getName());
-    return createFakeSegmentManager(true, new TimeSupplier(), 
String.valueOf(OFFSET_STREAM_SEGMENT_ROWS), "10m",
+    // getStreamConfigMaps() returns the table's own map, not a copy
+    
IngestionConfigUtils.getStreamConfigMaps(tableConfig).get(0).putAll(streamConfigs);
+    return createFakeSegmentManager(true, timeSupplier, 
String.valueOf(OFFSET_STREAM_SEGMENT_ROWS), "10m",
         tableConfig, serverMetrics);
   }
 
@@ -2240,6 +2767,14 @@ public class RealtimeSegmentDataManagerTest {
 
   /// Endless stream whose message at offset `n` has payload `n`.
   public static class OffsetPayloadConsumerFactory extends 
FakeStreamConsumerFactory {
+    static final List<Long> FETCH_START_OFFSETS = new CopyOnWriteArrayList<>();
+    // Like Kinesis, fetch from after the given offset, and give each message 
its own offset as next offset
+    static final AtomicBoolean FETCH_AFTER_START_OFFSET = new AtomicBoolean();
+    // Like Kafka tombstones, left out of the batch but counted in its 
unfiltered message count
+    static final Set<Long> TOMBSTONE_OFFSETS = ConcurrentHashMap.newKeySet();
+    // Like Kafka records with a key and headers, a record is larger than its 
value
+    static final int RECORD_OVERHEAD_IN_BYTES = 7;
+
     @Override
     public PartitionGroupConsumer createPartitionGroupConsumer(String clientId,
         PartitionGroupConsumptionStatus partitionGroupConsumptionStatus) {
@@ -2247,18 +2782,34 @@ public class RealtimeSegmentDataManagerTest {
         @Override
         public MessageBatch<byte[]> fetchMessages(StreamPartitionMsgOffset 
startOffset, int timeoutMs) {
           long start = ((LongMsgOffset) startOffset).getOffset();
+          FETCH_START_OFFSETS.add(start);
+          boolean fetchAfterStartOffset = FETCH_AFTER_START_OFFSET.get();
+          long firstOffset = fetchAfterStartOffset ? start + 1 : start;
           List<BytesStreamMessage> messages = new 
ArrayList<>(OFFSET_STREAM_BATCH_SIZE);
-          for (long offset = start; offset < start + OFFSET_STREAM_BATCH_SIZE; 
offset++) {
-            messages.add(new 
BytesStreamMessage(Long.toString(offset).getBytes(StandardCharsets.UTF_8),
-                new StreamMessageMetadata.Builder().setOffset(new 
LongMsgOffset(offset), new LongMsgOffset(offset + 1))
-                    .build()));
+          for (long offset = firstOffset; offset < firstOffset + 
OFFSET_STREAM_BATCH_SIZE; offset++) {
+            if (TOMBSTONE_OFFSETS.contains(offset)) {
+              continue;
+            }
+            long nextOffset = fetchAfterStartOffset ? offset : offset + 1;
+            byte[] value = 
Long.toString(offset).getBytes(StandardCharsets.UTF_8);
+            messages.add(new BytesStreamMessage(value,
+                new StreamMessageMetadata.Builder().setOffset(new 
LongMsgOffset(offset), new LongMsgOffset(nextOffset))
+                    .setSerializedValueSize(value.length + 
RECORD_OVERHEAD_IN_BYTES).build()));
           }
+          // The offset after the last one of the batch, or that offset for a 
stream fetching from after it
+          long offsetOfNextBatch = fetchAfterStartOffset ? firstOffset + 
OFFSET_STREAM_BATCH_SIZE - 1
+              : firstOffset + OFFSET_STREAM_BATCH_SIZE;
           return new MessageBatch<>() {
             @Override
             public int getMessageCount() {
               return messages.size();
             }
 
+            @Override
+            public int getUnfilteredMessageCount() {
+              return OFFSET_STREAM_BATCH_SIZE;
+            }
+
             @Override
             public BytesStreamMessage getStreamMessage(int index) {
               return messages.get(index);
@@ -2266,12 +2817,13 @@ public class RealtimeSegmentDataManagerTest {
 
             @Override
             public StreamPartitionMsgOffset getOffsetOfNextBatch() {
-              return new LongMsgOffset(start + OFFSET_STREAM_BATCH_SIZE);
+              return new LongMsgOffset(offsetOfNextBatch);
             }
 
+            // Like Kafka, the sum of the record sizes
             @Override
             public long getSizeInBytes() {
-              return messages.stream().mapToLong(message -> 
message.getLength()).sum();
+              return messages.stream().mapToLong(message -> 
message.getMetadata().getRecordSerializedSize()).sum();
             }
           };
         }
@@ -2283,14 +2835,42 @@ public class RealtimeSegmentDataManagerTest {
     }
   }
 
-  /// Drops [#DROPPED_OFFSETS] (returns `null`) and marks [#FILTERED_OFFSETS] 
to be filtered out.
+  /// Drops [#DROPPED_OFFSETS] (returns `null`) and marks [#FILTERED_OFFSETS] 
to be filtered out. For
+  /// [#RETRIABLE_FAILURES] it first throws [RetriableDecodeException] the 
given number of times.
   public static class OffsetPayloadDecoder implements 
StreamMessageDecoder<byte[]> {
     static final Set<Long> DROPPED_OFFSETS = ConcurrentHashMap.newKeySet();
     static final Set<Long> FILTERED_OFFSETS = ConcurrentHashMap.newKeySet();
+    // Offset -> number of attempts that throw RetriableDecodeException before 
the message decodes
+    static final Map<Long, AtomicInteger> RETRIABLE_FAILURES = new 
ConcurrentHashMap<>();
+    static final List<Long> RETRIABLE_FAILURE_OFFSETS = new 
CopyOnWriteArrayList<>();
+    // Offsets of all decode attempts, and indexes into it of the attempts 
that threw RetriableDecodeException
+    static final List<Long> DECODE_ATTEMPT_OFFSETS = new 
CopyOnWriteArrayList<>();
+    static final List<Integer> RETRIABLE_FAILURE_ATTEMPTS = new 
CopyOnWriteArrayList<>();
+    // Run before each RetriableDecodeException is thrown
+    static final AtomicReference<Runnable> ON_RETRIABLE_FAILURE = new 
AtomicReference<>();
 
     static void reset() {
       DROPPED_OFFSETS.clear();
       FILTERED_OFFSETS.clear();
+      RETRIABLE_FAILURES.clear();
+      RETRIABLE_FAILURE_OFFSETS.clear();
+      DECODE_ATTEMPT_OFFSETS.clear();
+      RETRIABLE_FAILURE_ATTEMPTS.clear();
+      ON_RETRIABLE_FAILURE.set(() -> {
+      });
+      OffsetPayloadConsumerFactory.FETCH_START_OFFSETS.clear();
+      OffsetPayloadConsumerFactory.FETCH_AFTER_START_OFFSET.set(false);
+      OffsetPayloadConsumerFactory.TOMBSTONE_OFFSETS.clear();
+    }
+
+    static List<Long> getFirstDecodeAttemptAfterEachRetriableFailure() {
+      List<Long> offsets = new ArrayList<>(RETRIABLE_FAILURE_ATTEMPTS.size());
+      for (int attempt : RETRIABLE_FAILURE_ATTEMPTS) {
+        if (attempt + 1 < DECODE_ATTEMPT_OFFSETS.size()) {
+          offsets.add(DECODE_ATTEMPT_OFFSETS.get(attempt + 1));
+        }
+      }
+      return offsets;
     }
 
     @Override
@@ -2301,6 +2881,15 @@ public class RealtimeSegmentDataManagerTest {
     @Override
     public GenericRow decode(byte[] payload, GenericRow destination) {
       long offset = Long.parseLong(new String(payload, 
StandardCharsets.UTF_8));
+      DECODE_ATTEMPT_OFFSETS.add(offset);
+      AtomicInteger retriableFailures = RETRIABLE_FAILURES.get(offset);
+      if (retriableFailures != null && retriableFailures.getAndDecrement() > 
0) {
+        RETRIABLE_FAILURE_OFFSETS.add(offset);
+        RETRIABLE_FAILURE_ATTEMPTS.add(DECODE_ATTEMPT_OFFSETS.size() - 1);
+        ON_RETRIABLE_FAILURE.get().run();
+        throw new RetriableDecodeException("Schema registry unavailable",
+            new SocketTimeoutException("Read timed out"));
+      }
       if (DROPPED_OFFSETS.contains(offset)) {
         return null;
       }
@@ -2357,6 +2946,13 @@ public class RealtimeSegmentDataManagerTest {
     public RealtimeTableDataManager _tableDataManager;
     private TimeSupplier _timeSupplier;
     private boolean _indexCapacityThresholdBreached;
+    // Requested decode retry backoffs, not slept. If _decodeRetrySleepStarted 
is set, backoff number
+    // _blockOnDecodeRetrySleep counts it down and blocks until interrupted or 
woken.
+    public final List<Long> _decodeRetrySleeps = new CopyOnWriteArrayList<>();
+    public volatile CountDownLatch _decodeRetrySleepStarted;
+    public volatile int _blockOnDecodeRetrySleep = 1;
+    public final List<Integer> _throttledMessageCounts = new 
CopyOnWriteArrayList<>();
+    public final List<Long> _throttledSizesInBytes = new 
CopyOnWriteArrayList<>();
 
     private static InstanceDataManagerConfig makeInstanceDataManagerConfig() {
       InstanceDataManagerConfig dataManagerConfig = 
mock(InstanceDataManagerConfig.class);
@@ -2515,6 +3111,32 @@ public class RealtimeSegmentDataManagerTest {
       super.stop();
     }
 
+    /// Sets the thread the real stop() interrupts, normally created by 
startConsumption().
+    public void setConsumerThread(Thread consumerThread)
+        throws Exception {
+      Field consumerThreadField = 
RealtimeSegmentDataManager.class.getDeclaredField("_consumerThread");
+      consumerThreadField.setAccessible(true);
+      consumerThreadField.set(this, consumerThread);
+    }
+
+    @Override
+    void throttle(MessageBatch<?> messageBatch) {
+      _throttledMessageCounts.add(messageBatch.getMessageCount());
+      _throttledSizesInBytes.add(messageBatch.getSizeInBytes());
+      super.throttle(messageBatch);
+    }
+
+    @Override
+    void sleepBeforeDecodeRetry(long backoffMs)
+        throws InterruptedException {
+      _decodeRetrySleeps.add(backoffMs);
+      CountDownLatch decodeRetrySleepStarted = _decodeRetrySleepStarted;
+      if (decodeRetrySleepStarted != null && _decodeRetrySleeps.size() >= 
_blockOnDecodeRetrySleep) {
+        decodeRetrySleepStarted.countDown();
+        super.sleepBeforeDecodeRetry(Long.MAX_VALUE);
+      }
+    }
+
     @Override
     SegmentCompletionProtocol.Response 
postSegmentStoppedConsuming(ConsumptionStopIndicator indicator) {
       _postConsumeStoppedCalled = true;
diff --git 
a/pinot-core/src/test/java/org/apache/pinot/core/realtime/stream/StreamConfigTest.java
 
b/pinot-core/src/test/java/org/apache/pinot/core/realtime/stream/StreamConfigTest.java
index 912517a28ee..d467d1b042c 100644
--- 
a/pinot-core/src/test/java/org/apache/pinot/core/realtime/stream/StreamConfigTest.java
+++ 
b/pinot-core/src/test/java/org/apache/pinot/core/realtime/stream/StreamConfigTest.java
@@ -359,4 +359,43 @@ public class StreamConfigTest {
     assertEquals(streamConfig.getFlushThresholdSegmentRows(), -1);
     assertEquals(streamConfig.getFlushThresholdSegmentSizeBytes(), -1);
   }
+
+  @Test
+  public void testDecodeRetryConfigs() {
+    String streamType = "fakeStream";
+    Map<String, String> streamConfigMap = new HashMap<>();
+    streamConfigMap.put(StreamConfigProperties.STREAM_TYPE, streamType);
+    streamConfigMap.put(
+        StreamConfigProperties.constructStreamProperty(streamType, 
StreamConfigProperties.STREAM_TOPIC_NAME),
+        "fakeTopic");
+    streamConfigMap.put(
+        StreamConfigProperties.constructStreamProperty(streamType, 
StreamConfigProperties.STREAM_DECODER_CLASS),
+        FakeStreamMessageDecoder.class.getName());
+    assertEquals(new StreamConfig("fakeTable_REALTIME", 
streamConfigMap).getDecodeRetryMaxBackoffMillis(),
+        StreamConfig.DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS);
+
+    
streamConfigMap.put(StreamConfigProperties.DECODE_RETRY_MAX_BACKOFF_MILLIS, 
"2500");
+    assertEquals(new StreamConfig("fakeTable_REALTIME", 
streamConfigMap).getDecodeRetryMaxBackoffMillis(), 2500L);
+
+    // Invalid values fall back to the default instead of failing the stream 
config
+    for (String invalidValue : new String[]{"abc", "0", "-1"}) {
+      
streamConfigMap.put(StreamConfigProperties.DECODE_RETRY_MAX_BACKOFF_MILLIS, 
invalidValue);
+      assertEquals(new StreamConfig("fakeTable_REALTIME", 
streamConfigMap).getDecodeRetryMaxBackoffMillis(),
+          StreamConfig.DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS, invalidValue);
+    }
+
+    // No limit on the retry duration by default, and 0 disables retries
+    assertEquals(new StreamConfig("fakeTable_REALTIME", 
streamConfigMap).getDecodeRetryMaxDurationMillis(),
+        Long.MAX_VALUE);
+    for (String value : new String[]{"0", "60000"}) {
+      
streamConfigMap.put(StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS, 
value);
+      assertEquals(new StreamConfig("fakeTable_REALTIME", 
streamConfigMap).getDecodeRetryMaxDurationMillis(),
+          Long.parseLong(value));
+    }
+    for (String invalidValue : new String[]{"abc", "-1"}) {
+      
streamConfigMap.put(StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS, 
invalidValue);
+      assertEquals(new StreamConfig("fakeTable_REALTIME", 
streamConfigMap).getDecodeRetryMaxDurationMillis(),
+          StreamConfig.DEFAULT_DECODE_RETRY_MAX_DURATION_MILLIS, invalidValue);
+    }
+  }
 }
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/DecodeRetryTracker.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/DecodeRetryTracker.java
new file mode 100644
index 00000000000..56c2fd87598
--- /dev/null
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/DecodeRetryTracker.java
@@ -0,0 +1,139 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.realtime;
+
+import java.util.concurrent.TimeUnit;
+import org.apache.pinot.spi.stream.StreamConfig;
+
+
+/// Retriable decode state of one partition consumer: whether to fetch a 
failing message again, the retry backoff and
+/// when to report. Retriable failures form an outage while a message is being 
retried or while they keep happening
+/// less than [StreamConfig#getDecodeRetryMaxDurationMillis()] apart; once the 
outage has lasted that long, failures
+/// are handled like any other decode failure. The state lives with its 
consumer, so each segment starts a fresh
+/// outage window. Not thread-safe.
+public class DecodeRetryTracker {
+  public static final long WARN_INTERVAL_MS = TimeUnit.MINUTES.toMillis(1);
+
+  /// What to do with a retriable failure, and whether to report it.
+  public enum Outcome {
+    /// Retry; the outage just started or follows a quiet [#WARN_INTERVAL_MS]: 
report with the cause.
+    RETRY_AND_REPORT(true),
+    /// Retry; at most every [#WARN_INTERVAL_MS] during the outage: remind 
that retries go on.
+    RETRY_AND_REMIND(true),
+    /// Retry without reporting.
+    RETRY(true),
+    /// Give up: the outage just reached the limit.
+    GIVE_UP_AND_REPORT(false),
+    /// Give up: the outage is past the limit.
+    GIVE_UP(false);
+
+    private final boolean _retry;
+
+    Outcome(boolean retry) {
+      _retry = retry;
+    }
+
+    public boolean isRetry() {
+      return _retry;
+    }
+  }
+
+  private final long _maxDurationMs;
+  private final long _maxBackoffMs;
+  private int _numRetries;
+  private long _backoffMs;
+  private boolean _inOutage;
+  private long _outageStartMs;
+  private long _lastFailureMs;
+  private long _lastWarnMs;
+  private boolean _limitReported;
+
+  public DecodeRetryTracker(StreamConfig streamConfig) {
+    this(streamConfig.getDecodeRetryMaxDurationMillis(), 
streamConfig.getDecodeRetryMaxBackoffMillis());
+  }
+
+  public DecodeRetryTracker(long maxDurationMs, long maxBackoffMs) {
+    _maxDurationMs = maxDurationMs;
+    _maxBackoffMs = maxBackoffMs;
+  }
+
+  /// Records a retriable failure of the current message at `nowMs`.
+  public Outcome onRetriableFailure(long nowMs) {
+    long sinceLastFailureMs = _inOutage ? nowMs - _lastFailureMs : 
Long.MAX_VALUE;
+    boolean outageStarts = !_inOutage || (_numRetries == 0 && 
sinceLastFailureMs >= _maxDurationMs);
+    if (outageStarts) {
+      _inOutage = true;
+      _outageStartMs = nowMs;
+      _limitReported = false;
+    }
+    _lastFailureMs = nowMs;
+    if (nowMs - _outageStartMs >= _maxDurationMs) {
+      _numRetries = 0;
+      if (_maxDurationMs > 0 && !_limitReported) {
+        _limitReported = true;
+        return Outcome.GIVE_UP_AND_REPORT;
+      }
+      return Outcome.GIVE_UP;
+    }
+    // Reported afresh after a quiet minute even mid-outage, since with no 
limit an outage never ends
+    boolean report = outageStarts || (_numRetries == 0 && sinceLastFailureMs 
>= WARN_INTERVAL_MS);
+    if (_numRetries++ == 0) {
+      _backoffMs = Math.min(StreamConfig.INITIAL_DECODE_RETRY_BACKOFF_MILLIS, 
_maxBackoffMs);
+    }
+    if (report) {
+      _lastWarnMs = nowMs;
+      return Outcome.RETRY_AND_REPORT;
+    }
+    if (nowMs - _lastWarnMs >= WARN_INTERVAL_MS) {
+      _lastWarnMs = nowMs;
+      return Outcome.RETRY_AND_REMIND;
+    }
+    return Outcome.RETRY;
+  }
+
+  /// Records that the current message decoded or failed for good; returns how 
many times it was retried.
+  public int onMessageDone() {
+    int numRetries = _numRetries;
+    _numRetries = 0;
+    return numRetries;
+  }
+
+  /// Returns the backoff before the next fetch of the message and doubles it, 
up to the cap.
+  public long nextBackoffMs() {
+    long backoffMs = _backoffMs;
+    _backoffMs = Math.min(backoffMs * 2, _maxBackoffMs);
+    return backoffMs;
+  }
+
+  public boolean isRetrying() {
+    return _numRetries > 0;
+  }
+
+  public int getNumRetries() {
+    return _numRetries;
+  }
+
+  public long getOutageDurationMs(long nowMs) {
+    return nowMs - _outageStartMs;
+  }
+
+  public long getMaxDurationMs() {
+    return _maxDurationMs;
+  }
+}
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
index 67a098c515c..9a803681f7d 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriter.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.segment.local.realtime.writer;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.Uninterruptibles;
 import java.io.Closeable;
@@ -38,6 +39,7 @@ import org.apache.pinot.common.utils.LLCSegmentName;
 import org.apache.pinot.common.utils.TarCompressionUtils;
 import org.apache.pinot.segment.local.indexsegment.mutable.MutableSegmentImpl;
 import org.apache.pinot.segment.local.io.writer.impl.MmapMemoryManager;
+import org.apache.pinot.segment.local.realtime.DecodeRetryTracker;
 import 
org.apache.pinot.segment.local.realtime.converter.RealtimeSegmentConverter;
 import org.apache.pinot.segment.local.realtime.impl.RealtimeSegmentConfig;
 import 
org.apache.pinot.segment.local.realtime.impl.RealtimeSegmentStatsHistory;
@@ -265,6 +267,25 @@ public class StatelessRealtimeSegmentWriter implements 
Closeable {
     }
   }
 
+  /// Returns whether to fetch and decode the message at `offset` again after 
a retriable decode failure, reporting it
+  /// as the realtime consumer does, minus segment errors.
+  private boolean shouldRetryDecode(DecodeRetryTracker decodeRetryTracker, 
StreamPartitionMsgOffset offset,
+      Exception cause) {
+    long nowMs = now();
+    DecodeRetryTracker.Outcome outcome = 
decodeRetryTracker.onRetriableFailure(nowMs);
+    if (outcome == DecodeRetryTracker.Outcome.GIVE_UP_AND_REPORT) {
+      _logger.warn("Retriable decode errors have lasted {}ms, giving up 
retrying the message at offset: {}. Until "
+              + "none happens for {}ms, retriable decode errors are handled 
like any other decode error",
+          decodeRetryTracker.getOutageDurationMs(nowMs), offset, 
decodeRetryTracker.getMaxDurationMs());
+    } else if (outcome == DecodeRetryTracker.Outcome.RETRY_AND_REPORT) {
+      _logger.warn("Retriable decode error at offset: {}. Fetching and 
decoding it again", offset, cause);
+    } else if (outcome == DecodeRetryTracker.Outcome.RETRY_AND_REMIND) {
+      _logger.warn("Still retrying: retriable decode error at offset: {}, {}ms 
into the outage", offset,
+          decodeRetryTracker.getOutageDurationMs(nowMs), cause);
+    }
+    return outcome.isRetry();
+  }
+
   private class PartitionConsumer implements Runnable {
     @Override
     public void run() {
@@ -272,6 +293,7 @@ public class StatelessRealtimeSegmentWriter implements 
Closeable {
         _consumer.start(_startOffset);
         _logger.info("Created new consumer thread {} for {}", _consumerThread, 
this);
         _currentOffset = _startOffset;
+        DecodeRetryTracker decodeRetryTracker = new 
DecodeRetryTracker(_streamConfig);
         while (_currentOffset.compareTo(_endOffset) < 0) {
           if (_shouldStop) {
             _consumptionException = new IllegalStateException(
@@ -293,6 +315,9 @@ public class StatelessRealtimeSegmentWriter implements 
Closeable {
           }
 
           int messageCount = messageBatch.getMessageCount();
+          // Refetch from the previous message's next offset, as some streams 
fetch from after the given offset
+          StreamPartitionMsgOffset currentMessageFetchOffset = _currentOffset;
+          boolean decodeRetryNeeded = false;
 
           for (int i = 0; i < messageCount; i++) {
             StreamMessage streamMessage = messageBatch.getStreamMessage(i);
@@ -304,6 +329,13 @@ public class StatelessRealtimeSegmentWriter implements 
Closeable {
 
             // Decode message
             StreamDataDecoderResult decodedResult = 
_decoder.decode(streamMessage);
+            if (decodedResult.isRetriable() && 
shouldRetryDecode(decodeRetryTracker, metadata.getOffset(),
+                decodedResult.getException())) {
+              // Refetch after a backoff rather than leave the message out; 
the re-ingestion timeout bounds retries
+              decodeRetryNeeded = true;
+              break;
+            }
+            decodeRetryTracker.onMessageDone();
             if (decodedResult.getException() == null) {
               // Index message
               GenericRow row = decodedResult.getResult();
@@ -315,8 +347,21 @@ public class StatelessRealtimeSegmentWriter implements 
Closeable {
             } else {
               _logger.warn("Failed to decode message at offset {}: {}", 
_currentOffset, decodedResult.getException());
             }
+            currentMessageFetchOffset = metadata.getNextOffset();
           }
 
+          if (decodeRetryNeeded) {
+            _currentOffset = currentMessageFetchOffset;
+            if (!_shouldStop) {
+              try {
+                sleepBeforeDecodeRetry(decodeRetryTracker.nextBackoffMs());
+              } catch (InterruptedException e) {
+                // stopConsumption() interrupts the backoff, and the 
_shouldStop check above ends consumption
+                Thread.currentThread().interrupt();
+              }
+            }
+            continue;
+          }
           _currentOffset = messageBatch.getOffsetOfNextBatch();
         }
         _isSuccess = true;
@@ -335,6 +380,13 @@ public class StatelessRealtimeSegmentWriter implements 
Closeable {
     }
   }
 
+  /// Sleeps the decode retry backoff; [#stopConsumption()] interrupts it.
+  @VisibleForTesting
+  void sleepBeforeDecodeRetry(long backoffMs)
+      throws InterruptedException {
+    Thread.sleep(backoffMs);
+  }
+
   public void stopConsumption() {
     _shouldStop = true;
     if (_consumerThread.isAlive()) {
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/DecodeRetryTrackerTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/DecodeRetryTrackerTest.java
new file mode 100644
index 00000000000..b68bf441f86
--- /dev/null
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/DecodeRetryTrackerTest.java
@@ -0,0 +1,79 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.segment.local.realtime;
+
+import org.apache.pinot.segment.local.realtime.DecodeRetryTracker.Outcome;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
+
+public class DecodeRetryTrackerTest {
+  private static final long MINUTE = DecodeRetryTracker.WARN_INTERVAL_MS;
+
+  @Test
+  public void testReportsOnceThenRemindsEveryMinute() {
+    DecodeRetryTracker tracker = new DecodeRetryTracker(Long.MAX_VALUE, 
10_000);
+    assertEquals(tracker.onRetriableFailure(0), Outcome.RETRY_AND_REPORT);
+    assertEquals(tracker.onRetriableFailure(1_000), Outcome.RETRY);
+    assertEquals(tracker.onRetriableFailure(MINUTE), Outcome.RETRY_AND_REMIND);
+    assertEquals(tracker.onRetriableFailure(MINUTE + 1_000), Outcome.RETRY);
+    assertEquals(tracker.getNumRetries(), 4);
+    assertEquals(tracker.onMessageDone(), 4);
+    assertFalse(tracker.isRetrying());
+    // The next failure after a quiet minute is reported afresh, even though 
the outage has no limit
+    assertEquals(tracker.onRetriableFailure(3 * MINUTE), 
Outcome.RETRY_AND_REPORT);
+  }
+
+  @Test
+  public void testGivesUpOnceTheOutageReachesTheLimit() {
+    DecodeRetryTracker tracker = new DecodeRetryTracker(5_000, 10_000);
+    assertEquals(tracker.onRetriableFailure(0), Outcome.RETRY_AND_REPORT);
+    assertEquals(tracker.onRetriableFailure(5_000), 
Outcome.GIVE_UP_AND_REPORT);
+    assertFalse(tracker.isRetrying());
+    // Failures less than the limit apart continue the outage, so they give up 
at once
+    assertEquals(tracker.onRetriableFailure(6_000), Outcome.GIVE_UP);
+    // A failure after a quiet period at least the limit long starts a new 
outage
+    assertEquals(tracker.onRetriableFailure(12_000), Outcome.RETRY_AND_REPORT);
+    assertEquals(tracker.getOutageDurationMs(13_000), 1_000);
+  }
+
+  @Test
+  public void testZeroLimitNeverRetries() {
+    DecodeRetryTracker tracker = new DecodeRetryTracker(0, 10_000);
+    assertEquals(tracker.onRetriableFailure(0), Outcome.GIVE_UP);
+    assertEquals(tracker.onRetriableFailure(1), Outcome.GIVE_UP);
+  }
+
+  @Test
+  public void testBackoffDoublesUpToTheCapAndRestartsPerMessage() {
+    DecodeRetryTracker tracker = new DecodeRetryTracker(Long.MAX_VALUE, 500);
+    assertTrue(tracker.onRetriableFailure(0).isRetry());
+    assertEquals(tracker.nextBackoffMs(), 100);
+    assertEquals(tracker.nextBackoffMs(), 200);
+    assertEquals(tracker.nextBackoffMs(), 400);
+    assertEquals(tracker.nextBackoffMs(), 500);
+    assertEquals(tracker.nextBackoffMs(), 500);
+    tracker.onMessageDone();
+    assertTrue(tracker.onRetriableFailure(1_000).isRetry());
+    assertEquals(tracker.nextBackoffMs(), 100);
+  }
+}
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriterTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriterTest.java
index 50fc8c136e0..222913f4104 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriterTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/realtime/writer/StatelessRealtimeSegmentWriterTest.java
@@ -23,12 +23,22 @@ import java.lang.reflect.Field;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import java.util.stream.LongStream;
 import javax.annotation.Nullable;
 import org.apache.commons.io.FileUtils;
 import org.apache.pinot.common.metadata.segment.SegmentZKMetadata;
@@ -46,6 +56,7 @@ import org.apache.pinot.spi.stream.LongMsgOffset;
 import org.apache.pinot.spi.stream.MessageBatch;
 import org.apache.pinot.spi.stream.PartitionGroupConsumer;
 import org.apache.pinot.spi.stream.PartitionGroupConsumptionStatus;
+import org.apache.pinot.spi.stream.RetriableDecodeException;
 import org.apache.pinot.spi.stream.StreamConfigProperties;
 import org.apache.pinot.spi.stream.StreamConsumerFactory;
 import org.apache.pinot.spi.stream.StreamMessage;
@@ -72,12 +83,14 @@ import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertTrue;
 
 
-/// Tests how [StatelessRealtimeSegmentWriter] stops consuming.
+/// Tests how [StatelessRealtimeSegmentWriter] consumes and stops consuming.
 public class StatelessRealtimeSegmentWriterTest {
   private static final String RAW_TABLE_NAME = "testTable";
   private static final String STREAM_TYPE = "test";
   // Counted down when the stream is fetched, so that consumption can be 
stopped while it is in progress
   private static final CountDownLatch FETCHED = new CountDownLatch(1);
+  private static final int OFFSET_STREAM_BATCH_SIZE = 10;
+  private static final long FAILING_OFFSET = 5;
 
   @Test(timeOut = 30_000)
   public void testStopConsumptionWithStreamIgnoringInterrupts()
@@ -364,6 +377,252 @@ public class StatelessRealtimeSegmentWriterTest {
     }
   }
 
+  @DataProvider
+  public Object[][] fetchAfterStartOffset() {
+    return new Object[][]{{false}, {true}};
+  }
+
+  @Test(timeOut = 30_000, dataProvider = "fetchAfterStartOffset")
+  public void 
testRetriableDecodeErrorFetchesTheMessageAgainInsteadOfDroppingIt(boolean 
fetchAfterStartOffset)
+      throws Exception {
+    OffsetPayloadDecoder.reset(3);
+    
OffsetPayloadConsumerFactory.FETCH_AFTER_START_OFFSET.set(fetchAfterStartOffset);
+    List<Long> sleeps = new CopyOnWriteArrayList<>();
+    try (StatelessRealtimeSegmentWriter writer = 
createOffsetPayloadWriter("250", sleeps, null)) {
+      writer.startConsumption();
+      TestUtils.waitForCondition(aVoid -> writer.isDoneConsuming(), 10_000L, 
"Consumption did not finish");
+      writer.stopConsumption();
+
+      assertThat(writer.isSuccess()).isTrue();
+      
assertThat(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS).containsExactly(FAILING_OFFSET,
 FAILING_OFFSET,
+          FAILING_OFFSET);
+      // Every message was decoded once, and each refetch started at the 
failing message
+      long firstOffset = fetchAfterStartOffset ? 1 : 0;
+      
assertThat(OffsetPayloadDecoder.DECODED_OFFSETS).containsExactlyElementsOf(
+          LongStream.range(firstOffset, 
20).boxed().collect(Collectors.toList()));
+      long failingMessageFetchOffset = fetchAfterStartOffset ? FAILING_OFFSET 
- 1 : FAILING_OFFSET;
+      
assertThat(OffsetPayloadConsumerFactory.FETCH_START_OFFSETS).startsWith(0L, 
failingMessageFetchOffset,
+          failingMessageFetchOffset, failingMessageFetchOffset);
+      // The backoff doubled up to the cap
+      assertThat(sleeps).containsExactly(100L, 200L, 250L);
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testStopConsumptionInterruptsTheDecodeRetryBackoff()
+      throws Exception {
+    OffsetPayloadDecoder.reset(Integer.MAX_VALUE);
+    // The backoff sleeps until interrupted
+    CountDownLatch backoffStarted = new CountDownLatch(1);
+    try (StatelessRealtimeSegmentWriter writer = 
createOffsetPayloadWriter("250", new CopyOnWriteArrayList<>(),
+        backoffStarted)) {
+      writer.startConsumption();
+      assertThat(backoffStarted.await(10, TimeUnit.SECONDS)).isTrue();
+      writer.stopConsumption();
+
+      assertThat(writer.isSuccess()).isFalse();
+      assertThat(writer.getConsumptionException()).hasMessage(
+          "Consumption stopped at offset: " + FAILING_OFFSET + " before 
reaching end offset: 20");
+      assertThat(OffsetPayloadDecoder.DECODED_OFFSETS).containsExactly(0L, 1L, 
2L, 3L, 4L);
+    }
+  }
+
+  @Test(timeOut = 30_000)
+  public void testDecodeRetryMaxDurationBoundsAnOutageOfInterleavedFailures()
+      throws Exception {
+    // Failures less than the limit apart, with messages decoding in between, 
then one after a quiet period
+    OffsetPayloadDecoder.reset(Integer.MAX_VALUE);
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(FAILING_OFFSET + 2, new 
AtomicInteger(Integer.MAX_VALUE));
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(FAILING_OFFSET + 4, new 
AtomicInteger(Integer.MAX_VALUE));
+    long nextOutageOffset = 15;
+    OffsetPayloadDecoder.RETRIABLE_FAILURES.put(nextOutageOffset, new 
AtomicInteger(1));
+    // Failures happen 600ms apart, except the last one, 2s after the previous 
one
+    AtomicLong clock = new AtomicLong();
+    OffsetPayloadDecoder.ON_RETRIABLE_FAILURE.set(() -> clock.addAndGet(
+        
OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.get(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS.size()
 - 1)
+            == nextOutageOffset ? 2000 : 600));
+    List<Long> sleeps = new CopyOnWriteArrayList<>();
+    try (StatelessRealtimeSegmentWriter writer = 
createOffsetPayloadWriter("250", sleeps, null,
+        Map.of(StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS, 
"1000"), clock)) {
+      writer.startConsumption();
+      TestUtils.waitForCondition(aVoid -> writer.isDoneConsuming(), 10_000L, 
"Consumption did not finish");
+      writer.stopConsumption();
+
+      assertThat(writer.isSuccess()).isTrue();
+      // The first message is retried until the outage has lasted 1s, then 
dropped; later failures of that outage are
+      // dropped at once. The failure 2s later starts a new outage and is 
retried.
+      
assertThat(OffsetPayloadDecoder.RETRIABLE_FAILURE_OFFSETS).containsExactly(FAILING_OFFSET,
 FAILING_OFFSET,
+          FAILING_OFFSET, FAILING_OFFSET + 2, FAILING_OFFSET + 4, 
nextOutageOffset);
+      
assertThat(OffsetPayloadConsumerFactory.FETCH_START_OFFSETS).containsExactly(0L,
 FAILING_OFFSET, FAILING_OFFSET,
+          nextOutageOffset, nextOutageOffset);
+      assertThat(sleeps).containsExactly(100L, 200L, 100L);
+      
assertThat(OffsetPayloadDecoder.DECODED_OFFSETS).containsExactlyElementsOf(LongStream.range(0,
 20)
+          .filter(offset -> offset != FAILING_OFFSET && offset != 
FAILING_OFFSET + 2 && offset != FAILING_OFFSET + 4)
+          .boxed().collect(Collectors.toList()));
+    }
+  }
+
+  /// Creates a writer re-ingesting offsets [0, 20). It records backoffs 
without sleeping, unless `backoffStarted` is
+  /// given: then the first backoff counts it down and sleeps until 
interrupted.
+  private static StatelessRealtimeSegmentWriter 
createOffsetPayloadWriter(String decodeRetryMaxBackoffMillis,
+      List<Long> sleeps, @Nullable CountDownLatch backoffStarted)
+      throws Exception {
+    return createOffsetPayloadWriter(decodeRetryMaxBackoffMillis, sleeps, 
backoffStarted, Map.of(), null);
+  }
+
+  private static StatelessRealtimeSegmentWriter 
createOffsetPayloadWriter(String decodeRetryMaxBackoffMillis,
+      List<Long> sleeps, @Nullable CountDownLatch backoffStarted, Map<String, 
String> streamConfigs,
+      @Nullable AtomicLong clock)
+      throws Exception {
+    Map<String, String> streamConfigMap = new 
HashMap<>(Map.of(StreamConfigProperties.STREAM_TYPE, STREAM_TYPE,
+        StreamConfigProperties.constructStreamProperty(STREAM_TYPE, 
StreamConfigProperties.STREAM_TOPIC_NAME),
+        "testTopic",
+        StreamConfigProperties.constructStreamProperty(STREAM_TYPE,
+            StreamConfigProperties.STREAM_CONSUMER_FACTORY_CLASS), 
OffsetPayloadConsumerFactory.class.getName(),
+        StreamConfigProperties.constructStreamProperty(STREAM_TYPE, 
StreamConfigProperties.STREAM_DECODER_CLASS),
+        OffsetPayloadDecoder.class.getName(),
+        StreamConfigProperties.DECODE_RETRY_MAX_BACKOFF_MILLIS, 
decodeRetryMaxBackoffMillis));
+    streamConfigMap.putAll(streamConfigs);
+    Schema schema = new Schema.SchemaBuilder().setSchemaName(RAW_TABLE_NAME)
+        .addSingleValueDimension("col", DataType.STRING)
+        .build();
+    TableConfig tableConfig =
+        new 
TableConfigBuilder(TableType.REALTIME).setTableName(RAW_TABLE_NAME).setStreamConfigs(streamConfigMap)
+            .build();
+    SegmentZKMetadata segmentZKMetadata =
+        new SegmentZKMetadata(new LLCSegmentName(RAW_TABLE_NAME, 0, 0, 
System.currentTimeMillis()).getSegmentName());
+    segmentZKMetadata.setStartOffset("0");
+    segmentZKMetadata.setEndOffset("20");
+    return new StatelessRealtimeSegmentWriter(segmentZKMetadata, new 
IndexLoadingConfig(tableConfig, schema), null) {
+      @Override
+      protected long now() {
+        return clock != null ? clock.get() : super.now();
+      }
+
+      @Override
+      void sleepBeforeDecodeRetry(long backoffMs)
+          throws InterruptedException {
+        sleeps.add(backoffMs);
+        if (backoffStarted != null) {
+          backoffStarted.countDown();
+          super.sleepBeforeDecodeRetry(Long.MAX_VALUE);
+        }
+      }
+    };
+  }
+
+  /// Endless stream whose message at offset `n` has payload `n`.
+  public static class OffsetPayloadConsumerFactory extends 
StreamConsumerFactory {
+    static final List<Long> FETCH_START_OFFSETS = new CopyOnWriteArrayList<>();
+    // Like Kinesis, fetch from after the given offset, and give each message 
its own offset as next offset
+    static final AtomicBoolean FETCH_AFTER_START_OFFSET = new AtomicBoolean();
+
+    @Nullable
+    @Override
+    public StreamMetadataProvider createPartitionMetadataProvider(String 
clientId, int partition) {
+      return null;
+    }
+
+    @Nullable
+    @Override
+    public StreamMetadataProvider createStreamMetadataProvider(String 
clientId) {
+      return null;
+    }
+
+    @Override
+    public PartitionGroupConsumer createPartitionGroupConsumer(String clientId,
+        PartitionGroupConsumptionStatus partitionGroupConsumptionStatus) {
+      return new PartitionGroupConsumer() {
+        @Override
+        public MessageBatch<byte[]> fetchMessages(StreamPartitionMsgOffset 
startOffset, int timeoutMs) {
+          long start = ((LongMsgOffset) startOffset).getOffset();
+          FETCH_START_OFFSETS.add(start);
+          boolean fetchAfterStartOffset = FETCH_AFTER_START_OFFSET.get();
+          long firstOffset = fetchAfterStartOffset ? start + 1 : start;
+          List<BytesStreamMessage> messages = new 
ArrayList<>(OFFSET_STREAM_BATCH_SIZE);
+          for (long offset = firstOffset; offset < firstOffset + 
OFFSET_STREAM_BATCH_SIZE; offset++) {
+            long nextOffset = fetchAfterStartOffset ? offset : offset + 1;
+            messages.add(new 
BytesStreamMessage(Long.toString(offset).getBytes(StandardCharsets.UTF_8),
+                new StreamMessageMetadata.Builder().setOffset(new 
LongMsgOffset(offset), new LongMsgOffset(nextOffset))
+                    .build()));
+          }
+          return new MessageBatch<>() {
+            @Override
+            public int getMessageCount() {
+              return messages.size();
+            }
+
+            @Override
+            public BytesStreamMessage getStreamMessage(int index) {
+              return messages.get(index);
+            }
+
+            @Override
+            public StreamPartitionMsgOffset getOffsetOfNextBatch() {
+              return messages.get(messages.size() - 
1).getMetadata().getNextOffset();
+            }
+
+            @Override
+            public long getSizeInBytes() {
+              return 0;
+            }
+          };
+        }
+
+        @Override
+        public void close() {
+        }
+      };
+    }
+  }
+
+  /// Throws [RetriableDecodeException] for [#RETRIABLE_FAILURES], as many 
times as given, then decodes.
+  public static class OffsetPayloadDecoder implements 
StreamMessageDecoder<byte[]> {
+    // Offset -> number of attempts that throw RetriableDecodeException before 
the message decodes
+    static final Map<Long, AtomicInteger> RETRIABLE_FAILURES = new 
ConcurrentHashMap<>();
+    static final List<Long> RETRIABLE_FAILURE_OFFSETS = new 
CopyOnWriteArrayList<>();
+    static final List<Long> DECODED_OFFSETS = new CopyOnWriteArrayList<>();
+    // Run before each RetriableDecodeException is thrown
+    static final AtomicReference<Runnable> ON_RETRIABLE_FAILURE = new 
AtomicReference<>();
+
+    static void reset(int retriableFailures) {
+      RETRIABLE_FAILURES.clear();
+      RETRIABLE_FAILURES.put(FAILING_OFFSET, new 
AtomicInteger(retriableFailures));
+      RETRIABLE_FAILURE_OFFSETS.clear();
+      DECODED_OFFSETS.clear();
+      ON_RETRIABLE_FAILURE.set(() -> {
+      });
+      OffsetPayloadConsumerFactory.FETCH_START_OFFSETS.clear();
+      OffsetPayloadConsumerFactory.FETCH_AFTER_START_OFFSET.set(false);
+    }
+
+    @Override
+    public void init(Map<String, String> props, Set<String> fieldsToRead, 
String topicName) {
+    }
+
+    @Nullable
+    @Override
+    public GenericRow decode(byte[] payload, GenericRow destination) {
+      String value = new String(payload, StandardCharsets.UTF_8);
+      long offset = Long.parseLong(value);
+      AtomicInteger retriableFailures = RETRIABLE_FAILURES.get(offset);
+      if (retriableFailures != null && retriableFailures.getAndDecrement() > 
0) {
+        RETRIABLE_FAILURE_OFFSETS.add(offset);
+        ON_RETRIABLE_FAILURE.get().run();
+        throw new RetriableDecodeException("Schema registry unavailable");
+      }
+      DECODED_OFFSETS.add(offset);
+      destination.putValue("col", value);
+      return destination;
+    }
+
+    @Nullable
+    @Override
+    public GenericRow decode(byte[] payload, int offset, int length, 
GenericRow destination) {
+      return decode(Arrays.copyOfRange(payload, offset, offset + length), 
destination);
+    }
+  }
+
   /// Stream that never returns a message and keeps polling when interrupted.
   public static class InterruptIgnoringConsumerFactory extends 
StreamConsumerFactory {
     @Nullable
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/RetriableDecodeException.java
 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/RetriableDecodeException.java
new file mode 100644
index 00000000000..094d3bc7619
--- /dev/null
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/RetriableDecodeException.java
@@ -0,0 +1,47 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.spi.stream;
+
+import org.apache.pinot.spi.annotations.InterfaceAudience;
+import org.apache.pinot.spi.annotations.InterfaceStability;
+
+
+/// Thrown by a [StreamMessageDecoder] when a message failed to decode but may 
decode later, e.g. because a schema
+/// registry it depends on is unavailable. Instead of dropping the message, 
the realtime consumer keeps its offset,
+/// backs off and fetches the message again, even when `stopOnDecodeError` is 
set.
+///
+/// Do not throw it for failures of the message itself, such as a malformed 
payload: unless
+/// [StreamConfigProperties#DECODE_RETRY_MAX_DURATION_MILLIS] is set, the 
consumer retries that message forever and
+/// stops ingesting the partition.
[email protected]
[email protected]
+public class RetriableDecodeException extends RuntimeException {
+
+  public RetriableDecodeException(String message) {
+    super(message);
+  }
+
+  public RetriableDecodeException(String message, Throwable cause) {
+    super(message, cause);
+  }
+
+  public RetriableDecodeException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfig.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfig.java
index fe37a681c88..94999d5ee3f 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfig.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfig.java
@@ -46,6 +46,11 @@ public class StreamConfig {
   public static final long DEFAULT_STREAM_CONNECTION_TIMEOUT_MILLIS = 30_000;
   public static final int DEFAULT_STREAM_FETCH_TIMEOUT_MILLIS = 5_000;
   public static final int DEFAULT_IDLE_TIMEOUT_MILLIS = 3 * 60 * 1000;
+  /// First decode retry backoff; it doubles on every retry up to 
[#getDecodeRetryMaxBackoffMillis()].
+  public static final long INITIAL_DECODE_RETRY_BACKOFF_MILLIS = 100;
+  public static final long DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS = 10_000;
+  /// No limit: a message is retried until it decodes.
+  public static final long DEFAULT_DECODE_RETRY_MAX_DURATION_MILLIS = 
Long.MAX_VALUE;
 
   public static final double CONSUMPTION_RATE_LIMIT_NOT_SPECIFIED = -1;
 
@@ -61,6 +66,9 @@ public class StreamConfig {
 
   private final long _idleTimeoutMillis;
 
+  private final long _decodeRetryMaxBackoffMillis;
+  private final long _decodeRetryMaxDurationMillis;
+
   private final int _flushThresholdRows;
   private final int _flushThresholdSegmentRows;
   private final long _flushThresholdTimeMillis;
@@ -170,6 +178,9 @@ public class StreamConfig {
     }
     _idleTimeoutMillis = idleTimeoutMillis;
 
+    _decodeRetryMaxBackoffMillis = 
extractDecodeRetryMaxBackoffMillis(streamConfigMap);
+    _decodeRetryMaxDurationMillis = 
extractDecodeRetryMaxDurationMillis(streamConfigMap);
+
     _flushThresholdRows = extractFlushThresholdRows(streamConfigMap);
     _flushThresholdSegmentRows = 
extractFlushThresholdSegmentRows(streamConfigMap);
     _flushThresholdTimeMillis = 
extractFlushThresholdTimeMillis(streamConfigMap);
@@ -214,6 +225,44 @@ public class StreamConfig {
     return _serverUploadToDeepStore;
   }
 
+  public static long extractDecodeRetryMaxBackoffMillis(Map<String, String> 
streamConfigMap) {
+    String key = StreamConfigProperties.DECODE_RETRY_MAX_BACKOFF_MILLIS;
+    String value = streamConfigMap.get(key);
+    if (value == null) {
+      return DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS;
+    }
+    try {
+      long decodeRetryMaxBackoffMillis = Long.parseLong(value);
+      if (decodeRetryMaxBackoffMillis > 0) {
+        return decodeRetryMaxBackoffMillis;
+      }
+    } catch (NumberFormatException e) {
+      // Handled below
+    }
+    LOGGER.warn("Invalid config {}: {}, must be a positive number of 
milliseconds, defaulting to: {}", key, value,
+        DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS);
+    return DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS;
+  }
+
+  public static long extractDecodeRetryMaxDurationMillis(Map<String, String> 
streamConfigMap) {
+    String key = StreamConfigProperties.DECODE_RETRY_MAX_DURATION_MILLIS;
+    String value = streamConfigMap.get(key);
+    if (value == null) {
+      return DEFAULT_DECODE_RETRY_MAX_DURATION_MILLIS;
+    }
+    try {
+      long decodeRetryMaxDurationMillis = Long.parseLong(value);
+      if (decodeRetryMaxDurationMillis >= 0) {
+        return decodeRetryMaxDurationMillis;
+      }
+    } catch (NumberFormatException e) {
+      // Handled below
+    }
+    LOGGER.warn("Invalid config {}: {}, must be a non-negative number of 
milliseconds, defaulting to no limit", key,
+        value);
+    return DEFAULT_DECODE_RETRY_MAX_DURATION_MILLIS;
+  }
+
   public static double extractFlushThresholdVarianceFraction(Map<String, 
String> streamConfigMap) {
     String key = StreamConfigProperties.FLUSH_THRESHOLD_VARIANCE_FRACTION;
     String flushThresholdVarianceFractionStr = streamConfigMap.get(key);
@@ -385,6 +434,15 @@ public class StreamConfig {
     return _idleTimeoutMillis;
   }
 
+  public long getDecodeRetryMaxBackoffMillis() {
+    return _decodeRetryMaxBackoffMillis;
+  }
+
+  /// See [StreamConfigProperties#DECODE_RETRY_MAX_DURATION_MILLIS]; 
[Long#MAX_VALUE] means no limit.
+  public long getDecodeRetryMaxDurationMillis() {
+    return _decodeRetryMaxDurationMillis;
+  }
+
   public int getFlushThresholdRows() {
     return _flushThresholdRows;
   }
@@ -455,6 +513,8 @@ public class StreamConfig {
         + ", _connectionTimeoutMillis=" + _connectionTimeoutMillis
         + ", _fetchTimeoutMillis=" + _fetchTimeoutMillis
         + ", _idleTimeoutMillis=" + _idleTimeoutMillis
+        + ", _decodeRetryMaxBackoffMillis=" + _decodeRetryMaxBackoffMillis
+        + ", _decodeRetryMaxDurationMillis=" + _decodeRetryMaxDurationMillis
         + ", _flushThresholdRows=" + _flushThresholdRows
         + ", _flushThresholdSegmentRows=" + _flushThresholdSegmentRows
         + ", _flushThresholdTimeMillis=" + _flushThresholdTimeMillis
@@ -491,6 +551,8 @@ public class StreamConfig {
         && _connectionTimeoutMillis == that._connectionTimeoutMillis
         && _fetchTimeoutMillis == that._fetchTimeoutMillis
         && _idleTimeoutMillis == that._idleTimeoutMillis
+        && _decodeRetryMaxBackoffMillis == that._decodeRetryMaxBackoffMillis
+        && _decodeRetryMaxDurationMillis == that._decodeRetryMaxDurationMillis
         && _flushThresholdRows == that._flushThresholdRows
         && _flushThresholdSegmentRows == that._flushThresholdSegmentRows
         && _flushThresholdTimeMillis == that._flushThresholdTimeMillis
@@ -511,8 +573,9 @@ public class StreamConfig {
   @Override
   public int hashCode() {
     return Objects.hash(_type, _topicName, _tableNameWithType, 
_consumerFactoryClassName, _decoderClass,
-        _decoderProperties, _connectionTimeoutMillis, _fetchTimeoutMillis, 
_idleTimeoutMillis, _flushThresholdRows,
-        _flushThresholdSegmentRows, _flushThresholdTimeMillis, 
_flushThresholdSegmentSizeBytes,
+        _decoderProperties, _connectionTimeoutMillis, _fetchTimeoutMillis, 
_idleTimeoutMillis,
+        _decodeRetryMaxBackoffMillis, _decodeRetryMaxDurationMillis, 
_flushThresholdRows, _flushThresholdSegmentRows,
+        _flushThresholdTimeMillis, _flushThresholdSegmentSizeBytes,
         _flushThresholdVarianceFraction, _flushAutotuneInitialRows, 
_partitionConsumptionRateLimit,
         _topicConsumptionRateLimit, _enableOffsetAutoReset, 
_offsetAutoResetOffsetThreshold,
         _offsetAutoResetTimeSecThreshold, _backfillTopic, _streamConfigMap, 
_offsetCriteria, _serverUploadToDeepStore);
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfigProperties.java
 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfigProperties.java
index 4c69eb6b861..8088d0bb8a5 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfigProperties.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamConfigProperties.java
@@ -127,6 +127,18 @@ public class StreamConfigProperties {
   /// Config used to indicate whether the topic is a temporary topic for 
offset auto reset backfilling
   public static final String BACKFILL_TOPIC = 
"realtime.segment.isBackfillTopic";
 
+  /// Cap, in milliseconds, of the backoff before a message whose decoder 
threw [RetriableDecodeException] is fetched
+  /// again. The backoff starts at 
[StreamConfig#INITIAL_DECODE_RETRY_BACKOFF_MILLIS] and doubles up to the cap.
+  /// Defaults to [StreamConfig#DEFAULT_DECODE_RETRY_MAX_BACKOFF_MILLIS] (10 
seconds).
+  public static final String DECODE_RETRY_MAX_BACKOFF_MILLIS = 
"decodeRetryMaxBackoffMillis";
+
+  /// How long, in milliseconds, retriable decode failures are retried during 
an outage of a decoder dependency. An
+  /// outage lasts while a message is being retried or retriable failures keep 
happening less than this apart; once it
+  /// has lasted this long, its failures are handled like any other decode 
failure. No limit by default; `0` disables
+  /// retries. The limit is per segment, not a hard cap: a new segment, pause, 
restart or rebalance starts a fresh
+  /// window.
+  public static final String DECODE_RETRY_MAX_DURATION_MILLIS = 
"decodeRetryMaxDurationMillis";
+
   /// Helper method to create a stream specific property
   public static String constructStreamProperty(String streamType, String 
property) {
     return Joiner.on(DOT_SEPARATOR).join(STREAM_PREFIX, streamType, property);
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoder.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoder.java
index 3784bec9de1..03c6c7c0246 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoder.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoder.java
@@ -24,6 +24,7 @@ public interface StreamDataDecoder {
   ///
   /// Please note that the expectation is that the implementations of this 
class should never throw an exception.
   /// Instead, it should encapsulate the exception within the 
[StreamDataDecoderResult] object.
+  /// A [RetriableDecodeException] is encapsulated as is, so that 
[StreamDataDecoderResult#isRetriable()] reports it.
   ///
   /// @param message [StreamMessage] that contains the data payload and 
optionally, a key and row metadata
   /// @return [StreamDataDecoderResult] that either contains the decoded row 
or the exception
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
index 3ad688c0f51..aed1ac2ab89 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderImpl.java
@@ -89,6 +89,9 @@ public class StreamDataDecoderImpl implements 
StreamDataDecoder {
         return new StreamDataDecoderResult(null,
             new RuntimeException("Encountered unknown exception when decoding 
a Stream message"));
       }
+    } catch (RetriableDecodeException e) {
+      // Not logged here: the consumer logs retriable failures, rate-limited
+      return new StreamDataDecoderResult(null, e);
     } catch (Exception e) {
       LOGGER.error("Failed to decode StreamMessage", e);
       return new StreamDataDecoderResult(null, e);
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderResult.java
 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderResult.java
index 2586e9f3618..cf67f9d7c1d 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderResult.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamDataDecoderResult.java
@@ -42,4 +42,9 @@ public final class StreamDataDecoderResult {
   public Exception getException() {
     return _exception;
   }
+
+  /// Whether decoding failed with a [RetriableDecodeException]: decode the 
message again, don't drop it.
+  public boolean isRetriable() {
+    return _exception instanceof RetriableDecodeException;
+  }
 }
diff --git 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamMessageDecoder.java 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamMessageDecoder.java
index 63d2351d423..e7ad299214e 100644
--- 
a/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamMessageDecoder.java
+++ 
b/pinot-spi/src/main/java/org/apache/pinot/spi/stream/StreamMessageDecoder.java
@@ -28,6 +28,14 @@ import org.apache.pinot.spi.data.Schema;
 import org.apache.pinot.spi.data.readers.GenericRow;
 
 /// Interface for a decoder of messages fetched from the stream
+///
+/// Failure contract of the `decode` methods:
+/// - Returning `null` or throwing any exception other than 
[RetriableDecodeException] drops the message, or stops
+///   consumption if the stream config `stopOnDecodeError` is set.
+/// - Throwing [RetriableDecodeException] means the message may decode later, 
e.g. once a schema registry is reachable
+///   again. Regardless of `stopOnDecodeError`, the consumer backs off and 
fetches the message again until it decodes or
+///   the outage outlasts 
[StreamConfigProperties#DECODE_RETRY_MAX_DURATION_MILLIS] (no limit by 
default). A segment
+///   that reaches its time threshold or is force committed (also on pause) 
meanwhile ends before that message.
 /// @param <T>
 @InterfaceAudience.Public
 @InterfaceStability.Stable
@@ -63,6 +71,7 @@ public interface StreamMessageDecoder<T> {
   /// @param payload The buffer from which to read the row.
   /// @return A new row decoded from the buffer. If the returned value is 
`null` the row is dropped from the
   ///         segment.
+  /// @throws RetriableDecodeException If the message may decode later (see 
the class doc)
   @Nullable
   GenericRow decode(T payload, GenericRow destination);
 
@@ -74,6 +83,7 @@ public interface StreamMessageDecoder<T> {
   /// @param destination The [GenericRow] to write the decoded row into
   /// @return A new row decoded from the buffer If the returned value is 
`null` the row is dropped from the
   ///         segment.
+  /// @throws RetriableDecodeException If the message may decode later (see 
the class doc)
   @Nullable
   GenericRow decode(T payload, int offset, int length, GenericRow destination);
 }
diff --git 
a/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
 
b/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
index 622681cba1c..d68b74b6d56 100644
--- 
a/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
+++ 
b/pinot-spi/src/test/java/org/apache/pinot/spi/stream/StreamDataDecoderImplTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.pinot.spi.stream;
 
+import java.net.SocketTimeoutException;
 import java.nio.charset.StandardCharsets;
 import java.util.Map;
 import java.util.Set;
@@ -131,9 +132,49 @@ public class StreamDataDecoderImplTest {
     Assert.assertNotNull(result);
     Assert.assertNotNull(result.getException());
     Assert.assertNull(result.getResult());
+    Assert.assertFalse(result.isRetriable());
+  }
+
+  @Test
+  public void testRetriableDecodeExceptionIsCarriedAsRetriable() {
+    SocketTimeoutException registryTimeout = new SocketTimeoutException("Read 
timed out");
+    RetriableDecodeException retriable = new RetriableDecodeException("Schema 
registry unavailable", registryTimeout);
+    BytesStreamMessage message = new 
BytesStreamMessage("Alice".getBytes(StandardCharsets.UTF_8), METADATA);
+
+    StreamDataDecoderResult result = new StreamDataDecoderImpl(new 
ThrowingDecoder(retriable)).decode(message);
+
+    Assert.assertNull(result.getResult());
+    Assert.assertTrue(result.isRetriable());
+    // Carried as is, so that the consumer can log the cause
+    Assert.assertSame(result.getException(), retriable);
+    Assert.assertSame(result.getException().getCause(), registryTimeout);
+  }
+
+  @Test
+  public void testOnlyRetriableDecodeExceptionIsRetriable() {
+    BytesStreamMessage message = new 
BytesStreamMessage("Alice".getBytes(StandardCharsets.UTF_8), METADATA);
+    // Returning null drops the message
+    StreamDataDecoderResult nullResult = new StreamDataDecoderImpl(new 
NullDecoder()).decode(message);
+    Assert.assertNotNull(nullResult.getException());
+    Assert.assertFalse(nullResult.isRetriable());
+    // So does any other exception, even one caused by a 
RetriableDecodeException
+    StreamDataDecoderResult wrappedResult = new StreamDataDecoderImpl(
+        new ThrowingDecoder(new IllegalStateException(new 
RetriableDecodeException("wrapped")))).decode(message);
+    Assert.assertNotNull(wrappedResult.getException());
+    Assert.assertFalse(wrappedResult.isRetriable());
+    Assert.assertFalse(new StreamDataDecoderImpl(new 
TestDecoder()).decode(message).isRetriable());
   }
 
   private static class ThrowingDecoder implements StreamMessageDecoder<byte[]> 
{
+    private final RuntimeException _exception;
+
+    ThrowingDecoder() {
+      this(new RuntimeException("something failed during decoding"));
+    }
+
+    ThrowingDecoder(RuntimeException exception) {
+      _exception = exception;
+    }
 
     @Override
     public void init(Map<String, String> props, Set<String> fieldsToRead, 
String topicName) {
@@ -142,13 +183,27 @@ public class StreamDataDecoderImplTest {
     @Nullable
     @Override
     public GenericRow decode(byte[] payload, GenericRow destination) {
-      throw new RuntimeException("something failed during decoding");
+      throw _exception;
+    }
+
+    @Nullable
+    @Override
+    public GenericRow decode(byte[] payload, int offset, int length, 
GenericRow destination) {
+      throw _exception;
+    }
+  }
+
+  private static class NullDecoder implements StreamMessageDecoder<byte[]> {
+    @Nullable
+    @Override
+    public GenericRow decode(byte[] payload, GenericRow destination) {
+      return null;
     }
 
     @Nullable
     @Override
     public GenericRow decode(byte[] payload, int offset, int length, 
GenericRow destination) {
-      throw new RuntimeException("something failed during decoding");
+      return null;
     }
   }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to