title: How to prioritize some messages using spring cloud stream with the kafka binder
body: <p>TLDR: I would like to be able to process some urgent messages before others in the same topic.</p>
  
  <p>More explanation : </p>
  
  <p>I'm working on a fairly large application using many spring microservices relying on spring-cloud-stream with the kafka-binder to talk between each other for some tasks.</p>
  
  <p>It can happen that a scheduled task produces lot of events. When these event are consumed intermediary events may be produced and send, and it can take quite some time till all the initial and  intermediary messages are consumed and all the work is done.</p>
  
  <p>During this time, if someone wants to manually send an event of the same type, it will be queued and processed only when everything else is done.</p>
  
  <p>I've been asked to see if I can not make these "manual events" be processed in priority, before all the other events.</p>
  
  <p>Usually in this case you see people advocating for duplicating all the topics (<code>topic-normal</code> and <code>topic-urgent</code> for example), duplicating the <code>@StreamListener</code>. This seems a rather complicated option, because we have lots of different topics involved here. We also have some kafka-streams aggregation that would need to be rewritten to take this into account.</p>
  
  <p>With a fellow developer we were thinking of maybe duplicating the consumer groups (<code>consumerGroupNormal</code>, <code>consumerGroupUrgentusing</code>) for each topic were urgent messages are needed. I would then add a priority header to each message, duplicate the <code>StreamListener</code> and consume only messages with  <code>priority: urgent</code> headers in one of the listener, and only messages with <code>priority:normal</code> in the other listener. </p>
  
  <p>I would also probably create a ChannelInterceptorAdapter to add and read this "priority" header automatically (<a href="https://github.com/spring-cloud/spring-cloud-sleuth/blob/master/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/messaging/AbstractTraceChannelInterceptor.java" rel="nofollow noreferrer">a bit like Sleuth does it</a>). </p>
  
  <p>But I still would have to add lots of configuration for the binders to write and would need to duplicate the listeners, add the little code that checks the header and executes or not the listener code.</p>
  
  <p>All in all, this looks like quite a bit of work for somehting that looks like quite a common and simple use case that could be useful for other people so I was wondering if there is not a simpler way to do it ?</p>