Receive webhooks
Build one endpoint that verifies, acknowledges and deduplicates Kausate's order results and monitor events, and recovers the ones it missed.
Kausate sends two kinds of payload to every active webhook of your organization: the result of each asynchronous order, and each event your monitors record. One endpoint can handle both. This page builds that endpoint. How to create a webhook, choose its payload version and rotate its secret is on the Webhooks reference.
What arrives
Every delivery is an HTTP POST with a JSON body and the
signed delivery headers.
Tell the two payloads apart by the body:
| Payload | How to recognize it | Keys | Example |
|---|---|---|---|
| Order result | has an orderId | camelCase | the order's GET response, such as Get Company Report Result |
| Monitor event | "event": "monitor.change_detected" | snake_case | Receive events |
An order result has the same shape as the order's response at the endpoint's
payload version. A monitor
event has the same shape in every API version, and its keys are snake_case
(event_id, monitor_id), unlike the API's camelCase responses.
A complete receiver
A receiver does four things, in this order:
- Read the raw body exactly as it arrived.
- Verify the signature over those bytes, and answer
401when it fails. - Store the delivery once, under its
Kausate-Webhook-Id. - Answer
2xxat once, and do the work later, outside the request.
Both receivers below do exactly that, using the verification functions from
the next section, saved beside them as verify.py or
verify.ts. They keep deliveries in a SQLite table so they run as they are;
use your own database or queue in production. Both are tested against
deliveries the Kausate sender signed.
import os
import sqlite3
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
from verify import verify_kausate_webhook
SIGNING_SECRET = os.environ["KAUSATE_WEBHOOK_SECRET"]
inbox = sqlite3.connect("kausate-inbox.db", check_same_thread=False)
inbox.execute(
"CREATE TABLE IF NOT EXISTS deliveries (webhook_id TEXT PRIMARY KEY, body BLOB NOT NULL)"
)
async def receive_kausate_webhook(request: Request) -> Response:
raw_body = await request.body()
if not verify_kausate_webhook(raw_body, request.headers, SIGNING_SECRET):
return Response(status_code=401)
# A retry repeats the webhook ID: keep the first copy, answer every copy.
with inbox:
inbox.execute(
"INSERT OR IGNORE INTO deliveries (webhook_id, body) VALUES (?, ?)",
(request.headers["Kausate-Webhook-Id"], raw_body),
)
# Process stored deliveries in the background, not before answering.
return Response(status_code=204)
app = Starlette(routes=[Route("/webhooks/kausate", receive_kausate_webhook, methods=["POST"])])import { DatabaseSync } from "node:sqlite";
import { verifyKausateWebhook } from "./verify";
function signingSecret(): string {
const secret = process.env.KAUSATE_WEBHOOK_SECRET;
if (!secret) throw new Error("Set KAUSATE_WEBHOOK_SECRET");
return secret;
}
const inbox = new DatabaseSync("kausate-inbox.db");
inbox.exec(
"CREATE TABLE IF NOT EXISTS deliveries (webhook_id TEXT PRIMARY KEY, body BLOB NOT NULL)",
);
const keepFirstCopy = inbox.prepare(
"INSERT OR IGNORE INTO deliveries (webhook_id, body) VALUES (?, ?)",
);
// A Next.js route handler: app/webhooks/kausate/route.ts
export async function POST(request: Request): Promise<Response> {
const rawBody = new Uint8Array(await request.arrayBuffer());
if (!verifyKausateWebhook(rawBody, request.headers, signingSecret())) {
return new Response(null, { status: 401 });
}
// A retry repeats the webhook ID: keep the first copy, answer every copy.
keepFirstCopy.run(request.headers.get("Kausate-Webhook-Id"), rawBody);
// Process stored deliveries in the background, not before answering.
return new Response(null, { status: 204 });
}The receiver must see the body before anything parses it. In other frameworks:
| Framework | Raw body |
|---|---|
| Starlette | await request.body() |
| Flask | request.get_data() |
| Django | request.body |
| Next.js, fetch API | await request.arrayBuffer() or await request.text() |
| Express | express.raw({ type: "application/json" }) on the route, then req.body |
Middleware that decodes JSON first, such as express.json(), or a call to
request.json() before verifying, consumes or reformats the body. A signature
checked over re-serialized JSON never matches.
Verify the signature
Verify every request before reading the payload:
- Read the raw request body as bytes. Do not re-serialize parsed JSON.
- Read
Kausate-Webhook-Id,Kausate-Webhook-Timestamp, andKausate-Webhook-Signature. Header names are case-insensitive: Node, AWS Lambda and many proxies pass them on in lower case. - Reject timestamps outside your allowed clock-skew window. Five minutes is a reasonable default.
- Remove the
kwhsec_prefix fromsigningSecretand base64-decode the remainder. - Build the signed bytes as
<id>.<timestamp>.<raw-request-body>. - Calculate HMAC-SHA256, then compare it with each base64-decoded
v1signature using a constant-time comparison. Accept the delivery when any one matches.
Both functions are tested against deliveries signed by Kausate, including the
two signatures sent while a secret is
rotated. A malformed
signingSecret raises an error instead of rejecting every delivery.
import base64
import hashlib
import hmac
import time
from collections.abc import Mapping
SIGNING_SECRET_PREFIX = "kwhsec_"
def verify_kausate_webhook(
raw_body: bytes,
headers: Mapping[str, str],
signing_secret: str,
*,
tolerance_seconds: int = 300,
) -> bool:
"""Return True when a delivery was signed by Kausate within the tolerance.
`headers` may use any capitalisation: frameworks and gateways differ in
whether they pass on `Kausate-Webhook-Id` or `kausate-webhook-id`.
"""
invalid_secret = f"The signing secret must be {SIGNING_SECRET_PREFIX!r} followed by base64"
if not signing_secret.startswith(SIGNING_SECRET_PREFIX):
raise ValueError(invalid_secret)
try:
secret = base64.b64decode(signing_secret.removeprefix(SIGNING_SECRET_PREFIX), validate=True)
except ValueError:
raise ValueError(invalid_secret) from None
if not secret:
raise ValueError(invalid_secret)
lowered = {name.lower(): value for name, value in headers.items()}
message_id = lowered.get("kausate-webhook-id")
timestamp = lowered.get("kausate-webhook-timestamp")
signatures = lowered.get("kausate-webhook-signature")
if not message_id or not timestamp or not signatures:
return False
# Unix seconds; a longer value is not a timestamp (and int() rejects
# strings past 4300 digits).
if not (timestamp.isascii() and timestamp.isdigit()) or len(timestamp) > 12:
return False
if abs(time.time() - int(timestamp)) > tolerance_seconds:
return False
signed_content = f"{message_id}.{timestamp}.".encode() + raw_body
expected = hmac.new(secret, signed_content, hashlib.sha256).digest()
# During a secret rotation the header carries one signature per secret.
for signature in signatures.split():
version, _, encoded = signature.partition(",")
if version != "v1":
continue
try:
provided = base64.b64decode(encoded, validate=True)
except ValueError: # binascii.Error, or non-ASCII input
continue
if hmac.compare_digest(expected, provided):
return True
return Falseimport { createHmac, timingSafeEqual } from "node:crypto";
const SIGNING_SECRET_PREFIX = "kwhsec_";
const CANONICAL_BASE64 =
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/;
/** A fetch `Headers` object, or a plain object such as Node's `req.headers`. */
type IncomingHeaders = Headers | Record<string, string | string[] | undefined>;
// Header names are case-insensitive: Node and many gateways lower-case them.
function header(headers: IncomingHeaders, name: string): string | undefined {
if (headers instanceof Headers) return headers.get(name) ?? undefined;
const wanted = name.toLowerCase();
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase() === wanted && typeof value === "string") {
return value;
}
}
return undefined;
}
/**
* Return true when a delivery was signed by Kausate within the tolerance.
* Pass the raw request body exactly as received, never re-serialized JSON.
*/
export function verifyKausateWebhook(
rawBody: string | Uint8Array,
headers: IncomingHeaders,
signingSecret: string,
toleranceSeconds = 300,
): boolean {
const encodedSecret = signingSecret.slice(SIGNING_SECRET_PREFIX.length);
if (
!signingSecret.startsWith(SIGNING_SECRET_PREFIX) ||
!CANONICAL_BASE64.test(encodedSecret)
) {
throw new Error(
`The signing secret must be "${SIGNING_SECRET_PREFIX}" followed by base64`,
);
}
const secret = Buffer.from(encodedSecret, "base64");
const messageId = header(headers, "Kausate-Webhook-Id");
const timestamp = header(headers, "Kausate-Webhook-Timestamp");
const signatures = header(headers, "Kausate-Webhook-Signature");
if (!messageId || !timestamp || !signatures) return false;
if (!/^\d{1,12}$/.test(timestamp)) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) {
return false;
}
const expected = createHmac("sha256", secret)
.update(`${messageId}.${timestamp}.`)
.update(rawBody)
.digest();
// During a secret rotation the header carries one signature per secret.
return signatures.split(/\s+/).some((signature) => {
const [version, encoded] = signature.split(",", 2);
if (version !== "v1" || !encoded) return false;
const provided = Buffer.from(encoded, "base64");
return (
provided.length === expected.length && timingSafeEqual(provided, expected)
);
});
}Each webhook has its own signing secret. When several webhooks point at the same URL, check the request against each of their secrets.
Test your verifier
This delivery is a real monitor.change_detected request from the
sandbox, signed again with this example secret:
kwhsec_fqDdBVNCDiDyGl3JoxQDe/uL7vZ7hRQj4Zqoa8AxDh8=Your verifier must accept it while its clock reads the
Kausate-Webhook-Timestamp, and reject it once a single byte of the body
changes:
POST /kausate/webhooks HTTP/1.1
Content-Type: application/json
Kausate-Version: 2026-08-01
Kausate-Webhook-Id: msg_2Yb7kQx9VdN4
Kausate-Webhook-Timestamp: 1795269600
Kausate-Webhook-Signature: v1,pSvB5M4jHL+Qo0zALK1TqrPDuPGZ/vrQ/yw1DM8cShU=
{"event":"monitor.change_detected","monitor_id":"00000000-0000-4000-8000-000000000002","kausate_id":"co_zz_4O3wnpE5u1K5AXnkARuhp","event_id":"00000000-0000-4000-8000-000000000003","event_code":"REGISTERED_ADDRESS_CHANGED","category":"address","severity":"info","detected_at":"2026-11-21T14:00:00+00:00","before":[{"type":"registered","source":"zz-sandbox","original":"Dradenaustraße 33, 21129 Hamburg, Germany","coordinate":null,"normalized":null,"normalizationMode":"enrich"}],"after":[{"type":"registered","source":"zz-sandbox","original":"Am Sandtorkai 12, 20457 Hamburg, Germany","coordinate":null,"normalized":null,"normalizationMode":"enrich"}],"diff_path":"companyReport.basicInformation.addresses","metadata":{"caseId":"CASE-12345","api_url":"https://api.kausate.com/v2/monitors/00000000-0000-4000-8000-000000000002/events/00000000-0000-4000-8000-000000000003"}}As a second layer, not your only control, you can also allow only Kausate's outbound IP addresses.
Acknowledge quickly
Any 2xx response completes a delivery. Everything else is a failed attempt
and is retried: 3xx, 4xx and 5xx responses, network errors, and requests
that take longer than the request timeout in
the retry schedules. A Retry-After header does not change the
schedule.
Answer as soon as the delivery is stored. Work that calls other systems, such as downloading a document or ordering a fresh report, belongs in a background job: an endpoint that does it inside the request risks a timeout, and a timed-out delivery is sent again.
A 401 for a bad signature is retried like any other failure, so deliveries
signed while your receiver had the wrong secret still arrive once you fix it,
as long as attempts remain.
Deduplicate on the webhook ID
Delivery is at least once: the same delivery can arrive more than once, for
example when your 2xx answer is lost on the way back. Deduplicate on
Kausate-Webhook-Id, after the signature check succeeds:
- Retries of a delivery keep its
Kausate-Webhook-Id. Each attempt gets a freshKausate-Webhook-Timestampand signature, so compare the ID, not the whole request. - A delivery you ask for gets a new
Kausate-Webhook-Id: a replayed monitor event, an order result resent from the dashboard, and the result of a repeated order answered with an earlier result ("cachedOrder": true, carrying the repeat request'scustomerReferenceandmetadata). Process these: they are new deliveries, not duplicates.
When your own records exist once per order or per event, write them keyed on
the orderId or event_id in the body, so that a replay or resend updates the
record instead of adding a second one.
Retries
A failed delivery is retried with exponential backoff, up to the endpoint's attempt limit. Which schedule applies depends on how the delivery started.
Results of orders placed through the API, including a result resent from the dashboard and a repeated order answered with an earlier result:
| Setting | Value |
|---|---|
| Attempts | 10 by default: the first request and 9 retries. maxAttempts can be 1 or 10 |
| First retry | 10 min after the first failed request |
| Later retries | Each wait is 2× the one before, at most 12 h |
| Waits with 10 attempts | 10 min, 20 min, 40 min, 1 h 20 min, 2 h 40 min, 5 h 20 min, 10 h 40 min, 12 h, 12 h |
| Waits in total | 45 h 10 min |
| Deadline | 48 h after the delivery starts, even if attempts remain |
| Request timeout | 30 s per attempt |
Monitor events, and results of orders placed in the dashboard:
| Setting | Value |
|---|---|
| Attempts | 10 by default: the first request and 9 retries. maxAttempts can be 1 or 10 |
| First retry | 1 s after the first failed request |
| Later retries | Each wait is 2× the one before, at most 4 h |
| Waits with 10 attempts | 1 s, 2 s, 4 s, 8 s, 16 s, 32 s, 1 min 4 s, 2 min 8 s, 4 min 16 s |
| Waits in total | 8 min 31 s |
| Request timeout | 30 s per attempt |
The waits do not include the time each attempt takes. A delivery keeps the attempt limit it started with; a change to the webhook applies to new deliveries. Retries to a webhook stop once you delete it.
For a development endpoint that is often down, set Delivery attempts to
One attempt (for development) in the dashboard, or maxAttempts to 1
through the webhook API: each delivery
then makes one request with no retries.
When the attempts or the deadline run out, the delivery is abandoned. The order result or event is not lost.
Recover missed deliveries
Monitor events. Every event stays queryable. List a monitor's events since your last delivery and replay the ones you missed, as described in Event history and replay.
Order results. Fetch the result again with the order's GET endpoint and
its orderId, for example
Get Company Report Result,
or resend the delivery with Resend Webhooks on the order in the dashboard's
logs.
Test the receiver
- Order results. Place an order on a Sandbox company: its result is delivered like any other.
- Monitor events. Sandbox companies change on every check and may be checked as often as hourly, so a monitor on one exercises event handling, retries and replay on demand.
- A failing endpoint. Answer
500once and watch the retry arrive with the sameKausate-Webhook-Idand a new timestamp.
Troubleshooting
Every delivery fails the signature check
- The body was parsed before it was verified. Verify the raw bytes, see the table of frameworks.
- The secret belongs to another webhook. Each webhook has its own.
- The server's clock is off by more than your tolerance. Sync it with NTP.
The same delivery arrives twice
Expected: delivery is at least once.
Deduplicate on Kausate-Webhook-Id.
Nothing arrives
Check that the webhook is active with
GET /v2/webhooks, and that your
endpoint answers 2xx in time. For monitor events, work through
My webhook is not firing.
Last updated on