<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ján Michalica on Medium]]></title>
        <description><![CDATA[Stories by Ján Michalica on Medium]]></description>
        <link>https://medium.com/@jan.michalica?source=rss-ce62f632c0a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Kj4WE4jCHw60nqy3Jh54_g.png</url>
            <title>Stories by Ján Michalica on Medium</title>
            <link>https://medium.com/@jan.michalica?source=rss-ce62f632c0a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:44:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jan.michalica/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Retryable Topics with Spring Kafka]]></title>
            <link>https://medium.com/jamf-engineering/retryable-topics-with-spring-kafka-946360f2d644?source=rss-ce62f632c0a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/946360f2d644</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[recovery]]></category>
            <category><![CDATA[retry]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[reliability]]></category>
            <dc:creator><![CDATA[Ján Michalica]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 13:29:27 GMT</pubDate>
            <atom:updated>2022-06-07T13:29:27.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>There are many use cases where applications have strong requirements on the reliability of processing Kafka messages. To address this requirement Spring Kafka provides retry functionality, either by using RetryTemplate with RetryingMessageListenerAdapter or, in the latest versions, by a properly configured error handler.</p><p>While this approach to retries preserves guarantees about message delivery ordering, it has also one inherent drawback: the retry (and eventual waiting if a retry delay is configured) is performed in the Kafka consumer thread. Each failure blocks processing of assigned topic partitions causing the consumer to lag. This renders the solution unsuitable for consumers of high-throughput topics. Moreover, this approach does not address situation when a Kafka message cannot be processed for extended time period.</p><p>Spring Kafka 2.7 introduced new functionality called <em>non-blocking retries</em> (<a href="https://docs.spring.io/spring-kafka/reference/html/#retry-topic">https://docs.spring.io/spring-kafka/reference/html/#retry-topic</a>). This feature uses additional <em>retry</em> Kafka topics where are the un-processed messages sent to for later re-delivery. The number of topics (and hence of retries) is arbitrary and each one can be configured with different retry delay. As the retries are non-blocking, the guarantees about Kafka message ordering are no longer possible.</p><h3>How It Works</h3><p>When a topic is configured to be retryable and the listener processing the message throws an exception, then Spring-configured error recovery mechanism performs following steps:</p><ul><li>computes the <em>due time</em> when the message should be processed again</li><li>creates a retry message as the copy of the original message with additional headers (like the message due time, exception details, …)</li><li>computes the next retry topic and publishes the message to it</li><li>or if the number of retries is exhausted, the message is either simply dropped or sent to the dead letter topic allowing for later investigations</li></ul><p>Spring Kafka will automatically create message listener containers for retry topics (and the dead letter queue) and those containers use by default the same message listener and configuration as the main topic. The listeners are wrapped in special adapters that implement the delayed message processing:</p><ul><li>The due time of the incoming message is checked (in KafkaBackoffAwareMessageListenerAdapter) — if it has passed already, the message is passed to the listener.</li><li>If the due time has not yet come to pass, the adapter makes the backoff manager (PartitionPausingBackoffManager) to throw a KafkaBackoffException with information on how long should be the processing delayed.</li><li>The partition offset is reset and the Kafka consumer paused for the required time period.</li><li>Once the consumer wakes up, message is delivered again.</li></ul><h3>A Practical Example</h3><p>Jamf provides integration data feeds about customers’ network traffic, threats, applications, and devices to the customers’ systems. The data are ingested from various Kafka topics, enriched, and pushed to the configured Syslog, HTTP, or S3 endpoints.</p><p>The availability of configured 3rd party systems depends on the particular customer and their infrastructure and the network itself is unreliable in general. If the system was unavailable or unable to process the data feed request, the messages were simply dropped.</p><p>Being aware of this problem, we planned to create a message re-delivery mechanism since the integration streams had been designed. The inspiration for the final solution (using dedicated Kafka topics) came from <a href="https://eng.uber.com/reliable-reprocessing/">this</a> article.</p><p>By the time we moved to the actual implementation, Spring Kafka already provided all the needed building blocks.</p><h3>Overall Design</h3><p>When sending a message to a particular target fails, the sender creates a recovery message and publishes it to the recovery queue topic. The message contains the complete payload to be sent and an identification of the integration target.</p><p>The Kafka listener of the recovery queue receives the failed message and attempts the re-delivery immediately. If this fails, message is passed to the next recovery queue (with increasing delay) until it is sent successfully or the number of attempts is exhausted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*DU2W7ZxZOSl4jUots9XkHg.png" /><figcaption>Message delivery retries with dedicated topics</figcaption></figure><h3>Spring Configuration</h3><p>The easiest way to configure a retryable topic is using the@RetryableTopic (see <a href="https://docs.spring.io/spring-kafka/reference/html/#using-the-retryabletopic-annotation">https://docs.spring.io/spring-kafka/reference/html/#using-the-retryabletopic-annotation</a>) annotation on the message listener method, together with the@KafkaListener annotation. The annotation can configure most of retry functionality properties like number of delivery attempts, topics auto-creation and backoff strategy to compute delivery delays.</p><p>Alternative to the annotation is to create a RetryTopicConfiguration bean(s) that allows a more fine-grained configuration:</p><pre>@Bean<br>public RetryTopicConfiguration recoveryQueueConfiguration(<br>		@Qualifier(RecoveryQueueConfig.TEMPLATE) KafkaTemplate&lt;String, RecoveryMessage&gt; template,<br>		@Qualifier(RecoveryQueueConfig.CONTAINER_FACTORY)<br>				ConcurrentKafkaListenerContainerFactory&lt;String, RecoveryMessage&gt; containerFactory,<br>		MessageRecoveryConfig messageRecoveryConfig) {</pre><pre>	return RetryTopicConfigurationBuilder.newInstance()<br>			.includeTopic(RecoveryQueueConfig.TOPIC)<br>			.suffixTopicsWithIndexValues()<br>			.doNotAutoCreateRetryTopics()<br>			.maxAttempts(messageRecoveryConfig.getAttempts())<br>			.customBackoff(new IntervalBackOffPolicy(messageRecoveryConfig.getIntervals()))<br>			.notRetryOn(MethodArgumentResolutionException.class)<br>			.notRetryOn(MethodArgumentNotValidException.class)<br>			.notRetryOn(DeserializationException.class)<br>			.dltHandlerMethod(RecoveryQueueConfig.MESSAGE_LISTENER, &quot;deadLetter&quot;)<br>			.doNotRetryOnDltFailure()<br>			.listenerFactory(containerFactory)<br>			.create(template);<br>}</pre><p>Of course we still had to create obligatory Kafka-related beans, like producer and consumer factories, Kafka template to send the recovery queue messages, and naturally the message listener that takes care for the actual message re-delivery.</p><h3>Lessons Learned</h3><p>The functional and performance testing revealed some unexpected behaviour that had to be addressed in the configuration so that the recovery queue behaviour and performance would meet our expectations. Namely:</p><ul><li>Messages produced to the retry topics were ~10x bigger than the original ones — this is caused by adding exception-related headers (exception stacktrace, FQN and message) to the messages. This is not configurable so far, so we solved this on the Kafka client level, by removing exception headers in a custom producer interceptor right before the message is sent.</li><li>Messages that fail to be de-serialized or validated (we use a validating message listener) are retried, so we had to explicitly exclude the corresponding exceptions from the retry topic configuration (this is partially addressed in Spring Kafka 2.8).</li><li>Dead letter queue/topic (DLT) works in a peculiar way: it is also a destination for messages that were not retried, e.g. due to de-serialization errors. In such case they carry the de-serialization exception with all the data that could not be de-serialized. When such DLT message is delivered to the dead letter handler and it fails to be de-serialized, a new, even larger, DLT message is produced. This creates a loop when DLT is filled with ever-growing messages until the maximum Kafka record size is exceeded. Solution is to disable sending failed dead letters to DLT (this is default in Spring Kafka 2.8).</li><li>Metrics for Kafka consumers did not work properly until the client ID prefix was explicitly set in the listener annotation:</li></ul><pre>@KafkaListener(<br>      id = RecoveryQueueConfig.ID,<br>      idIsGroup = false,<br>      topics = RecoveryQueueConfig.TOPIC,<br>      clientIdPrefix = &quot;${kafka.consumers.recovery-queue.clientId}&quot;,<br>      containerFactory = RecoveryQueueConfig.CONTAINER_FACTORY,<br>      groupId = RecoveryQueueConfig.GROUP_ID)<br>public void listen(@Header(KafkaHeaders.RECEIVED_TOPIC) String topic,<br>      @Header(name = KafkaHeaders.RECEIVED_MESSAGE_KEY, required = false) String key,<br>      @Nullable @Header(RetryTopicHeaders.DEFAULT_HEADER_ATTEMPTS) byte[] attempts,<br>      @Valid @Payload RecoveryMessage recoveryMessage) {<br>      ...<br>}</pre><ul><li>Currently, the tracing information is not propagated.</li><li>A retried message is by default sent to the same partition of the next topic as it was received from — this causes fetching topic partition information from the broker to verify the partition presence.</li><li>Messages are sent to the next retry topic <em>synchronously</em> by default, presumably to increase the reliability of the whole feature. This has huge impact on the throughput — it was just ones of messages per second with our testing configuration.</li></ul><pre>@Bean(RetryTopicInternalBeanNames.DEAD_LETTER_PUBLISHING_RECOVERER_FACTORY_BEAN_NAME)<br>public DeadLetterPublishingRecovererFactory deadLetterRecovererFactory(DestinationTopicResolver resolver) {<br>	var recovererFactory = new DeadLetterPublishingRecovererFactory(resolver);<br>	recovererFactory.setDeadLetterPublishingRecovererCustomizer(recoverer -&gt; {<br>		recoverer.setAppendOriginalHeaders(false);<br>		recoverer.setStripPreviousExceptionHeaders(true); // do not accumulate exception info from previous attempts<br>		recoverer.setVerifyPartition(false); // do not verify destination partition presence<br>		recoverer.setFailIfSendResultIsError(false); // send messages asynchronously<br>	});<br>	return recovererFactory;<br>}</pre><ul><li>KafkaBackoffException, even it is a part of the normal working of the feature, was logged at the WARN level. This was changed to DEBUG in Spring Kafka 2.8.</li></ul><h3>Conclusion</h3><p>Retryable topics provided by Spring Kafka allowed us to implement the recovery queue with relatively low amount of coding. However, thorough testing of its performance and of various corner-cases proved to be crucial in finding the optimal configuration for a performant and reliable solution that would satisfy our use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946360f2d644" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jamf-engineering/retryable-topics-with-spring-kafka-946360f2d644">Retryable Topics with Spring Kafka</a> was originally published in <a href="https://medium.com/jamf-engineering">Jamf Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>