← Blog

·

Serverless WhatsApp webhook on AWS Lambda, Cloudflare Workers and Vercel

Updated on October 29, 2026

You can run the WhatsApp Business API webhook on serverless functions such as AWS Lambda, and for many projects it is the cheapest and simplest option to maintain. The rule is the same on every platform: validate the X-Hub-Signature-256 signature, write the event to a queue and return 200 right away, leaving the processing to another function. This guide covers the pros and cons and shows a short example for Cloudflare Workers, AWS Lambda and Vercel.

The examples use JavaScript, since all three platforms run it. The verification and signature logic is the same one explained in our tutorials on building a bot with Node.js and validating the webhook signature.

Serverless for webhooks: pros and cons

A WhatsApp webhook receives traffic in bursts: nothing overnight, spikes after a campaign. That profile fits serverless well, but there are pitfalls.

AspectProCon
CostYou pay per invocation; low traffic costs littleAt high, steady volume, a server may be cheaper
ScalingCampaign spikes are absorbed with no configurationMany concurrent instances can exceed your database’s connection limit
Cold startWorkers uses isolates, with fast startupOn Lambda and Vercel, the first request after idle time is slower
Execution timeEnough to validate and enqueueEach platform has a limit; background tasks after the response are limited or cancelled
StateNothing to manageThere is no shared memory: deduplication needs external storage
HTTPSValid certificate includedThe URL can change between environments; pin a custom domain

Execution time is the factor that matters most. Meta’s documentation says that deliveries without a 200 are retried immediately and then a few more times, with decreasing frequency, for up to 7 days. It does not set a maximum response time, but a slow webhook increases the chance of a retry. If the function calls an AI model, a database and the send API before responding, it becomes slow and expensive. If it responds first and tries to keep going in the background, the platform may kill the work halfway through.

The pattern: validate, enqueue, respond

The design that works on all three platforms has two functions:

  1. Receiver (HTTP). Answers the verification GET. On POST, reads the raw body, validates the HMAC, sends the event to a queue and returns 200.
  2. Consumer (queue). Reads the events, discards the ones already processed, decides on the reply and calls the messages API.

The receiver does very little and finishes in milliseconds. The consumer can take its time, fail and be re-run by the queue without Meta noticing. Since Meta may resend the same event, the consumer must be idempotent: store the id of each message (the wamid) in storage that supports conditional writes and ignore repeats.

Three details apply to every example:

  • Raw body. The HMAC is computed over the bytes received. Read the body as text or a buffer before any JSON.parse.
  • Safe comparison. Use a constant-time comparison function (crypto.subtle.verify or timingSafeEqual).
  • Batches. Meta may group up to 1,000 updates into a single POST, with no guarantee of grouping. Your code must handle an entry with several changes and several messages.

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

Cloudflare Workers + Queues

In Workers, the handler receives a standard Request. The Web Crypto API is available, and crypto.subtle.verify already compares in constant time. The producer sends to a Queue and the consumer is the queue function of the same Worker (or another one).

export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    if (request.method === "GET") {
      const p = url.searchParams;
      if (p.get("hub.mode") === "subscribe" && p.get("hub.verify_token") === env.VERIFY_TOKEN) {
        return new Response(p.get("hub.challenge"), { status: 200 });
      }
      return new Response("forbidden", { status: 403 });
    }

    const body = await request.arrayBuffer();
    if (!(await validSignature(env.APP_SECRET, body, request.headers.get("x-hub-signature-256")))) {
      return new Response("invalid signature", { status: 401 });
    }
    await env.WHATSAPP_QUEUE.send(JSON.parse(new TextDecoder().decode(body)));
    return new Response("ok", { status: 200 });
  },

  async queue(batch, env) {
    for (const msg of batch.messages) {
      try {
        await handleEvent(msg.body, env); // your logic: dedupe + reply
        msg.ack();
      } catch (err) {
        console.error(err);
        msg.retry({ delaySeconds: 30 });
      }
    }
  },
};

async function validSignature(secret, body, header) {
  if (!header?.startsWith("sha256=")) return false;
  const hex = header.slice(7);
  if (!/^[0-9a-f]{64}$/i.test(hex)) return false;
  const sig = new Uint8Array(hex.match(/../g).map((h) => parseInt(h, 16)));
  const key = await crypto.subtle.importKey(
    "raw", new TextEncoder().encode(secret),
    { name: "HMAC", hash: "SHA-256" }, false, ["verify"]
  );
  return crypto.subtle.verify("HMAC", key, sig, body);
}

The wrangler.jsonc configuration binds the queue as both producer and consumer:

{
  "name": "whatsapp-webhook",
  "main": "src/index.js",
  "queues": {
    "producers": [{ "queue": "whatsapp-events", "binding": "WHATSAPP_QUEUE" }],
    "consumers": [{ "queue": "whatsapp-events", "max_batch_size": 10, "max_retries": 5, "dead_letter_queue": "whatsapp-events-dlq" }]
  }
}

Secrets go in with wrangler secret put APP_SECRET (and the same for VERIFY_TOKEN and the API token). Limits to know, according to Cloudflare’s documentation:

  • Each Queue message must be smaller than 128 KB. A POST carrying a large batch from Meta can exceed that; in that case, enqueue each change separately with sendBatch.
  • ctx.waitUntil() keeps the Worker alive for at most 30 seconds after the response. It is meant for logs and metrics, not for processing the conversation.
  • Without max_retries, a failing message is retried up to 3 times and then deleted from the queue. With a dead_letter_queue, messages that ran out of attempts go there instead of disappearing.

For deduplication, Workers KV does not offer conditional writes; a Durable Object or a D1 database with a unique key on the wamid works better.

AWS Lambda + SQS

On AWS, the shortest path is a function URL (no API Gateway) for the receiver and an SQS queue wired to the consumer. The function URL event follows the API Gateway payload format 2.0: queryStringParameters, headers, body and isBase64Encoded.

// receiver.mjs (Node.js 22)
import { createHmac, timingSafeEqual } from "node:crypto";
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";

const sqs = new SQSClient({});

export const handler = async (event) => {
  const method = event.requestContext.http.method;
  const q = event.queryStringParameters ?? {};

  if (method === "GET") {
    const ok = q["hub.mode"] === "subscribe" && q["hub.verify_token"] === process.env.VERIFY_TOKEN;
    return ok
      ? { statusCode: 200, headers: { "content-type": "text/plain" }, body: q["hub.challenge"] }
      : { statusCode: 403, body: "forbidden" };
  }

  const raw = Buffer.from(event.body ?? "", event.isBase64Encoded ? "base64" : "utf8");
  const header = headerValue(event.headers, "x-hub-signature-256");
  if (!validSignature(raw, header)) return { statusCode: 401, body: "invalid signature" };

  await sqs.send(new SendMessageCommand({
    QueueUrl: process.env.QUEUE_URL,
    MessageBody: raw.toString("utf8"),
  }));
  return { statusCode: 200, body: "ok" };
};

function headerValue(headers = {}, name) {
  const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
  return key ? headers[key] : undefined;
}

function validSignature(raw, header) {
  if (!header?.startsWith("sha256=")) return false;
  const expected = Buffer.from(
    "sha256=" + createHmac("sha256", process.env.APP_SECRET).update(raw).digest("hex")
  );
  const received = Buffer.from(header);
  return expected.length === received.length && timingSafeEqual(expected, received);
}

The consumer receives the SQS records and returns only the ones that failed, so that only those go back to the queue:

// consumer.mjs
export const handler = async (event) => {
  const batchItemFailures = [];
  for (const record of event.Records) {
    try {
      await handleEvent(JSON.parse(record.body)); // your logic: dedupe + reply
    } catch (err) {
      console.error(err);
      batchItemFailures.push({ itemIdentifier: record.messageId });
    }
  }
  return { batchItemFailures };
};

Configuration points:

  • Partial batch responses. Returning batchItemFailures only works if the SQS event source mapping has ReportBatchItemFailures enabled. Without it, a single failure sends the whole batch back to the queue.
  • Visibility timeout. On the queue, it must be greater than the consumer’s timeout, or the same message is delivered again while it is still being processed.
  • Dead-letter queue. Configure a DLQ with a maximum receive count so you don’t reprocess a broken event forever.
  • Deduplication. A DynamoDB PutItem with ConditionExpression: "attribute_not_exists(pk)" writes the wamid only once; if the condition fails, the event has already been handled.
  • Cold start. The receiver has little code and one dependency; keep it that way. If first-call latency bothers you, AWS offers provisioned concurrency, billed separately.

The function URL must use auth type NONE, since Meta does not sign requests with SigV4. Protection comes from the HMAC validation.

Vercel Functions

On Vercel, a function at api/webhook.js can export a handler in the standard Web format. The waitUntil from the @vercel/functions package lets a promise finish after the response, but the documentation is clear: those promises share the function’s timeout and are cancelled if it is exceeded. Use it to enqueue or log, not to talk to the AI.

// api/webhook.js
import { waitUntil } from "@vercel/functions";

export default {
  async fetch(request) {
    const url = new URL(request.url);

    if (request.method === "GET") {
      const p = url.searchParams;
      return p.get("hub.mode") === "subscribe" && p.get("hub.verify_token") === process.env.VERIFY_TOKEN
        ? new Response(p.get("hub.challenge"))
        : new Response("forbidden", { status: 403 });
    }

    const body = await request.arrayBuffer();
    if (!(await validSignature(process.env.APP_SECRET, body, request.headers.get("x-hub-signature-256")))) {
      return new Response("invalid signature", { status: 401 });
    }
    waitUntil(enqueue(new TextDecoder().decode(body)));
    return new Response("ok");
  },
};

async function enqueue(rawJson) {
  // Publish to an external queue: SQS, an HTTP queue service or a Redis list.
  // E.g.: await fetch(process.env.QUEUE_ENDPOINT, { method: "POST", body: rawJson, headers: { ... } });
}

// validSignature: the same crypto.subtle function from the Cloudflare Workers example

If the project uses Next.js 15.1 or later, Vercel recommends after() from next/server instead of waitUntil, with the same idea. The function duration limit is configurable (maxDuration) within your plan’s ceiling; check the function duration page in Vercel’s documentation.

A note about waitUntil in this example: if the external queue is down, the event is lost after the 200. When that is unacceptable, switch to await enqueue(...) before responding. The response gets a few milliseconds slower, but Meta only receives 200 once the event is safe.

Which one to choose

PlatformBest whenNatural queue
Cloudflare WorkersYou want low latency and everything in one placeCloudflare Queues
AWS LambdaThe rest of your system already runs on AWSSQS (with DLQ)
VercelThe product is a Next.js app on VercelExternal queue service

In every case, the consumer does the heavy lifting: it calls the messages API, respects sending limits and stores state. To understand what arrives with each event type, see the webhook payload reference. If events aren’t arriving, the checklist for a webhook that isn’t working covers the common causes, such as the certificate and field subscriptions.

How to do it with Vectalk

Vectalk is a proxy for the official WhatsApp API and delivers to your URLs the same payload Meta sends. What changes in a serverless setup:

  • No verification GET. You register the URL with POST https://apis.vectalk.com.br/api/webhooks, passing instance_id, url and name. You can register several URLs per instance, for example one function for production and another for staging.
  • Protection via a secret in the URL. Vectalk’s webhook documentation does not describe a signature header. Register the URL with a secret parameter (?key=LONG_RANDOM_VALUE) and reject requests without it, in place of HMAC validation.
  • 20-second deadline. Vectalk expects a 200 in under 20 seconds and retries if it doesn’t get one. The validate-enqueue-respond pattern meets that with plenty of room, and deduplication in the consumer absorbs the retries.
  • Sending. The consumer calls POST https://apis.vectalk.com.br/api/messages with an instance token, without needing the phone_number_id.

Create your account at apps.vectalk.com.br/register and check the endpoints in the documentation.

Frequently asked questions

Can I process the message directly in the function, without a queue?

Yes, if the reply is fast and occasionally losing an event is acceptable. For AI bots or slow integrations, the queue prevents late responses to the webhook, retries and work cancelled halfway by the execution limit.

Does cold start get in the way of webhook verification?

Verification is a one-off request, and a slower startup usually doesn’t prevent the response. For events, occasional extra latency is tolerated, since Meta resends whatever didn’t get a 200. Keep the receiver small to reduce the effect.

How do I avoid replying twice to the same customer?

Store the id of each incoming message in storage with conditional writes (DynamoDB, D1, Postgres with a unique key, Redis with SET NX). If the write fails because the id already exists, ignore the event.

Do I need to validate the signature even with a secret URL?

With Meta, yes: the signature is the documented way to know the event came from Meta. URLs end up showing in logs and dashboards. A secret in the URL is the alternative when the sender doesn’t sign, as with Vectalk.


Official sources consulted on October 29, 2026: Create a webhook endpoint (Meta), Cloudflare Workers: Context (waitUntil), Cloudflare Queues: JavaScript APIs, Cloudflare Queues: configure queues, AWS Lambda: invoking function URLs, AWS Lambda: error handling for SQS, Vercel: @vercel/functions, Vectalk: webhooks.

Try the official WhatsApp API today

Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.