SQS, SNS and EventBridge: which AWS queue or event bus to use when
One working example each for SQS, SNS and EventBridge in Terraform and Go: a queue with a dead-letter queue, SNS to SQS fan-out with a filter, an EventBridge rule, plus a Go worker that extends the visibility timeout and backs off on failure.
AWS has three services that all look like "send a message, something else picks it up": SQS, SNS and EventBridge. People mix them up all the time and it's easy to end up with EventBridge where a plain queue would do, or SNS where nobody is subscribed. Basically they solve different problems. Once you see which problem each one solves, the choice takes about a minute.
In this blog we will build one small example of each for shorty, the URL shortener from Designing a URL shortener from requirements to scale, in Terraform and Go. A work queue with a dead-letter queue, a fan-out from SNS to two SQS queues, and an EventBridge rule. Then a Go worker that does the two things most SQS consumers get wrong: it extends the visibility timeout while it's busy, and it backs off when a message keeps failing. The level is intermediate. You should know basic Go and have read IAM explained by writing policies or know what a resource policy is.
Versions: Go 1.27.3, aws-sdk-go-v2 1.48.0 (sqs 1.53.0, sns 1.48.0, eventbridge 1.55.11), Terraform 1.17.1 with the AWS provider 6.73.0. I built, vetted and tested the Go code and validated the Terraform. I did not run any of it against an AWS account for this post. Prices are for ap-south-1 (Mumbai), from the AWS Price List API on 19 November 2026.
The short answer
| SQS | SNS | EventBridge | |
|---|---|---|---|
| Shape | a queue, one consumer group pulls | a topic, pushes a copy to every subscriber | a bus, rules match events and route them |
| Keeps messages | yes, up to 14 days | no | no (unless you turn on archive) |
| Consumer is down | messages wait | delivery retries, then lost or DLQ | retries up to 24 hours, then DLQ |
| Filtering | none | filter policy per subscription | rich event patterns per rule |
| Price in Mumbai | $0.40 per million requests, first million free | $0.50 per million publishes, first million free, delivery to SQS free | $1.00 per million custom events |
My rule of thumb. If one service hands work to another, use SQS. If one event must reach several consumers and you own all of them, put SNS in front of SQS queues. If many teams or services publish events and you want routing rules, or you want events from AWS itself, like an EC2 state change, use EventBridge, still with an SQS queue at the end.
Notice SQS show up in all three. The consumer almost always reads from a queue, because a queue is the only one of the three that holds messages while your worker is down or deploying.
SQS: a work queue with a dead-letter queue
Shorty counts clicks. The redirect handler shouldn't wait on a database write, so it drops a message on a queue and a worker does the write. Here is the queue.
resource "aws_sqs_queue" "clicks_dlq" {
name = "${local.name}-clicks-dlq"
message_retention_seconds = 1209600 # 14 days, the maximum
}
resource "aws_sqs_queue" "clicks" {
name = "${local.name}-clicks"
visibility_timeout_seconds = 60
receive_wait_time_seconds = 20 # long polling
message_retention_seconds = 345600
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.clicks_dlq.arn
maxReceiveCount = 5
})
}
resource "aws_sqs_queue_redrive_allow_policy" "clicks_dlq" {
queue_url = aws_sqs_queue.clicks_dlq.id
redrive_allow_policy = jsonencode({
redrivePermission = "byQueue"
sourceQueueArns = [aws_sqs_queue.clicks.arn]
})
}
Three settings matter. visibility_timeout_seconds is how long a received message stays hidden from other consumers. If the worker doesn't delete it in that time, it comes back and someone handles it again. receive_wait_time_seconds = 20 turns on long polling, so an idle worker makes three calls a minute instead of hammering the API with empty receives. And maxReceiveCount = 5 moves a message to the DLQ after it has been received five times without being deleted.
Give the DLQ the longest retention. On a standard queue the message keeps its original enqueue time when it moves, so a DLQ with the same 4 day retention as the source can expire messages almost as soon as they land there. I just set 14 days on every DLQ and never think about it again.
SNS: fan-out to two queues
When a link is created, two things should happen: fetch a preview of the page, and write an audit entry. Two consumers, one event. That's SNS.
resource "aws_sns_topic" "links" {
name = "${local.name}-links"
}
resource "aws_sqs_queue" "subscriber" {
for_each = toset(["preview", "audit"])
name = "${local.name}-${each.key}"
visibility_timeout_seconds = 30
receive_wait_time_seconds = 20
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.subscriber_dlq[each.key].arn
maxReceiveCount = 5
})
}
data "aws_iam_policy_document" "from_sns" {
for_each = aws_sqs_queue.subscriber
statement {
actions = ["sqs:SendMessage"]
resources = [each.value.arn]
principals {
type = "Service"
identifiers = ["sns.amazonaws.com"]
}
condition {
test = "ArnEquals"
variable = "aws:SourceArn"
values = [aws_sns_topic.links.arn]
}
}
}
resource "aws_sqs_queue_policy" "from_sns" {
for_each = aws_sqs_queue.subscriber
queue_url = each.value.id
policy = data.aws_iam_policy_document.from_sns[each.key].json
}
resource "aws_sns_topic_subscription" "subscriber" {
for_each = aws_sqs_queue.subscriber
topic_arn = aws_sns_topic.links.arn
protocol = "sqs"
endpoint = each.value.arn
raw_message_delivery = true
filter_policy = each.key == "audit" ? jsonencode({ origin = ["admin"] }) : null
}
The DLQs for the two subscriber queues are in the full code, same as the one above. Queue policy is the part people actually forget. Without it the subscription looks fine in the console and messages silently never arrive, because SNS isn't allowed to send to the queue.
raw_message_delivery = true makes the SQS message body the exact string you published. Without it, SNS wraps your message in a JSON envelope with Type, MessageId, Signature and so on, and every consumer has to unwrap it. I turn it on unless the consumer needs the SNS metadata.
The filter policy means the audit queue only gets messages published with a message attribute origin equal to admin. Filtering happens in SNS, so the audit worker never sees the rest and you don't pay to receive them.
EventBridge: a rule on a custom bus
When a link is deleted, a cleanup job should purge it from the cache and any CDN. As of today only one thing cares, but later analytics might too, and maybe another team's service. That's where EventBridge fits: publishers put events on a bus and don't know who listens, and each consumer adds its own rule.
resource "aws_cloudwatch_event_bus" "shorty" {
name = local.name
}
resource "aws_cloudwatch_event_rule" "link_deleted" {
name = "${local.name}-link-deleted"
event_bus_name = aws_cloudwatch_event_bus.shorty.name
event_pattern = jsonencode({
source = ["shorty.links"]
"detail-type" = ["link.deleted"]
})
}
resource "aws_cloudwatch_event_target" "cleanup" {
rule = aws_cloudwatch_event_rule.link_deleted.name
event_bus_name = aws_cloudwatch_event_bus.shorty.name
arn = aws_sqs_queue.cleanup.arn
retry_policy {
maximum_event_age_in_seconds = 3600
maximum_retry_attempts = 10
}
dead_letter_config {
arn = aws_sqs_queue.cleanup_dlq.arn
}
}
The Terraform resources are still called aws_cloudwatch_event_* because EventBridge grew out of CloudWatch Events. The queue policy for events.amazonaws.com is in the full code. It has to cover the target queue and the DLQ, since EventBridge writes to both.
The dead-letter config here is a different thing from the SQS redrive above. This DLQ catches events EventBridge itself couldn't deliver to the target, for example because the queue policy was wrong. I'd rather find those in a queue than not at all.
EventBridge costs more per event than SNS, $1.00 per million against $0.50. For a few million events a month that's still small change, so I don't pick between them on price. I pick on who owns the consumers.
Publishing from Go
One message each way. The interesting line is at the end: PutEvents can return no error and still have failed entries, so you must check FailedEntryCount.
// 1. SQS: a job for exactly one consumer.
click, _ := json.Marshal(map[string]any{"code": "golang", "at": time.Now().UTC()})
sq, err := sqs.NewFromConfig(cfg).SendMessage(ctx, &sqs.SendMessageInput{
QueueUrl: aws.String(os.Getenv("QUEUE_URL")),
MessageBody: aws.String(string(click)),
})
if err != nil {
log.Fatal("sqs: ", err)
}
fmt.Println("sqs message", aws.ToString(sq.MessageId))
// 2. SNS: one event, every subscriber gets a copy.
created, _ := json.Marshal(map[string]string{"code": "golang", "url": "https://go.dev/"})
sn, err := sns.NewFromConfig(cfg).Publish(ctx, &sns.PublishInput{
TopicArn: aws.String(os.Getenv("TOPIC_ARN")),
Message: aws.String(string(created)),
MessageAttributes: map[string]snstypes.MessageAttributeValue{
"origin": {DataType: aws.String("String"), StringValue: aws.String("admin")},
},
})
if err != nil {
log.Fatal("sns: ", err)
}
fmt.Println("sns message", aws.ToString(sn.MessageId))
// 3. EventBridge: an event on a bus; rules decide who gets it.
deleted, _ := json.Marshal(map[string]string{"code": "golang"})
eb, err := eventbridge.NewFromConfig(cfg).PutEvents(ctx, &eventbridge.PutEventsInput{
Entries: []ebtypes.PutEventsRequestEntry{{
EventBusName: aws.String(os.Getenv("BUS_NAME")),
Source: aws.String("shorty.links"),
DetailType: aws.String("link.deleted"),
Detail: aws.String(string(deleted)),
}},
})
if err != nil {
log.Fatal("eventbridge: ", err)
}
if eb.FailedEntryCount > 0 {
log.Fatalf("eventbridge: %d entries failed: %s", eb.FailedEntryCount, aws.ToString(eb.Entries[0].ErrorMessage))
}
fmt.Println("event", aws.ToString(eb.Entries[0].EventId))
In a real service you would not publish straight after a database write like this. If the write commits and the publish fails, the event is lost. The outbox pattern fixes that, and it works the same with all three services.
A worker that doesn't drop or double-handle work
Now the consumer. The worker takes an interface instead of *sqs.Client, so I can test it without AWS.
type API interface {
ReceiveMessage(ctx context.Context, in *sqs.ReceiveMessageInput, opts ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error)
DeleteMessage(ctx context.Context, in *sqs.DeleteMessageInput, opts ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error)
ChangeMessageVisibility(ctx context.Context, in *sqs.ChangeMessageVisibilityInput, opts ...func(*sqs.Options)) (*sqs.ChangeMessageVisibilityOutput, error)
}
The receive loop asks for up to 10 messages with a 20 second wait, and asks for the receive count so it knows how many times a message has failed.
out, err := w.API.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(w.QueueURL),
MaxNumberOfMessages: 10,
WaitTimeSeconds: int32(w.WaitTime / time.Second),
MessageSystemAttributeNames: []types.MessageSystemAttributeName{types.MessageSystemAttributeNameApproximateReceiveCount},
})
Each message is handled in its own goroutine with context.WithoutCancel(ctx). When the worker gets SIGTERM during a deploy it stops receiving, but it finishes the messages it already has and deletes them. Otherwise they'd come back after the timeout and get handled twice. There's more on that in Graceful shutdown of a golang HTTP server on ECS Fargate, same idea.
Here is the handling.
func (w *Worker) handle(ctx context.Context, m types.Message) {
hbCtx, stop := context.WithCancel(ctx)
defer stop()
go w.heartbeat(hbCtx, m.ReceiptHandle)
err := w.Handler(ctx, aws.ToString(m.Body))
stop()
if err == nil {
_, derr := w.API.DeleteMessage(ctx, &sqs.DeleteMessageInput{
QueueUrl: aws.String(w.QueueURL),
ReceiptHandle: m.ReceiptHandle,
})
if derr != nil {
w.Log.Error("delete failed", "id", aws.ToString(m.MessageId), "err", derr)
}
return
}
receives, _ := strconv.Atoi(m.Attributes[string(types.MessageSystemAttributeNameApproximateReceiveCount)])
delay := Backoff(receives)
w.Log.Warn("handler failed, retrying later",
"id", aws.ToString(m.MessageId), "receives", receives, "retry_in", delay.String(), "err", err)
_, _ = w.API.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
QueueUrl: aws.String(w.QueueURL),
ReceiptHandle: m.ReceiptHandle,
VisibilityTimeout: int32(delay / time.Second),
})
}
func (w *Worker) heartbeat(ctx context.Context, receipt *string) {
t := time.NewTicker(w.Heartbeat)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
_, err := w.API.ChangeMessageVisibility(ctx, &sqs.ChangeMessageVisibilityInput{
QueueUrl: aws.String(w.QueueURL),
ReceiptHandle: receipt,
VisibilityTimeout: int32(w.Visibility / time.Second),
})
if err != nil && ctx.Err() == nil {
w.Log.Warn("heartbeat failed", "err", err)
}
}
}
}
func Backoff(receives int) time.Duration {
if receives < 1 {
receives = 1
}
d := 10 * time.Second
for i := 1; i < receives && d < 15*time.Minute; i++ {
d *= 2
}
return min(d, 15*time.Minute)
}
Tuning the visibility timeout
See, this is where most of the trouble with SQS comes from. Set the timeout too short and a slow message reappears while the first worker is still on it, so it runs twice. Set it too long and a crashed worker's messages sit invisible for ages before anyone retries them.
Heartbeat removes the guessing. The queue timeout is 60 seconds, and every 20 seconds the worker sets it back to 60 for each message it's still working on. A message that takes five minutes stays hidden for five minutes. A worker that dies stops sending heartbeats, so its messages come back within a minute.
On failure the worker does the opposite. Instead of letting the message come back after the full timeout, it sets the visibility to a back-off based on the receive count: 10 seconds, then 20, then 40. With maxReceiveCount = 5 a broken message gets five tries over a couple of minutes and then sits in the DLQ for you to look at. For retry ideas beyond this, Designing for failure goes deeper.
Even with all of this, SQS standard queues deliver at least once. A message can still arrive twice, so the handler must be safe to run twice. For clicks that means an insert keyed on a message ID, as in Idempotent payment webhooks in golang with an event table.
Testing it without AWS
The test uses a fake that hands out one batch of three messages: one fast, one that takes longer than the heartbeat, and one that fails on its third receive. Then it checks what the worker did.
if len(f.deleted) != 2 {
t.Fatalf("deleted %v, want rh-ok and rh-slow", f.deleted)
}
if hb := f.visibility["rh-slow"]; len(hb) < 2 || hb[0] != 60 {
t.Errorf("slow message heartbeats = %v, want at least two of 60", hb)
}
if got := f.visibility["rh-bad"]; len(got) == 0 || got[len(got)-1] != 40 {
t.Errorf("failed message visibility = %v, want back-off 40 on third receive", got)
}
The heartbeat interval in the test is 20 milliseconds instead of 20 seconds, which is why Heartbeat is a field and not a constant.
go vet ./...
go test -race -count=1 ./...
? github.com/fenixara/shorty-events/cmd/publish [no test files]
? github.com/fenixara/shorty-events/cmd/worker [no test files]
ok github.com/fenixara/shorty-events/internal/worker 1.698s
I always run this one with -race only. The fake's slices and map are written from several goroutines at once, so the mutex in it is not optional, and the race detector is there to tell me if I forget it.
Looking at a dead-letter queue
When something lands in the DLQ, read it first, fix the bug, then move the messages back. The redrive allow policy above is what lets you do that with one command.
aws sqs receive-message \
--queue-url https://sqs.ap-south-1.amazonaws.com/111122223333/shorty-clicks-dlq \
--max-number-of-messages 10 \
--visibility-timeout 0 \
--message-system-attribute-names ApproximateReceiveCount
aws sqs start-message-move-task \
--source-arn arn:aws:sqs:ap-south-1:111122223333:shorty-clicks-dlq
--visibility-timeout 0 means just peeking doesn't hide the messages from the move task. Without a destination, start-message-move-task sends them back to the queue they came from. Put an alarm on the DLQ's ApproximateNumberOfMessagesVisible so you hear about it before a user does.