Sub topic 12
Subscribing endpoints: SQS, Lambda, HTTP/S, email, and more
An SNS topic does nothing by itself. It delivers messages to its subscriptions, and each subscription pairs a protocol with an endpoint. This chapter covers the protocols, how each one is confirmed and authorized, and the errors that most often leave a subscription silent.
It assumes you can publish to a topic (previous chapter), can read IAM policy JSON, and have boto3 configured with credentials and a region.
What a subscription is
A subscription has four parts:
- The topic ARN it belongs to.
- A protocol, such as
sqsorhttps. - An endpoint, such as a queue ARN or a URL.
- Optional attributes:
RawMessageDelivery,FilterPolicy,RedrivePolicy, andDeliveryPolicy.
SNS pushes each published message to every confirmed subscription whose filter policy matches. Consumers do not poll SNS.
Protocols at a glance
| Protocol | Endpoint | Confirmation | Typical use |
|---|---|---|---|
| `sqs` | Queue ARN | Automatic in the same account | Durable fan-out, buffering |
| `lambda` | Function ARN | Automatic, but the function needs a resource policy | Run code per event |
| `http` / `https` | URL | Your endpoint must confirm | Webhooks, external systems |
| `email` / `email-json` | Address | Recipient clicks a link | Human alerts |
| `sms` | Phone number | Opt-in rules apply | Text alerts |
| `application` | Mobile push endpoint ARN | Through the platform application | Mobile push |
| `firehose` | Delivery stream ARN | Automatic, needs an IAM role | Archiving to S3 or analytics |
Standard topics accept all of these. FIFO topics accept only a subset (SQS, Lambda, Firehose, HTTPS). They do not deliver to email or SMS.
Subscription confirmation
A new subscription starts as pending and receives nothing until it is confirmed. This stops someone from subscribing an address or URL they do not own.
The confirmation rules differ by protocol:
- SQS and Lambda in the same account are confirmed automatically. Cross-account subscriptions need the endpoint owner to approve.
- HTTP/S endpoints get a
SubscriptionConfirmationPOST and must confirm it, as the example below shows. - Email recipients get a message with a confirm link. Until they click it, the ARN is
PendingConfirmation.
Subscribing a Lambda function
Two things must be true. The subscription must exist, and the function's resource-based policy must allow SNS to invoke it. The console adds the permission for you. The API does not.
import boto3
sns = boto3.client("sns")
lam = boto3.client("lambda")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
function_arn = lam.get_function(FunctionName="order-notifier")["Configuration"]["FunctionArn"]
# Allow only this topic to invoke the function
lam.add_permission(
FunctionName="order-notifier",
StatementId="allow-sns-order-events",
Action="lambda:InvokeFunction",
Principal="sns.amazonaws.com",
SourceArn=topic_arn,
)
resp = sns.subscribe(
TopicArn=topic_arn,
Protocol="lambda",
Endpoint=function_arn,
ReturnSubscriptionArn=True,
)
print(resp["SubscriptionArn"])SNS invokes the function asynchronously. Lambda's own retry behavior and failure destinations apply, not the SQS visibility timeout. If you need controlled batching and retry, subscribe a queue and let Lambda poll it instead (covered in a later chapter).
Subscribing an HTTP/S endpoint
SNS sends a POST with a Content-Type of text/plain, even though the body is JSON. The header x-amz-sns-message-type tells you whether the request is a SubscriptionConfirmation, a Notification, or an UnsubscribeConfirmation.
import json
import boto3
from flask import Flask, request
app = Flask(__name__)
sns = boto3.client("sns")
@app.post("/sns")
def receive():
message_type = request.headers.get("x-amz-sns-message-type")
body = json.loads(request.get_data(as_text=True))
if message_type == "SubscriptionConfirmation":
sns.confirm_subscription(TopicArn=body["TopicArn"], Token=body["Token"])
elif message_type == "Notification":
print("received", body["Message"])
return "", 200Subscribe with sns.subscribe(TopicArn=topic_arn, Protocol="https", Endpoint="https://example.com/sns").
SNS treats any 2xx response as success. Other responses, timeouts, and connection failures trigger the retry policy covered in a later chapter.
Subscribing email
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="ops-alerts")["TopicArn"]
resp = sns.subscribe(
TopicArn=topic_arn,
Protocol="email",
Endpoint="[email protected]",
ReturnSubscriptionArn=True,
)
print(resp["SubscriptionArn"])Use email-json if a program parses the mail and you want the full JSON envelope instead of plain text. Email suits low-volume, human-facing alerts. It is not a delivery channel for systems.
Inspecting and removing subscriptions
import boto3
sns = boto3.client("sns")
topic_arn = "arn:aws:sns:us-east-1:123456789012:order-events"
paginator = sns.get_paginator("list_subscriptions_by_topic")
for page in paginator.paginate(TopicArn=topic_arn):
for sub in page["Subscriptions"]:
print(sub["Protocol"], sub["Endpoint"], sub["SubscriptionArn"])A pending subscription shows PendingConfirmation in place of its ARN. Pass a real ARN to sns.unsubscribe(SubscriptionArn=...) to remove it. Pending subscriptions that are never confirmed are deleted automatically after about 48 hours.
Common errors
- Messages never arrive at a queue. Either the queue policy does not allow
sqs:SendMessagefrom the topic ARN, or the subscription is still pending. Checkget_subscription_attributesand theNumberOfNotificationsFailedmetric. - Lambda never runs. The resource policy is missing, or its
SourceArnnames a different topic. - HTTPS stays pending. The endpoint returned an error to the confirmation POST, or it parsed the body as
application/jsonand rejected thetext/plaincontent type. - Subscribe returns "pending confirmation" as a string. That is expected for email and HTTP/S. Pass
ReturnSubscriptionArn=Trueif you need the actual ARN immediately. - Region mismatch. A topic and an SQS queue or Lambda function can be in different regions only in supported combinations. Keep them together unless you have a reason not to.
- Unconfirmed cross-account subscriptions. The endpoint owner must authorize the subscription in their own account.
Choosing a protocol
Choose by what you need after delivery:
- Choose SQS when you need buffering, retries under your control, or several independent consumers.
- Choose Lambda for short, independent reactions where occasional retries are acceptable.
- Choose HTTP/S to reach systems you do not run, and accept that you must verify signatures and handle retries.
- Choose email or SMS for humans, not for automation.
Exercise
You subscribed a Lambda function to a topic with the API, the subscription shows a valid ARN, but the function never runs when you publish. What is the most likely cause, and how do you fix it?
Show answer
The function has no resource-based policy that lets sns.amazonaws.com invoke it. The console adds this permission automatically, but the API does not. Call lambda add_permission with Action lambda:InvokeFunction, Principal sns.amazonaws.com, and SourceArn set to the topic ARN.
Exercise
An HTTPS subscription stays in PendingConfirmation. Your endpoint returns 200 for every request but never calls ConfirmSubscription. Why does it stay pending, and what must the handler do?
Show answer
SNS sends a SubscriptionConfirmation message that contains a Token. Returning 200 is not enough. The handler must check the x-amz-sns-message-type header, parse the text/plain body as JSON, and call ConfirmSubscription with the TopicArn and Token from that message.