Publish messages to SNS with the AWS SDK for Go v2, add message attributes, batch publishes and FIFO settings, fan out to SQS consumers, and see how typed topics in Go replace the setup.

Amazon SNS is the AWS publish and subscribe service, and a Go backend uses it to announce events such as an order placed, so billing and email each react through their own SQS queue.
The AWS SDK for Go v2 makes publishing one call, while attributes, partly failed batches, FIFO IDs and queue policies take the rest of the effort. This guide covers each of those with service/sns v1.48 on Go 1.24.
config.LoadDefaultConfig resolves credentials from the default chain, which on ECS is the task role, and the topic ARN usually comes from configuration because the topic is created outside the app. The publisher below wraps the client, so handlers depend on a small type rather than the SDK:
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go-v2/service/sns/types"
)
type OrderPlaced struct {
OrderID string `json:"order_id"`
TotalCents int64 `json:"total_cents"`
Country string `json:"country"`
}
type Publisher struct {
client *sns.Client
topicARN string
}
func (p *Publisher) OrderPlaced(ctx context.Context, evt OrderPlaced) (string, error) {
body, err := json.Marshal(evt)
if err != nil {
return "", err
}
out, err := p.client.Publish(ctx, &sns.PublishInput{
TopicArn: aws.String(p.topicARN),
Message: aws.String(string(body)),
MessageAttributes: map[string]types.MessageAttributeValue{
"event_type": {DataType: aws.String("String"), StringValue: aws.String("order.placed")},
"country": {DataType: aws.String("String"), StringValue: aws.String(evt.Country)},
},
})
if err != nil {
return "", fmt.Errorf("publish order %s: %w", evt.OrderID, err)
}
return aws.ToString(out.MessageId), nil
}
func main() {
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
log.Fatal(err)
}
pub := &Publisher{client: sns.NewFromConfig(cfg), topicARN: os.Getenv("ORDER_EVENTS_TOPIC_ARN")}
id, err := pub.OrderPlaced(ctx, OrderPlaced{OrderID: "ord_1", TotalCents: 4200, Country: "DE"})
if err != nil {
log.Fatal(err)
}
log.Printf("published %s", id)
}
Messages are limited to 256 KiB by default, and a topic's MaximumMessageSize attribute can raise that to 1 MiB for topics whose subscribers are SQS, Lambda or Firehose, as the large message docs describe. Larger payloads belong in S3, with the object key in the message.
PublishBatch sends up to 10 messages per request, and the response reports each entry separately, so a request can succeed while some entries fail:
// PublishMany sends events in batches of 10, the PublishBatch maximum.
func (p *Publisher) PublishMany(ctx context.Context, evts []OrderPlaced) error {
for start := 0; start < len(evts); start += 10 {
end := min(start+10, len(evts))
entries := make([]types.PublishBatchRequestEntry, 0, end-start)
for i, evt := range evts[start:end] {
body, err := json.Marshal(evt)
if err != nil {
return err
}
entries = append(entries, types.PublishBatchRequestEntry{
Id: aws.String(strconv.Itoa(start + i)),
Message: aws.String(string(body)),
})
}
out, err := p.client.PublishBatch(ctx, &sns.PublishBatchInput{
TopicArn: aws.String(p.topicARN),
PublishBatchRequestEntries: entries,
})
if err != nil {
return err
}
// A partly failed batch returns no error: check Failed explicitly.
if len(out.Failed) > 0 {
f := out.Failed[0]
return fmt.Errorf("%d of %d messages failed, first: %s %s",
len(out.Failed), len(entries), aws.ToString(f.Code), aws.ToString(f.Message))
}
}
return nil
}
For a FIFO topic, each entry also gets MessageGroupId, usually the order or customer ID so that events for one entity stay in order, and a MessageDeduplicationId unless content-based deduplication is on. SNS drops a repeated deduplication ID within five minutes, which makes retrying a failed batch safe.
The usual consumer is an SQS queue per service, subscribed to the topic. Each queue needs a resource policy allowing sns.amazonaws.com to call sqs:SendMessage with an aws:SourceArn condition on the topic, and a subscription that only wants some events gets a filter policy such as {"country": ["DE", "AT"]}. Unless RawMessageDelivery is enabled, the SQS body is an SNS envelope whose Message field holds your JSON, and delivery is at least once, so consumers should ignore events they already handled.
The publisher's role needs sns:Publish on the topic ARN, which also authorizes PublishBatch. An encrypted topic with a customer managed KMS key needs kms:GenerateDataKey and kms:Decrypt granted to the publisher, and the key policy must let SNS use the key to deliver to encrypted queues.
Encore brings infrastructure from code, and a Pub/Sub topic in Go is a typed package-level variable. On AWS each topic becomes an SNS topic and each subscription its own SQS queue with a dead-letter queue, so the publisher wrapper, queue policies and envelope parsing above are not part of the app.

Run in your terminal to get started locally.
The orders service declares the topic and publishes from an endpoint:
// orders/orders.go
package orders
import (
"context"
"encore.dev/pubsub"
)
type OrderPlaced struct {
OrderID string `json:"order_id"`
TotalCents int64 `json:"total_cents"`
Country string `json:"country"`
}
// SNS plus an SQS queue per subscription on AWS, GCP Pub/Sub on GCP,
// a local broker under encore run.
var OrderEvents = pubsub.NewTopic[*OrderPlaced]("order-events", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type PlaceResponse struct {
MessageID string `json:"message_id"`
}
//encore:api public method=POST path=/orders
func Place(ctx context.Context, p *OrderPlaced) (*PlaceResponse, error) {
id, err := OrderEvents.Publish(ctx, p)
if err != nil {
return nil, err
}
return &PlaceResponse{MessageID: id}, nil
}
The receipts service subscribes and uses its own database to skip repeats, since delivery is at least once:
// receipts/receipts.go
package receipts
import (
"context"
"encore.app/orders"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
// migrations/1_create_receipts.up.sql:
// CREATE TABLE receipts (order_id TEXT PRIMARY KEY, sent_at TIMESTAMPTZ NOT NULL DEFAULT now());
var db = sqldb.NewDatabase("receipts", sqldb.DatabaseConfig{Migrations: "./migrations"})
var _ = pubsub.NewSubscription(orders.OrderEvents, "send-receipt",
pubsub.SubscriptionConfig[*orders.OrderPlaced]{
Handler: sendReceipt,
},
)
func sendReceipt(ctx context.Context, evt *orders.OrderPlaced) error {
res, err := db.Exec(ctx,
`INSERT INTO receipts (order_id) VALUES ($1) ON CONFLICT DO NOTHING`, evt.OrderID)
if err != nil {
return err // retried with backoff, then the dead-letter queue
}
if res.RowsAffected() == 0 {
return nil // duplicate delivery
}
rlog.Info("sending receipt", "order_id", evt.OrderID, "country", evt.Country)
return nil
}
encore run starts the database and a local broker, so posting an order logs one receipt, and the trace shows the publish and the handler together. On deploy to your own AWS account, Encore creates the SNS topic, the SQS queue and its dead-letter queue, and the database on RDS, as the AWS infrastructure docs describe. Encore provisions an IAM role for the service.
Topics and subscriptions are Go declarations, so a coding agent adding a fraud check on large orders writes a second subscription and its handler in one change and watches both run locally before the change reaches AWS.
Best fit: Services that publish events between their own services and want SNS and SQS in their AWS account from typed topics.
Use the SDK directly when the topic is shared with systems outside your codebase, when you need SNS features such as SMS or mobile push, or when the topic is already managed in Terraform. Use Encore when the topic connects your own services, because the topic, the per-consumer queues and the dead-letter queues follow from the Go code and behave the same under encore run as in AWS.
Load a config with config.LoadDefaultConfig, create a client with sns.NewFromConfig, and call client.Publish(ctx, &sns.PublishInput{TopicArn: aws.String(arn), Message: aws.String(body)}). Marshal structured events to JSON first, and add MessageAttributes for values that subscription filter policies should match.
No. PublishBatch returns a nil error when the request itself succeeds, even if some entries failed. Check the Failed slice in the output, which carries the entry ID, an error code and whether the failure was the sender's fault, and retry the failed entries.
Each Publish or batch entry needs MessageGroupId, and a MessageDeduplicationId unless content-based deduplication is enabled on the topic. Messages with the same group ID are delivered in order to the subscribed SQS queues.
Put the client behind a small interface with a Publish method and use a fake in unit tests, or run LocalStack for integration tests. With Encore, Pub/Sub topics run locally under encore run, and et.Topic(topic).PublishedMessages() returns what a test published.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.