<?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"><channel><title><![CDATA[Week 11: Building Resilient Webhooks - Exponential Backoff and the Art of Retry Logic]]></title><description><![CDATA[Week 11: Building Resilient Webhooks - Exponential Backoff and the Art of Retry Logic]]></description><link>https://week-11.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 29 Nov 2026 20:21:22 GMT</lastBuildDate><atom:link href="https://week-11.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building Resilient Webhooks: Exponential Backoff and the Art of Retry Logic]]></title><description><![CDATA[Sim-Pesa Build Log — Week 11 of 16 Welcome to another build log of Sim-Pesa. If you're new here, Sim-Pesa is a project I'm building to level up my backend…]]></description><link>https://week-11.hashnode.dev/building-resilient-webhooks-exponential-backoff-and-the-art-of-retry-logic</link><guid isPermaLink="true">https://week-11.hashnode.dev/building-resilient-webhooks-exponential-backoff-and-the-art-of-retry-logic</guid><dc:creator><![CDATA[Paul Murithi Kirera]]></dc:creator><pubDate>Thu, 02 Apr 2026 14:49:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/68f319caa305480f4cebccb8/45c2c718-5cf8-4285-8eb1-1297ddb7d7f0.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Sim-Pesa Build Log — Week 11 of 16</em></p>
<hr />
<p>Welcome to another build log of Sim-Pesa. If you're new here, <strong>Sim-Pesa</strong> is a project I'm building to level up my backend development skills. It's a transactional state appliance that runs locally and enables developers to test their M-Pesa integration logic even offline, complementing the Daraja sandbox.I've been writing weekly breakdowns, so be sure to check out other weeks before diving into this one.</p>
<p>Last week, I worked on the <strong>Webhook Dispatcher</strong> logic. A webhook dispatcher is a reliable delivery system that sends event notifications to a merchant-provided URL when a transaction reaches a certain state.</p>
<p>What I did last week was set up the most basic version — one that always assumed a <strong>happy path</strong>. We managed to send a webhook to a local mock server successfully. But real systems are messier. Network drops, offline systems, slow endpoints — there are edge cases we didn't account for.</p>
<p>For instance: <strong>What if the merchant URL is down? What if we have slow endpoints?</strong> We need a way to guarantee that the callback is eventually sent — what we define as <strong>"at-least-once delivery"</strong>.</p>
<p>Our architecture from last week was:</p>
<pre><code class="language-plaintext">Transaction Worker → Enqueue webhook job → Webhook Worker → Send once → Done (or fail forever)
</code></pre>
<p>This week, I fixed the last part to ensure <strong>eventual delivery</strong>.</p>
<hr />
<h2>What Is a Reliable Webhook Delivery System?</h2>
<p>For this project, I aimed to keep it simple for the MVP and improve later. So my definition of a reliable system started by listing the <strong>edge cases</strong> the system must cover:</p>
<h3>1. Merchant URL Is Down</h3>
<p>This happens when you cannot reach the merchant URL immediately due to:</p>
<ul>
<li><p>Timeouts</p>
</li>
<li><p>DNS failure</p>
</li>
<li><p>500 errors</p>
</li>
</ul>
<p><strong>Solution:</strong> Retries with backoff.</p>
<h3>Why Backoff and Not Immediate Retries?</h3>
<p>When a webhook fails, it's often because something temporary broke — a network hiccup, the other server is overloaded, rate limiting kicks in, or the server is restarting.</p>
<p>If you retry instantly in a tight loop, a few bad things happen:</p>
<ul>
<li><p><strong>Amplify the problem</strong> — If their server is already struggling, blasting it with rapid retries keeps it down longer</p>
</li>
<li><p><strong>Rate limits</strong> — Many APIs will block or throttle you harder if you retry aggressively</p>
</li>
<li><p><strong>Waste resources</strong> — The system burns CPU/network on retries that have almost zero chance of succeeding right away</p>
</li>
<li><p><strong>Retry storms</strong> — When thousands of jobs all retry instantly, both systems get flooded</p>
</li>
</ul>
<p><strong>Backoff retries space things out.</strong> First retry after 1s, then 2s, 4s, 8s, and so on.</p>
<h3>2. Slow Endpoints</h3>
<p>This is where the merchant takes too long to respond.</p>
<p><strong>Solution:</strong> Set timeouts so as not to block the main transaction flow.</p>
<h3>3. Duplicate Deliveries</h3>
<p>Retries + crashes can cause duplicates.</p>
<p><strong>Solution:</strong> Use <strong>idempotency keys</strong> that act as unique identifiers so merchants can dedupe on their end.</p>
<h3>4. Idempotency Is Key</h3>
<p>Since BullMQ (or any message broker) retries the job completely, we have to make sure the system handles retries without producing unwanted side effects.</p>
<hr />
<h2>My Naive Mistake with Manual Updates</h2>
<p>After defining the expected goals, I got to work turning them into code. I created 2 new database tables:</p>
<ol>
<li><p><code>webhook_dispatches</code> — The intent (shows that this transaction needs a callback sent)</p>
</li>
<li><p><code>webhook_attempts</code> — The reality (logs each time we tried and probably failed)</p>
</li>
</ol>
<h3>Why 2 Tables?</h3>
<p>To ensure we keep <strong>clean state and logs separately</strong>:</p>
<ul>
<li><p><code>dispatches</code> is the state machine</p>
</li>
<li><p><code>attempts</code> holds the logs</p>
</li>
</ul>
<p>Mixing them into one table doesn't enforce that boundary and leads to stressful debugging.</p>
<p>Another advantage: when I start working on the UI, I can easily add transaction monitoring and simulation visibility. We get a clean view — say we want to see a webhook that was delivered after 3 attempts. That's literally impossible to do cleanly with one table.</p>
<h3>The Naive Implementation</h3>
<p>The first implementation I tried was to <strong>manually handle retries in the database</strong>. I had columns like <code>attempt_count</code> and <code>next_retry_at</code>, where my idea was to manually increment logic like this:</p>
<pre><code class="language-sql">-- name: markWebhookDeliverFailed
UPDATE webhook_dispatches
SET status = 'failed',
    attempt_count = attempt_count + 1,
    last_attempt_at = NOW(),
    next_retry_at = NOW() + (INTERVAL '1 second' * POWER(2, attempt_count)),
    updated_at = NOW()
WHERE id = $1;
</code></pre>
<h3>Problem 1: Using <code>attempt_count</code></h3>
<pre><code class="language-typescript">const attemptNumber = dispatch.attempt_count + 1;
</code></pre>
<p>This is <strong>WRONG</strong> in a BullMQ system.</p>
<p><strong>Why?</strong></p>
<ul>
<li><p>BullMQ already tracks attempts</p>
</li>
<li><p>The DB counter will drift / become inconsistent</p>
</li>
<li><p>We are duplicating state</p>
</li>
</ul>
<h3>Problem 2: Manual Increment</h3>
<pre><code class="language-typescript">await service.incrementDispatchAttempt(dispatch.id);
</code></pre>
<p>This is a <strong>design bug</strong>.</p>
<p>Because we are:</p>
<ul>
<li><p>Duplicating BullMQ's job state</p>
</li>
<li><p>Introducing possible race conditions</p>
</li>
<li><p>Doing something completely unnecessary</p>
</li>
</ul>
<h3>The Solution: Let BullMQ Handle It</h3>
<p>BullMQ already gives us the ability to manage queues with a simple configuration like this:</p>
<pre><code class="language-typescript">attempts: 5,
backoff: {
  type: "exponential",
  delay: 2000,
}
</code></pre>
<p>With that, BullMQ handles:</p>
<ul>
<li><p>The count</p>
</li>
<li><p>Maximum attempts allowed</p>
</li>
<li><p>The retry strategy with exponential backoff</p>
</li>
</ul>
<p>So I was trying to <strong>reinvent the wheel</strong> with manual retries (which could be fragile), when BullMQ already offers tested mechanisms.</p>
<h3>The Core Mistake</h3>
<p>I was <strong>mixing BullMQ retry state with database retry state</strong>.</p>
<p><strong>Lesson learned:</strong> BullMQ owns retries. The database stores history.</p>
<p>The problems I quickly ran into:</p>
<ul>
<li><p>Duplicates BullMQ logic</p>
</li>
<li><p>Causes drift</p>
</li>
<li><p>Harder to reason about</p>
</li>
<li><p>Introduces race conditions</p>
</li>
</ul>
<hr />
<h2>The Corrected Architecture</h2>
<p>After realizing those fragile mistakes, I started work on fixing them with a new architecture design.</p>
<h3>Database Migration</h3>
<p>First, I ran a DB migration to alter the <code>webhook_dispatches</code> table and remove every manual retry logic. This involved dropping the columns:</p>
<ul>
<li><p><code>attempt_count</code></p>
</li>
<li><p><code>max_attempts</code></p>
</li>
<li><p><code>next_retry_at</code></p>
</li>
<li><p><code>last_attempt_at</code></p>
</li>
</ul>
<p>Those were already being handled by BullMQ. Having 2 different places handling that state is a recipe for inconsistencies. <strong>Now we have a single source of truth.</strong></p>
<h3>Code Changes</h3>
<p>I replaced the hardcoded increment logic:</p>
<pre><code class="language-typescript">// BEFORE (wrong)
const attemptNumber = dispatch.attempt_count + 1;

// AFTER (correct)
const attemptNumber = job.attemptsMade + 1;
</code></pre>
<p>I also removed the manual increment completely:</p>
<pre><code class="language-typescript">// DELETED - no longer needed
await service.incrementDispatchAttempt(dispatch.id);
</code></pre>
<h3>Final Database Schema</h3>
<p><code>webhook_dispatches</code><strong>:</strong></p>
<ul>
<li><p><code>id</code></p>
</li>
<li><p><code>payload</code></p>
</li>
<li><p><code>callback_url</code></p>
</li>
<li><p><code>status</code> (pending, delivered, failed, etc.)</p>
</li>
</ul>
<p><code>webhook_attempts</code> (no changes):</p>
<ul>
<li><p><code>dispatch_id</code></p>
</li>
<li><p><code>attempt_number</code></p>
</li>
<li><p><code>response_status</code></p>
</li>
<li><p><code>response_body</code></p>
</li>
<li><p><code>duration_ms</code></p>
</li>
<li><p><code>created_at</code></p>
</li>
<li><p><code>error_message</code></p>
</li>
</ul>
<p>With this design:</p>
<ul>
<li><p><strong>BullMQ</strong> handles "Should I retry this job?"</p>
</li>
<li><p><strong>The database</strong> shows "What happened each time?"</p>
</li>
</ul>
<h3>Final Architecture Flow</h3>
<p><strong>Transaction Worker:</strong></p>
<ol>
<li><p>Processes transaction</p>
</li>
<li><p>Builds webhook payload</p>
</li>
<li><p>Inserts <code>webhook_dispatch</code></p>
</li>
<li><p>Enqueues job with <code>dispatch_id</code></p>
</li>
</ol>
<p><strong>Webhook Worker:</strong></p>
<ol>
<li><p>Fetches dispatch</p>
</li>
<li><p>Sends HTTP request</p>
</li>
<li><p>Logs attempt in <code>webhook_attempts</code></p>
</li>
<li><p>Throws error on failure (to trigger retry)</p>
</li>
<li><p>Marks success on completion</p>
</li>
</ol>
<p><strong>BullMQ (Source of Truth for Retries):</strong></p>
<ul>
<li><p>Tracks <code>attemptsMade</code></p>
</li>
<li><p>Applies exponential backoff</p>
</li>
<li><p>Stops after max attempts</p>
</li>
<li><p>Emits <code>failed</code> event on final failure</p>
</li>
</ul>
<p><strong>Database (Source of Truth for History):</strong></p>
<ul>
<li><p><code>webhook_dispatches</code> — One row per webhook lifecycle; tracks status: pending, delivered, failed</p>
</li>
<li><p><code>webhook_attempts</code> — One row per attempt</p>
</li>
</ul>
<h3>Retry Mechanism (How It Works)</h3>
<ol>
<li><p>Worker processes job</p>
</li>
<li><p>If webhook fails:</p>
<pre><code class="language-typescript">throw new Error("Webhook delivery failed");
</code></pre>
</li>
<li><p>BullMQ:</p>
<ul>
<li><p>Increments attempt count</p>
</li>
<li><p>Schedules retry using backoff</p>
</li>
</ul>
</li>
<li><p>Repeat until max attempts reached</p>
</li>
<li><p>On final failure:</p>
<ul>
<li><p><code>failed</code> event fires</p>
</li>
<li><p>Dispatch marked as failed</p>
</li>
</ul>
</li>
</ol>
<h3>Exponential Backoff Configuration</h3>
<pre><code class="language-typescript">attempts: 5,
backoff: {
  type: "exponential",
  delay: 2000,
}
</code></pre>
<hr />
<h2>Analyzing the Outcome: Does It Work?</h2>
<p>With the design locked in, I got into coding and implemented the logic. After a while, it was ready for testing.</p>
<p>The first test used a local mock server listening on <code>localhost:3000/callback</code> — the merchant endpoint that receives the callback job. But that was already working from last week. What we really wanted to test was the <strong>failure mode</strong>. What happens if the callback URL is offline or experiencing issues?</p>
<h3>The Test Setup</h3>
<p>I manually configured the POST callback to <strong>fail randomly</strong> to mimic flaky systems. Based on a random function, the endpoint would either:</p>
<ul>
<li><p>Respond with 5XX errors</p>
</li>
<li><p>Respond with 2XX OK</p>
</li>
</ul>
<p>I also added <strong>simulated timeouts</strong> by delaying the response using JavaScript's <code>setTimeout</code>.</p>
<h3>The Results</h3>
<p>Observing the logs in the worker terminal, I could see the job retrying with a backoff delay. Here's what happened:</p>
<p><strong>Initial job execution (transaction worker):</strong></p>
<ul>
<li><p>20:48:01.424 → Start processing</p>
</li>
<li><p>20:48:01.682 → Completed</p>
</li>
<li><p><strong>Total: ~258ms</strong></p>
</li>
</ul>
<p><strong>Webhook job — per attempt breakdown:</strong></p>
<table>
<thead>
<tr>
<th>Attempt</th>
<th>Start Time</th>
<th>Fail Time</th>
<th>Duration</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>20:48:01.686</td>
<td>20:48:01.891</td>
<td>~205ms</td>
</tr>
<tr>
<td>2</td>
<td>20:48:03.906</td>
<td>20:48:03.956</td>
<td>~50ms</td>
</tr>
<tr>
<td>3</td>
<td>20:48:07.980</td>
<td>20:48:08.020</td>
<td>~40ms</td>
</tr>
<tr>
<td>4</td>
<td>20:48:16.123</td>
<td>20:48:16.163</td>
<td>~40ms</td>
</tr>
<tr>
<td>5 (final)</td>
<td>20:48:32.189</td>
<td>20:48:32.282</td>
<td>~93ms</td>
</tr>
</tbody></table>
<h3>Computing Gaps Between Attempts</h3>
<table>
<thead>
<tr>
<th>From → To</th>
<th>Delay</th>
</tr>
</thead>
<tbody><tr>
<td>1 → 2</td>
<td>~2.22s</td>
</tr>
<tr>
<td>2 → 3</td>
<td>~4.07s</td>
</tr>
<tr>
<td>3 → 4</td>
<td>~8.14s</td>
</tr>
<tr>
<td>4 → 5</td>
<td>~16.07s</td>
</tr>
</tbody></table>
<h3>Verdict: Is Exponential Backoff Working?</h3>
<p><strong>Yeah — 100%. Textbook exponential.</strong></p>
<p>This is basically:</p>
<pre><code class="language-plaintext">~2s → ~4s → ~8s → ~16s
</code></pre>
<p>Which matches the formula:</p>
<pre><code class="language-plaintext">delay = baseDelay * 2^(attempt - 1)
</code></pre>
<p>Our config is effectively working like:</p>
<pre><code class="language-typescript">backoff: {
  type: 'exponential',
  delay: 2000
}
</code></pre>
<hr />
<h2>The Subtle Bug</h2>
<p>While exponential backoff was doing its job perfectly, I noticed something important:</p>
<p>For one test run, I shut down the <code>/callback</code> endpoint entirely, so it always returned a <strong>404 (endpoint doesn't exist)</strong>.</p>
<p>Right now, our system treats:</p>
<ul>
<li><p><strong>500 (temporary issue)</strong> → Retry makes sense</p>
</li>
<li><p><strong>Timeout (network flake)</strong> → Retry makes sense</p>
</li>
<li><p><strong>404 (bad URL)</strong> → Retry is pointless</p>
</li>
</ul>
<p><strong>But BullMQ doesn't know that — you have to decide that.</strong></p>
<h3>The Fix</h3>
<p>I added logic to only throw <strong>retryable errors</strong> for real retry cases:</p>
<pre><code class="language-typescript">// Non-retryable
if (status === 400 || status === 404) {
  throw new Error(`Non-retryable error: ${status}`);
}

// Retryable conditions
const isRetryable =
  !error.response || // network failure
  status &gt;= 500 ||
  status === 429 ||
  status === 408 ||
  error.code === 'ETIMEDOUT';

if (isRetryable) {
  throw new Error(`Retryable webhook failure: ${status || error.code}`);
}
</code></pre>
<p>This prevents wasting retry attempts on errors that will never resolve.</p>
<hr />
<h2>Conclusion and What's Next</h2>
<p>Retries are behaving perfectly with:</p>
<ul>
<li><p>Backoff doubling correctly</p>
</li>
<li><p>No jitter (pure exponential — I may add this later for production)</p>
</li>
<li><p>Clean scheduling, no weird delays</p>
</li>
</ul>
<p>With that, I've successfully hit my <strong>Week 11 KPI</strong>:</p>
<blockquote>
<p>Implement exponential backoff for failed webhook deliveries and ensure the system retries a failed webhook 5 times before giving up.</p>
</blockquote>
<h3>What I Learned</h3>
<ol>
<li><p><strong>Don't duplicate state</strong> — Let BullMQ own retry logic; let the database store history</p>
</li>
<li><p><strong>Not all errors should be retried</strong> — 404s won't fix themselves; 500s might</p>
</li>
<li><p><strong>Exponential backoff is elegant</strong> — Simple config, powerful results</p>
</li>
<li><p><strong>Two tables are better than one</strong> — Separate state from logs for clean architecture</p>
</li>
</ol>
<p>For <strong>Week 12</strong>, I'll be working on <strong>security mocking</strong> — ensuring the API rejects calls without a valid (simulated) authorization header.</p>
<p>Stay locked in for the next breakdown.</p>
<hr />
<p><em>Tags: Webhooks · Exponential Backoff · BullMQ · Retry Logic · Error Handling · BuildInPublic</em></p>
]]></content:encoded></item></channel></rss>