<?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 Anh Em Đinh Đức on Medium]]></title>
        <description><![CDATA[Stories by Anh Em Đinh Đức on Medium]]></description>
        <link>https://medium.com/@ace53thntu?source=rss-13f2e4c0bf84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UiE47s1QZKB4GH-d9X7KNQ.jpeg</url>
            <title>Stories by Anh Em Đinh Đức on Medium</title>
            <link>https://medium.com/@ace53thntu?source=rss-13f2e4c0bf84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:29:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ace53thntu/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[Speed Up KafkaJS with BullMQ: Mastering Slow Task Offloading for High-Throughput Systems (Part 1)]]></title>
            <link>https://medium.com/@ace53thntu/speed-up-kafkajs-with-bullmq-mastering-slow-task-offloading-for-high-throughput-systems-part-1-0e5ae2c14205?source=rss-13f2e4c0bf84------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e5ae2c14205</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[bullmq]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Anh Em Đinh Đức]]></dc:creator>
            <pubDate>Mon, 12 May 2025 12:42:47 GMT</pubDate>
            <atom:updated>2025-05-13T04:54:56.134Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to integrate BullMQ with KafkaJS to handle slow processing tasks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPwP_x-AqHzZFRJ8CVpunA.png" /><figcaption>Speed Up KafkaJS with BullMQ</figcaption></figure><h3>Introduction</h3><p>Picture this: you’re building a high-throughput system with <strong>KafkaJS</strong>, processing thousands of messages per second to power a real-time platform. Everything runs smoothly until a slow database query or external API call sneaks into your Kafka consumer’s eachMessage handler. Suddenly, your consumer lags, messages pile up, and Kafka triggers a rebalance, disrupting your entire system. This is exactly what I faced while working on <strong>YaraConnect</strong>, a retailer-support platform where we handled thousands of daily transactions across 9 countries to connect farmers and retailers.</p><p><strong>KafkaJS</strong> is a modern JavaScript library for interacting with Apache Kafka, a distributed streaming platform designed for high-throughput, fault-tolerant messaging. But when slow tasks bog down your consumer, even Kafka’s robustness can’t save you from latency and rebalancing chaos. That’s where <strong>BullMQ</strong>, a powerful Node.js queue library backed by Redis, comes in. BullMQ allows you to offload heavy tasks to a queue, letting your Kafka consumer focus on fetching messages while workers handle the heavy lifting.</p><p>In this two-part series, I’ll share how I tackled slow message processing at YaraConnect by integrating <strong>KafkaJS</strong> with <strong>BullMQ</strong> in a <strong>NestJS</strong> app.</p><ul><li>Part 1 explains the problem of slow tasks, introduces BullMQ as a solution.</li><li>Part 2 dives into the code, including setup and error handling.</li></ul><p>Whether you’re new to Kafka or a seasoned developer, you’ll learn practical techniques to build faster, more reliable message-processing systems. Let’s get started! 🚀</p><h3>The Problem: Slow Message Processing in KafkaJS</h3><p>To grasp why slow tasks wreak havoc, let’s break down how KafkaJS and Kafka work. <strong>KafkaJS</strong> is a JavaScript client for Apache Kafka, enabling Node.js apps to produce and consume messages from Kafka topics. A Kafka topic is divided into <strong>partitions</strong>, each holding an ordered sequence of messages (e.g., offset 0, 1, 2). Consumers in a <strong>consumer group</strong> subscribe to topics, with each consumer handling one or more partitions. Kafka ensures messages within a partition are processed in order, making it ideal for use cases like transaction processing.</p><p>In KafkaJS, you define a consumer with the eachMessage handler to process messages:</p><pre>await consumer.run({<br>  eachMessage: async ({ topic, partition, message }) =&gt; {<br>    console.log(`Processing message: ${message.value.toString()}`);<br>    await processRetailerTransaction(message.value.toString()); // Slow task<br>  },<br>});</pre><p>This works great — until processRetailerTransaction takes too long. At YaraConnect, we had a task that queried a PostgresDB, calling Loyalty Core to evaluate the rules (I&#39;ll talk about this in a future article), and then called an external API to get Product information, to get Coupon,..., and all of them take time to perform. With thousands of messages flooding in, our consumer couldn&#39;t keep up. Here&#39;s why this is a problem:</p><ul><li><strong>Consumer Timeout</strong>: Kafka expects consumers to send heartbeats to confirm they&#39;re alive. If a task takes too long, the consumer misses heartbeats, and Kafka assumes it&#39;s dead, triggering a <strong>rebalance</strong>—reassigning messages to other consumers. This can cause delays or even lost messages. (Refer this <a href="https://kafka.js.org/docs/2.0.0/consuming#a-name-each-message-a-eachmessage">doc</a>)</li><li><strong>Backlog Buildup</strong>: Slow processing creates a backlog, increasing latency and potentially overwhelming your system.</li><li><strong>Order Risks</strong>: Kafka guarantees message order within a partition (e.g., offset 1 processed before offset 2). A bogged-down consumer might tempt you to scale with multiple consumers, which can disrupt this order if not handled carefully.</li></ul><p>In short, a single slow task in eachMessage can grind your system to a halt. I tried quick fixes like sending heartbeats early or increasing timeouts, but they were merely temporary solutions. Let me show you the pros and cons of the solutions I tried, and we will see which one is the better solution.</p><h3>Approach 1: Sending Heartbeats Early</h3><p>To send heartbeats early, we can do something like this:</p><pre>await consumer.run({<br>  autoCommit: false,<br>  eachMessage: async ({ topic, partition, message, heartbeat }) =&gt; {<br>    console.log(`Processing offset ${message.offset}`);<br>    await heartbeat(); // Sending heartbeat early to avoid rebalance<br>    await processRetailerTransaction(); // Slow task<br>    await consumer.commitOffsets([{ topic, partition, offset: (Number(message.offset) + 1).toString() }]);<br>  },<br>});</pre><p>This approach use eachMessage with autoCommit: false, send a heartbeat before processing the message, and commit the offset after the slow task is done.</p><p><strong>Pros</strong>:</p><ol><li><strong>Precise control of commit offsets</strong>: With autoCommit: false, we can control when to commit the offset. This ensures the message is marked as &quot;processed&quot; when processRetailerTransaction is done. It reduces the lost messages problem if the consumer crashes.</li><li><strong>Avoid rebalance</strong>: With heartbeat(), we tell the Kafka coordinator that the consumer is alive even processRetailerTransaction takes too long.</li><li><strong>Simple</strong>: This is the simplest approach, we don’t need to write any additional code.</li></ol><p><strong>Cons</strong>:</p><ol><li><strong>The risk of rebalance still exists</strong>: Although sending heartbeat() early reduces the risk of rebalance, if someLongRunningTask takes longer than sessionTimeout, Kafka may still consider the consumer dead and trigger a rebalance.</li></ol><p>To fix the above cons, I have tried the 2nd approach below.</p><h3>Approach 2: Combine approach 1 with increased sessionTimeout</h3><pre>await consumer.run({<br>  autoCommit: false,<br>  sessionTimeout: 60000, // 1 minutes<br>  eachMessage: async ({ topic, partition, message, heartbeat }) =&gt; {<br>    console.log(`Processing offset ${message.offset}`);<br>    await heartbeat(); // Sending heartbeat early to avoid rebalance<br>    await processRetailerTransaction(); // Slow task<br>    await consumer.commitOffsets([{ topic, partition, offset: (Number(message.offset) + 1).toString() }]);<br>  },<br>});</pre><p>This approach can resolve the cons of the first approach, but it has a few drawbacks:</p><ol><li><strong>Increased latency</strong>: Since processRetailerTransaction takes longer (it can be more &gt; 1 minute), the consumer will wait for the task to finish before processing the next message. This increases the latency and can cause delays.</li><li><strong>Potential error in </strong><strong>someLongRunningTask</strong>: If someLongRunningTask throws an exception and is not handled properly (e.g. missing try-catch), the consumer may crash or skip the message without committing the offset. This results in the message being stuck (not processed again unless the consumer is restarted).</li></ol><p>These approaches were like putting a Band-Aid on a broken leg — functional but far from ideal. I needed a solution that was robust, scalable, and didn’t choke on slow tasks.</p><h3>Approach 3: Offloading Heavy Tasks with BullMQ and Redis</h3><p>After countless hours of scouring docs, chugging coffee, and muttering “there’s gotta be a better way,”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2VX_GNkwv6l_XWdV2lSzw.png" /><figcaption>Lightbulb representing the idea of offloading tasks</figcaption></figure><p>I struck gold with Approach 3 — offloading heavy tasks to a separate queue using BullMQ and Redis. Picture this as handing off your dirty laundry to a super-efficient dry cleaner while you focus on looking fabulous. BullMQ, a Node.js queue library backed by Redis, lets you push slow tasks to a queue and process them with dedicated workers, freeing your Kafka consumer to zip through messages like a caffeinated cheetah. 😎</p><p>Here’s the gist: instead of processing processRetailerTransaction in the eachMessage handler, the consumer pushes the task to a <strong>BullMQ</strong> queue. A separate worker (or workers) then picks up the task, queries the database, hits the API, and does all the heavy lifting without slowing down the consumer. This approach keeps the consumer lean and mean, fetching messages at full speed while <strong>BullMQ</strong> handles the grunt work.</p><p>Example code:</p><pre>await this.consumer.run({<br>  autoCommit: true, // Auto-commit offsets after pushing to BullMQ<br>  eachMessage: async ({ topic, partition, message }) =&gt; {<br>    this.logger.log(`Received message: Partition ${partition}, Offset ${message.offset}`);<br>    <br>    const jobData = {<br>      value: message.value.toString(),<br>      topic,<br>      partition,<br>      offset: message.offset,<br>    };<br><br>    /**<br>    * Push to the appropriate BullMQ queue, this `await` is very fast<br>    * So, it will not block the consumer<br>    */<br>    await queue.add(&#39;process-transaction&#39;, jobData, {<br>      attempts: 3, // Retry up to 3 times on failure<br>      backoff: { type: &#39;exponential&#39;, delay: 1000 },<br>    });<br><br>    this.logger.log(`Pushed to BullMQ queue`);<br>  },<br>});</pre><p><strong>How It Works</strong>:</p><ul><li>The KafkaJS consumer grabs a message and pushes it to a BullMQ queue with metadata (e.g., topic, partition, offset).</li><li>A BullMQ worker processes the task asynchronously, storing results in PostgresDB or triggering further actions.</li></ul><p><strong>Pros</strong>:</p><ul><li><strong>Lightning-fast consumer</strong>: Offloading tasks keeps the consumer focused on fetching messages, preventing timeouts and rebalances.</li><li><strong>Scalability</strong>: Multiple queues and workers can handle tasks in parallel across partitions, leveraging Kafka’s parallelism.</li><li><strong>Robustness</strong>: BullMQ supports retries, error handling, and job monitoring, making it ideal for unreliable APIs or flaky databases</li></ul><p><strong>Cons</strong>:</p><ul><li><strong>Complexity</strong>: Managing multiple queues and Redis adds infrastructure overhead</li><li><strong>Redis dependency</strong>: We need a Redis instance, which might be new for some teammates</li></ul><p><strong>Why It Rocks</strong>: At YaraConnect, we already had Redis running in our cluster. So we don’t need to worry about the infrastructure overhead. And this approach worked like a charm, resolve the rebalance issue. Plus, BullMQ’s retry mechanism saved us from flaky API calls — talk about a win! 🎉. Apart from that, with BullMQ Dashboard we can monitor the queues and workers as well.</p><p>Here’s a sneak peek at the data flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poIPl9YNOSnqG99nAtNWLw.png" /><figcaption>Kafka and BullMQ</figcaption></figure><p>Now, it’s time to take a break. In Part 2, we’ll dive into the NestJS code to set up KafkaJS, BullMQ, and Redis, plus tips for error handling and scaling. Stay tuned!</p><p><strong>Disclaimer</strong>: I’m no Kafka guru — just a developer who wrestled with slow tasks and lived to tell the tale! 😄 This is my journey of solving a real-world problem at YaraConnect, and I’d love to hear your thoughts, tips, or alternative approaches. Drop your feedback or questions in the comments, and let’s learn together!</p><p>This article is from my blog post: <a href="https://emdinh.dev/blog/speed-up-kafkajs-bullmq-part-1">https://emdinh.dev/blog/speed-up-kafkajs-bullmq-part-1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e5ae2c14205" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>