An SMS webhook endpoint on serverless should do three things before it replies: read the raw body, verify the signature, and put the event on a queue. Then it returns a 2xx and lets a separate worker do everything slow. Keep the reply path short enough that a cold start and a timeout can't turn a good delivery into a retry.

This applies to inbound texts, delivery reports and opt-out notices alike. We make Ready, and our webhook setup lives in the API quickstart. Event names, payload fields and the signature scheme differ between providers, so the code below is generic. Wherever you see a field name, read it as "whatever your provider documents" and take the real names from their docs.

Why slow handlers cause duplicate events

Most SMS providers treat a webhook as delivered only when your endpoint answers 2xx within a short window. If you're late or you return an error, they retry. Your handler then sees the same event again, sometimes while the first run is still going.

On serverless that failure chain is easy to hit. A cold start adds latency before your code even runs. A database connection opened inside the handler adds more. A lookup, a CRM write or an outbound call to another service can push you past the timeout, and the platform kills the function before it replies. The provider records a failure and retries, and now two copies of the work are racing.

The cure isn't a faster database. It's moving work out of the reply path. If you want the full picture of what the statuses mean once they arrive, see our guide to SMS webhook delivery reports.

The fast path: what stays and what moves

Keep the reply path to the smallest set of steps that make the event safe to hold.

StepIn the request?Why
Read the raw bodyYesThe signature covers the exact bytes
Verify the signatureYesReject forged calls before you store anything
Write to a queueYesThis is the durable handoff
Return 2xxYesTells the provider you have it
Parse into your modelsNoCan fail, and the queue holds the original
Look up the contact or accountNoNetwork call, variable latency
Update the CRM, send alertsNoSlow and retryable
Send an auto-replyNoA second outbound call

The queue write is the only network dependency left, and a managed queue answers in tens of milliseconds. Everything else runs in a worker with its own timeout and retry policy.

A handler that acknowledges first

This sketch uses the standard Request and Response types, so it fits most serverless runtimes with small changes. The names SIGNATURE_HEADER, enqueue and the secret variable are placeholders. Replace them with what your provider and your queue actually use.

import { createHmac, timingSafeEqual } from 'node:crypto';

// Placeholder: use the header name and signing scheme in your provider's docs.
const SIGNATURE_HEADER = 'x-provider-signature';
const SECRET = process.env.WEBHOOK_SIGNING_SECRET;

function validSignature(rawBody, received) {
  if (!received) return false;
  const expected = createHmac('sha256', SECRET).update(rawBody).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(received);
  return a.length === b.length && timingSafeEqual(a, b);
}

export async function handler(request) {
  const rawBody = await request.text(); // raw bytes, before any JSON parsing

  if (!validSignature(rawBody, request.headers.get(SIGNATURE_HEADER))) {
    return new Response('invalid signature', { status: 401 });
  }

  try {
    await enqueue({ receivedAt: Date.now(), raw: rawBody });
  } catch (err) {
    console.error('enqueue failed', err);
    return new Response('try again', { status: 503 });
  }

  return new Response('ok', { status: 200 });
}

Two details matter. First, read the body as text and sign over that exact string. If you parse the JSON and re-serialize it, key order or whitespace changes and the signature check fails on valid calls. Second, the 503 on a failed enqueue is deliberate: if you couldn't store the event, you want the provider to retry, so don't claim success you can't back up.

Verify the signature the way your provider documents it

Different providers sign differently. Some use an HMAC over the body, some sign the timestamp plus the body, some use a public key. Follow your provider's documentation exactly, including how they encode the digest and which header carries it. Don't copy the HMAC above as if it were universal.

A few rules hold across schemes:

  • Compare with a constant-time function, as above, not ===.
  • If the scheme includes a timestamp, reject events outside a short tolerance, which blunts replays.
  • Keep the signing secret in your platform's secret store and rotate it if it leaks.
  • Reject first and cheaply. An unsigned call should cost you one HMAC and a 401, not a database read.

If your docs don't describe a signature at all, treat the endpoint as public. Put an unguessable token in the path and tighten what the worker will trust.

Cold starts and timeouts

You can't remove cold starts, but you can shrink their share of the budget.

Create clients outside the handler, so a warm instance reuses them. Import only what the handler needs, because a smaller bundle starts faster. Skip database drivers entirely in this function, since the only thing it talks to is the queue. And set the function's own timeout well under the provider's wait, so you fail with a clean 5xx instead of being cut off mid-response.

If your platform offers a minimum number of warm instances, it can help for an endpoint that takes steady traffic. For a bursty one, a fast, dependency-light handler matters more than warmth. Measure the p99 of the handler on a cold run before you decide.

Duplicates and order after the handoff

Fast acknowledgment trades one problem for two. Providers retry, and events can arrive in any order, so the worker has to cope with both.

Pick the event's unique id, whatever your provider calls it, and record it in a table with a unique constraint before you act. If the insert conflicts, you've seen it, so skip it. That makes redelivery harmless. For ordering, store a status rank or the provider's timestamp and never move a message backward, for example from delivered to sent. Our write-up on out-of-order events goes into the details.

When the worker fails

A queue only moves the failure, so plan for it. Give the worker a bounded number of retries with backoff, and send events that still fail to a dead letter queue with the raw body intact. Because you stored the original bytes, you can replay them after you fix the bug. Our guide to an SMS webhook dead letter queue and replay covers the replay side, including how to keep a replay from double-processing.

Alert on queue age and dead letter depth. Those two numbers tell you the pipeline is healthy even when every webhook is returning 200.

A short checklist

  • Reply 2xx only after the event is on a durable queue.
  • Verify the signature on the raw body, per your provider's docs.
  • Do no lookups, writes or outbound calls before the reply.
  • Return 5xx if the enqueue fails, 401 if the signature is wrong.
  • Deduplicate on the event id in the worker.
  • Keep the raw payload so you can replay it.

For error codes on the sending side, the errors reference is the place to look. A test key lets you exercise the whole path without real texts while you tune timeouts.