Amazon SQS: Configure a Dead-Letter Queue
See more Amazon SQS Examples
Configure two existing queues in the same region. queue_url identifies the source; dlq_url identifies the dead-letter queue. GetQueueAttributes obtains their actual ARNs, then the code checks that both are standard or both FIFO. It replaces the DLQ RedriveAllowPolicy with byQueue for this source and replaces the source RedrivePolicy with that DLQ and maxReceiveCount=5. The outer Attributes values contain serialized JSON strings, not nested objects.
These writes are not atomic. Inspect both policies after propagation and reconcile partial failure before retrying. Include other permitted sources if the DLQ is shared; replacing its allow policy can otherwise remove their permission. Choose receive count and retention for the workload; for standard queues, DLQ retention should exceed source retention. A FIFO DLQ can break strict end-to-end processing order. This configures future failed-message routing; it does not move existing DLQ messages back.
Uses SQS's AWS JSON protocol: POST to the regional root / with Content-Type: application/x-amz-json-1.0 and an operation-specific X-Amz-Target: AmazonSQS.... Chilkat.Rest and AuthAws sign with AWS Signature Version 4, service sqs. AWS still supports the older Query/XML protocol; these examples use JSON for simpler request and response handling. No AWS SDK is required.
Provide current IAM credentials in a private qa_data/aws/sqs.json with string fields access_key, secret_key, and session_token for temporary credentials. Queue-specific examples also read queue_url from this file. Set the region in the code to match the queue. These examples use commercial regional endpoints; other partitions or custom endpoints require corresponding changes. Prefer short-lived role credentials. The file is explicitly loaded; profiles and credential refresh are not automatic. Keep it outside public content and source control. The temporary token is included in the signed query; keep URLs and diagnostics private. TLS certificate verification is enabled.
Transport completion, HTTP status, and response validity are checked separately. Use bounded backoff with jitter for retryable errors, and refresh expired credentials. A timed-out write or receive may already have been accepted. Standard queues can deliver duplicates: make application processing idempotent and delete only after successful processing. Automatic reconnection is disabled for writes and receives to avoid replay after a lost response. Read-only queue listing permits reconnection.
Requires sqs:GetQueueAttributes and sqs:SetQueueAttributes on the relevant queues. Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.
AWS SetQueueAttributes reference
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Private configuration, not a file in public web content or source control.
-- Load current IAM credentials authorized for the SQS operation.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
success = credentials:load_file("qa_data/aws/sqs.json")
if not success then
print("Could not load private AWS credentials.")
return
end
textCompare:clear()
textCompare:set_string(credentials:string_of("access_key"))
local sameText1 = textCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (sameText1) then
print("Missing or invalid access_key.")
return
end
textCompare:clear()
textCompare:set_string(credentials:string_of("secret_key"))
local sameText2 = textCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (sameText2) then
print("Missing or invalid secret_key.")
return
end
-- Set this once to the region containing the queue.
local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
success = endpoint:append("sqs.")
if not success then
print("Could not prepare the request.")
return
end
success = endpoint:append(region)
if not success then
print("Could not prepare the request.")
return
end
success = endpoint:append(".amazonaws.com")
if not success then
print("Could not prepare the request.")
return
end
-- Use the exact QueueUrl returned by CreateQueue, GetQueueUrl, or ListQueues.
-- This example targets a standard commercial regional endpoint, not a custom endpoint.
local queueUrl = credentials:string_of("queue_url")
textCompare:clear()
textCompare:set_string(queueUrl)
local sameText3 = textCompare:contents_equal("", true)
if (credentials:json_type_of("queue_url") ~= 1) or (sameText3) then
print("Missing or invalid queue_url in sqs.json.")
return
end
local expectedPrefix = chilkat.StringBuilder.new()
success = expectedPrefix:append("https://")
if not success then
print("Could not prepare the request.")
return
end
success = expectedPrefix:append(endpoint:get_as_string())
if not success then
print("Could not prepare the request.")
return
end
success = expectedPrefix:append("/")
if not success then
print("Could not prepare the request.")
return
end
local queueText = chilkat.StringBuilder.new()
success = queueText:append(queueUrl)
if not success then
print("Could not prepare the request.")
return
end
if not queueText:starts_with(expectedPrefix:get_as_string(), true) then
print("Queue URL must use HTTPS and the configured SQS region.")
return
end
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "sqs"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
success = rest:set_auth_aws(aws)
if not success then
print("Could not configure AWS signing.")
return
end
-- Temporary IAM/STS credentials require their session token on every signed request.
-- AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
-- Leave session_token absent or empty only for credentials that do not have one.
if credentials:has_member("session_token") then
if credentials:json_type_of("session_token") ~= 1 then
print("session_token must be a string.")
return
end
textCompare:clear()
textCompare:set_string(credentials:string_of("session_token"))
local sameText4 = textCompare:contents_equal("", true)
if not sameText4 then
success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
if not success then
print("Could not set the session-token parameter.")
return
end
end
end
-- Supply a Socket to explicitly enable TLS certificate verification.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS connection failed; inspect diagnostics privately.")
return
end
-- Do not automatically reconnect/replay a write or receive after a lost response.
success = rest:use_connection(connection, false)
if not success then
print("Could not attach the TLS connection.")
return
end
success = rest:add_header("Content-Type", "application/x-amz-json-1.0")
if not success then
print("Could not set the content type.")
return
end
local body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
local requestBody = chilkat.StringBuilder.new()
local responseBody = chilkat.StringBuilder.new()
success = rest:add_header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("QueueUrl", queueUrl)
if not success then
print("Could not prepare the request.")
return
end
local dlqUrl = credentials:string_of("dlq_url")
textCompare:clear()
textCompare:set_string(dlqUrl)
local sameText5 = textCompare:contents_equal("", true)
if (credentials:json_type_of("dlq_url") ~= 1) or (sameText5) then
print("Supply dlq_url in the private configuration.")
return
end
textCompare:clear()
textCompare:set_string(dlqUrl)
local sameText6 = textCompare:contents_equal(queueUrl, true)
if sameText6 then
print("Source queue and dead-letter queue must differ.")
return
end
local dlqText = chilkat.StringBuilder.new()
success = dlqText:append(dlqUrl)
if not success then
print("Could not prepare the request.")
return
end
if not dlqText:starts_with(expectedPrefix:get_as_string(), true) then
print("DLQ URL must use the configured region.")
return
end
success = body:update_string("AttributeNames[0]", "QueueArn")
if not success then
print("Could not prepare the request.")
return
end
-- EmitSb appends, so clear both builders before each request/page.
requestBody:clear()
responseBody:clear()
success = body:emit_sb(requestBody)
if not success then
print("Could not serialize JSON.")
return
end
success = rest:full_request_sb("POST", "/", requestBody, responseBody)
if not success then
print("Request did not complete; inspect diagnostics privately.")
-- A write or receive may have reached SQS. Do not blindly replay it.
return
end
if rest.response_status_code ~= 200 then
print("SQS HTTP status: " .. rest.response_status_code)
print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
success = result:load_sb(responseBody)
if (success) and (result:json_type_of("__type") == 1) then
print("AWS error type: " .. result:string_of("__type"))
else
print("AWS error type: " .. rest:response_hdr_by_name("x-amzn-errortype"))
end
-- Error messages, payloads, receipt handles and signed URLs can be private.
-- HTTP 400 can be throttling, expired credentials, or invalid parameters.
return
end
success = responseBody:trim()
if not success then
print("Could not inspect response.")
return
end
if not responseBody:starts_with("{", true) then
print("Expected a JSON object response.")
return
end
success = result:load_sb(responseBody)
if not success then
print("Expected well-formed JSON.")
return
end
textCompare:clear()
textCompare:set_string(result:string_of("Attributes.QueueArn"))
local sameText7 = textCompare:contents_equal("", true)
if (result:json_type_of("Attributes.QueueArn") ~= 1) or (sameText7) then
print("Missing or invalid Attributes.QueueArn.")
return
end
local sourceArn = result:string_of("Attributes.QueueArn")
-- This is a distinct, deliberate next operation, not replay of a failed request.
rest:disconnect(10)
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS reconnection failed.")
return
end
success = rest:use_connection(connection, false)
if not success then
print("Could not attach the TLS connection.")
return
end
success = rest:add_header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
if not success then
print("Could not prepare the request.")
return
end
success = body:load("{}")
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("QueueUrl", dlqUrl)
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("AttributeNames[0]", "QueueArn")
if not success then
print("Could not prepare the request.")
return
end
-- EmitSb appends, so clear both builders before each request/page.
requestBody:clear()
responseBody:clear()
success = body:emit_sb(requestBody)
if not success then
print("Could not serialize JSON.")
return
end
success = rest:full_request_sb("POST", "/", requestBody, responseBody)
if not success then
print("Request did not complete; inspect diagnostics privately.")
-- A write or receive may have reached SQS. Do not blindly replay it.
return
end
if rest.response_status_code ~= 200 then
print("SQS HTTP status: " .. rest.response_status_code)
print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
success = result:load_sb(responseBody)
if (success) and (result:json_type_of("__type") == 1) then
print("AWS error type: " .. result:string_of("__type"))
else
print("AWS error type: " .. rest:response_hdr_by_name("x-amzn-errortype"))
end
-- Error messages, payloads, receipt handles and signed URLs can be private.
-- HTTP 400 can be throttling, expired credentials, or invalid parameters.
return
end
success = responseBody:trim()
if not success then
print("Could not inspect response.")
return
end
if not responseBody:starts_with("{", true) then
print("Expected a JSON object response.")
return
end
success = result:load_sb(responseBody)
if not success then
print("Expected well-formed JSON.")
return
end
textCompare:clear()
textCompare:set_string(result:string_of("Attributes.QueueArn"))
local sameText8 = textCompare:contents_equal("", true)
if (result:json_type_of("Attributes.QueueArn") ~= 1) or (sameText8) then
print("Missing or invalid Attributes.QueueArn.")
return
end
local dlqArn = result:string_of("Attributes.QueueArn")
textCompare:clear()
textCompare:set_string(sourceArn)
local sameText9 = textCompare:contents_equal(dlqArn, true)
if sameText9 then
print("Source and DLQ ARNs must differ.")
return
end
local sourceArnText = chilkat.StringBuilder.new()
local dlqArnText = chilkat.StringBuilder.new()
success = sourceArnText:append(sourceArn)
if not success then
print("Could not prepare the request.")
return
end
success = dlqArnText:append(dlqArn)
if not success then
print("Could not prepare the request.")
return
end
local sourceIsFifo = sourceArnText:ends_with(".fifo", true)
local dlqIsFifo = dlqArnText:ends_with(".fifo", true)
if sourceIsFifo ~= dlqIsFifo then
print("Source and DLQ must both be standard or both FIFO.")
return
end
-- Replace the DLQ allow policy with a policy permitting THIS source only.
-- If other sources use this DLQ, include them too before applying the policy.
local allowPolicy = chilkat.JsonObject.new()
success = allowPolicy:update_string("redrivePermission", "byQueue")
if not success then
print("Could not prepare the request.")
return
end
success = allowPolicy:update_string("sourceQueueArns[0]", sourceArn)
if not success then
print("Could not prepare the request.")
return
end
-- This is a distinct, deliberate next operation, not replay of a failed request.
rest:disconnect(10)
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS reconnection failed.")
return
end
success = rest:use_connection(connection, false)
if not success then
print("Could not attach the TLS connection.")
return
end
success = rest:add_header("X-Amz-Target", "AmazonSQS.SetQueueAttributes")
if not success then
print("Could not prepare the request.")
return
end
success = body:load("{}")
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("QueueUrl", dlqUrl)
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("Attributes.RedriveAllowPolicy", allowPolicy:emit())
if not success then
print("Could not prepare the request.")
return
end
-- EmitSb appends, so clear both builders before each request/page.
requestBody:clear()
responseBody:clear()
success = body:emit_sb(requestBody)
if not success then
print("Could not serialize JSON.")
return
end
success = rest:full_request_sb("POST", "/", requestBody, responseBody)
if not success then
print("Request did not complete; inspect diagnostics privately.")
-- A write or receive may have reached SQS. Do not blindly replay it.
return
end
if rest.response_status_code ~= 200 then
print("SQS HTTP status: " .. rest.response_status_code)
print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
success = result:load_sb(responseBody)
if (success) and (result:json_type_of("__type") == 1) then
print("AWS error type: " .. result:string_of("__type"))
else
print("AWS error type: " .. rest:response_hdr_by_name("x-amzn-errortype"))
end
-- Error messages, payloads, receipt handles and signed URLs can be private.
-- HTTP 400 can be throttling, expired credentials, or invalid parameters.
return
end
-- This operation normally returns an empty HTTP body on success.
-- Also accept an empty JSON object; never require XML for this protocol.
if responseBody.length > 0 then
success = responseBody:trim()
if not success then
print("Could not inspect response.")
return
end
if not responseBody:starts_with("{", true) then
print("Expected a JSON object response.")
return
end
success = result:load_sb(responseBody)
if not success then
print("Expected well-formed JSON.")
return
end
if result.size ~= 0 then
print("Unexpected fields in the empty-result response.")
return
end
end
print("DLQ allow-policy update accepted. The source policy has not been updated yet.")
local redrivePolicy = chilkat.JsonObject.new()
success = redrivePolicy:update_string("deadLetterTargetArn", dlqArn)
if not success then
print("Could not prepare the request.")
return
end
success = redrivePolicy:update_int("maxReceiveCount", 5)
if not success then
print("Could not prepare the request.")
return
end
-- This is a distinct, deliberate next operation, not replay of a failed request.
rest:disconnect(10)
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS reconnection failed.")
return
end
success = rest:use_connection(connection, false)
if not success then
print("Could not attach the TLS connection.")
return
end
success = rest:add_header("X-Amz-Target", "AmazonSQS.SetQueueAttributes")
if not success then
print("Could not prepare the request.")
return
end
success = body:load("{}")
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("QueueUrl", queueUrl)
if not success then
print("Could not prepare the request.")
return
end
success = body:update_string("Attributes.RedrivePolicy", redrivePolicy:emit())
if not success then
print("Could not prepare the request.")
return
end
-- EmitSb appends, so clear both builders before each request/page.
requestBody:clear()
responseBody:clear()
success = body:emit_sb(requestBody)
if not success then
print("Could not serialize JSON.")
return
end
success = rest:full_request_sb("POST", "/", requestBody, responseBody)
if not success then
print("Request did not complete; inspect diagnostics privately.")
-- A write or receive may have reached SQS. Do not blindly replay it.
return
end
if rest.response_status_code ~= 200 then
print("SQS HTTP status: " .. rest.response_status_code)
print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
success = result:load_sb(responseBody)
if (success) and (result:json_type_of("__type") == 1) then
print("AWS error type: " .. result:string_of("__type"))
else
print("AWS error type: " .. rest:response_hdr_by_name("x-amzn-errortype"))
end
-- Error messages, payloads, receipt handles and signed URLs can be private.
-- HTTP 400 can be throttling, expired credentials, or invalid parameters.
return
end
-- This operation normally returns an empty HTTP body on success.
-- Also accept an empty JSON object; never require XML for this protocol.
if responseBody.length > 0 then
success = responseBody:trim()
if not success then
print("Could not inspect response.")
return
end
if not responseBody:starts_with("{", true) then
print("Expected a JSON object response.")
return
end
success = result:load_sb(responseBody)
if not success then
print("Expected well-formed JSON.")
return
end
if result.size ~= 0 then
print("Unexpected fields in the empty-result response.")
return
end
end
print("Source redrive-policy update accepted. Read both policies after propagation.")
-- These two writes are not a transaction. A later failure leaves the earlier change.