I built a webhook delivery service so a product can send an event once and trust that every subscribed endpoint gets it: signed, retried, recorded, and never lost when a process dies. Every SaaS product ends up sending webhooks, and most teams have an incident story about them. Retries hammer an endpoint that has been down for a day. One big customer’s backlog delays everyone else’s events. A receiver cannot tell a real request from a forged one. Support asks “did we send it?” and nobody can answer.
Sending an HTTP request is the easy part. The interesting questions are what happens around it. Where does a message live between the API call and the HTTP request? What happens when the process sending it is killed halfway through? How does one slow customer stay slow on their own, without slowing everyone else? I wanted to answer those with as few moving parts as possible: one Go binary and one Postgres, with no Kafka, Redis or Kubernetes required. It is released as v1.0.0, with a container image for amd64 and arm64. The project page has the overview, a quickstart and the benchmarks. The code, tests and benchmark script are on GitHub, and the repository has an interactive architecture diagram where every box links to the code it describes.
Choosing what to promise
Before writing any code I had to decide what the service guarantees, because every later decision follows from it. The tempting answer is “exactly once”. It is also impossible over HTTP. A receiver can process a request and crash before it answers, and from the sender’s side that looks exactly like a request that never arrived. Any system that claims exactly-once delivery to an arbitrary HTTP endpoint is either retrying and hoping, or dropping events and hoping.
So the service promises at-least-once, unordered delivery, and says so loudly. Every request carries a stable webhook-id, which is the message id and never changes across retries or replays, and receivers drop ids they have already processed. That puts a small, well-understood burden on the receiver in exchange for a guarantee the sender can actually keep. I also chose unordered on purpose. Strict per-endpoint ordering means one failing event blocks every event behind it, which turns a single bad payload into an outage. Most receivers want the latest state anyway and can fetch it.
One binary, two roles, one database
webhookd runs in one of two roles, api or dispatcher, or both in one process. The API writes; dispatchers send. They never talk to each other directly. Postgres is the only shared state, and any number of either role can run side by side.
I considered the more common shape: an API that writes to Postgres and publishes to a broker such as Kafka or SQS, with workers consuming from the broker. That is a familiar approach, but it creates a dual-write problem. The database commit and the broker publish are two separate operations, and a crash between them either loses the event or publishes one that was never stored. The usual fix is a transactional outbox, which is a Postgres table polled by a relay that publishes to the broker. At that point Postgres is already acting as the queue, with an extra system bolted on behind it.
I chose to make the database the queue. A send is one transaction. It inserts the message, then inserts one deliveries row for each active or paused endpoint subscribed to that event type, so a paused endpoint queues its events until it is resumed. A crash can never leave a message without its deliveries, and there is no second system to keep in step. The delivery row is the queue item. The trade-off is that Postgres now takes every queue write, so its write throughput is the ceiling of the whole system. For a self-hosted service that a team runs next to its own product, I think one database you already know how to back up beats two systems you have to keep consistent.
Sending the same event twice, safely
At-least-once cuts both ways. The receiver has to tolerate duplicates from the service, and the service has to tolerate duplicates from the product calling it. A product sends an event, its HTTP client times out before the response arrives, and it retries. Without protection, that one business event becomes two messages, and every endpoint receives it twice with two different webhook-ids, which the receiver’s deduplication cannot catch.
So every create call (apps, endpoints and messages) accepts an optional Idempotency-Key header. The key is stored in a unique column on the row it creates. For a message, the insert uses ON CONFLICT DO NOTHING inside the same transaction that writes the deliveries. A repeat call with the same key returns the original message and an Idempotent-Replayed: true header, and creates nothing. A repeat with the same key but a different body is a client bug, so it gets a 422 instead of silently returning the first message. I considered keeping keys in a separate cache with an expiry, which is how many payment APIs do it. That bounds storage, but it adds a second store and a window where a late retry slips through. Keeping the key on the row it protects makes the check part of the same atomic write, at the cost of one indexed column.
Claiming work without holding locks across the network
A dispatcher claims due deliveries with SELECT … FOR UPDATE SKIP LOCKED. SKIP LOCKED is what makes a table behave like a queue: two dispatchers running the same query skip each other’s locked rows instead of waiting on them, so they never claim the same delivery.
The first version I sketched held that transaction open while it made the HTTP call, and committed the outcome at the end. It is simple and it is correct, but it pins a database connection and a row lock for as long as the receiver takes to answer, which is up to the 15-second request timeout. With 16 concurrent sends per dispatcher, a few slow receivers would exhaust the connection pool.
Instead, a claim marks the rows in_flight with a lease, a locked_until timestamp 30 seconds out, commits immediately, and only then makes the HTTP call. If the dispatcher dies mid-send, nothing is left holding a lock. The lease simply expires, a sweeper returns the row to pending, and another dispatcher sends it again. That retry after a crash is exactly where “at least once” comes from, and it is why the stable webhook-id matters.
Leases have a well-known failure mode. A dispatcher can stall past its lease, through a long GC pause or a frozen VM, while another dispatcher takes the delivery over. When the first one wakes up, it must not overwrite the second one’s result. So the lease value also works as a fencing token. When an attempt is recorded, the state update applies only WHERE locked_until = <the lease I was given>. A stale dispatcher’s update matches nothing. Its attempt is still written to the log, because that HTTP call really happened, but the delivery’s state belongs to whoever holds the current lease.
To check that this actually holds, there is a crash test. It queues 100,000 messages and kill -9s the dispatcher 8 times while it is sending, then lets a final dispatcher finish. Every message arrived, and 38 were delivered twice. Those duplicates are the guarantee working as designed, not a bug. Writing the test taught me something too. The first version killed each new dispatcher at a random moment between 200 and 800 ms. A killed dispatcher’s leases keep its endpoint slots occupied for the full 2-second test lease, so the replacement could not claim anything before it was killed in turn, and the later kills were only testing startup. The test now waits until each new dispatcher has delivered something before killing it.
Shutting down without dropping work
Deploys are the most common way a process dies, so a clean shutdown matters more than a crash. When webhookd receives SIGTERM, the dispatcher stops claiming new work, but it lets every send already in progress finish and record its result. Sends run on a context that the shutdown signal does not cancel, and the dispatcher only returns once every one of its worker slots is free again. The HTTP server gets a bounded shutdown window, 10 seconds by default, to finish in-flight API requests.
The lease is the safety net behind this. If a deploy tool loses patience and sends SIGKILL, the unfinished deliveries come back after their lease and are sent again. A graceful drain keeps routine deploys from producing duplicates, and the lease keeps an ungraceful one from losing anything. A rolling deploy of dispatchers needs no coordination at all, because they never talk to each other.
Fairness lives in the claim query
The classic webhook outage is head-of-line blocking. If dispatchers always claim the oldest due deliveries first, one endpoint with a 50,000-message backlog that takes 10 seconds to answer will occupy every worker, and every other customer waits behind it.
I considered a queue per endpoint, or per customer, with workers rotating between them. That is how you would do it with a broker, but it means creating and tracking thousands of queues and deciding how workers are assigned to them. I chose to make the claim query itself the scheduler. Each endpoint has a concurrency cap, max_in_flight (4 by default), and an optional rate limit, and both are enforced inside the claim in one transaction. First the query picks endpoints that are active, have a closed circuit breaker, are below their cap, have a rate-limit token available and have due work. It orders them by when each was last served, which gives round robin, and locks them with SKIP LOCKED so that two dispatchers never hand out the same endpoint’s slots. Then it shares the free worker slots between those endpoints and claims that many due deliveries from each.
The rate limit is GCRA, a token bucket stored as a single timestamp per endpoint (the “theoretical arrival time”). Because the limiter’s state lives in the same row the claim already locks, every dispatcher replica shares it with no extra coordination. There is no Redis, and no second round trip. A limit set to 10 requests a second stays 10 a second whether one dispatcher is running or twenty.
Two details only showed up under load. The first was lock strength. A plain FOR UPDATE on an endpoint row also blocks the foreign-key check on every send that inserts a delivery for that endpoint, so busy endpoints slowed down the API. Switching to FOR NO KEY UPDATE keeps the claims exclusive without blocking those inserts. The second was claim size. Claiming one row every time a slot freed up meant one round trip per delivery, so a dispatcher now waits until a quarter of its slots are free and claims a batch. That leaves some slots idle for a moment. Together with the lock change, it raised single-replica throughput from 458 to 576 deliveries a second at the time.
The test that matters is the noisy neighbour. One endpoint answers in 10 seconds, or returns 500, with 500 deliveries queued, while nine healthy endpoints receive 90 deliveries a second. The healthy endpoints’ p99 lag is about 30 ms. With the cap removed, the slow endpoint’s backlog takes every slot and the test fails, which is how I know the cap is doing the work.
Failing politely
Retries follow a fixed schedule: 5 s, 30 s, 2 m, 10 m, 30 m, 1 h, 3 h, 6 h and 12 h, after which the delivery is marked dead. That is ten attempts over about 23 hours. The design doc originally said “full jitter”, where each delay is chosen at random anywhere between zero and its full value. That is a familiar recommendation, but over nine delays it averages about 11 hours in total, half the window receivers are told to expect. I chose ±25% jitter instead. It still spreads retries out so that a recovering endpoint is not hit by a synchronized wave, and it keeps the schedule’s total close to its promise.
A Retry-After header on a 429 or 503 is honoured, capped at 24 hours, so a receiver that asks for room gets it. After 10 consecutive failures, a circuit breaker stops sending to the endpoint. After a cool-down that starts at 1 minute and doubles up to 1 hour, a single probe goes out. If the probe succeeds, normal delivery resumes. The retry schedule, jitter, breaker threshold, cool-downs and the disable window are all environment settings, so an operator can tune them without a code change; the numbers here are the defaults. The breaker is just two columns that the claim query reads, not a separate component. An endpoint that has failed continuously for 5 days is disabled, and an endpoint.disabled event is sent in the same transaction that disables it, so it goes out exactly once. Replay resets a delivery to pending with the same webhook-id, so a receiver that already processed it still drops it.
Making requests verifiable
A receiver has to be able to prove a request came from you. Instead of inventing a signature scheme, I used Standard Webhooks: an HMAC-SHA256 over id.timestamp.body and the recommended body shape, {"type", "timestamp", "data"}. Putting the event type inside the body means the signature covers it, and the timestamp lets receivers reject replays older than five minutes. Following a standard means any Standard Webhooks library can verify the requests, and the Go SDK does it in one call with VerifyRequest. Rotating a secret is the step most schemes get wrong. For 24 hours after a rotation, every request carries two signatures, one for the old secret and one for the new, so receivers can switch over whenever they are ready instead of in lockstep with the sender.
The sender needs protecting too. Webhook senders are a classic SSRF hole. A customer registers http://169.254.169.254/ as an endpoint and reads your cloud provider’s metadata through it. Validating the URL when it is registered is not enough, because a hostname can resolve to a public address at registration and a private one later. That attack is called DNS rebinding. So the check lives in the dialer. It refuses loopback, private, link-local and reserved addresses after DNS resolution, at the moment of each connection.
Keeping the attempt log cheap
Every attempt is stored with its status, latency and the start of the response body, because “did we send it, and what did they say?” is the most common support question. That makes the attempt table the fastest-growing table in the system. It is range-partitioned by UTC day. Dispatchers create the next week’s partitions every hour and drop days older than the retention period, 30 days by default.
I considered a nightly DELETE … WHERE attempted_at < …. That is the obvious approach, but in Postgres a delete leaves dead rows behind for vacuum to clean up, and a large delete competes with live traffic for I/O. Dropping a partition is a metadata change. It is instant and leaves nothing to clean up. The trade-off is that retention can only be set in whole days, which is fine for a log.
Messages need a delete, because a message cannot be dropped until all its deliveries have finished. Every hour a dispatcher deletes finished messages past their own retention period, also 30 days by default, in batches of 1,000 with SKIP LOCKED, so no transaction holds many locks and two dispatchers never fight over the same rows. Their deliveries and attempts go with them by cascade. A message with a delivery still pending is never deleted.
Seeing what it is doing
A delivery system that cannot explain itself is hard to trust, so every process exposes Prometheus metrics at /metrics and writes structured JSON logs. The metrics answer the operator’s questions directly. webhookd_delivery_attempts_total is split by outcome (succeeded, retry or dead). webhookd_delivery_attempt_duration_seconds shows how slow receivers are. webhookd_delivery_lag_seconds measures the time from a delivery becoming due to a dispatcher claiming it, which is the number that rises first when the service is falling behind. Counters for circuit-breaker trips and disabled endpoints flag problems on the customer’s side before the customer reports them.
Lag is the one I would alert on. Throughput alone cannot tell “quiet” apart from “stuck”, but a rising claim lag means work is waiting, whatever the cause. Every log line about a delivery carries its delivery, message and endpoint ids, so one id from a support ticket leads straight to every attempt and the receiver’s response.
What the numbers say
I measured on a 4-CPU Linux VM with Postgres, the API, the dispatchers and the load generator all on the same machine. Each message fans out to 20 endpoints on a receiver that answers in 20 ms, and lag is measured end to end, from the send call to the request arriving. With 1, 2 and 4 dispatcher replicas, a burst of 60,000 deliveries cleared at 560, 1,056 and 1,584 deliveries a second. At a steady 400 deliveries a second, p99 lag was 45, 21 and 24 ms, and p50 was 8 to 9 ms. Every run delivered every message with no duplicates.
Those numbers have limits worth saying out loud. Going from 2 to 4 replicas gains less than going from 1 to 2 because the whole stack shares 4 CPUs, so this shows the design scales out, not what the ceiling is. Lag used to be dominated by the 250 ms poll interval: p99 was 155 to 256 ms when an idle dispatcher only checked for new work four times a second. Now each send runs pg_notify inside its transaction, and every dispatcher holds one connection that LISTENs, so new work is picked up as soon as it commits. The poll stays as a fallback for retries coming due and for notifications missed while a connection was down.
One optimisation taught me to distrust microbenchmarks. Adding an EXISTS filter to the claim query made a single claim about 30 times faster in isolation, but it cut burst throughput by about 45%, so I reverted it. What did help was removing a redundant index and adding an ORDER BY to the per-endpoint lookup, which keeps the planner on an index scan instead of a sequential scan. On separate machines the real limit would be Postgres’s write rate: each delivery costs about three row writes, one for the claim, one for the attempt and one for the completion.
Testing the claims, not just the code
Most of this design is a set of promises, so the tests are written as promises. The crash test checks that nothing is lost. The noisy-neighbour test checks that one slow endpoint cannot hurt the others. A signing test uses the Standard Webhooks specification’s own test vector, so compatibility is checked against the standard rather than against my reading of it. Tests that need Postgres each create a throwaway database, so no test can see another’s rows, and the whole suite runs under Go’s race detector in CI.
Timing tests on shared CI machines taught me to be careful about what a failure means. The noisy-neighbour test first sent 180 healthy deliveries a second and failed intermittently in CI. The cause was not fairness. Under the race detector, the CI machine simply could not keep up with that load. The fix was to offer the healthy endpoints 90 a second, well under capacity, so the test measures fairness and nothing else. A flaky test that is retried until it passes teaches the team to ignore red builds, which costs more than the test is worth.
Keeping the developer side honest
Documentation drifts unless something fails when it does. The API is described by an OpenAPI 3.1 file, which the server also serves at /openapi.json. That file is the source of truth. Contract tests fail CI if a route, request field or response field differs between the spec, the server and the Go SDK. I considered generating the SDK from the spec. That keeps them in sync automatically, but generated Go clients tend to be awkward to read and use, so I wrote the SDK by hand on the standard library and let the contract tests do the syncing. A small CLI, webhookctl, is built on the SDK. For the “did we send it?” question, GET /v1/apps/{app}/messages lists an app’s messages newest first, and each message leads to its deliveries and every attempt. CI also runs the README’s quickstart block word for word on every push, so the first thing a new user tries cannot quietly break. It also runs govulncheck, which caught two advisories in a transitive dependency before the release. Each version tag builds and publishes the container image and a GitHub release, so running it is docker pull ghcr.io/rishirajpal01/webhook-delivery-platform:v1.0.0 plus a Postgres. The operations guide covers every setting and a short checklist for production: TLS in front, /metrics kept private, and enough shutdown grace for in-flight sends to finish.
What I would revisit
The biggest lesson was that most of the hard problems collapsed into one place, the claim query. Fairness, rate limits, the circuit breaker and crash recovery are not separate subsystems. They are conditions on which rows a dispatcher is allowed to take, and they hold across every replica because the database enforces them. That is the main thing a single Postgres buys you, and it is also the main thing to revisit at scale.
The claim’s cost also grows with the number of endpoints, because it looks at every active one: about 4 ms with 20 endpoints, but about 190 ms with 10,000 endpoints of which only 100 have work due. The first change I would make is to track which endpoints have due work, so a claim only looks at those. Next, I would benchmark with Postgres on its own machine to find the real write ceiling rather than a CPU-bound one. Beyond that ceiling, the attempt log is the natural thing to move out first, to an append-only store or batched inserts, because it is write-heavy and nothing reads it on the hot path.
On the product side, the obvious additions are an opt-in FIFO mode for receivers that really need order, accepting that a failing event then blocks its endpoint; per-tenant quotas so one customer’s send volume cannot fill the queue; and a small dashboard over the attempt log for the “did we send it?” question. Each of these is an addition to the same model rather than a new system, which is the property I most wanted to keep.
The code, design doc, crash test and benchmark script are all in the repository. docker compose up and the README quickstart produce a verified, signed delivery in under a minute.