Spring Kafka
Consumer
Skip corrupt messages
Serialization
Error handling

How to skip corrupt (non-serializable) messages in Spring Kafka Consumer?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

When consuming messages from a Kafka topic using Spring Kafka, you may encounter corrupt or non-serializable messages that can cause your application to throw serialization exceptions and stop processing further messages. Handling these exceptions effectively ensures that your application remains robust and resilient.

Understanding Serialization in Spring Kafka

Serialization in Kafka involves converting the data in a Kafka message's key and value into bytes to be sent over the network. Deserialization is the reverse process—converting these bytes back into objects when reading messages from a topic.

In Spring Kafka, the KafkaListener uses a ConsumerFactory which in turn configures a Deserializer for the keys and values of the messages. The serialization process needs to match the structure and data type expected by the consumer. If a message does not match the expected format, the deserializer can throw a SerializationException.

Strategies to Handle Corrupt Messages

1. Custom Error Handling with ContainerProperties

Spring Kafka provides ways to handle exceptions using the ContainerProperties configuration on the ConcurrentKafkaListenerContainerFactory. By setting an ErrorHandler or a RecoveryCallback, you can decide how to handle errors such as serialization failures.

Here's how you might configure this in your Spring Kafka consumer:

java
1@Configuration
2public class KafkaConfig {
3
4    @Autowired
5    private ConsumerFactory<Object, Object> consumerFactory;
6
7    @Bean
8    public ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory() {
9        ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
10        factory.setConsumerFactory(consumerFactory);
11        factory.setErrorHandler(new SeekToCurrentErrorHandler(
12           new DeadLetterPublishingRecoverer(kafkaTemplate()), 
13           new FixedBackOff(1000L, 2))); // retry twice after one second delay
14        return factory;
15    }
16}

2. Custom Deserializer

A more proactive approach is to implement your own deserializer which can safely handle corrupt messages and skip them. Here is an example of a custom deserializer:

java
1public class SafeDeserializer<T> implements Deserializer<T> {
2
3    private final Deserializer<T> delegate;
4
5    // Constructor injecting the actual deserializer
6    public SafeDeserializer(Deserializer<T> delegate) {
7        this.delegate = delegate;
8    }
9
10    @Override
11    public T deserialize(String topic, byte[] data) {
12        try {
13            return delegate.deserialize(topic, data);
14        } catch (Exception e) {
15            // handle the exception, log it, and return null or a default value
16            return null;
17        }
18    }
19}

You then need to configure your Spring Kafka consumer to use this deserializer:

java
1@Bean
2public ConsumerFactory<Object, Object> consumerFactory() {
3    return new DefaultKafkaConsumerFactory<>(configProps, new StringDeserializer(), new SafeDeserializer<>(new JsonDeserializer<>(YourObjectType.class)));
4}

Summary Table

StrategyImplementation LevelProsCons
Error Handling with ContainerPropertiesConsumer ConfigurationSimple; Uses built-in recovery featuresLess control over individual messages
Custom DeserializerMessage DeserializationHigh control; Can handle message-by-messageMore complex to implement

Conclusion

By implementing one of these strategies, you can enhance the robustness of your Spring Kafka application, ensuring it can handle corrupt or non-serializable messages gracefully without impacting overall message processing. Whether you choose to handle errors after they occur or preemptively filter out problematic messages, depends largely on your specific application needs and constraints.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design