The Inbox Pattern

The Inbox Pattern: Managing Long-Running Tasks for Kafka Consumers

At PMU, we use an event-driven microservices architecture, primarily in Java, with Spring-boot for our microservices and Apache Kafka as our message broker. While this remains a fairly standard architecture, it’s worth noting that the various messages are very different in nature, and the processing times for these messages vary greatly, from a few milliseconds to several minutes. What might seem painless at first glance quickly turned into a nightmare, leading to an almost complete blockage of part of our Information System and numerous data inconsistencies that had to be addressed.

The Problem

Kafka consumers in Spring are configured by default to “poll” at most every 5 minutes. If a consumer doesn’t poll within these 5 minutes, it will be considered dead and will leave the group. With Spring, as soon as an event is polled, the system starts processing it on the consumer thread until it’s finished. This means that by default, the consumer won’t be able to poll again until the processing is complete (since the consumer thread is busy processing the event).

Let’s take the following example: a microservice (let’s call it SDJ) is in charge of calculating the odds and associated winnings for players. To do this, it listens to the broker and waits for the race finish message. This processing is a batch job that can take several minutes and is tied to the volume of data. If this batch doesn’t finish within 5 minutes, the consumer session will time out and the message won’t be acknowledged. The consumer will then be removed, leading to a rebalancing and redistribution of topics and partitions to a new consumer. As we’ve done things properly and tried to address some resilience issues, our microservices are redundant and share the same group-id, mutually excluding each other. A second consumer will then be elected and will try to reprocess this same message, while the first consumer’s process is likely still ongoing. And as you might guess, after several minutes, all consumers will have been removed, processes will have been repeated multiple times, leading to resource waste and probably inconsistent data if idempotence hasn’t been properly managed.

A small diagram to illustrate this problem:

Kafka problem

Basic Solutions

There are a few solutions that can be implemented:

Code Optimization

This is of course the most obvious and essential. All complexity issues and n+1 select problems must be addressed.

Increase the timeout

Easily done with Spring configuration:

spring.kafka.consumer.properties.max.poll.interval.ms= 300000

While this may seem obvious and sufficient, it is unfortunately not ideal. The consequence is that if a problem occurs on the consumer, it will only be detected after this specific time. If the timeout has been set to 1 hour, this will create other problems. Moreover, this time is not necessarily predictable.

Threading - fire & forget

Une solution qui peut fonctionner pour certains use case : acquitter le message immédiatement et effectuer le traitement dans un thread dédié. en utilisant l’annotation @Async de Spring, cela peut facilement être mis en place. Mais attention, cela a pour conséquence d’augmenter les ressources du micro-service en particulier si le process est intensif et qu’il y a plusieurs traitements simultanés. Un autre souci est que désormais l’ordre des messages ne sera pas respecté.

Pause du consommateur & callback

Le consommateur continuera à interroger le broker, mais il n’acceptera simplement aucun nouvel événement provenant de la partition jusqu’à ce qu’il reprenne. Le poll sert simplement de keep-alive. le traitement est effectué dans un thread mais contrairement au fire & forget, un callback permettra de gérer la réponse du traitement (qui peut-être en erreur) et de débloquer le thread du consommateur afin de dépiler les messages restants sur le topic. Cette solution a le mérite d’éviter le fameux timeout, elle est assez couteuse en développement et elle est compliquée à mettre en place dans certains scenarios nécessitant des traitements en parallèle.

The Inbox Pattern

At PMU, we opted for a different approach that better suits our needs. We have specific requirements inherent to our business. As we’ve seen, the finish of a race triggers long processing tasks. However, if another race starts during this processing, we want to ensure that betting is no longer possible for this second race. Thus, we need a pattern that allows us to:

  • Handle long-running processes and thus avoid all possible errors due to timeouts
  • Be able to perform multiple processes in parallel according to a partitioning key
  • Process messages while respecting the order for all messages of the same partition

The Outbox Pattern

The Outbox pattern is well-known to developers who want to ensure that an update in a repository (database) and the publication of a message on a broker are transactional. We use an “Outbox” table and, by leveraging the transaction, we ensure that the message will be delivered at least once (at-least-once semantics).

The Inbox Pattern

We have reused and repurposed the Outbox pattern to accomplish the same tasks, but in reverse…

  • The consumer retrieves the message
  • It is recorded in an Inbox table
  • The consumer sends the message acknowledgment to the broker
  • Messages are dequeued by an asynchronous process

Due to its extremely simple processing, there are no more long-running tasks and therefore no more possible timeouts. Good job!

Note: We must ensure that all messages are recorded in the database before acknowledging the message.

Outbox vs Inbox

Advantages:

  • Messages are processed only once (exactly once semantics)
  • No Kafka consumer session timeout issues
  • Possibility of sharding for message processing

Disadvantages:

  • More complex code to write and maintain
  • Significant increase in resources used by the microservice (threads and memory)

Sharding

By default, the inbox processes events in order, and each processing must wait for the previous one to finish before starting. If we use a fire & forget threading mode, we would also lose the notion of order, which is essential in our system.

Sharding fig-4

  • The start of Race 2 must be processed immediately, even if the processing of Race 1’s finish is not complete.
  • We cannot afford to process messages out of order. E.g., a start processed after a finish for a given race

At PMU, we determined that the best sharding key was the race, which is unique in our repository. Thus, for each received message:

  • We extract the referenced race from this message to deduce the key
  • We record the message and the key
  • For each key, we create a thread and an associated queue
  • This thread will be responsible for enqueuing inbox messages with the corresponding key and dequeuing them in the order of reception

Sharding fig-5

To limit resources, these threads are regularly cleaned up/deleted

Conclusion

Outbox and Inbox are among the essential patterns to use and implement in a microservice architecture. Once mastered and implemented, they can address a very large part of the problems that can occur with a message broker, particularly the management of distributed transactions between multiple components.

Coding

We hope to open-source our libraries quite soon. We use Java, Spring, Quartz, but we are strongly convinced that Debezium is the best option for the Outbox pattern, especially in cases of high volume.
To be continued. More in the next issue…