Sub topic 16
Raw message delivery and the SNS message envelope
This chapter assumes you can publish to an SNS topic and subscribe an SQS queue to it, as covered in the fan-out chapters. You should also be comfortable reading JSON in Python. Here you will see what SNS puts in the queue by default, what changes when you turn on raw message delivery, and how to switch without breaking consumers.
The default: an SNS envelope around your message
When SNS delivers to an SQS queue, it does not put your published text in the queue as the message body. It wraps it in a JSON document called the envelope. Your original text becomes one field inside that document, and SNS adds metadata around it.
{
"Type": "Notification",
"MessageId": "5f1c0a3e-8d2b-5c4e-9a11-0c9d1f2e7b10",
"TopicArn": "arn:aws:sns:us-east-1:123456789012:order-events",
"Subject": "Order created",
"Message": "{\"orderId\": \"1001\"}",
"Timestamp": "2026-11-26T18:16:06.113Z",
"SignatureVersion": "1",
"Signature": "EXAMPLE...",
"SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-example.pem",
"UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=...",
"MessageAttributes": {
"eventType": {"Type": "String", "Value": "order_created"}
}
}Three points about this structure cause most of the bugs people hit:
Messageis a string, not a nested object. If you published JSON, you must parse it a second time.MessageAttributeshere is SNS's own format (TypeandValue). It is different from the SQS attribute format (DataTypeandStringValue).- The signature, certificate URL, and unsubscribe URL exist so HTTP/S endpoints can verify that a request came from SNS. An SQS consumer rarely needs them.
Raw message delivery
Raw message delivery is a subscription attribute named RawMessageDelivery. When it is true, SNS skips the envelope. The SQS message body is exactly the string you passed as Message to publish.
| Aspect | Envelope (default) | Raw message delivery |
|---|---|---|
| SQS message body | JSON envelope with `Message` inside | Your published message only |
| Parsing in the consumer | Parse twice: envelope, then `Message` | Parse once |
| `Subject` | Present in the envelope | Not delivered |
| `MessageId`, `Timestamp`, `TopicArn` | In the body | Not in the body |
| Message attributes | Inside the body as `MessageAttributes` | Mapped to SQS message attributes |
| Body size overhead | Envelope adds several hundred bytes | None |
The attribute mapping is the useful part. With raw delivery, eventType from the earlier example arrives as a real SQS message attribute. The consumer must request it with MessageAttributeNames when it calls receive_message.
Turning it on
You can set the attribute when you subscribe, as the fan-out chapter did, or change it on an existing subscription.
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
queue_arn = boto3.client("sqs").get_queue_attributes(
QueueUrl=boto3.client("sqs").get_queue_url(QueueName="orders")["QueueUrl"],
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
# Find the existing subscription for this queue
subs = sns.list_subscriptions_by_topic(TopicArn=topic_arn)["Subscriptions"]
sub_arn = next(s["SubscriptionArn"] for s in subs if s["Endpoint"] == queue_arn)
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="RawMessageDelivery",
AttributeValue="true",
)The setting belongs to one subscription. Two queues on the same topic can receive different formats, so you decide per consumer.
Changing the format safely
Switching the flag changes the body shape immediately. Messages already in the queue keep the old envelope, and new ones arrive raw. A consumer written for one shape will fail on the other during the transition.
The safest approach is to deploy a consumer that accepts both shapes, then flip the flag, then remove the envelope branch once the queue has drained.
import json
def extract_payload(body: str):
"""Return the application payload from either body shape."""
try:
data = json.loads(body)
except json.JSONDecodeError:
return body # plain text published with raw delivery
is_envelope = (
isinstance(data, dict)
and data.get("Type") == "Notification"
and "TopicArn" in data
and "Message" in data
)
if not is_envelope:
return data
inner = data["Message"]
try:
return json.loads(inner)
except json.JSONDecodeError:
return inner
print(extract_payload('{"orderId": "1001"}'))
print(extract_payload(
'{"Type": "Notification", "TopicArn": "arn:aws:sns:us-east-1:1:t",'
' "Message": "{\\"orderId\\": \\"1001\\"}"}'
))Both calls print {'orderId': '1001'}.
The check is deliberately strict. A raw payload that happens to have a Message field should not be mistaken for an envelope, so the function also requires Type and TopicArn.
Reading attributes with raw delivery
With raw delivery, ask SQS to return the attributes SNS mapped.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
MessageAttributeNames=["eventType"],
)
for msg in resp.get("Messages", []):
event_type = msg["MessageAttributes"]["eventType"]["StringValue"]
print(event_type, msg["Body"])If you leave out MessageAttributeNames, the attributes are delivered to the queue but not returned to you.
Edge cases and gotchas
- Subject is dropped. If a consumer relies on
Subject, put the value in a message attribute or in the body before enabling raw delivery. - Filter policies are unaffected. SNS evaluates the filter on the published attributes before it picks a format, so filtering works the same in both modes.
- Attribute limits apply. SQS allows at most 10 message attributes per message. Publishing more to a raw-delivery SQS subscription can cause delivery failures.
- Size. The 256 KB limit covers the message plus attributes. An envelope adds bytes on delivery, so raw delivery leaves more headroom for large payloads.
- Not every protocol supports it. Raw delivery applies to SQS, HTTP/S, and Firehose endpoints. Lambda subscriptions receive their own event structure instead.
- Forwarding to a dead-letter queue. A message that the consumer fails on and moves to a DLQ keeps whichever body shape it had, so a DLQ can hold a mix of both after a format change.
Exercise
A queue subscribed to an SNS topic receives bodies whose top-level fields are Type, MessageId, TopicArn, and Message. Your consumer calls json.loads(body)["orderId"] and raises KeyError. Why does this happen, and what are two ways to fix it?
Show answer
The subscription has raw message delivery off, so the body is the SNS envelope and orderId is inside the Message string, not at the top level. One fix is to parse the body, then parse its Message field as JSON a second time. The other is to set RawMessageDelivery to true on the subscription so the body is only the published message. If the queue already holds envelope messages, make the consumer accept both shapes before changing the setting.