Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

Amazon SQS: Start, Inspect, and Cancel Dead-Letter Redrive

See more Amazon SQS Examples

Default list mode reads the ten most recent movement tasks for a DLQ ARN. Start mode begins redrive at ten messages per second; an empty destinationArn returns messages to their original source queues, or supply a same-type destination queue ARN. Cancel mode requires a running task handle. Each run performs one chosen operation, with no automatic polling or write replay. IDs and large returned counts stay strings.

This service redrive supports DLQs whose sources are SQS queues, not arbitrary queues or non-SQS sources. Only one task can be active per source DLQ. Cancellation stops remaining movement and does not undo moved messages. Redriven messages get new message IDs/enqueue times and can interleave with new producer traffic. Fix the processing problem before redrive to avoid cycling messages. List results are recent task history, not a paginated complete audit.

Start requires StartMessageMoveTask, ReceiveMessage, DeleteMessage and GetQueueAttributes on the DLQ, plus SendMessage on destinations. List requires ListMessageMoveTasks and GetQueueAttributes. Cancel requires CancelMessageMoveTask with the relevant receive/delete/attributes permissions. Encrypted messages also need appropriate KMS access. See AWS redrive permissions.

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.

Required permissions depend on the selected operation, as described above. Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.

AWS StartMessageMoveTask reference

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
-- list is read-only. Choose start or cancel deliberately to change message movement.
local operation = "list"
local sourceArn = "arn:aws:sqs:us-west-2:123456789012:ExampleDeadLetterQueue"
local destinationArn = ""
local taskHandle = "TASK_HANDLE_FROM_START_OR_LIST"
textCompare:clear()
textCompare:set_string(operation)
local sameText1 = textCompare:contents_equal("list", true)
textCompare:clear()
textCompare:set_string(operation)
local sameText2 = textCompare:contents_equal("start", true)
textCompare:clear()
textCompare:set_string(operation)
local sameText3 = textCompare:contents_equal("cancel", true)
if (not sameText1) and ((not sameText2) and (not sameText3)) then
    print("Choose list, start, or cancel.")
    return
end

-- 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 sameText4 = textCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (sameText4) then
    print("Missing or invalid access_key.")
    return
end

textCompare:clear()
textCompare:set_string(credentials:string_of("secret_key"))
local sameText5 = textCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (sameText5) 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

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 sameText6 = textCompare:contents_equal("", true)
    if not sameText6 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.ListMessageMoveTasks")
if not success then
    print("Could not prepare the request.")
    return
end

textCompare:clear()
textCompare:set_string(operation)
local sameText7 = textCompare:contents_equal("start", true)
if sameText7 then
    success = rest:add_header("X-Amz-Target", "AmazonSQS.StartMessageMoveTask")
    if not success then
        print("Could not prepare the request.")
        return
    end

    success = body:update_string("SourceArn", sourceArn)
    if not success then
        print("Could not prepare the request.")
        return
    end

    success = body:update_int("MaxNumberOfMessagesPerSecond", 10)
    if not success then
        print("Could not prepare the request.")
        return
    end

    textCompare:clear()
    textCompare:set_string(destinationArn)
    local sameText8 = textCompare:contents_equal("", true)
    if not sameText8 then
        success = body:update_string("DestinationArn", destinationArn)
        if not success then
            print("Could not prepare the request.")
            return
        end
    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("TaskHandle"))
    local sameText9 = textCompare:contents_equal("", true)
    if (result:json_type_of("TaskHandle") ~= 1) or (sameText9) then
        print("Missing or invalid TaskHandle.")
        return
    end

    print("Redrive started. Task handle: " .. result:string_of("TaskHandle"))
    -- Save the handle privately; use list mode later to inspect progress.
    return
end

textCompare:clear()
textCompare:set_string(operation)
local sameText10 = textCompare:contents_equal("cancel", true)
if sameText10 then
    textCompare:clear()
    textCompare:set_string(taskHandle)
    local sameText11 = textCompare:contents_equal("", true)
    textCompare:clear()
    textCompare:set_string(taskHandle)
    local sameText12 = textCompare:contents_equal("TASK_HANDLE_FROM_START_OR_LIST", true)
    if (sameText11) or (sameText12) then
        print("Supply taskHandle from the application before running.")
        return
    end

    success = rest:add_header("X-Amz-Target", "AmazonSQS.CancelMessageMoveTask")
    if not success then
        print("Could not prepare the request.")
        return
    end

    success = body:update_string("TaskHandle", taskHandle)
    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

    if result:json_type_of("ApproximateNumberOfMessagesMoved") ~= 2 then
        print("Expected approximate moved count.")
        return
    end

    print("Cancellation accepted; messages already moved remain at their destination.")
    print("Approximate messages moved: " .. result:string_of("ApproximateNumberOfMessagesMoved"))
    return
end

success = body:update_string("SourceArn", sourceArn)
if not success then
    print("Could not prepare the request.")
    return
end

success = body:update_int("MaxResults", 10)
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

local resultsType = result:json_type_of("Results")
if (resultsType == (-1)) or (resultsType == 6) then
    print("No recent redrive tasks returned.")
    return
end

if resultsType ~= 4 then
    print("Expected Results array.")
    return
end

local i = 0
while i < result:size_of_array("Results") do
    result.i = i
    textCompare:clear()
    textCompare:set_string(result:string_of("Results[i].Status"))
    local sameText13 = textCompare:contents_equal("", true)
    if (result:json_type_of("Results[i].Status") ~= 1) or (sameText13) then
        print("Missing or invalid Results[i].Status.")
        return
    end

    print("Status: " .. result:string_of("Results[i].Status"))
    -- TaskHandle can be absent for tasks that are no longer running.
    if result:json_type_of("Results[i].TaskHandle") == 1 then
        print("Task handle: " .. result:string_of("Results[i].TaskHandle"))
    end

    if result:json_type_of("Results[i].ApproximateNumberOfMessagesMoved") == 2 then
        -- Use text to preserve counts beyond a 32-bit int.
        print("Approximate moved count: " .. result:string_of("Results[i].ApproximateNumberOfMessagesMoved"))
    end

    if result:json_type_of("Results[i].ApproximateNumberOfMessagesToMove") == 2 then
        print("Approximate total: " .. result:string_of("Results[i].ApproximateNumberOfMessagesToMove"))
    end

    if result:json_type_of("Results[i].StartedTimestamp") == 2 then
        print("Started timestamp: " .. result:string_of("Results[i].StartedTimestamp"))
    end

    -- FailureReason can contain sensitive details; inspect privately if status is FAILED.
    i = i + 1
end

print("Recent redrive tasks inspected. This API returns at most ten recent tasks.")