<?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 Rishi Kant Rana on Medium]]></title>
        <description><![CDATA[Stories by Rishi Kant Rana on Medium]]></description>
        <link>https://medium.com/@rishi-rana?source=rss-daa1038dd01d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F77HEA3ckSBDxd9cQ2F80Q.jpeg</url>
            <title>Stories by Rishi Kant Rana on Medium</title>
            <link>https://medium.com/@rishi-rana?source=rss-daa1038dd01d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:04:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishi-rana/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[You Don’t Need ZooKeeper for Distributed Locking — Just the Postgres You Already Have]]></title>
            <link>https://blog.stackademic.com/you-dont-need-zookeeper-for-distributed-locking-just-the-postgres-you-already-have-999559ae2029?source=rss-daa1038dd01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/999559ae2029</guid>
            <category><![CDATA[distributed-locks]]></category>
            <dc:creator><![CDATA[Rishi Kant Rana]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 02:45:09 GMT</pubDate>
            <atom:updated>2026-08-30T02:45:09.944Z</atom:updated>
            <content:encoded><![CDATA[<p>Every backend eventually needs the same primitive: run this job on exactly one instance at a time. A nightly report. A poller that shouldn’t fire twice. A reconciliation job that would corrupt data if two copies raced each other. The need is boring and universal, which is exactly why it’s strange how heavy the usual answers are.</p><p>To be precise about scope up front: ZooKeeper does a lot more than this — service discovery, config distribution, group membership, general-purpose coordination primitives. This isn’t a case study in replacing ZooKeeper wholesale. It’s about the one slice of what it’s often reached for — “make sure only one instance of this job runs at a time” — and why that one slice doesn’t need a coordination service at all if you already run a database.</p><p>Multiple dispatcher instances pulled from a shared queue, and a handful of jobs — retry sweeps, dead-letter reconciliation, per-tenant rate-limit resets — needed a single owner at a time, not five instances stepping on each other. Nothing else about the system needed coordinating — no service discovery, no shared config, no cluster membership — just this one lock. And yet the “correct” answers people reach for by default all involve infrastructure sized for a much bigger problem:</p><ul><li><strong>ZooKeeper / Consul / etcd</strong> — solid, battle-tested, and a second distributed system to operate, monitor, and page someone about at 3am, just so a cron-ish job doesn’t double-fire. All of it earns its keep if you need service discovery or cluster coordination too. None of it earns its keep if locking is the only thing you need.</li><li><strong>Redis Redlock</strong> — if you already run Redis, tempting. But Redlock’s correctness under partition and clock skew has been litigated in public for years, and we didn’t want to relitigate it ourselves in an incident review.</li><li><strong>SELECT … FOR UPDATE</strong> — fine for a lock held for the duration of one transaction. Wrong shape for “hold this for the next 20 minutes while a job runs” — it blocks other queries and doesn’t degrade gracefully when a connection just hangs.</li></ul><p>(The Redlock correctness debate, if you haven’t seen it: <a href="https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html">https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html</a>)</p><p>We already had Postgres. Every service already talked to it. The job that needed coordinating was itself writing to Postgres. Standing up a coordination service to get one primitive — mutual exclusion — out of a tool built for a much broader job felt backwards when the database that was already sitting underneath everything could give us that one primitive directly. So instead of reaching outward for more infrastructure, we looked at what the infrastructure we already had could do.</p><h3>The insight: let a UNIQUE constraint be the mutex</h3><p>The entire mechanism is one table:</p><pre>CREATE TABLE mutex_lock (<br>  lock_name      VARCHAR(64) NOT NULL,<br>  locked         INT NOT NULL DEFAULT 1,<br>  instance_id    VARCHAR(64) NOT NULL,<br>  last_heartbeat TIMESTAMPTZ NOT NULL,<br>  acquired_at    TIMESTAMPTZ NOT NULL,<br>  CONSTRAINT uq_mutex_lock UNIQUE (locked, lock_name),<br>  CONSTRAINT chk_locked CHECK (locked = 1)<br>);</pre><p>UNIQUE(locked, lock_name) plus CHECK (locked = 1) means at most one row can ever exist for a given lock_name — the constant locked = 1 column is a trick to make the whole row itself unique-or-nothing. Acquiring the lock is just: try to insert a row. Whoever’s INSERT lands first wins, and Postgres’s own MVCC and constraint machinery is what enforces it — not application code, not a CAS retry loop, not a lease algorithm we had to get right ourselves. There is no more elegant lock than “the database physically will not let a second row exist.”</p><p>Releasing is a DELETE. That’s the whole happy path.</p><h3>The part that isn’t the happy path</h3><p>The happy path is trivial. Distributed locks are hard because of what happens when a holder disappears without releasing — the process gets OOM-killed, the node reboots, the network partitions. Something has to notice and take the lock back, or the system deadlocks forever waiting for a process that no longer exists.</p><p>The standard fix is a heartbeat: the holder periodically touches a timestamp, and anyone else can steal the lock once that timestamp goes stale. Almost every tutorial-grade implementation of this uses <strong>one timeout</strong> — heartbeat older than N seconds, lock is up for grabs.</p><p>That single timeout is a mistake, and it’s a mistake that only shows up under load, which is exactly when you can’t afford it.</p><p>Here’s the failure mode: your holder isn’t dead, it’s just slow — a GC pause, a lock-contended query, a noisy neighbor on the same host. Heartbeat misses the timeout. Another instance reclaims the lock and starts the same expensive, slow operation. If the slowness was caused by system-wide load rather than something specific to that one process, the new holder hits the exact same wall, misses its own heartbeat, and a third instance takes over. You now have a livelock where the lock ping-pongs between instances and the job never actually finishes — and from the outside it looks like “the lock is broken,” when actually the lock did exactly what it was configured to do.</p><p>The fix we landed on is two thresholds instead of one:</p><ul><li><strong>30 seconds without a heartbeat</strong> → emit an alert. Don’t touch the lock. This is a signal for a human: is the holder dead, or just slow? You have a window to look before anything happens.</li><li><strong>10 minutes without a heartbeat</strong> → now it’s safe to assume the holder is actually gone, and another instance is allowed to reclaim the row outright.</li></ul><p>The 30-second alert threshold doesn’t change the lock’s behavior at all — it exists purely so a human finds out before the system self-heals, instead of finding out after, when the ping-pong has already happened three times and someone’s asking why the nightly job ran on four instances at once. The 10-minute auto-release threshold is the actual safety net, set long enough that transient slowness almost never crosses it.</p><p>Two numbers instead of one. It costs nothing to implement — it’s the same heartbeat column, just read with two comparisons instead of one — and it’s the difference between a lock that degrades gracefully under load and one that amplifies the load that’s already hurting you.</p><h3>One subtlety: whose clock is it anyway</h3><p>A design that compares “now” to a stored timestamp has an obvious failure mode: whose “now”? If the client computes staleness using its own wall clock and sends that to the database, then clock skew between instances — or a single instance’s clock jumping during an NTP correction — can make a perfectly healthy lock look stale, or a genuinely stale lock look fine.</p><p>The fix is to never let a client clock enter the comparison at all. Every staleness check runs now() — last_heartbeat as a single expression evaluated inside one Postgres statement:</p><pre>SELECT instance_id, EXTRACT(EPOCH FROM (now() - last_heartbeat)) AS seconds_since_heartbeat<br>FROM mutex_lock<br>WHERE lock_name = %(lock_name)s<br>FOR UPDATE</pre><p>now() here is the database server’s clock, computed at execution time on the server. No client ever sends “I think it’s currently X” — the comparison never leaves Postgres. It doesn’t matter if two competing instances have clocks that are seconds apart, or if one of them just had its clock stepped backward; the only clock the algorithm ever consults is the one clock all of them already have to agree on to make writes durable in the first place.</p><h3>What it actually costs</h3><p>“It’s just a table” is a nice pitch, but it’s only worth something if the numbers back it up. Everything below is measured against a real Postgres 16 instance (Docker, local machine, client and server on the same box — full methodology and reproduction steps are in the repo’s benchmarks/ directory); treat these as a best-case floor, not a promise, since real deployments have real network latency between client and database.</p><p><strong>Uncontended acquire + release</strong>, 1000 iterations after warmup:</p><ul><li>Raw DB round trip (no heartbeat thread): mean 0.556 ms · p50 0.539 ms · p95 0.642 ms · p99 0.711 ms</li><li>Public API, acquire()+release(): mean 0.579 ms · p50 0.572 ms · p95 0.641 ms · p99 0.732 ms</li></ul><p>Sub-millisecond, as you’d hope for one SELECT … FOR UPDATE plus one INSERT in an explicit transaction. The public API adds ~20–30µs on top for spinning up and tearing down the background heartbeat thread — noise.</p><p><strong>Throughput under contention</strong> is the more interesting number, and it wasn’t what I expected going in. N worker threads, each its own connection standing in for a separate service instance, compete for one lock continuously for 5 seconds; every winner holds it for a simulated 5ms critical section.</p><p>At the library’s default poll_interval of 0.5 seconds:</p><ul><li>1 worker: 104.9 hand-offs/sec</li><li>4 workers: 105.3 hand-offs/sec</li><li>8 workers: 104.6 hand-offs/sec</li><li>16 workers: 104.4 hand-offs/sec</li><li>32 workers: 104.3 hand-offs/sec</li></ul><p>Flat. One competing instance and thirty-two perform identically. My first assumption was that a 500ms poll interval would badly throttle hand-off speed under contention — a single poller checking every half-second averages a 250ms wait after a release. But thirty-two pollers aren’t synchronized; their check-in times are spread across that window, so the time until any one of them notices a release shrinks as you add more of them. Aggregate polling frequency across N independent instances compensates for a relaxed per-instance interval. This is precisely why 0.5s is a reasonable default instead of something aggressive — for any workload with more than a couple of competing instances, it’s costing you almost nothing.</p><p>Dropping to poll_interval=0.01 does help — up to ~130 hand-offs/sec at 8–16 workers, closer to the ~200/sec ceiling the 5ms hold time sets — but it tapers off by 32 workers, where the polling itself (32 × 100 checks/sec = 3,200 acquire attempts/sec hitting Postgres) starts adding its own load back onto the thing you’re trying to make faster. Tighter polling helps up to a point and then becomes its own tax. Don’t reach for it as a default; tune it only after measuring that a specific low-contender workload actually needs faster hand-off.</p><h3>What you don’t get</h3><p>This is deliberately a mutex, not a coordination service. It doesn’t do fencing tokens, so a reclaimed lock doesn’t hand the new holder cryptographic proof the old one is really gone — if a “dead” holder resumes writing after being reclaimed, that’s on the caller to guard against (a heartbeat call after being reclaimed raises immediately, which is the tool’s only line of defense here). No read/write locks, no lock hierarchies, no cross-database coordination. If you need any of that, you need ZooKeeper or etcd, and you should use them — they solve a harder problem than this does. What we needed was “run this job once,” and reaching for a full coordination service to get that felt like renting a warehouse to store a bicycle.</p><h3>Try it</h3><p>The library is postgres-mutex, on PyPI as postgres-mutex:</p><pre>pip install postgres-mutex</pre><pre>from postgres_mutex import Mutex</pre><pre>mutex = Mutex(dsn=&quot;postgres://...&quot;, lock_name=&quot;nightly-report-job&quot;)</pre><pre>with mutex.acquire(blocking=False) as acquired:<br>    if acquired:<br>        run_the_job()<br>    else:<br>        log.info(&quot;another instance is running the job&quot;)</pre><p>Sync and async both work, there’s a @mutex.singleton decorator if you want to skip the if acquired branch entirely, and a metrics hook if you want to wire the 30-second alert into whatever pages your team. It’s one table and zero new infrastructure. If you already run Postgres, that’s the whole dependency list.</p><p>Repo, README, and the full design rationale (failure modes, “why not X” in more detail, dual-threshold defaults): <a href="https://github.com/rishi-rana/postgres-mutex">https://github.com/rishi-rana/postgres-mutex</a></p><p>PyPI: <a href="https://pypi.org/project/postgres-mutex/">https://pypi.org/project/postgres-mutex/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999559ae2029" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/you-dont-need-zookeeper-for-distributed-locking-just-the-postgres-you-already-have-999559ae2029">You Don’t Need ZooKeeper for Distributed Locking — Just the Postgres You Already Have</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a High-Throughput Webhook Delivery System at Scale]]></title>
            <link>https://blog.stackademic.com/designing-a-high-throughput-webhook-delivery-system-at-scale-e617f3cc031c?source=rss-daa1038dd01d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e617f3cc031c</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Rishi Kant Rana]]></dc:creator>
            <pubDate>Mon, 25 May 2026 22:33:58 GMT</pubDate>
            <atom:updated>2026-06-01T06:52:04.017Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Rishi Kant Rana</em></p><p>Webhooks are deceptively simple on the surface — make an HTTP POST to a URL when something happens. But when you need to deliver 100,000 events per second reliably, across thousands of enterprise customers, with retry semantics, failure isolation, and delivery guarantees, the problem becomes one of the most interesting distributed systems challenges you can design.</p><p>This article walks through a production-grade webhook delivery system from scratch — covering every layer from change capture to delivery, with the failure modes and operational considerations that matter in the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8EIhaD8c19ftJi5Y4TNPIw.png" /><figcaption>End To End Architecture Diagram</figcaption></figure><h3>Requirements</h3><p>Before jumping into architecture, let’s establish constraints:</p><p><strong>Functional:</strong></p><ul><li>Deliver webhook events to thousands of enterprise customer endpoints via HTTP POST</li><li>Each customer registers one or more endpoint URLs</li><li>Support multiple event types (Order, Shipment, Inventory, Product, Customer etc.)</li><li>At-least-once delivery — duplicates are acceptable, silent drops are not</li></ul><p><strong>Non-functional:</strong></p><ul><li>Peak throughput: 100,000 events/second</li><li>Delivery latency: within a few seconds of event occurrence</li><li>Client timeout: 10 seconds per HTTP call</li><li>Retry semantics: exponential backoff, max 5 consecutive failures before pausing</li><li>Customers must be isolated — one slow endpoint cannot block others</li></ul><h3>High-Level Architecture</h3><p>The system breaks into four distinct layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0K2nCCU9cZ_FU8g5dH89PA.png" /></figure><p>Let’s go deep on each layer.</p><h3>Layer 1 — The Capture Layer</h3><h3>The Dual Write Problem</h3><p>The first challenge is atomic event capture. A webhook event must be fired if and only if the underlying business operation succeeds. A naive approach — write to the DB, then publish to Kafka — introduces a dangerous window: the app crashes after the DB commit but before the Kafka publish. The event is silently lost.</p><p>The solution is the <strong>Transactional Outbox Pattern</strong>.</p><h3>The Transactional Outbox Pattern</h3><p>Instead of publishing directly to Kafka, the application writes the event to an EntityCDC table in the <strong>same database transaction</strong> as the business operation. Either both commit or neither does — atomicity is guaranteed by the DB.</p><pre>-- Business operation and event capture in one transaction<br>BEGIN;<br>  UPDATE orders SET status = &#39;SHIPPED&#39; WHERE id = :orderId;<br>  INSERT INTO OrderCDC (entity_id, entity_type, payload, status, created_at)<br>  VALUES (:orderId, &#39;ORDER&#39;, :payload, &#39;UNPROCESSED&#39;, NOW());<br>COMMIT;</pre><p>A separate <strong>Poller Service</strong> then reads from the outbox table and publishes to Kafka.</p><h3>Outbox Table Design</h3><p>A single monolithic outbox table becomes a bottleneck at scale. Instead, create one table per entity type:</p><pre>OrderCDC<br>ShipmentCDC<br>InventoryCDC<br>CustomerCDC</pre><p>Each table is partitioned by customer_id (or tenant_id) — the natural partition key that also maps cleanly to downstream Kafka partitioning. This gives you:</p><ul><li>Independent scaling per entity type</li><li>Partition pruning on queries</li><li>One entity’s backlog cannot slow another</li></ul><p>The full schema for each outbox table:</p><pre>CREATE TABLE OrderCDC (<br>  id               BIGSERIAL PRIMARY KEY,<br>  entity_id        VARCHAR(64) NOT NULL,<br>  entity_type      VARCHAR(32) NOT NULL,<br>  customer_id      VARCHAR(64) NOT NULL,<br>  payload          JSONB NOT NULL,<br>  status           VARCHAR(20) NOT NULL DEFAULT &#39;UNPROCESSED&#39;,<br>  retry_count      INT NOT NULL DEFAULT 0,<br>  last_attempted_at TIMESTAMP,<br>  error_message    TEXT,<br>  created_at       TIMESTAMP NOT NULL DEFAULT NOW()<br>) PARTITION BY HASH (customer_id);</pre><p>Status transitions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*RmoGDXAXL_M1tOsrIBLBQw.png" /></figure><h3>Distributed Poller Coordination</h3><p>The Poller Service is horizontally scaled — multiple instances run concurrently. But only one instance should poll a given entity table at a time to avoid double-processing. This is a distributed locking problem.</p><p>Rather than introducing ZooKeeper or Consul as a dependency, a simple <strong>DB-based distributed mutex with heartbeating</strong> solves this cleanly:</p><pre>CREATE TABLE EntityLock (<br>  entity_type    VARCHAR(32) NOT NULL,<br>  locked         INT NOT NULL DEFAULT 1,<br>  instance_id    VARCHAR(64) NOT NULL,<br>  last_heartbeat TIMESTAMP NOT NULL,<br>  acquired_at    TIMESTAMP NOT NULL,<br>  CONSTRAINT uq_entity_lock UNIQUE (locked, entity_type),<br>  CONSTRAINT chk_locked CHECK (locked = 1)<br>);</pre><p>The UNIQUE(locked, entity_type) constraint — combined with the check constraint that locked can only be 1 — means only one row per entity type can ever exist. Whoever inserts wins the lock. No compare-and-swap complexity, no race conditions.</p><pre>// Acquire lock — succeeds or throws constraint violation<br>INSERT INTO EntityLock (entity_type, locked, instance_id, last_heartbeat, acquired_at)<br>VALUES (&#39;ORDER&#39;, 1, :instanceId, NOW(), NOW())<br>ON CONFLICT DO NOTHING;</pre><pre>// Heartbeat every 10 seconds while holding lock<br>UPDATE EntityLock SET last_heartbeat = NOW() <br>WHERE entity_type = &#39;ORDER&#39; AND instance_id = :instanceId;</pre><pre>// Release on clean shutdown<br>DELETE FROM EntityLock WHERE entity_type = &#39;ORDER&#39; AND instance_id = :instanceId;</pre><p><strong>Stale lock handling</strong> uses two thresholds, not one:</p><ul><li><strong>30 seconds without heartbeat</strong> → alert on-call (investigate: is the instance alive but slow, or crashed?)</li><li><strong>10 minutes without heartbeat</strong> → auto-release (safe to assume crash)</li></ul><p>This matters because blindly releasing after 30 seconds could hand the lock to another instance hitting the same slow-processing problem. The alert window gives engineers time to investigate before the system self-heals.</p><h3>The Sweeper Job</h3><p>The Poller Service can fail mid-flight — it picks up a row, sets it to PROCESSING, then crashes before completing. A <strong>Sweeper Job</strong> runs on a schedule to handle these cases:</p><pre>-- Rows stuck in PROCESSING beyond timeout → reset to UNPROCESSED<br>UPDATE OrderCDC <br>SET status = &#39;UNPROCESSED&#39;, retry_count = retry_count + 1<br>WHERE status = &#39;PROCESSING&#39; <br>  AND last_attempted_at &lt; NOW() - INTERVAL &#39;5 minutes&#39;;</pre><pre>-- Rows in FAILED below max retries → reset to UNPROCESSED  <br>UPDATE OrderCDC<br>SET status = &#39;UNPROCESSED&#39;<br>WHERE status = &#39;FAILED&#39; <br>  AND retry_count &lt; 5<br>  AND last_attempted_at &lt; NOW() - INTERVAL &#39;1 minute&#39; * POWER(2, retry_count);</pre><pre>-- Rows exceeding max retries → permanent failure<br>UPDATE OrderCDC<br>SET status = &#39;PERMANENT_FAILURE&#39;<br>WHERE status = &#39;FAILED&#39; AND retry_count &gt;= 5;</pre><p>The retry backoff is baked into the last_attempted_at check — exponential backoff without a separate scheduler.</p><h3>Layer 2 — The Streaming Layer</h3><h3>Kafka Topic Design</h3><p>One Kafka topic per entity type:</p><pre>webhook-order-events<br>webhook-shipment-events<br>webhook-inventory-events<br>webhook-customer-events</pre><p><strong>Why not one topic for everything?</strong> A single topic forces all entity types to share partitions, making it impossible to scale or tune independently. If shipment events spike, you don’t want order delivery affected.</p><p><strong>Why not one topic per customer?</strong> With thousands of customers, that’s thousands of topics — a management nightmare and a ZooKeeper/Controller bottleneck.</p><h3>Partition Count and Key</h3><p><strong>Partition key: </strong><strong>entity_id</strong></p><p>This guarantees all events for the same entity land on the same partition, preserving strict ordering per entity. A customer’s Order events always arrive in sequence.</p><p><strong>Partition count: start at 30–50</strong></p><p>The math: at 100K events/second across 20 entity types, each topic handles ~5,000 events/second. Each event averages ~1KB, so ~5MB/second per topic. A single Kafka partition handles ~10MB/second comfortably. 10 partitions would cover throughput, but you start at 30–50 to allow consumer parallelism headroom as you scale horizontally.</p><p>Kafka partitions cannot be decreased — only increased. Start conservatively high.</p><p><strong>Retention: 7 days, no log compaction</strong></p><p>Log compaction keeps only the latest record per key — useful for changelog topics but wrong here. You need every event delivered, not just the latest state. If an Order goes from Created → Updated → Shipped, the customer needs all three webhooks.</p><p>7-day retention gives you replay capability if a customer endpoint is down for an extended period.</p><h3>Layer 3 — The Delivery Layer</h3><p>This is where most webhook systems break down. The core problem: <strong>one slow or failing customer endpoint must not block delivery to other customers.</strong></p><h3>Consumer Architecture</h3><p>The Consumer Service is a standard Kafka consumer group — auto-scaled, with one consumer instance per partition at most. Each instance handles multiple customers’ events simultaneously.</p><h3>Virtual Threads for I/O-Bound Delivery</h3><p>Webhook delivery is almost entirely I/O bound — make HTTP call, wait up to 10 seconds for response. Traditional thread-per-request models break down here: 10,000 concurrent in-flight calls at 1MB per thread stack = 10GB memory just for threads.</p><p>Java 21’s virtual threads (Project Loom) solve this elegantly. Virtual threads are JVM-scheduled, ~few KB each, and block on I/O without blocking the underlying OS thread:</p><pre>// Each webhook delivery runs on a virtual thread<br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>    for (WebhookEvent event : batch) {<br>        executor.submit(() -&gt; deliverWithRetry(event));<br>    }<br>}</pre><p>This allows hundreds of thousands of concurrent in-flight HTTP calls with a fraction of the memory overhead of traditional thread pools — ideal for this workload.</p><h3>Customer Isolation</h3><p>Even with virtual threads, you need fairness across customers. A single customer with a slow endpoint should not monopolize the executor. The solution: <strong>bound concurrency per customer</strong>:</p><pre>// ConcurrentHashMap of per-customer semaphores<br>ConcurrentHashMap&lt;String, Semaphore&gt; customerSemaphores = new ConcurrentHashMap&lt;&gt;();</pre><pre>Semaphore semaphore = customerSemaphores.computeIfAbsent(<br>    customerId, k -&gt; new Semaphore(5) // max 5 concurrent deliveries per customer<br>);</pre><pre>if (semaphore.tryAcquire()) {<br>    executor.submit(() -&gt; {<br>        try {<br>            deliver(event);<br>        } finally {<br>            semaphore.release();<br>        }<br>    });<br>} else {<br>    // Customer already at max concurrency — requeue or back off<br>}</pre><h3>Endpoint Health State Machine</h3><p>Each customer endpoint has a tracked health state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*CZKE1yknO9Cmg-jEtDxJbA.png" /></figure><p>This is the <strong>circuit breaker pattern</strong> applied to webhook endpoints. The graduated states give customers warning before hard pausing, reducing support escalations.</p><p>Health state is stored in a fast read/write store (Redis or a small DB table) keyed by customer_id + endpoint_url.</p><h3>Metrics to Instrument</h3><pre>webhook_delivery_latency_ms     (p50, p95, p99 per customer)<br>webhook_delivery_error_rate     (per customer, per endpoint)<br>webhook_endpoint_health_state   (HEALTHY/DEGRADED/WARNING/PAUSED)<br>webhook_consumer_lag            (per topic, per partition)<br>webhook_retry_count             (histogram)<br>webhook_dlq_size                (per customer)</pre><h3>Layer 4 — The Dead Letter Queue</h3><h3>DLQ Design</h3><p>When a customer’s subscription is PAUSED, in-flight events move to a DLQ Kafka topic:</p><pre>webhook-dlq-events</pre><p>Keyed by customer_id so all a customer&#39;s DLQ events are colocated. Retention: 30 days.</p><p>Events continue being generated for a paused customer — they accumulate in the main topic until the customer resumes (within the 7-day retention window) or are routed to DLQ immediately at the consumer level via a routing check.</p><h3>Replay Strategy</h3><p>When a customer resumes their subscription, <strong>do not auto-replay DLQ events</strong>. This is a critical product decision that most designs get wrong.</p><p>The problem with auto-replay:</p><ul><li>Events may be stale — the entity was updated multiple times since the failed delivery</li><li>The customer’s system may not be idempotent — replaying could cause duplicate processing</li><li>A large backlog could immediately overwhelm a just-recovered endpoint</li></ul><p>Instead, give customers explicit control:</p><pre>Resume options:<br>  Option A: Start fresh (default) — receive live events from now, DLQ discarded<br>  Option B: Replay at controlled rate — customer accepts responsibility for <br>            handling stale/duplicate events, rate-limited to 100 events/second<br>  Option C: Export DLQ — download as JSON for manual reconciliation</pre><p>On resume, always start consuming from the <strong>current Kafka offset</strong>, not the paused offset. The customer gets live events immediately regardless of their DLQ choice.</p><h3>Operational Considerations</h3><h3>Capacity Estimates</h3><p>At 100K events/second:</p><ul><li><strong>Kafka ingestion</strong>: ~100MB/second (at 1KB/event). Across 20 topics, ~5MB/second per topic — well within single-broker limits</li><li><strong>Kafka storage</strong>: 100MB/s × 86,400 seconds × 7 days ≈ 60TB for 7-day retention. Use tiered storage (S3-backed) for cost efficiency</li><li><strong>Consumer instances</strong>: At 5,000 events/second per topic and 50 partitions per topic, each partition handles 100 events/second. One consumer thread per partition, virtual threads handle the I/O concurrency</li><li><strong>Outbox table writes</strong>: 100K rows/second across all entity tables. Partition aggressively, archive PROCESSED rows to cold storage after 24 hours</li></ul><h3>Ordering Guarantees</h3><p>The system provides <strong>per-entity ordering</strong>, not global ordering. All events for order_id=123 arrive in sequence. Events for order_id=123 and order_id=456 may interleave. This is the right tradeoff — global ordering at 100K/second would require a single partition, eliminating all parallelism.</p><p>Customers should be designed to be idempotent — include an event_sequence_number per entity in the payload so customers can detect and handle out-of-order delivery at their end.</p><h3>Schema Evolution</h3><p>Webhook payloads evolve over time. Use <strong>versioned schemas</strong>:</p><pre>{<br>  &quot;specversion&quot;: &quot;1.0&quot;,<br>  &quot;type&quot;: &quot;com.company.order.updated&quot;,<br>  &quot;schemaversion&quot;: &quot;2.1&quot;,<br>  &quot;data&quot;: { ... }<br>}</pre><p>Never remove fields — only add. Maintain a schema registry. Customers pin to a schema version; breaking changes require a new event type, not a modification of existing ones.</p><h3>Summary</h3><p>Layer Key Design Decision Rationale Capture Transactional outbox per entity Atomic event capture, no dual write Coordination DB mutex with heartbeat Simple, no extra infra dependency Streaming Topic per entity, entity_id partition key Isolation + per-entity ordering Delivery Virtual threads + per-customer semaphore I/O concurrency + customer isolation Health Circuit breaker state machine Graduated response, reduce false pauses DLQ Customer-controlled replay Avoids stale data and endpoint overload</p><p>The webhook delivery problem is a microcosm of distributed systems design — it touches event sourcing, distributed locking, stream processing, circuit breaking, and operational observability. Getting each layer right independently is necessary but not sufficient; the system only works when the failure modes across layers are handled cohesively.</p><p><em>Rishi Kant Rana is a Staff Software Engineer specializing in distributed systems, event-driven architecture, and backend platform engineering.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e617f3cc031c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/designing-a-high-throughput-webhook-delivery-system-at-scale-e617f3cc031c">Designing a High-Throughput Webhook Delivery System at Scale</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>