<?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 Sonali Mendis on Medium]]></title>
        <description><![CDATA[Stories by Sonali Mendis on Medium]]></description>
        <link>https://medium.com/@sonali.mendis?source=rss-faf00a669c98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8SOn876lkawHaQkDYgwygA.jpeg</url>
            <title>Stories by Sonali Mendis on Medium</title>
            <link>https://medium.com/@sonali.mendis?source=rss-faf00a669c98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:07:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sonali.mendis/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[Why Open Source Isn’t One-Size-Fits-All — and How to Find Your Fit]]></title>
            <link>https://medium.com/@sonali.mendis/why-open-source-isnt-one-size-fits-all-and-how-to-find-your-fit-9ddc0cdf5206?source=rss-faf00a669c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ddc0cdf5206</guid>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Sonali Mendis]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 10:33:43 GMT</pubDate>
            <atom:updated>2026-04-10T13:26:20.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KG9ydPxYFe1QxTO7-LQ0CA.png" /></figure><p>Feeling stuck in your day job? Tinkering with the same libraries, juggling different versions, or endlessly maintaining old code? You’re not alone. I’ve been there. When I worked as a developer in software product companies, I felt truly alive and curious only when I changed roles and faced new challenges. In consultancy, things moved too fast for deep learning — leaving me stagnant.</p><p>This feeling isn’t uncommon. Talk to experienced engineers at meetups or your workplace, and you’ll find almost everyone has felt like a “frog in the well” at some point in their career.</p><h3><strong>Beyond the Bubble</strong></h3><p>There are many ways to break out of this bubble without constantly changing jobs. One path that often comes up is contributing to open source projects. It’s frequently seen as a go-to way to learn, explore, and grow—but in my experience, it’s not quite that simple.</p><p>Maybe you’ve wanted to try a new role but never had the chance. Maybe you’ve wanted to explore a new language or framework. Open source can offer those opportunities—on real projects that people actually use, not just small hobby experiments that fade away.</p><p>But as I’ve learned, it’s not a one-size-fits-all solution. And figuring out whether it works for you is just as important as jumping in.</p><p>Along the way, you’ll discover that contributing to open source:</p><ul><li>Connects you with new people</li><li>Exposes you to different expectations and workflows</li><li>Gives you the freedom to explore and experiment</li></ul><h3><strong>What is Open Source?</strong></h3><p>If you’re new to open source, here’s a quick primer:</p><blockquote>Open source software is publicly accessible software that anyone can view, modify, and distribute. It’s built by communities of contributors from around the world.</blockquote><p>Open source software is:</p><ul><li>Free to use, study, modify, and share</li><li>Transparent in how it’s developed</li><li>Built collaboratively by diverse communities of enthusiasts</li><li>Licensed under open source licenses like MIT, Apache, GPL, LGPL, etc.</li></ul><p>Since the GNU Project in 1983, open source development has grown tremendously. Today, it’s hard to imagine building proprietary software — or even doing your daily work — without relying on open source libraries, platforms, or tools. Just to name a few major projects that have shaped modern software: Node.js, Docker, Apache, Linux, MySQL, and the AWS CDK toolkit. These projects touch almost every developer’s workflow, often without us realizing it.</p><h3><strong>My First Attempt (Failure Story)</strong></h3><p>In 2011, I was working as a developer on a product that used Adobe Flex for its frontend. It was my first job after graduating in 2010. I was doing well — confident in my skills and comfortable in my role.</p><p>At the same time, I saw some of my former batchmates contributing to open source projects and getting recognized for their work. That world intrigued me. I wanted to be part of it.</p><p>The first piece of advice I received was simple: <em>find something close to your work and your interests</em>.</p><p>So I chose Apache Flex. Adobe had just open-sourced Flex and donated it to the Apache Software Foundation. It felt like the perfect fit — it was the same technology I used every day.</p><p>I joined the mailing list, excited and motivated to contribute.</p><p>That excitement didn’t last long.</p><p>Almost immediately, I was flooded with emails — threads full of experienced contributors discussing topics I barely understood. It felt like everyone was speaking a language I didn’t know. My confidence started to fade.</p><p>The same person who felt capable at work suddenly felt completely out of place.</p><p>Still, I pushed myself to pick up an issue that seemed simple. But once I started, I was lost. I didn’t know where to begin, and more importantly, I didn’t know where to ask for help.</p><p>This wasn’t like my workplace, where there were clear roles — tech leads, architects, teammates I could turn to. Here, everything felt unstructured and distant.</p><p>I hesitated to ask questions on the mailing list. I didn’t want to sound inexperienced or “silly.”</p><p>After struggling for quite some time, I managed to put together a fix and opened a pull request.</p><p>And then… nothing.</p><p>It wasn’t prioritized. There were bigger issues the maintainers were focusing on. I waited for feedback, but none came.</p><p>Eventually, I gave up.</p><p>I left the mailing list, stopped following the project, and never went back to that pull request again.</p><h3><strong>Why it Failed?</strong></h3><p>Looking back, it’s clear why this attempt failed. It wasn’t the project — it was my approach and my mindset at the time.</p><p>Here’s what went wrong:</p><p><strong>1. Lack of experience with ambiguity<br></strong>I was less than a year into my career. At work, everything was structured — tasks were clearly defined, and guidance was always available. Open source was the opposite. Issues were often loosely defined, and I wasn’t yet comfortable navigating that uncertainty.</p><p><strong>2. Fear of communication<br></strong>Unlike my workplace, this was a remote, distributed community. I didn’t know anyone personally, and that made me hesitant to ask questions. I was afraid of being judged. In reality, that fear held me back more than anything else.</p><p><strong>3. Jumping in too quickly<br></strong>I tried to contribute immediately without first understanding the project or the community. I didn’t spend time observing discussions, understanding workflows, or learning how contributors collaborated.</p><p><strong>4. Imposter syndrome<br></strong>The biggest issue wasn’t technical — it was psychological. Seeing so many experienced contributors made me feel like I didn’t belong. I started doubting my own abilities.</p><p>One important thing to clarify: the initial advice I received — to find a project close to my work and interests — was not wrong. In fact, it’s still one of the best pieces of advice for anyone starting out in open source.</p><p>The problem wasn’t the choice of project. Apache Flex was a good fit for my skills at the time. The real issue was how I approached the contribution process. I focused only on what to contribute, not how to contribute within a community.</p><p>With over 15 years of experience now, I can confidently say that the community was likely more welcoming than I assumed. If I had taken the time to engage — join discussions, attend calls, or simply ask for help — I would have had a very different experience.</p><p>But at that stage in my career, I wasn’t ready. And that’s okay.</p><h3><strong>My Second Attempt (Success Story)</strong></h3><p>In 2023 — more than a decade after my first failed attempt — I found myself back in the open source world. This time, it wasn’t entirely by choice. I was assigned to work on an open source project that my company was supporting.</p><p>But something was different this time.</p><p>Instead of jumping straight into contributing code, I started by listening. I joined community calls regularly — even before the project had a name. At first, I was just there because it was part of my job. But soon, the idea of reshaping how cloud services could be used in the future started to fascinate me.</p><p>I began observing how the community worked. Who spoke? Who made decisions? What problems were being discussed?</p><p>One thing quickly stood out.</p><p>There were many subject matter experts — people with deep knowledge in areas like threat modelling and security controls. But there was a gap.</p><p>No one was actually doing the groundwork.</p><p>There were ideas, discussions, and expertise — but no clear structure, no roadmap, and no one driving things forward.</p><p>This time, instead of feeling overwhelmed by the ambiguity, I leaned into it.</p><p>I started small. Before each community call, I spent a few hours doing my own research. I didn’t fully understand threat modelling, but I tried to piece together what the project might need.</p><p>Then I shared my thoughts openly — with no expectation of being “right.”</p><p>To my surprise, the community responded very positively. People started reaching out, thanking me for driving the project forward and asking for my opinion. That was a turning point — I realized I had gone from being an outsider to someone whose contributions actually mattered.</p><p>What started as small contributions — notes, ideas, early drafts — began to shape the direction of the project, FINOS Common Cloud Controls. Slowly, we started building a framework together. Not because anyone had a perfect plan, but because we were making progress step by step.</p><p>After two months, I was moved off the project to focus on a client engagement. But by then, something had changed. I had built a connection with the project and the community. Out of curiosity — and a genuine sense of ownership — I requested to continue contributing in my own time as a representative of my company.</p><p>Over time, my role in the FINOS CCC evolved. People came and went. New contributors and organizations joined. But the vision remained the same: to shape how cloud services are used in financial institutions, with the right level of controls in place.</p><p>I went from being a contributor, to an active participant, then to a project maintainer, a working group lead, and eventually an ambassador — speaking about the project at FINOS conferences.</p><p>What started as an assignment became something much more meaningful.</p><h3><strong>Why the Second Attempt Worked</strong></h3><p>So why did this attempt succeed where the first one failed?</p><p>The biggest difference wasn’t the project — it was me.</p><p><strong>1. Comfort with uncertainty<br></strong>In 2011, ambiguity overwhelmed me. In 2023, I embraced it. With over a decade of experience, I had learned that not having all the answers is normal. I trusted myself to figure things out along the way.</p><p><strong>2. Focusing on contribution, not perfection<br></strong>Earlier, I hesitated because I didn’t want to be wrong. This time, I shared ideas freely — even when they were incomplete. That openness helped move the project forward.</p><p><strong>3. Active participation in the community<br></strong>I didn’t just show up to contribute code — I showed up to listen, learn, and engage. Attending calls regularly helped me understand the vision, the people, and the direction of the project. Nothing felt “over my head” anymore because I was part of the conversation.</p><p><strong>4. Leveraging what I already knew<br></strong>I wasn’t a security expert. I didn’t know much about threat modelling or writing controls. But I knew AWS. And I knew that if the project involved cloud systems, that knowledge would be useful. Instead of focusing on what I lacked, I contributed what I had.</p><p><strong>5. Growth beyond technical skills<br></strong>One of the biggest surprises was how much I learned outside of coding. I learned by listening to principals and CTOs handle tough questions. I learned how to communicate ideas clearly, how to ask for resources, and how to encourage collaboration.</p><p>I was pushed into areas I had never explored before — public speaking, facilitating meetings, and leading discussions.</p><p><strong>6. A sense of ownership<br></strong>Over time, the project stopped feeling like “just work.” It became something I cared deeply about. I wanted it to succeed — not because I had to, but because I was invested in it.</p><p>In the end, the relationship was mutual.</p><p>The project benefited from my contributions, and I grew immensely because of it. It was truly a win-win situation.</p><h3><strong>How to Find the Right Project</strong></h3><p>Finding the right open source project can make all the difference. As I learned from my own experience, it’s not just about picking a project — it’s about finding one that fits you.</p><p>Here’s a simple way to get started:</p><p><strong>1. Find a project you care about<br></strong>Start with something you already use or are curious about. It could be a library you rely on, a framework you want to learn, or even a tool you use daily. Interest makes a huge difference — it keeps you going when things get difficult.</p><p><strong>2. Engage with the community<br></strong>Before writing code, spend time understanding the project. Join community channels like Slack, Discord, forums, or mailing lists.</p><p>Choose these channels wisely — pick the ones that suit you and avoid overwhelming yourself with too much information at once.</p><p>Listen to discussions. Observe how people collaborate. This step is often overlooked, but it makes a big difference.</p><p><strong>3. Make your first contribution<br></strong>Look for issues labeled “good first issue” or “beginner-friendly.” These are intentionally designed to help new contributors get started.</p><p>Don’t aim for big changes early on — small, consistent contributions build confidence and momentum.</p><p>Your first contribution doesn’t have to be code. It could be improving documentation, fixing a typo, or asking a thoughtful question. The goal is to get comfortable with the process.</p><h3><strong>Setting the Correct Mindset</strong></h3><p>Finding the right project is only part of the journey. Just as important is having the right mindset when working in open source — because it can feel very different from a typical workplace environment.</p><p>Here are a few things to keep in mind:</p><ul><li><strong>Contributions are voluntary:<br></strong>People contribute on a best-effort basis. Everyone has different priorities, so responses and progress may take time.</li><li><strong>There is less structure:</strong> <br>Unlike your day job, there may not be clearly defined roles or responsibilities. This can feel uncomfortable at first — but it also creates opportunities to step up.</li><li><strong>Progress can be slow:<br></strong>Decisions take time, discussions evolve, and direction may change. Patience is key.</li><li><strong>You learn through feedback:<br></strong>Code reviews and discussions are one of the best ways to grow. Be open to feedback — it’s part of the process.</li><li><strong>Direction can change:<br></strong>Open source projects evolve based on community input. What you start may not always be what gets shipped — and that’s okay.</li><li><strong>Share your ideas openly:<br></strong>Don’t wait for perfection. Sharing early helps move the project forward and invites collaboration.</li><li><strong>Help create a welcoming environment:<br></strong>Open source thrives on community. The more welcoming and supportive you are, the better the experience becomes for everyone — including you.</li></ul><h3><strong>Myths About Open Source</strong></h3><p>Before concluding it’s important to talk about misconceptions about open source that stop people from even getting started. Let’s clear up a few of the most common ones:</p><p><strong>Myth 1: “I need to be an expert”<br>Reality: </strong>Everyone starts somewhere.<br>Most contributors you see today were once beginners trying to understand the same codebase. Open source is not about knowing everything — it’s about learning in public and improving over time.</p><p><strong>Myth 2: “I don’t have enough time”<br>Reality:</strong> Even a small amount of time is enough.<br>You don’t need to spend hours every day. Even one or two hours a week can make a meaningful contribution over time. Consistency matters more than intensity.</p><p><strong>Myth 3: “I need to write code to contribute”<br>Reality:</strong> Contributions go far beyond code.<br>Documentation, testing, reporting bugs, improving examples, or even helping others in discussions are all valuable contributions. In many projects, these are just as important as writing code.</p><p><strong>Myth 4: “Open source communities are unwelcoming”<br>Reality:</strong> Most communities are supportive and encouraging.<br>While every community is different, most open source projects genuinely want contributors to succeed. In my own experience, once I started engaging, I found people willing to guide, support, and collaborate.</p><p>Everyone’s journey is different, and so are the opportunities we come across. Sometimes, the right opportunities don’t present themselves — and in those moments, we have to create our own.</p><p>Open source is one of the most powerful ways to do that.</p><p>Think of it like walking into a shoe shop. Not every shoe will fit you. Some may look good but feel uncomfortable. Others may fit well but not excite you.</p><p>The key is to find the one that fits you — your interests, your skills, and your goals.</p><p>And just like any good pair of shoes, there’s a price. In this case, it’s your time and effort.</p><p>But when you find the right fit — something that matches both your interests and your commitment — the return is immense.</p><p>That’s when growth accelerates. That’s when you start enjoying the journey.</p><p>Choose the right open source project, and it won’t just be another activity — it can become a catalyst for your career and personal growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ddc0cdf5206" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into RabbitMQ with Spring Boot — Part 2: Retry & Parallel Processing]]></title>
            <link>https://medium.com/@sonali.mendis/deep-dive-into-rabbitmq-with-spring-boot-part-2-retry-parallel-processing-7edc64a64888?source=rss-faf00a669c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/7edc64a64888</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[retry]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Sonali Mendis]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 12:00:55 GMT</pubDate>
            <atom:updated>2023-04-25T17:33:04.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive into RabbitMQ with Spring Boot — Part 2: Retry &amp; Parallel Processing</h3><p>This is the final post of 2 part series on RabbitMQ with Spring Boot. In the previous post, I explained the spring version of RabbitMQ acknowledgement mode (<a href="https://medium.com/@sonali.mendis/deep-dive-into-rabbitmq-with-spring-boot-c8189d63f7b">Part 1</a>). In this post, I’m hoping to explain how to tweak your RabbitMQ configuration to alter the retry behavior, and how to add multiple consumers to allow parallel processing, in your Spring Boot application.</p><p>This article is not for you if you are only interested in getting a basic RabbitMQ publisher/consumer pattern to work in your Spring Boot application.</p><h3>Altering Retry Behavior</h3><p>In spring boot default configuration for RabbitMQ, if a consumer throws an exception while processing the message, it will republish the message to the queue over and over again forever. It looks as follows in the management console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIUh2c-ZJVlC7wfQYfUPGA.png" /></figure><p>This is not what we want in most of the cases. What we would generally expect is to retry only a predefined number of times to consume the message, if not publish it to the dead letter queue. It can be achieved fairly easily by adding the following configuration to your <em>application.yml </em>file<strong> if your message is just a simple String or is of a primitive data type</strong>. We will discuss later how to handle if your message is a complex object in this post.</p><pre>spring:<br>  rabbitmq:<br>    host: localhost<br>    port: 5672<br>    listener:<br>      simple:<br>        retry:<br>          enabled: true<br>          initial-interval: 3s<br>          max-attempts: 3<br>          max-interval: 10s<br>          multiplier: 2</pre><p>If an exception thrown while consuming the message, it will be republished to the queue only 2 more times (making it total 3 attempts) and then will be sent to the dead letter queue. 2nd attempt will be after 3 seconds from the 1st failed attempt, because the initial interval is set to 3. The 3rd attempt will be after 3 x 2 = 6 seconds, where 3 is the current wait and 2 is the multiplier. Then the message will be sent to the dead letter queue. If max-attempts count was 4 or more consequent attempts will occur 10 seconds apart as 6 x 2 = 12 is greater than 10 where 6 is the current wait, 2 is the multiplier but the resulting 12 is greater than the max interval defined as 10 seconds which will be the wait after the 3rd attempt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuZbCPpU33t1Wa47UsPP8w.png" /></figure><p>This will be shown in the management console as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6LookxQn6M4_rBpH02DeQ.png" /></figure><p>What if we don’t want to send the message to the dead letter queue after 3 attempts and wish to publish it to some other queue conditionally after 3 retries. To implement this, we need to set the retry configuration in code instead in the <em>application.yml</em> as shown below.</p><pre>spring:<br>  rabbitmq:<br>    host: localhost<br>    port: 5672<br>app:<br>  rabbitmq:<br>    direct-exchange: my.direct<br>    request-queue: my.direct.request<br>    response-queue: my.direct.response<br>    retry-attempts: 3<br>    backoff-interval: 1000<br>    backoff-multiplier: 2<br>    backoff-max-interval: 5000</pre><p>Let’s configure a simple rabbit listener in <em>RabbitMqConfig.java</em> file with retry interceptor as below. I have added a <em>Jackson2JsonMessageConverter</em> and configured it to be used in the rabbit listener because I’m expecting to receiving a complex message of type <em>MyMessage</em> from the queue.</p><pre>Jackson2JsonMessageConverter messageConverter(ObjectMapper mapper){<br>    var converter = new Jackson2JsonMessageConverter(mapper);<br>    converter.setCreateMessageIds(true); //create a unique message id for every message<br>    return converter;<br>}<br><br>@Bean<br>public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(<br>        ConnectionFactory connectionFactory,<br>        RetryOperationsInterceptor retryInterceptor,<br>        ObjectMapper objectMapper) {<br>    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();<br>    factory.setConnectionFactory(connectionFactory);<br>    factory.setMessageConverter(messageConverter(objectMapper));<br>    factory.setAdviceChain(retryInterceptor);<br>    return factory;<br>}<br><br>@Bean<br>public RetryOperationsInterceptor messageRetryInterceptor(){<br>    return RetryInterceptorBuilder.StatelessRetryInterceptorBuilder<br>            .stateless()<br>            .maxAttempts(properties.getRetryAttempts())<br>            .backOffOptions(<br>                    properties.getBackoffInterval(),<br>                    properties.getBackoffMultiplier(),<br>                    properties.getBackoffMaxInterval()<br>            )<br>            .recoverer(new RejectAndDontRequeueRecoverer())<br>            .build();<br>}</pre><p>Properties values will be read from <em>application.yml</em> with the prefix <em>app.rabbitmq</em>.</p><p>The message retry interceptor can be either stateful or stateless. See the spring boot documentation for retry (<a href="https://docs.spring.io/spring-batch/docs/1.0.x/spring-batch-docs/reference/html/ch06.html">here</a>) to determine whether you need a stateless or stateful interceptor. In short, if you have transactions or database updates that needs to be reverted back if the code fails, you will need a stateful retry interceptor to avoid data inconsistencies. If you were to use a stateful retry interceptor your <em>rabbitListenerContainerFactory</em> and <em>messageRetryInterceptor</em> methods will change as follows,</p><pre>@Bean<br>public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(<br>        ConnectionFactory connectionFactory,<br>        StatefulRetryOperationsInterceptor retryInterceptor,<br>        ObjectMapper objectMapper) {<br>    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();<br>    factory.setConnectionFactory(connectionFactory);<br>    factory.setMessageConverter(messageConverter(objectMapper));<br>    factory.setAdviceChain(retryInterceptor);<br>    return factory;<br>}<br><br>@Bean<br>public StatefulRetryOperationsInterceptor messageRetryInterceptor(){<br>    return RetryInterceptorBuilder.StatefulRetryInterceptorBuilder<br>            .stateful()<br>            .maxAttempts(properties.getRetryAttempts())<br>            .backOffOptions(<br>                    properties.getBackoffInterval(),<br>                    properties.getBackoffMultiplier(),<br>                    properties.getBackoffMaxInterval()<br>            )<br>            .recoverer(new RejectAndDontRequeueRecoverer())<br>            .build();<br>}</pre><p>In the retry interceptor we specify it needs to be retried 3 times max, set of backoff options namely, initial interval, multiplier and max interval. If exhausted with all retry attempts then the <em>recoverer</em> of the retry interceptor will be called. To this method we need to pass an implementation of a <em>MessageRecoverer</em> interface.</p><p><em>RejectAndDontRequeueRecoverer</em> class which implements the <em>MessageRecoverer</em> interface will send the message to the dead letter queue by throwing an <em>AmpqRejectAndDontRequeueException</em> in it’s <em>recover</em> method.</p><p><em>RepublishMessageRecoverer</em> class which implements the <em>MessageRecoverer</em> interface will publish the message to a given exchange.</p><p>To provide a custom implementation having both of these features conditionally, we will implement <em>ErrorMessageResolver</em> which implements the <em>MessageRecoverer</em> interface.</p><p>Update your <em>messageRetryInterceptor </em>method as follows to accept instance of <em>ErrorMessageResolver</em> class in <em>recoverer</em> as follows. Here I’m using a stateless retry interceptor but can be done with a stateful retry interceptor in the same manner. I’m adding a bean definition for rabbit template in the config as it will be needed in the <em>ErrorMessageResolver</em> class as we are dealing with complex messages.</p><pre>@Bean<br>public RetryOperationsInterceptor messageRetryInterceptor(<br>        MessageRecoverer messageRecoverer){<br>    return RetryInterceptorBuilder.StatelessRetryInterceptorBuilder<br>            .stateless()<br>            .maxAttempts(properties.getRetryAttempts())<br>            .backOffOptions(<br>                    properties.getBackoffInterval(),<br>                    properties.getBackoffMultiplier(),<br>                    properties.getBackoffMaxInterval()<br>            )<br>            .recoverer(messageRecoverer)<br>            .build();<br>}<br><br>@Bean<br>public MessageRecoverer messageRecoverer(RabbitTemplate template, AppProperties properties, ObjectMapper objectMapper){<br>    return new ErrorMessageResolver(<br>            template,<br>            properties,<br>            messageConverter(objectMapper)<br>    );<br>}<br><br>@Bean<br>public RabbitTemplate rabbitTemplate(ConnectionFactory factory, ObjectMapper objectMapper){<br>    RabbitTemplate template = new RabbitTemplate();<br>    template.setConnectionFactory(factory);<br>    template.setMessageConverter(messageConverter(objectMapper));<br>    return template;<br>}</pre><p>Our <em>ErrorMessageResolver</em> class will be implementing the recover method from the <em>MessageRecoverer</em> interface. It is important to note that every exception thrown by the listener method is wrapped by a <em>ListenerExecutionFailedException. </em>We have defined a custom exception as<em> FailedProcessException. </em>If the listener method throws an exception of type <em>FailedProcessException </em>it will publish the message to the response queue, and for all other types of exceptions it will publish the message to the dead letter queue.</p><pre>public class ErrorMessageResolver implements MessageRecoverer {<br>    private final RabbitTemplate template;<br>    private final AppProperties properties;<br>    private final Jackson2JsonMessageConverter converter;<br><br>    public ErrorMessageResolver(RabbitTemplate rabbitTemplate,<br>                                AppProperties properties,<br>                                Jackson2JsonMessageConverter converter) {<br>        this.template = rabbitTemplate;<br>        this.properties = properties;<br>        this.converter = converter;<br>    }<br><br>    @Override<br>    public void recover(Message message, Throwable cause){<br>        if(cause instanceof ListenerExecutionFailedException &amp;&amp;<br>                cause.getCause() instanceof FailedProcessException){<br>            try {<br>                //retrieve original message<br>                message.getMessageProperties().setInferredArgumentType(MyMessage.class);<br>                MyMessage originalRequest = (MyMessage) converter.fromMessage(message, MyMessage.class);<br><br>                FailedMessage failedMessage = new FailedMessage(<br>                        originalRequest.getMessageId(),<br>                        originalRequest.getMessage(),<br>                        cause.getCause().getMessage()<br>                );<br>                //send the message to response queue<br>                this.template.convertAndSend(<br>                        properties.getDirectExchange(),<br>                        properties.getResponseQueue(),<br>                        failedMessage<br>                );<br><br>            } catch (Exception ex){<br>                //send the message to dead letter queue<br>                throw new AmqpRejectAndDontRequeueException(&quot;Unable to recover message&quot;, ex);<br>            }<br>        } else {<br>            //send the message to dead letter queue<br>            throw new AmqpRejectAndDontRequeueException(&quot;Unable to recover message&quot;);<br>        }<br>    }<br>}</pre><p>Let’s try sending a message that throws a <em>FailedProcessException </em>when get executed by the listener method. This is what you will see in the management console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoowF9r-3z7-OGBW9ljsyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yeIlIIKxsgRFveMzdG-9Q.png" /></figure><p>Let’s empty the response queue for clarity and try sending a message that throws a exception of type <em>Exception </em>when get executed by the listener method. This is what you will see in the management console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dsn4e3FY58AX6z6GU41zUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8953nXr4K-mBp7T3WFCprQ.png" /></figure><p>This is what we wanted to achieve by altering the retry behavior with retry interceptors and message recoverers.</p><h3>Allow parallel consuming of messages</h3><p>You may be able to see that if you are using the default configuration for concurrent consumers you get only 1 consumer per queue with a message prefetch count of 250. This means that 1 consumer you have for the queue will fetch up to 250 messages at once and do sequential processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vefdQnXI57RkTu3yM-aog.png" /></figure><p>So if we send 2 messages both messages get delivered to the same consumer and while it process the first message the second message is stored on in memory of the consumer. This is not the desired behavior in general. We would like to have multiple consumers to handle messages and ideally will not want them to accept more than 1 message at once.</p><p>We can achieve this simply by configuring the <em>application.yml </em>given that you are not creating your own rabbit listener factory in the code.</p><pre>spring:<br>  rabbitmq:<br>    host: localhost<br>    port: 5672<br>    listener:<br>      simple:<br>        concurrency: 5<br>        max-concurrency: 10</pre><p>Your management console will now display 5 concurrent consumers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4koBHJzj40XoWBCjeH15g.png" /></figure><p>If you have defined your own rabbit listener factory in the configuration, your <em>application.yml</em> will be fairly simple as follows,</p><pre>spring:<br>  rabbitmq:<br>    host: localhost<br>    port: 5672</pre><p>But will require to add the related configuration inthe rabbit listener factory in <em>RabbitMqConfig.java</em> class.</p><pre>@Bean<br>public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(<br>        ConnectionFactory connectionFactory,<br>        RetryOperationsInterceptor retryInterceptor,<br>        ObjectMapper objectMapper) {<br>    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();<br>    factory.setConnectionFactory(connectionFactory);<br>    factory.setMessageConverter(messageConverter(objectMapper));<br>    factory.setPrefetchCount(0);<br>    factory.setConcurrentConsumers(properties.getConcurrentConsumers());<br>    factory.setMaxConcurrentConsumers(properties.getMaxConcurrentConsumers());<br>    return factory;<br>}</pre><p>Setting the prefetch count to zero will make sure the consumers will not accept more than 1 message at a time. Concurrent consumers will specify the number of consumers you will initially create and max concurrent consumers will set the maximum number of parallel consumers the system can initiate for you.</p><p>Please note that if you do not set the prefetch count to zero, even though you have specified multiple consumers, 1 consumer will greedily accept up to 251 messages at once and sequentially process them one after the other.</p><p>Complete code for RabbitMQ producer can be found <a href="https://github.com/smendis-scottlogic/rabbitmq-producer">here</a>.</p><p>Complete code for RabbitMQ consumer with retry and concurrency implementations can be found <a href="https://github.com/smendis-scottlogic/rabbitmq-advanced-consumer">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7edc64a64888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into RabbitMQ with Spring Boot]]></title>
            <link>https://medium.com/@sonali.mendis/deep-dive-into-rabbitmq-with-spring-boot-c8189d63f7b?source=rss-faf00a669c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8189d63f7b</guid>
            <category><![CDATA[acknowledgement]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Sonali Mendis]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 14:57:02 GMT</pubDate>
            <atom:updated>2023-04-25T12:01:44.358Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first of 2 part series of RabbitMQ with Spring Boot. In this post, I’m hoping to explain the spring version of RabbitMQ acknowledgement mode. Part 2 (<a href="https://medium.com/@sonali.mendis/deep-dive-into-rabbitmq-with-spring-boot-part-2-retry-parallel-processing-7edc64a64888">here</a>) will elaborate how to tweak your RabbitMQ configuration to alter the retry behavior, and how to add parallel consumers, in your Spring Boot Application.</p><p>This article is not for you if you are only interested in getting a basic RabbitMQ publisher/consumer pattern to work in your Spring Boot Application.</p><h3>Confusion between RabbitMQ Acknowledgement Mode and Spring Acknowledgement Mode</h3><p>In RabbitMQ there are 2 main types of message delivery acknowledgements.</p><ol><li>Auto Acknowledgement (Default) — deliveries require no acknowledgement, a.k.a. “fire and forget”. This will delete the message from the queue as soon as it has been written to the TCP socket of the consumer.</li><li>Manual Acknowledgement —deliveries require explicit consumer acknowledgements. This will ensure that no message is lost when a consumer crashes while processing the message or when it encounters an error which prevent it from processing the message completely.</li></ol><p>Let’s spin up a RabbitMQ docker container, a spring boot RabbitMQ producer rest API (<a href="https://github.com/smendis-scottlogic">code</a>) and a spring boot RabbitMQ consumer service (<a href="https://github.com/smendis-scottlogic/rabbitmq-basic-consumer">code</a>) to test this. Open up the management console on <a href="http://localhost:15672/">http://localhost:15672/</a> and send a POST message from Postman to the produce endpoint of the producer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cLCzRqs0Fa2ZQGAn1UV5g.png" /></figure><p>14:52:00 — Message is published to the queue. No consumers.<br>14:52:40 — Consumer comes online. Delivery acknowledgement received. Message is no longer eligible to consume as it is in Unacked state, but message is not deleted from the queue.<br>14:52:50 — Consumer acknowledgement received and message is removed from the queue.</p><p>This is exactly what is explained in the manual acknowledgement mode in the RabbitMQ documentation given above. And you can also see in the legend of the chart that it received a Delivery (manual ack) at 14:52:40</p><p><em>So… We must be using manual acknowledgement in spring boot application.</em></p><p>Let’s see the code on the consumer of our spring boot endpoint.</p><pre>@RabbitListener(<br>        queues = &quot;#{requestQueue.name}&quot;,<br>        containerFactory = &quot;rabbitListenerContainerFactory&quot;<br>)<br>public void receiveMessage(MyMessage message) throws Exception {<br>    Thread.sleep(5000);<br>    if(message.getMessageId() &gt; 5){<br>        throw new Exception(&quot;abc&quot;);<br>    } else if(message.getMessageId() == 3){<br>        Thread.sleep(5000);<br>        System.out.println(&quot;Listener method executed successfully&quot;);<br>    } else {<br>        System.out.println(&quot;Listner method executed successfully&quot;);<br>    }<br>}</pre><p>Where is the manual acknowledgment part. RabbitMQ documentation says the consumer should explicitly send the acknowledgements. Bit of googling tells me that if you are to implement manual acknowledgement your RabbitListener should look like this.</p><pre>@RabbitListener(<br>        queues = &quot;#{requestQueue.name}&quot;,<br>        containerFactory = &quot;rabbitListenerContainerFactory&quot;<br>)<br>public void receiveMessage(MyMessage message, Channel channel,<br>           @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {<br>    Thread.sleep(5000);<br>    if(message.getMessageId() &gt; 5){<br>        channel.basicNack(tag, false, true);<br>    } else if(message.getMessageId() == 3){<br>        Thread.sleep(5000);<br>        System.out.println(&quot;Listener method executed successfully&quot;);<br>        channel.basicAck(tag, false);<br>    } else {<br>        System.out.println(&quot;Listner method executed successfully&quot;);<br>        channel.basicAck(tag, false);<br>    }<br>}</pre><p>Yes! This looks like what RabbitMQ requires for manual acknowledgment.</p><p><em>So… We must me using auto acknowledgment in our spring boot application.</em></p><p>This is very confusing… Management console can’t be wrong, can it be?</p><p>According to the Spring AMQP documentation <a href="https://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp/core/AcknowledgeMode.html">here</a>, it has 3 acknowledgment modes instead of 2 provided by the RabbitMQ.</p><p><strong>AUTO — </strong>(Default) the container will issue the ack/nack based on whether the listener returns normally, or throws an exception.<br><strong>MANUAL</strong> — user must ack/nack via a channel aware listener.<br><strong>NONE — </strong>No acks. autoAck=true in Channel.basicConsume().</p><p>And most importantly under AUTO it says,</p><blockquote>Do not confuse with RabbitMQ autoAck which is represented by NONE here.</blockquote><p>The confusion lies here. Spring has used the word AUTO but underneath uses the RabbitMQ Manual acknowledgments. If the listener executes without any exception it will send back <em>basicAck</em> for us, or else will send a <em>basicNack</em>. If using Spring’s MANUAL the container does not handle anything for us. We need to send <em>basicAck</em> or <em>basicNack</em> as needed. If using Spring’s NONE then the RabbitMQ’s Auto acknowledgment is implemented in spring.</p><p>Let’s implement these 3 acknowledgment modes and test the behavior on RabbitMQ management console.</p><h4>Implementing Spring’s AUTO Acknowledgment Mode</h4><p>This is the default behavior. But you can explicitly set it at the <em>SimpleRabbitListenerContainerFactory</em>. See the <em>RabbitMQConfig.java</em> class in the <strong>rabbitmq-basic-consumer</strong> repo.</p><pre>@Bean<br>public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(<br>        ConnectionFactory connectionFactory,<br>        StatefulRetryOperationsInterceptor retryInterceptor,<br>        ObjectMapper objectMapper) {<br>    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();<br>    factory.setConnectionFactory(connectionFactory);<br>    factory.setMessageConverter(messageConverter(objectMapper));<br>    factory.setAcknowledgeMode(AcknowledgeMode.AUTO);<br>    return factory;<br>}</pre><p>And the RabbitListener looks like follows in <em>MessageReceiver.java</em> class in the <strong>rabbitmq-basic-consumer </strong>repo.</p><pre>@RabbitListener(<br>        queues = &quot;#{requestQueue.name}&quot;,<br>        containerFactory = &quot;rabbitListenerContainerFactory&quot;<br>)<br>public void receiveMessage(MyMessage message) throws Exception {<br>    Thread.sleep(5000);<br>    if(message.getMessageId() &gt; 5){<br>        throw new Exception(&quot;abc&quot;);<br>    } else if(message.getMessageId() == 3){<br>        Thread.sleep(5000);<br>        System.out.println(&quot;Listener method executed successfully&quot;);<br>    } else {<br>        System.out.println(&quot;Listner method executed successfully&quot;);<br>    }<br>}</pre><p>Management console looks as same as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cLCzRqs0Fa2ZQGAn1UV5g.png" /></figure><h4>Implementing Spring’s Manual Acknowledgment Mode</h4><p>You can set this at the <em>SimpleRabbitListenerContainerFactory </em>just like before. See the <em>RabbitMQConfig.java</em> class in the <strong>rabbitmq-basic-consumer</strong> repo.</p><pre>@Bean<br>public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(<br>        ConnectionFactory connectionFactory,<br>        StatefulRetryOperationsInterceptor retryInterceptor,<br>        ObjectMapper objectMapper) {<br>    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();<br>    factory.setConnectionFactory(connectionFactory);<br>    factory.setMessageConverter(messageConverter(objectMapper));<br>    factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);<br>    return factory;<br>}</pre><p>And the RabbitListener looks like follows in <em>MessageReceiver.java</em> class in the <strong>rabbitmq-basic-consumer </strong>repo.</p><pre>@RabbitListener(<br>        queues = &quot;#{requestQueue.name}&quot;,<br>        containerFactory = &quot;rabbitListenerContainerFactory&quot;<br>)<br>public void receiveMessage(MyMessage message, Channel channel,<br>           @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {<br>    Thread.sleep(5000);<br>    if(message.getMessageId() &gt; 5){<br>        channel.basicNack(tag, false, true);<br>    } else if(message.getMessageId() == 3){<br>        Thread.sleep(5000);<br>        System.out.println(&quot;Listener method executed successfully&quot;);<br>        channel.basicAck(tag, false);<br>    } else {<br>        System.out.println(&quot;Listner method executed successfully&quot;);<br>        channel.basicAck(tag, false);<br>    }<br>}</pre><p>Management console looks as same as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cLCzRqs0Fa2ZQGAn1UV5g.png" /></figure><h4>Implementing Spring’s NONE Acknowledgment Mode</h4><p>You can set this at the <em>SimpleRabbitListenerContainerFactory </em>just like before. See the <em>RabbitMQConfig.java</em> class in the <strong>rabbitmq-basic-consumer</strong> repo.</p><pre>@Bean<br>public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(<br>        ConnectionFactory connectionFactory,<br>        StatefulRetryOperationsInterceptor retryInterceptor,<br>        ObjectMapper objectMapper) {<br>    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();<br>    factory.setConnectionFactory(connectionFactory);<br>    factory.setMessageConverter(messageConverter(objectMapper));<br>    factory.setAcknowledgeMode(AcknowledgeMode.NONE);<br>    return factory;<br>}</pre><p>And the RabbitListener looks like follows in <em>MessageReceiver.java</em> class in the <strong>rabbitmq-basic-consumer </strong>repo.</p><pre>@RabbitListener(<br>        queues = &quot;#{requestQueue.name}&quot;,<br>        containerFactory = &quot;rabbitListenerContainerFactory&quot;<br>)<br>public void receiveMessage(MyMessage message) throws Exception {<br>    Thread.sleep(5000);<br>    if(message.getMessageId() &gt; 5){<br>        throw new Exception(&quot;abc&quot;)<br>    } else if(message.getMessageId() == 3){<br>        Thread.sleep(5000);<br>        System.out.println(&quot;Listener method executed successfully&quot;);<br>    } else {<br>        System.out.println(&quot;Listner method executed successfully&quot;);<br>    }<br>}</pre><p>Management console looks different now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-Wg7vP1HmFT36edEtDXVQ.png" /></figure><p>15:46:20 — Message published to the exchange. No consumers<br>15:47:00- A Consumer comes online and consume the message. Message get immediately removed from the queue.</p><h4>Summary</h4><p>Even though the names misleads you, Spring boot by default use RabbitMQ’s Manual Acknowledgment Mode and in addition will send the acknowledgment on behalf of you from the container, base on whether the listener method executed successfully without throwing any Exceptions. This will ensure no message is lost if the consumer crashers or unable to complete the execution of the message.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8189d63f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>