> ## Documentation Index
> Fetch the complete documentation index at: https://www.voiceflow.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy SMS with AWS End User Messaging

> Host a text relay between AWS End User Messaging and a Voiceflow Chat agent.

## Overview

This developer-led walkthrough connects **SMS Voice v2 API with SNS and SQS** to an existing Voiceflow Chat agent. Your server receives customer texts, selects the intended agent session, sends the text to Voiceflow, then delivers the answer through AWS End User Messaging. You host and maintain the relay; a provider send action alone does not establish this conversation path.

**Note:** 

**Managed alternative:** [Voiceflow SMS](/docs/guides/channels/sms/voiceflow) hosts the two-way channel for connected Twilio numbers. This page teaches the AWS End User Messaging relay.

<a id="prepare-provider"></a>

## Before you begin

Prepare the agent, provider account and relay host.

An AWS End User Messaging SMS origination number supporting two-way SMS in its country, the required registrations, production SMS access or a verified sandbox recipient, and an operator able to create SNS/SQS resources and IAM policies.

| Owner | Required input |
| --- | --- |
| Voiceflow owner | An existing [Chat agent](/docs/documentation/build/overview), a **published test Environment**, its alias, project ID and project runtime API key. Prepare approved text answers and a fallback. |
| Provider administrator | The number, account permissions and the SMS Voice v2 API with SNS and SQS configuration below. Verify country coverage and sender registration before testing. |
| Backend operator | A server with Docker Engine and Compose, a domain you control, DNS pointed at the server, inbound ports 80/443 and outbound HTTPS. Use one relay process and its persistent volume. |
| Tester | A separate phone that expects the messages, a known answer and a follow-up question. |

Examples use 🇺🇸 US `+14155550100` as the business number and `+12025550123` as the customer. Replace these fictional numbers with your controlled, eligible numbers. Use the provider’s required international representation at its boundary; the relay stores normalized E.164.

This sample handles incoming-first **text support**, one provider and one business number per deployment. It returns text traces, suppresses the launch greeting, and sends one answer of at most 640 UTF-16 units. It does not implement MMS, rich controls or human agent hand-off. Review [Chat agents](/docs/api-reference/agent-runtime/chat) before extending those behaviors.

<a id="host-relay"></a>

## Host the relay

Install the server and connect its persistent store and credentials.

### 1. Download the runnable relay

Download the [SMS relay archive](/docs/examples/sms-relay/sms-relay.zip) and unpack it on the host:

```sh
unzip sms-relay.zip -d sms-relay
cd sms-relay
cp .env.example .env
chmod 600 .env
```

The archive includes the server, provider adapters, SQLite worker, pinned dependency lock, Docker/HTTPS configuration and offline tests. The [README](/docs/examples/sms-relay/README.md) owns the shared operations and recovery commands.

### 2. Configure the agent and secrets

Edit `.env`: set `PROVIDER=aws`, `SMS_DOMAIN` to your domain, `PUBLIC_ORIGIN` to its HTTPS origin without a trailing slash, and `SMS_FROM` to the owned E.164 business number. Set `VF_PROJECT_ID`, `VF_ENVIRONMENT` and `VF_API_KEY` to the published test Chat Environment and its runtime key. These are server secrets, never browser inputs.

Generate **two separate** random values with the following command, putting one in `IDENTITY_SECRET` and the other in `WEBHOOK_SECRET`. Set `ROUTE_GENERATION=1`.

```sh
openssl rand -hex 32
```

Keep `IDENTITY_SECRET` stable so sender identity and local opt-out records survive restarts. Add this provider’s variables:

| Variable | Value and source |
| --- | --- |
| `AWS_REGION` | The AWS Region holding the phone number, SNS topic and SQS queue. |
| `AWS_PHONE_NUMBER_ID` | The dedicated origination phone-number ID or ARN. |
| `AWS_CONFIGURATION_SET` | A configuration set with a delivery event destination. |
| `AWS_SQS_URL` | The standard queue URL subscribed to the two-way SNS topic. |
| `AWS_SNS_TOPIC_ARN` | That topic’s exact ARN. |

Remove the unused Telnyx entries from `.env.example` when selecting another provider. AWS SDK credentials, when needed, follow the credential-chain instructions in the provider setup below.

### 3. Prepare the host before provider setup

Point the domain’s DNS at the host and allow the HTTPS ports prepared above. **Leave the worker stopped** while you create the AWS topic, queue, configuration set and IAM identity below, then fill their real values in `.env`. Startup validates them; placeholder values do not establish a connection. AWS receives through SQS, so no public incoming/status callback URL is registered. Keep the persistent `sms-data` volume and one worker.

<a id="connect-provider"></a>

## Connect AWS End User Messaging

Save the provider’s incoming route and prepare outgoing replies.

### 1. Create the two-way SNS topic

Create a **standard SNS topic** in the number’s Region. Its policy must permit the `sms-voice.amazonaws.com` service to `sns:Publish` for your AWS account and this origination resource. Follow the [AWS two-way topic policy](https://docs.aws.amazon.com/sms-voice/latest/userguide/two-way-sms.html). Keep this topic dedicated to incoming SMS.

### 2. Subscribe a durable SQS queue

Create a standard SQS queue and a dead-letter queue, with a redrive policy after five failed receives. Subscribe the queue to the SNS topic; leave **Raw message delivery disabled** so the worker can check `TopicArn`. In the queue policy allow only `sns.amazonaws.com` to `sqs:SendMessage`, with `aws:SourceArn` equal to this topic ARN. Record the queue URL. Do not grant other publishers permission to write SMS-shaped queue messages.

### 3. Enable two-way SMS on the number

Open **AWS End User Messaging → Configurations → Phone numbers**, select the controlled number, then **Two-way SMS → Edit settings → Enable two-way message**. Choose the SNS topic and its topic-policy authorization, then **Save changes**. Set the saved topic ARN in `AWS_SNS_TOPIC_ARN`.

### 4. Give the worker its own IAM identity

On EC2, attach the dedicated instance role and enable IMDSv2 access from the relay container. This Compose network adds a hop: a metadata response hop limit of `1` can prevent credential retrieval. In the instance’s metadata options, require IMDSv2, enable the metadata endpoint and set a response hop limit that supports the container (`2` in [AWS’s container guidance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html)). Check the host firewall permits that access.

Alternatively, supply dedicated AWS credentials in `.env`. The SDK credential chain recognizes `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and, for temporary credentials, `AWS_SESSION_TOKEN`. Grant `sqs:ReceiveMessage`, `sqs:DeleteMessage` and `sqs:GetQueueAttributes` on only this queue, and `sms-voice:SendTextMessage` on the origination resources required by your account. Do not place credentials in the downloaded code.

### 5. Configure delivery records

Create an SMS configuration set and an event destination for delivery/failure events, such as CloudWatch Logs with its required delivery role. Save the set’s name in `AWS_CONFIGURATION_SET`. This delivery destination is separate from the incoming SNS topic. The worker will long-poll SQS and delete each queue message only after the inbound job is committed.

### 6. Start and verify the worker

Fill every AWS value in `.env` from the resources just created. Start the worker and confirm HTTPS health:

Point the domain’s DNS at the host, then run:

```sh
docker compose up -d --build
docker compose logs --tail=30 relay
curl --fail https://YOUR_SMS_DOMAIN/health
```

Replace `YOUR_SMS_DOMAIN` with `SMS_DOMAIN`. Caddy obtains TLS and proxies to the private relay port. Expect `{"ok":true}` from health. Keep the `sms-data` volume: it stores message IDs, session keys, pending replies and suppression records. Do not scale this SQLite example to several processes.

Then run this read-only check inside the actual container:

```sh
docker compose exec -T relay node --input-type=module <<'JS'
import {SQSClient, GetQueueAttributesCommand} from '@aws-sdk/client-sqs';
const client = new SQSClient({region: process.env.AWS_REGION});
await client.config.credentials();
await client.send(new GetQueueAttributesCommand({
  QueueUrl: process.env.AWS_SQS_URL,
  AttributeNames: ['QueueArn']
}));
console.log('Worker credentials and queue access verified');
JS
```

Expect the confirmation without credentials being printed. A failure means the container’s credential chain, metadata access, queue Region or IAM permissions still need attention. This does not prove `SendTextMessage` permission or SMS delivery; test those below.

This path exposes no provider webhook: IAM authenticates SQS reads, the queue policy restricts SNS writes, and the worker checks the exact SNS TopicArn before decoding the message. SNS-to-SQS delivery needs no public webhook signature verification. Retain the envelope; enabling raw delivery would remove the TopicArn check.

<a id="map-conversations"></a>

## Map messages and sessions

Keep the sender, agent release and reply direction consistent.

| Boundary | Mapping |
| --- | --- |
| Transport identity | SNS `TopicArn` inside an IAM-protected SQS queue |
| Event ID | `Message.inboundMessageId` after decoding the SNS envelope |
| Customer → business / text | `originationNumber` → `destinationNumber`; `messageBody` |
| Reply | SDK `SendTextMessage`: destination customer, `OriginationIdentity`, `MessageBody`, `ConfigurationSetName` |

| Event | Relay behavior |
| --- | --- |
| First customer text | Commits the inbound ID, creates a v4 session in the explicit published Environment, launches it, then sends the customer’s text. |
| Follow-up | Reuses the stored session token for the provider/business/customer combination; the user ID is a keyed hash, not a raw phone number. |
| Duplicate / restart | Duplicate inbound IDs do not rerun the turn. Queued work survives restarts; interrupted turns/sends become `uncertain` and need operator review. |
| End / expiry | An `end` trace clears the local token. A definite session `404` creates a replacement once; a timeout never automatically replays a turn. |
| STOP / START / HELP | The relay bypasses the agent for these keywords and keeps a local suppression record. Configure the provider’s required keyword responses; the sample does not send its own compliance response. |
| Non-text / hand-off | No fabricated SMS reply: missing text, oversized answers or a hand-off trace hold the job for review. This sample does not deliver later help-desk messages. |

The server calls `POST /v4/project/{projectID}/environment/{alias}/session` with the runtime API key, then `POST /v4/interact` with the returned session token. The [session](/docs/api-reference/v4interact/start-session-specific-environment) and [interact](/docs/api-reference/v4interact/interact-non-stream) references own the full contracts. This route uses the Environment’s Published release; compiling a Draft alone does not release it. Transcripts identify these relay sessions as API conversations.

<a id="test-provider"></a>

## Test a customer conversation

Verify the real incoming text, agent session and delivered reply.

### 1. Run the offline checks

Before installing real provider credentials, run the archive’s tests with Node 22.13 or later:

```sh
npm ci --ignore-scripts
npm test
```

These tests use synthetic provider events and mocked agent/sender responses. They check mappings, signatures, duplicate handling and restart behavior without sending a message. They do not establish live provider acceptance.

### 2. Send the known question and follow-up

From your separate phone, text “What are your collection hours?” to the AWS End User Messaging business number. Expect the prepared answer, for example “Northstar collection hours are 10 am to 6 pm.” Reply “Are you open at noon?” and check that the answer uses the same conversation. Inspect the intended project’s [Transcripts](/docs/documentation/measure/transcripts). Confirm no launch greeting is sent separately.

### 3. Compare ingestion, sending and receipt

Inspect `docker compose logs relay` for the hashed job ID and `phase:"accepted"`, then use the retained provider ID/reference to find the outgoing message. Confirm its sender is the business number, its recipient is the customer, and the phone receives one answer per turn.

Retain the send’s `MessageId`. Inspect the configuration set’s delivery/failure event in its CloudWatch destination and the phone. An SQS delete only proves local ingestion; it does not prove an agent answer or SMS delivery. SNS standard topics provide best-effort ordering and repeated events can occur.

### 4. Exercise continuity and recovery

Send a new question after restarting only the relay container; the stored session should continue. On a controlled recipient, test the configured STOP/START/HELP route and verify STOP prevents an agent send. Re-submit a captured **authorized synthetic fixture** only to a local/offline test receiver to check duplicate behavior; do not replay a production callback, which can trigger paid messages. Test a second customer to confirm their context remains separate.

### The provider has the text but the relay has no job

Check the saved incoming route, callback authorization and payload family.

Inspect the relay’s SQS error log and dead-letter queue. Re-run the container credential/queue check, then verify the number’s Region, two-way SNS topic, queue subscription and restricted policies. Keep Raw message delivery disabled and confirm the envelope’s `TopicArn` equals `AWS_SNS_TOPIC_ARN`. A wrong or malformed envelope stays on the queue for retry and eventual dead-letter review. The public health endpoint does not establish SQS access; this transport has no provider HTTP callback or callback status code.

### The relay records uncertain or held work

Resolve the original remote outcome before allowing another attempt.

Inspect the job with the README’s `inspect` command, the corresponding Transcript and provider log. An agent tool or send might have succeeded before its response was lost. The worker does not automatically retry this job and holds later messages for that conversation. Resolve the original outcome, then use the explicit recovery command; never clear the database to force a resend.

### The provider accepts the reply but the phone gets nothing

Check delivery evidence, sender eligibility and recipient suppression.

Find the exact outgoing ID/reference in the provider log, inspect final delivery status and errors, and confirm the destination, sender registration, balance, country permissions and opt-out state. An accepted request is not a delivery receipt. If the account rewrites the sender, correct its two-way routing before launch.

<a id="release-provider"></a>

## Release and maintain the channel

Cut over the provider number and the published agent together.

### 1. Release the reviewed agent and relay

[Publish](/docs/documentation/deploy/environments/publishing) the reviewed Chat Environment. Stop inbound routing temporarily or schedule the cutover, let queued work drain, and back up the persistent volume. Set the final `VF_PROJECT_ID`/`VF_ENVIRONMENT` and increase `ROUTE_GENERATION` to start fresh sessions on this deployment configuration. Recreate the relay container with `docker compose up -d`. The program refuses a route change while old queued jobs remain.

### 2. Verify the production route

Repeat the [known question and follow-up](#test-provider) through the final AWS End User Messaging number. Check the Published instructions, provider sender, destination and final delivery evidence. Keep the earlier route ready until this acceptance succeeds.

### Update or disconnect the relay

Coordinate secrets, provider routing and the persistent message ledger.

Rotate a provider credential in `.env`, recreate the container and repeat the customer test. Rotate a webhook token/signing secret with the provider endpoint in the same change window. Keep `IDENTITY_SECRET` and the persistent volume stable; replacing them resets local sender identity and suppression history.

To stop this channel, disable the provider’s route/subscription first, then stop the worker after queued jobs drain. Restore the recorded prior provider route if required. Keep the volume/backup according to your data-retention policy; `docker compose down -v` deletes the message ledger and is not a recovery step. Number release and billing cancellation remain provider-account actions.
