Skip to main content
Tutorial

A webhook receiver that survives retries

Build a mailkube webhook receiver in Node, Python and Go that verifies signed bounce events and acts on each one exactly once, from a Redis queue.

mailkube 8 min read Updated November 30, 2026
webhookssdk

mailkube delivers email.bounced to POST /webhooks/mailkube

  1. 1 Attempt 1 No answer in 10 s
    X-Webhook-Id
    same on every attempt
    X-Webhook-Ts
    2026-11-30T17:42:09Z

    Handler queued the event, then the response was lost.

  2. 2 Attempt 2 500
    X-Webhook-Id
    same on every attempt
    X-Webhook-Ts
    2026-11-30T17:44:19Z

    Redis was restarting, so the push failed and nothing was queued.

  3. 3 Attempt 3 204
    X-Webhook-Id
    same on every attempt
    X-Webhook-Ts
    2026-11-30T17:48:19Z

    Verified, queued, answered. Delivery done.

Worker, reading mailkube:events

  • 1email.bouncedtaylor@example.comHandled
  • 3email.bouncedtaylor@example.comSeen, skipped

Your database

taylor@example.com marked undeliverable

550 5.1.1 user unknown

1 update

Three attempts, one delivery id, one side effect. Addresses and identifiers are examples.

mailkube has no endpoint that tells you a message bounced. The REST API sends; outcomes come back only as webhook events, POSTed to your server. If your receiver drops an email.bounced, your app keeps mailing a dead address, and every later send to it is accepted, counted against your quota and never delivered. This post builds a webhook receiver in Node, Python and Go that verifies each event, queues it within the 10-second budget, and lets a worker mark the address bounced exactly once, however many times mailkube retries.

Prerequisites

  • An active sending domain. Last week’s post, Send your first email with Cloudflare Auto Setup, gets you one.
  • A public https:// URL for the endpoint. Private, loopback and link-local addresses are rejected, so local development needs a tunnel.
  • Redis, for the queue and the deduplication keys.
  • Node 22.12 or later, Python 3.12 or later, or Go 1.23 or later.

What mailkube sends, and what it does with your answer

Every delivery is a POST with the event as JSON and three headers:

HeaderValue
X-Webhook-Sigsha256=<hex>, an HMAC-SHA256 over {id}.{ts}.{raw body} with your endpoint’s signing secret
X-Webhook-TsISO 8601 time of this attempt, fresh on every retry
X-Webhook-IdThe delivery id, the same on every retry of the same event

The response status is the only thing mailkube reads. It ignores your body and never follows a redirect.

Your answerWhat mailkube does
2xx within 10 secondsDelivery done
3xx, 4xx, 5xxFailed attempt, retried
No answer in 10 seconds, TLS error, refused connectionFailed attempt, retried
Payload over 64 KBDropped, never retried

The first retry waits two minutes and every wait after that doubles, up to 48 hours, for 15 attempts in total. Add those waits up and the last attempt lands about 8 days and 20 hours after the first. That is how long a delivery id has to stay in your deduplication store; the code below keeps it for 10 days.

An endpoint that keeps failing its first attempt is also disabled automatically, with a “Low quality” reason in the dashboard. A slow handler costs you more than retries.

Deduplicate in the worker, not at the door

The common advice is to check X-Webhook-Id in the HTTP handler and return early on a repeat. Follow it and one failure loses the event. The handler records the id, the push to your queue fails, the handler answers 500, mailkube retries two minutes later, and the retry is turned away as a duplicate it never was.

So the handler here does three things only: echo the one-time challenge, verify the signature over the raw bytes, and push id + body onto a list. The worker that changes your database is the one that checks the id. The cost is a few extra queue entries when a 2xx gets lost on the way back, which is rare and harmless.

Check the door with curl

When you add the endpoint in the dashboard, mailkube sends one GET with a challenge and expects the token back, with a 200, within 5 seconds. The endpoint is not created otherwise, so the receiver has to be running and reachable before you submit the form. Check both paths from a terminal first:

# The challenge: the body must be exactly the token
curl -i "https://hooks.example.com/webhooks/mailkube?hub.mode=subscribe&hub.challenge=4f2c9a71"

# An unsigned delivery must be refused
curl -i -X POST https://hooks.example.com/webhooks/mailkube \
  -H "Content-Type: application/json" \
  -d '{"type":"email.bounced"}'

The first should answer 200 with 4f2c9a71 as the whole body. The second should answer 400 from the Node and Python receivers below, and 401 from the Go one.

The webhook receiver in Node

// npm install express redis @mailkube/mailkube-node   (Express 5)
import express from "express";
import { createClient } from "redis";
import { verify, SignatureVerificationError } from "@mailkube/mailkube-node";

const redis = await createClient().connect();
const app = express();

app.get("/webhooks/mailkube", (req, res) => {
  if (req.query["hub.mode"] !== "subscribe") return res.sendStatus(400);
  res.type("text/plain").send(req.query["hub.challenge"]);
});

app.post("/webhooks/mailkube", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    await verify(req.body, req.headers, process.env.MAILKUBE_WEBHOOK_SECRET);
  } catch (error) {
    if (error instanceof SignatureVerificationError) return res.sendStatus(400);
    throw error;
  }
  const id = req.get("X-Webhook-Id");
  await redis.lPush("mailkube:events", Buffer.concat([Buffer.from(`${id}\n`), req.body]));
  res.sendStatus(204);
});

app.listen(3000);

express.raw() is the line that matters. With express.json() the raw bytes are gone, and a re-serialized object never matches the signature. verify is async because the SDK uses crypto.subtle, which is also why the SDK runs unchanged on Workers and Bun. It rejects a delivery whose X-Webhook-Ts is more than 300 seconds old, which is what stops a captured request from being replayed later.

The receiver in Python

# pip install flask redis mailkube
import os

import redis
from flask import Flask, request
from mailkube import SignatureVerificationError, verify

app = Flask(__name__)
r = redis.Redis()
SECRET = os.environ["MAILKUBE_WEBHOOK_SECRET"]


@app.get("/webhooks/mailkube")
def challenge():
    if request.args.get("hub.mode") != "subscribe":
        return "", 400
    return request.args.get("hub.challenge", ""), 200


@app.post("/webhooks/mailkube")
def receive():
    body = request.get_data()
    try:
        verify(body, dict(request.headers), SECRET)
    except SignatureVerificationError:
        return "", 400
    r.lpush("mailkube:events", request.headers["X-Webhook-Id"].encode() + b"\n" + body)
    return "", 204

request.get_data() is the raw body; request.json is not. The 300-second window is the tolerance_seconds= keyword on verify if your clocks need slack.

The receiver in Go

// go get github.com/mailkube/mailkube-go github.com/redis/go-redis/v9
package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"github.com/mailkube/mailkube-go"
	"github.com/redis/go-redis/v9"
)

func main() {
	rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})

	handler := mailkube.WebhookHandler{
		Secret:       os.Getenv("MAILKUBE_WEBHOOK_SECRET"),
		MaxBodyBytes: 64 << 10, // mailkube never sends more than 64 KB
		OnEvent: func(ctx context.Context, event *mailkube.Event) error {
			item := append([]byte(event.ID+"\n"), event.Raw...)
			return rdb.LPush(ctx, "mailkube:events", item).Err()
		},
	}

	http.Handle("/webhooks/mailkube", handler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Go needs no GET route of its own: WebhookHandler answers the challenge when it is mounted for both methods, which http.Handle does. event.ID is the X-Webhook-Id, and event.Raw is the body exactly as it arrived. Returning the Redis error from OnEvent makes the handler answer 500, so a failed push becomes a retry. Otherwise it answers 204, and a bad signature gets 401.

The worker, once

The worker is where the id gets checked. It is shown in Python; the three Redis calls (BRPOP, SET NX EX, DEL) exist under those names in every client.

import redis
from mailkube import parse_event

r = redis.Redis()
TEN_DAYS = 10 * 24 * 3600  # the last retry can land 8 days 20 hours after the first


def handle(event):
    if event.type == "email.bounced":
        mark_undeliverable(event.data.bounce.recipient, event.data.bounce.reason)
    elif event.type == "email.suppressed":
        for address in event.data.suppression.recipients:
            mark_undeliverable(address, "suppressed")


while True:
    _, item = r.brpop("mailkube:events")
    delivery_id, _, body = item.partition(b"\n")
    seen = b"mailkube:seen:" + delivery_id
    if not r.set(seen, 1, nx=True, ex=TEN_DAYS):
        continue  # this delivery was already handled
    try:
        handle(parse_event(body))
    except Exception:
        r.delete(seen)
        r.lpush("mailkube:events:failed", item)

parse_event parses bytes that were already verified, so the worker never needs the signing secret. email.bounced only fires on a permanent failure; a deferral, such as a greylisting server, arrives as email.delivery_delayed and should not touch the address. email.suppressed is the other case worth handling: mailkube accepted the send, counted it, and dropped it because the address bounced before, and data.suppression.recipients lists who.

Prove the retries are harmless

The CLI can post a correctly signed synthetic event at your local handler, with no real send and no quota spent:

mailkube webhooks simulate --event email.bounced --url http://localhost:3000/webhooks/mailkube

To watch real deliveries, run mailkube webhooks listen --public-url <your tunnel> --forward http://localhost:3000/webhooks/mailkube --forward-duplicates. The last flag forwards redeliveries too, so the worker’s continue branch gets exercised by mailkube itself. Point it at a test domain: an event type goes to one endpoint per domain, and subscribing your laptop takes it away from production for as long as it stays subscribed.

Troubleshooting

SymptomCauseFix
The dashboard will not save the endpointThe challenge did not come back as a 200 with the exact token within 5 seconds: wrong body, a redirect, a TLS error, or the receiver was not running yetStart the receiver first, then run the curl check above against the public URL
Every delivery gets 400 from your own handler (401 in Go)The body was parsed before verifying (express.json(), request.json), or the secret is stale after a rollVerify express.raw() bytes or request.get_data(); after rolling, deploy the new secret, since the old one stops working immediately
The endpoint shows “Low quality” and receives nothingToo many first attempts failed or took longer than 10 secondsFix the handler, then toggle Active back on; the rate starts again from a clean slate
Production stopped getting email.bouncedA test endpoint on the same domain subscribed to itRemove the event from the test endpoint and add it back on production; events in flight are not redelivered

Where to go next

Bounced addresses now land in your database once each. Next week’s post routes Keycloak’s password-reset and verification emails through mailkube over SMTP, so those bounces reach this same receiver. The Webhooks(opens in a new tab) page has every event payload, including email.delivery_delayed and the domain.status lifecycle event.

Three steps to your first send

Create an account, verify a domain, and send your first message today.

Get started