AWS SDK for Go
Developer Guide

Using Dead Letter Queues in Amazon SQS

This AWS SDK for Go example shows you how to configure source Amazon SQS queues that send messages to a dead letter queue.

You can download complete versions of these example files from the aws-doc-sdk-examples repository on GitHub.


A dead letter queue is one that other (source) queues can target for messages that can't be processed successfully. You can set aside and isolate these messages in the dead letter queue to determine why their processing didn't succeed. You must individually configure each source queue that sends messages to a dead letter queue. Multiple queues can target a single dead letter queue.

The code uses this method of the Amazon SQS client class:


Configure Source Queues

After you create a queue to act as a dead letter queue, you must configure the other queues that route unprocessed messages to the dead letter queue. To do this, specify a redrive policy that identifies the queue to use as a dead letter queue and the maximum number of receives by individual messages before they are routed to the dead letter queue.

Create a new Go file with the name sqs_deadletterqueue.go.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

package main import ( "encoding/json" "fmt" "" "" "" )

Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/credentials.

func main() { sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) // Create a SQS service client. svc := sqs.New(sess)

Define the redrive policy for the queue, then marshal the policy to use as input for the SetQueueAttributes call.

policy := map[string]string{ "deadLetterTargetArn": "SQS_QUEUE_ARN", "maxReceiveCount": "10", } b, err := json.Marshal(policy) if err != nil { fmt.Println("Failed to marshal policy:", err) return }

Set the policy on the queue.

result, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ QueueUrl: aws.String("SQS_QUEUE_URL"), Attributes: map[string]*string{ sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)), }, }) if err != nil { fmt.Println("Error", err) return } fmt.Println("Success", result) }