Guides

Webhook Engineering for SMS Delivery Receipts: Idempotency, Signature Verification, and Out-of-Order DLRs

Delivery receipts arrive duplicated, reordered, and occasionally forged. The listener architecture that turns a raw deliver_sm stream into an auditable, exactly-once billing and state pipeline.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Oct 15, 2026 β€’ 11 min read

A subscription fintech reconciled its billing ledger against SMS delivery receipts every night. One Tuesday, the pipeline marked 1.2 million messages delivered that had never reached a handset β€” and invoiced customers for them. The receipts themselves were genuine SMPP deliver_sm PDUs from the upstream. What broke was everything downstream of the socket: a duplicate-delivery burst after an upstream failover double-applied state transitions, a retry loop replayed old receipts with new timestamps, and the handler trusted every receipt as a first-ordered event. Nobody had built the pipeline to be wrong. So when the stream lied, the ledger believed it.

The question every backend team eventually faces: what does it take to turn a raw stream of delivery receipts into an auditable, exactly-once billing and state pipeline? The head fake is that the hard part is not receiving the webhook. Receipts arrive duplicated, reordered, and occasionally forged β€” and the state machine you build around them determines whether your DLR stream is a source of truth or a source of liability.

What does a delivery receipt actually contain?

Key Takeaway / Direct Answer

A receipt arrives as an SMPP deliver_sm (command_id 0x00000005) whose short_message body parses as id:… sub:… dlvrd:… submit date:… done date:… stat:… err:… text:. The stat field is the only terminal authority: DELIVRD, UNDELIV, EXPIRED, DELETED, REJECTD, UNKNOWN, or the non-terminal ENROUTE β€” and it must be processed as an idempotent event, never as an imperative.

The wire format is older than most of the teams consuming it. The GSM 03.40 receipt syntax was designed for store-and-forward debugging, not for driving financial ledgers, and it shows: field widths are padded, dates are local-time with no timezone, and the id in the receipt body is whatever identifier the terminating SMSC chose β€” which may or may not match the ID your gateway recorded at submission. Robust pipelines join on the gateway's own message ID first and treat the receipt's id field as a secondary key, because the day you bet on the carrier's ID convention is the day a partner swap renumbers everything.

stat value Terminal? Meaning Correct pipeline action
ENROUTE No Accepted by an intermediate SMSC Record; never bill; never notify
DELIVRD Yes Handset (or its VMSC) confirmed Bill once; emit delivered event
UNDELIV / EXPIRED Yes Failed after retry window Credit back; classify err code
REJECTD / DELETED Yes Filtered or cancelled upstream Credit back; alert compliance
UNKNOWN Ambiguous Carrier lost the state Hold in dispute bucket; do not auto-bill

The distinction between terminal and non-terminal is where most pipelines leak money. An ENROUTE receipt followed by a DELIVRD is the normal happy path β€” two events, one billing. But carriers also emit ENROUTE after terminal states when intermediaries replay their queues, and a naive handler that treats "latest receipt wins" will happily walk a delivered message back to in-flight. State in your pipeline must be monotonic: once terminal, never un-terminal.

How do you verify that a receipt is genuinely from your gateway?

Key Takeaway / Direct Answer

Sign every webhook with HMAC-SHA256 over the raw request body using a per-endpoint secret, embed a timestamp in the signed payload, and reject anything whose signature fails comparison or whose timestamp sits outside a 5-minute window. Verification must run on the raw bytes before JSON parsing, routing, or logging β€” the moment you re-serialize the body before hashing, you have built a signature that verifies your serializer, not the sender.

The timestamp half of that rule is what kills replay attacks. Without it, an attacker who captures one valid signed delivery receipt β€” from a proxy log, a misconfigured sidecar, or an unencrypted internal hop β€” can resubmit it forever, re-billing settled messages or re-triggering downstream side effects. With a bounded window and an idempotency key derived from message ID plus state, a captured receipt is worth exactly one replay, and that one replay is absorbed by the dedupe store.

dlr-webhook.mjs
Node.js 22 / HMAC + Idempotent Settlement
import { createHmac, timingSafeEqual } from "node:crypto";

const TERMINAL = new Set(["DELIVRD", "UNDELIV", "EXPIRED", "DELETED", "REJECTD"]);

export async function handleDlr(req, res) {
  const raw = await readRawBody(req);                 // bytes, before any parsing
  const ts = req.headers["x-smsroute-timestamp"];
  const sig = req.headers["x-smsroute-signature"];

  // 1. Freshness β€” bound replay to a 5-minute window
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) {
    return res.writeHead(401).end("stale timestamp");
  }

  // 2. Authenticity β€” HMAC over timestamp + "." + raw body, constant-time compare
  const expected = createHmac("sha256", process.env.DLR_WEBHOOK_SECRET)
    .update(`${ts}.`)
    .update(raw)
    .digest("hex");
  if (!safeEqual(sig, expected)) {
    return res.writeHead(401).end("bad signature");
  }

  const receipt = JSON.parse(raw);                    // safe: signature already bound these bytes
  const idempotencyKey = `${receipt.message_id}:${receipt.stat}`;

  // 3. Idempotency β€” the dedupe store absorbs replays and duplicate carrier bursts
  const firstSighting = await dedupe.setIfAbsent(idempotencyKey, { ts: Date.now() }, { ttlSec: 2_592_000 });
  if (!firstSighting) return res.writeHead(200).end("duplicate");

  // 4. Monotonic transition β€” terminal states never regress on late ENROUTE arrivals
  const current = await stateStore.get(receipt.message_id);
  if (current && TERMINAL.has(current.stat)) {
    if (!TERMINAL.has(receipt.stat)) return res.writeHead(200).end("ignored regression");
    if (TERMINAL.has(current.stat))  return res.writeHead(200).end("already settled");
  }
  await stateStore.put(receipt.message_id, receipt);

  // 5. Settle exactly once β€” billing and outbound events hang off the first terminal write
  if (TERMINAL.has(receipt.stat)) {
    await ledger.settleOnce(receipt.message_id, {
      status: receipt.stat,
      errCode: receipt.err,
      cost: receipt.stat === "DELIVRD" ? receipt.price : "0.00",
    });
    await events.emit("dlr.terminal", receipt);
  }

  res.writeHead(200).end("ok");                        // fast ack; heavy work already queued
}

function safeEqual(a, b) {
  const ab = Buffer.from(a || "", "hex");
  const bb = Buffer.from(b, "hex");
  return ab.length === bb.length && timingSafeEqual(ab, bb);
}

Five lines carry disproportionate weight. Reading the raw body before parsing keeps the signature honest. The 300-second timestamp bound converts captured traffic into expired traffic. setIfAbsent collapses the duplicate bursts that upstream failovers produce β€” carriers re-transmit whole receipt queues after maintenance windows, and these bursts arrive hundreds per second precisely when your infrastructure is already stressed. The monotonic guard stops late ENROUTE replays from de-settling delivered messages. And settleOnce makes the ledger idempotent at the storage layer, not merely in application code β€” because application code gets redeployed.

How do out-of-order receipts break naive state machines?

Key Takeaway / Direct Answer

SMPP gives you ordering per TCP connection, not per message across the delivery chain β€” receipts traverse different SMSC hops, intermediary retries, and failover paths than the original submission. Model state as a monotonic lattice, not a timeline: every terminal state dominates every non-terminal state, two conflicting terminal states resolve by first-writer-wins with audit retention, and receipt timestamps are evidence, never ordering. The invariant to test is simple: no sequence of input receipts may move a message from settled back to pending.

The failure mode hides well in staging, where single-hop test routes deliver receipts in submission order and every integration test passes. Production corridors are multi-hop: a message may route through an aggregator's primary SMSC, fail over to a secondary during congestion, and receive its terminal receipt from a system that never saw the first ENROUTE. The receipts interleave arbitrarily at your endpoint, and wall-clock timestamps make it worse β€” carriers stamp in local time, NTP drift across partners is routine, and a "later" receipt can carry an earlier timestamp.

The engineering response is to stop treating the stream as ordered and start treating every handler invocation as a convergence step: read current state, compute the join-semilattice merge, write if changed, emit side effects only on change. Combined with per-endpoint secrets, bounded replay windows, and a dispute bucket for UNKNOWN outcomes, this architecture turns the DLR stream into something you can defend in a billing dispute: a monotonic, signed, deduplicated audit trail. The signature-verification pattern and full receipt field semantics are covered in depth in our DLR webhook security guide, and the routing-side detection of fabricated receipts lives in sub-second OTP routing architecture.

How do you monitor receipt health without drowning in dashboards?

Four derived metrics cover nearly every failure mode worth waking up for. Receipt latency β€” submission to terminal-state β€” tracked as P50/P95 per corridor: a rising P95 with flat P50 usually means one intermediate SMSC is queueing. Duplicate ratio β€” replays absorbed by the dedupe store divided by total receipts: a spike predicts an upstream failover event before your delivery numbers move. Terminal-state distribution β€” the DELIVRD/UNDELIV/EXPIRED/REJECTD mix per route: a sudden UNDELIV jump with flat latency is the signature of a carrier-side filtering change, not an infrastructure fault. Orphan receipts β€” receipts whose message ID matches nothing in your submission store: a non-zero, steady orphan rate means ID mapping is broken somewhere in the chain, and every orphan is an audit finding waiting to surface.

Alert on rate-of-change, not absolute values. Every corridor has a baseline failure rate β€” handsets off, full inboxes, dead prepaid accounts β€” and static thresholds either cry wolf at the baseline or fire too late during an incident. A paged alert should mean "this metric moved three standard deviations from its own seven-day window," which catches both the slow drift of a degrading route and the step-function of a filtering change, without training the team to ignore notifications.

Should the webhook return 200 before processing finishes?

Yes β€” verify, dedupe, and enqueue, then acknowledge within milliseconds. Long-running handlers collide with carrier retry timers (often 30 seconds or less) and cause the duplicate deliveries you were trying to avoid. Heavy settlement work belongs in a consumer of your own queue, not in the request path.

How long should dedupe state be retained?

At least as long as your maximum validity period plus carrier retry horizon β€” 30 days covers the overwhelming majority of corridors; 90 days if you send with long validity windows. Storage is cheap; a duplicate settlement discovered by a customer six weeks later is not.

What if the provider does not support signed webhooks?

Move verification to the transport: mTLS or IP allowlisting at the load balancer, plus mandatory timestamp headers you inject at the edge. It is weaker than payload signatures β€” a compromised upstream can forge receipts either way β€” but it still eliminates off-path replay, which is the majority of real-world webhook abuse.

Audit your own pipeline against the five-step handler above: raw-body signature, 5-minute window, idempotency key, monotonic guard, settle-once ledger. Any step you cannot check off is a billing incident waiting for its Tuesday. SMSRoute signs every delivery receipt webhook with HMAC-SHA256 and exposes terminal states as first-class API events β€” see /developers for the payload schema, /prices for per-segment costs, and /signup to start sending with email only.

JH

Jacky Hossein

Verified Author

Principal Telecommunications & Cryptographic Systems Architect at SMSRoute. Specializes in carrier-grade SS7/SMPP routing protocols, non-custodial cryptocurrency billing rails, and zero-knowledge telecommunications privacy.