<?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 Atharva on Medium]]></title>
        <description><![CDATA[Stories by Atharva on Medium]]></description>
        <link>https://medium.com/@tribhuwane.a?source=rss-734a5a339426------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Atharva on Medium</title>
            <link>https://medium.com/@tribhuwane.a?source=rss-734a5a339426------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:32:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tribhuwane.a/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[Your API Is Doing Too Much. Move The Work to a Queue]]></title>
            <link>https://medium.com/@tribhuwane.a/your-api-is-doing-too-much-move-the-work-to-a-queue-149e25cb8e91?source=rss-734a5a339426------2</link>
            <guid isPermaLink="false">https://medium.com/p/149e25cb8e91</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Atharva]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 18:34:54 GMT</pubDate>
            <atom:updated>2026-10-21T18:34:54.870Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How background jobs work, when to use them, and what you need to know before putting them into production.</em></p><p>Imagine a user clicks Submit in your application. your server saves the data, sends an email, generates a PDF, calls an external API, and finally returns a response.<br>Evrything works until one of those external services becomes slow. An API that usually responds in 200 ms now takes four seconds. If a service goes down entirely, the request might fail even though the data was already saved.</p><blockquote>Sounds scary? Now imagine that happening during a Friday evening deployment. Because production apparently has a calendar, and it knows exactly when you’re about to log off. 🙃</blockquote><p>The obvious reaction is to optimize the code. But, sometimes the problem isn’t how fast your code executes. It’s how much work you’ve decided to do before returning response.</p><p>This is where background jobs become useful.</p><p><strong>The problem with doing everything inside an API request</strong></p><p>Consider a simple order-processing endpoint:</p><pre>app.post(&quot;/orders&quot;, async (req, res) =&gt; {<br>   const order = await createOrder(req.body);<br><br>   await sendConfirmationEmail(order);<br>   await generateInvoice(order);<br>   await syncWithExternalService(order);<br><br>   res.status(201).json({ order });<br> });</pre><p>There’s nothing inherently wrong with this code if every operation genuinely needs to finish before the request can succeed. But does generating an invoice need to block the user’s request?<br>Does an email have to be delivered before the application can confirm that an order was created?</p><p>Often, the answer is no. Each additional network call adds another dependency, and your response time is now tied to services with their own performance characteristics and failure modes.</p><p>And if the user retries because the response took too long, you can end up with a second problem: duplicate orders. A faster response makes retries less likely, though preventing duplicates entirely takes an idempotency key on the endpoint. Either way, we can do better by separating the work.</p><p><strong>What if the API didn’t have to do everything?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LQP9fhc_S9VMnSqg8yqvA.png" /><figcaption><em>A simplified background-job flow.</em></figcaption></figure><p>Instead of executing every operation immediately, we can move some work into a background-processing system. The API does only the essential work: it saves the order and submits a job to a queue. A separate worker picks up that job and processes it.</p><p>The API can respond after the order has been saved and the job has been accepted by the queue. The background work may still be running when the user receives the response. That’s intentional.</p><p>A queue doesn’t automatically make your application faster. It moves work out of the request path, which can improve response times and allow independent scaling. The total amount of work still has to be performed.</p><p><strong>Let’s build a simple example with Node.js and BullMQ</strong></p><p>BullMQ is a Node.js job queue library. It uses Redis as the backing store to coordinate jobs and workers.</p><p>Install the dependencies:</p><pre>npm install bullmq ioredis</pre><p><strong>Step 1: Create a queue</strong></p><p>Create a file called queue.js:</p><pre>const { Queue } = require(&quot;bullmq&quot;); <br>const IORedis = require(&quot;ioredis&quot;);  <br><br>const connection = new IORedis({   <br>  host: &quot;127.0.0.1&quot;,   <br>  port: 6379,   <br>  maxRetriesPerRequest: null, <br>});  <br><br>const emailQueue = new Queue(&quot;email-jobs&quot;, {<br>   connection,<br>});  <br><br>module.exports = { emailQueue, connection };</pre><p>We’ve created a queue named email-jobs. Think of it as a place where the application can submit work without needing to execute that work immediately.</p><p>BullMQ workers need `maxRetriesPerRequest: null` on their Redis connection. For simplicity, this example uses the same connection settings for the queue and the worker, but that has a cost on the API side: if Redis goes down, emailQueue.add() waits indefinitely instead of failing, and so does the request that called it. In production, give the producer its own connection with enableOfflineQueue: false so it fails fast. See the BullMQ docs on connections and on failing fast when Redis is down.</p><p><strong>Step 2: Add a job</strong></p><p>Next, create jobs.js to submit an email job:</p><pre>const { emailQueue } = require(&quot;./queue&quot;);<br><br>async function queueConfirmationEmail(order) {<br>  await emailQueue.add(&quot;send-confirmation&quot;, {<br>    orderId: order.id,<br>    email: order.email,<br>  });<br>}<br><br>module.exports = { queueConfirmationEmail };<br>const { emailQueue } = require(&quot;./queue&quot;);<br><br>async function queueConfirmationEmail(order) {<br>  await emailQueue.add(&quot;send-confirmation&quot;, {<br>    orderId: order.id,<br>    email: order.email,<br>  });<br>}<br><br>module.exports = { queueConfirmationEmail };</pre><p>Job data is serialized to JSON and stored in Redis, so we pass only the information the worker needs, not a live JavaScript object containing database connections or application services. In a real application, keep job payloads small and avoid including secrets or unnecessary personal information.</p><p>Back in the order endpoint, the email call becomes a queue call:</p><pre>app.post(&quot;/orders&quot;, async (req, res) =&gt; {<br>  const order = await createOrder(req.body);<br>  await queueConfirmationEmail(order);<br>  res.status(201).json({ order });<br>});</pre><p><strong>Step 3: Create a worker</strong></p><p>Create worker.js:</p><pre>const { Worker } = require(&quot;bullmq&quot;);<br>const { connection } = require(&quot;./queue&quot;);<br><br>async function sendConfirmationEmail({ orderId, email }) {<br>  // Replace this with your email provider integration.<br>  console.log(`Sending email to ${email} for order ${orderId}`);<br>}<br><br>const worker = new Worker(<br>  &quot;email-jobs&quot;,<br>  async (job) =&gt; {<br>    if (job.name !== &quot;send-confirmation&quot;) {<br>      throw new Error(`Unsupported job: ${job.name}`);<br>    }<br><br>    await sendConfirmationEmail(job.data);<br>  },<br>  { connection, concurrency: 5 },<br>);<br><br>worker.on(&quot;completed&quot;, (job) =&gt; {<br>  console.log(`Job ${job.id} completed`);<br>});<br><br>worker.on(&quot;failed&quot;, (job, error) =&gt; {<br>  console.error(`Job ${job?.id} failed:`, error.message);<br>});<br><br>worker.on(&quot;error&quot;, (error) =&gt; {<br>  console.error(&quot;Worker error:&quot;, error);<br>});</pre><p>Run the worker in a separate terminal with node worker.js. Whenever the application adds a job to email-jobs, a running worker can pick it up.</p><p>The concurrency: 5 option lets this worker process up to five jobs at the same time. That can be useful for I/O-bound work, such as calling an email API. CPU-intensive jobs need a different approach because they can block Node.js’s event loop; BullMQ’s sandboxed processors are one option.</p><p>See the official BullMQ <a href="https://docs.bullmq.io/guide/workers/concurrency">worker concurrency guide</a>.</p><p><strong>What happens when a job fails?<br></strong>Suppose your email provider becomes temporarily unavailable. By default, BullMQ tries a job only once, so a failed job stays in the failed state until someone or something retries it.</p><p>BullMQ supports retry attempts and backoff strategies. For example:</p><pre>await emailQueue.add(<br>  &quot;send-confirmation&quot;,<br>  { orderId: order.id, email: order.email },<br>  { attempts: 5, backoff: { type: &quot;exponential&quot;, delay: 1000 } },<br>);</pre><p>This configures up to five attempts, with the delay doubling between retries: 1s, 2s, 4s, then 8s. But should every failure be retried? A temporary network timeout might be worth retrying. An invalid email address probably isn’t. For that case, throw BullMQ’s UnrecoverableError from the worker: the job fails immediately instead of using up its remaining attempts.</p><p>Retries are useful only when they’re designed around the failure being handled. Blindly retrying every error can waste resources or make a bad situation worse.</p><p>Read more in BullMQ’s guide to <a href="https://docs.bullmq.io/guide/retrying-failing-jobs">retrying failing jobs</a>.</p><p><strong>The part most of us skip: duplicate execution</strong></p><p>A job queue doesn’t guarantee that a task runs exactly once. Imagine your worker sends an email successfully, then crashes before the job is recorded as completed. When the job’s lock expires, BullMQ treats it as stalled and processes it again, so the email goes out twice. In other words, delivery is at-least-once, not exactly-once.</p><p>This is why reliable background processing requires thinking about idempotency: designing an operation so repeating it doesn’t produce unintended additional effects.</p><p>The solution depends on the task. It might involve a provider-supported idempotency key, a database record tracking the operation, or a business workflow that can safely resume after a failure.</p><p>A queue gives you tools for managing work. It doesn’t remove the need to design the work itself safely.</p><p><strong>There’s another failure worth considering</strong></p><p>Suppose your API saves an order successfully, but Redis becomes unavailable before the job is added. Your database contains the order, but no email job was queued.</p><p>This is a consistency problem between two systems. For a simple application, you might catch the error, flag the order, and have a periodic task re-queue anything that was missed. For a workflow where losing the event is unacceptable, investigate the transactional outbox pattern.</p><p>With an outbox, the business change and a record describing the work are saved in the same database transaction. A separate process then publishes the recorded work to the queue.</p><p>This is more involved, but it addresses a failure mode that a basic queue implementation doesn’t solve by itself.</p><p><strong>When should you use a background queue?<br></strong>Consider a queue for sending emails and notifications, generating reports and exports, processing uploaded files, synchronizing data with external APIs, handling webhook deliveries, or running scheduled tasks.</p><p>A queue isn’t automatically the right choice for every slow operation. If the user needs a result before continuing, the operation may belong in the request path. If the workload is small and reliable enough, adding a queue may introduce more operational complexity than it removes.</p><p>The decision should come from the requirements, not from a desire to use another technology.</p><blockquote>Personally, the first time I used it was for a <strong>bi-directional synchronization system</strong> that involved exchanging a tremendous amount of data between the client and server, along with several operations that needed to be performed before ingesting the data into the database.</blockquote><blockquote>My approach was fairly straightforward: I split the process into two separate stages.</blockquote><blockquote>The first stage was responsible for validating incoming requests and minimizing the risk of failures caused by invalid client data. This helped reduce the chances of data-related failures by approximately 95%.</blockquote><blockquote>The second stage handled the heavier processing required before database ingestion, keeping the validation process separate from the more resource-intensive operations.</blockquote><blockquote>This separation made the overall workflow more structured and helped prevent invalid data from reaching the expensive processing stage.</blockquote><p><strong>Before putting it into production</strong></p><p>A working local example is only the beginning. When you deploy a queue-based system, think about:</p><ul><li><strong>Monitoring:</strong> Are jobs failing or accumulating faster than workers can process them?</li><li><strong>Retries:</strong> Which errors are temporary, and which should not be retried?</li><li><strong>Idempotency:</strong> What happens if a job runs again?</li><li><strong>Redis availability:</strong> What happens when the queue backend is temporarily unreachable?</li><li><strong>Redis configuration:</strong> Is persistence (AOF) enabled, and is <strong><em>maxmemory-policy</em></strong> set to noeviction? BullMQ can’t work correctly if Redis evicts its keys.</li><li><strong>Shutdown:</strong> Can workers finish or safely recover their active jobs during a deployment?</li><li><strong>Recovery:</strong> Can you inspect failed jobs and safely retry them?</li></ul><p>BullMQ provides worker.close() for graceful shutdown and stalled-job detection for recovery, but your application still needs an operational strategy. Read the <a href="https://docs.bullmq.io/guide/going-to-production">production guide</a>.</p><p><strong>Final words</strong></p><p>Background jobs aren’t just about making APIs faster. They’re about separating responsibilities, controlling how work is processed, and deciding what should happen when something fails.</p><p>The next time you find yourself adding another external API call to a request handler, pause for a moment and ask: Does this work need to finish before the user can receive a meaningful response?</p><p>If it doesn’t, a background job may be worth considering. And if you introduce one, don’t stop when the happy path works. Think about duplicate execution, failed jobs, recovery, and what happens when the queue itself becomes unavailable.</p><p>That’s where the real engineering begins. Cheers! 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=149e25cb8e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>