To send an SMS from AWS Lambda, call your provider's REST API from the handler with an API key pulled from Secrets Manager, and derive the idempotency key from something stable in the event. Lambda retries failed invocations on its own, so the idempotency key is what stops a customer from getting the same text twice.

We make Ready, so the example uses the Ready REST API and only the request shape we document. The handler is Node.js 20, which ships fetch, so there's nothing to bundle. The same ideas apply in any Lambda runtime.

Why Lambda changes the retry story

A normal web server sends a text and returns. Lambda adds two behaviors that bite texting code:

  • Asynchronous invocations retry. If a function invoked from S3, EventBridge or SNS throws, Lambda retries it. Your handler can run two or three times for the same event.
  • SQS redelivers. If a function reading from a queue doesn't finish before the visibility timeout, the message comes back.

Both are fine when sends are idempotent and expensive when they aren't. The rule: the idempotency key comes from the event, never from randomUUID() inside the handler. An SQS messageId or an order ID plus a template name works. A fresh UUID per invocation defeats the whole point.

The handler

Load the key once, outside the handler, so warm invocations reuse it. This version reads from Secrets Manager, and the secret name is yours to pick.

import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

const sm = new SecretsManagerClient({});
let apiKey;

async function getKey() {
  if (!apiKey) {
    const out = await sm.send(new GetSecretValueCommand({ SecretId: process.env.READY_KEY_SECRET }));
    apiKey = out.SecretString;
  }
  return apiKey;
}

export const handler = async (event) => {
  const key = await getKey();
  const results = [];
  for (const record of event.Records) {
    const job = JSON.parse(record.body);
    const res = await fetch("https://api.tryready.com/v1/messages", {
      method: "POST",
      headers: {
        "X-API-Key": key,
        "Content-Type": "application/json",
        "Idempotency-Key": `${job.orderId}-shipped`,
      },
      body: JSON.stringify({ to: job.phone, body: job.text, consent_attested: true }),
      signal: AbortSignal.timeout(10000),
    });
    const err = res.ok ? {} : await res.json().catch(() => ({}));
    // 503 and 504 are not retried under this key: record them and follow up (see below).
    const sameKeyRetry = res.status === 429 || (res.status >= 500 && res.status !== 503 && res.status !== 504)
      || (res.status === 409 && err.code === "idempotency_in_progress");
    if (sameKeyRetry) {
      throw new Error(`retryable ${res.status}`);
    }
    results.push({ id: record.messageId, status: res.status, code: err.code });
  }
  return results;
};

Two details. The timeout on fetch is shorter than the function timeout, so a slow API call fails cleanly instead of killing the invocation mid-send. And a retryable status throws, which tells SQS to redeliver (including a 409 idempotency_in_progress, which means your first attempt is still running, so the redelivery with the same key waits for its answer instead of recording a failure), while a 4xx is recorded and moved past because retrying a refused send won't change the answer. One exception: a 503 was not sent, but the same key replays that stored error on every redelivery, so the sample records it rather than rethrowing, and you send it again under a new key; after a 504, or a code ending in OUTCOME_UNKNOWN, check GET /v1/messages first. The exact error bodies are in the error reference.

Batching from SQS without losing messages

If one bad record throws, the whole batch is retried, including sends that already worked. The idempotency key makes that harmless, but it still wastes calls. Turn on partial batch responses (ReportBatchItemFailures) and return the failed itemIdentifier values only. Then successful records are deleted and only the failures come back.

Keep concurrency in mind too. Lambda can scale to many parallel invocations, and texting has a per-second ceiling per registered campaign. Cap it with reserved concurrency on the function or the SQS event source's maximum concurrency. Our posts on SMS API rate limits and queue design for platforms go deeper.

Setup checklist

  1. Store the API key in Secrets Manager and grant the function secretsmanager:GetSecretValue on that one secret.
  2. Put an SQS queue in front of the function, with a dead-letter queue after a few receives. A redrive after Ready has forgotten the idempotency key (the docs give the window) sends again, so check GET /v1/messages before redriving an old message.
  3. Set the function timeout above your fetch timeout, and the queue visibility timeout to at least six times the function timeout.
  4. Use idempotency keys built from event data.
  5. Alert on the dead-letter queue depth.

Cost and registration

On Ready, a segment is $0.0075 plus a $0.0045 carrier fee, passed through at cost, and that doesn't include optional screening. Lambda's own cost for a text-sending function is small next to that. An account can send up to 500 texts a month before it registers for 10DLC, and most approvals take 2 to 7 days. See the pricing page.

FAQ

Can I send SMS from Lambda without a VPC or NAT gateway?

Yes, as long as the function isn't attached to a VPC. A function outside a VPC reaches public HTTPS endpoints directly. If you do put it in a VPC for a database, it needs a NAT gateway or a VPC endpoint route to reach the API.

Where should the idempotency key come from in Lambda?

From the event: an SQS message ID, an order ID plus the message purpose, or a business key you store. Never generate it inside the handler, because every retry would get a new one.

Should I call the SMS API directly or queue first?

Queue first when the text isn't needed in the same request. A queue absorbs spikes, lets you throttle, and gives you a dead-letter queue to inspect. Call directly for something like a one-time code where latency matters.

The short version

Lambda will run your handler more than once, so make the send idempotent, throttle concurrency, and let a queue carry retries. For the same call from other stacks, see sending SMS with Node.js and how to add SMS to your app.