Menu
AWS SDK for C++
Developer Guide

Using Dead Letter Queues in Amazon SQS

Amazon SQS provides support for dead letter queues. A dead letter queue is a queue 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 did not succeed.

To create a dead letter queue, you must first create a redrive policy, and then set the policy in the queue's attributes.

Important

A dead letter queue must be the same type of queue (FIFO or standard) that the source queue is. It must also be created using the same AWS account and region as the source queue.

Note

These code snippets assume that you understand the material in Getting Started Using the AWS SDK for C++ and have configured default AWS credentials using the information in Providing AWS Credentials.

Creating a Redrive Policy

A redrive policy is specified in JSON. To create it, you can use the JSON utility class provided with the AWS SDK for C++.

Here is an example function that creates a redrive policy by providing it with the ARN of your dead letter queue and the maximum number of times the message can be received and not processed before it's sent to the dead letter queue.

Includes

Copy
#include <aws/core/Aws.h> #include <aws/core/utils/json/JsonSerializer.h>

Code

Copy
Aws::String MakeRedrivePolicy(const Aws::String& queue_arn, int max_msg) { Aws::Utils::Json::JsonValue redrive_arn_entry; redrive_arn_entry.AsString(queue_arn); Aws::Utils::Json::JsonValue max_msg_entry; max_msg_entry.AsInteger(max_msg); Aws::Utils::Json::JsonValue policy_map; policy_map.WithObject("deadLetterTargetArn", redrive_arn_entry); policy_map.WithObject("maxReceiveCount", max_msg_entry); return policy_map.WriteReadable(); }

See the complete example.

Setting the Redrive Policy on your Source Queue

To finish setting up your dead letter queue, call the SQSClient class' SetQueueAttributes member function with a SetQueueAttributesRequest object for which you've set the RedrivePolicy attribute with your JSON redrive policy.

Includes

Copy
#include <aws/core/Aws.h> #include <aws/sqs/SQSClient.h> #include <aws/sqs/model/SetQueueAttributesRequest.h>

Code

Copy
Aws::SQS::SQSClient sqs; Aws::String redrivePolicy = MakeRedrivePolicy(queue_arn, max_msg); Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(src_queue_url); request.AddAttributes( Aws::SQS::Model::QueueAttributeName::RedrivePolicy, redrivePolicy); auto outcome = sqs.SetQueueAttributes(request); if (outcome.IsSuccess()) { std::cout << "Successfully set dead letter queue for queue " << src_queue_url << " to " << queue_arn << std::endl; } else { std::cout << "Error setting dead letter queue for queue " << src_queue_url << ": " << outcome.GetError().GetMessage() << std::endl; }

See the complete example.

More Info