Sample code for 30+ languages & platforms
AutoIt 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 AutoIt Downloads

AutoIt
Local $bSuccess = False

;  StringBuilder compares text by value in every generated language.
$oTextCompare = ObjCreate("Chilkat.StringBuilder")
;  list is read-only. Choose start or cancel deliberately to change message movement.
Local $sOperation = "list"
Local $sourceArn = "arn:aws:sqs:us-west-2:123456789012:ExampleDeadLetterQueue"
Local $sDestinationArn = ""
Local $sTaskHandle = "TASK_HANDLE_FROM_START_OR_LIST"
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText1 = $oTextCompare.ContentsEqual("list",True)
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText2 = $oTextCompare.ContentsEqual("start",True)
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText3 = $oTextCompare.ContentsEqual("cancel",True)
If (($bSameText1 <> True) And ($bSameText2 <> True) And ($bSameText3 <> True)) Then
    ConsoleWrite("Choose list, start, or cancel." & @CRLF)
    Exit
EndIf

;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
;  Private configuration, not a file in public web content or source control.
;  Load current IAM credentials authorized for the SQS operation.
$oCredentials = ObjCreate("Chilkat.JsonObject")
$oCredentials.Strict = True
$bSuccess = $oCredentials.LoadFile("qa_data/aws/sqs.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load private AWS credentials." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($oCredentials.StringOf("access_key"))
Local $bSameText4 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($bSameText4 = True)) Then
    ConsoleWrite("Missing or invalid access_key." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($oCredentials.StringOf("secret_key"))
Local $bSameText5 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($bSameText5 = True)) Then
    ConsoleWrite("Missing or invalid secret_key." & @CRLF)
    Exit
EndIf

;  Set this once to the region containing the queue.
Local $sRegion = "us-west-2"
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oEndpoint.Append("sqs.")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oEndpoint.Append($sRegion)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oEndpoint.Append(".amazonaws.com")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$oAws = ObjCreate("Chilkat.AuthAws")
$oAws.AccessKey = $oCredentials.StringOf("access_key")
$oAws.SecretKey = $oCredentials.StringOf("secret_key")
$oAws.Region = $sRegion
$oAws.ServiceName = "sqs"
$oAws.SignatureVersion = 4
$oRest = ObjCreate("Chilkat.Rest")
$oRest.ConnectTimeoutMs = 20000
$oRest.IdleTimeoutMs = 60000
$bSuccess = $oRest.SetAuthAws($oAws)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not configure AWS signing." & @CRLF)
    Exit
EndIf

;  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 ($oCredentials.HasMember("session_token") = True) Then
    If ($oCredentials.JsonTypeOf("session_token") <> 1) Then
        ConsoleWrite("session_token must be a string." & @CRLF)
        Exit
    EndIf

    $oTextCompare.Clear 
    $oTextCompare.SetString($oCredentials.StringOf("session_token"))
Local $bSameText6 = $oTextCompare.ContentsEqual("",True)
    If ($bSameText6 <> True) Then
        $bSuccess = $oRest.AddQueryParam("X-Amz-Security-Token",$oCredentials.StringOf("session_token"))
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not set the session-token parameter." & @CRLF)
            Exit
        EndIf

    EndIf

EndIf

;  Supply a Socket to explicitly enable TLS certificate verification.
$oConnection = ObjCreate("Chilkat.Socket")
$oConnection.RequireSslCertVerify = True
$oConnection.MaxReadIdleMs = 60000
$oConnection.MaxSendIdleMs = 60000
$bSuccess = $oConnection.Connect($oEndpoint.GetAsString(),443,True,20000)
If ($bSuccess <> True) Then
    ConsoleWrite("TLS connection failed; inspect diagnostics privately." & @CRLF)
    Exit
EndIf

;  Do not automatically reconnect/replay a write or receive after a lost response.
$bSuccess = $oRest.UseConnection($oConnection,False)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not attach the TLS connection." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddHeader("Content-Type","application/x-amz-json-1.0")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set the content type." & @CRLF)
    Exit
EndIf

$oBody = ObjCreate("Chilkat.JsonObject")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oRequestBody = ObjCreate("Chilkat.StringBuilder")
$oResponseBody = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oRest.AddHeader("X-Amz-Target","AmazonSQS.ListMessageMoveTasks")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText7 = $oTextCompare.ContentsEqual("start",True)
If ($bSameText7 = True) Then
    $bSuccess = $oRest.AddHeader("X-Amz-Target","AmazonSQS.StartMessageMoveTask")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oBody.UpdateString("SourceArn",$sourceArn)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oBody.UpdateInt("MaxNumberOfMessagesPerSecond",10)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    $oTextCompare.Clear 
    $oTextCompare.SetString($sDestinationArn)
Local $bSameText8 = $oTextCompare.ContentsEqual("",True)
    If ($bSameText8 <> True) Then
        $bSuccess = $oBody.UpdateString("DestinationArn",$sDestinationArn)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

    EndIf

    ;  EmitSb appends, so clear both builders before each request/page.
    $oRequestBody.Clear 
    $oResponseBody.Clear 
    $bSuccess = $oBody.EmitSb($oRequestBody)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not serialize JSON." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oRest.FullRequestSb("POST","/",$oRequestBody,$oResponseBody)
    If ($bSuccess <> True) Then
        ConsoleWrite("Request did not complete; inspect diagnostics privately." & @CRLF)
        ;  A write or receive may have reached SQS. Do not blindly replay it.
        Exit
    EndIf

    If ($oRest.ResponseStatusCode <> 200) Then
        ConsoleWrite("SQS HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
        ConsoleWrite("AWS request ID: " & $oRest.ResponseHdrByName("x-amzn-RequestId") & @CRLF)
        $bSuccess = $oResult.LoadSb($oResponseBody)
        If (($bSuccess = True) And ($oResult.JsonTypeOf("__type") = 1)) Then
            ConsoleWrite("AWS error type: " & $oResult.StringOf("__type") & @CRLF)
        Else
            ConsoleWrite("AWS error type: " & $oRest.ResponseHdrByName("x-amzn-errortype") & @CRLF)
        EndIf

        ;  Error messages, payloads, receipt handles and signed URLs can be private.
        ;  HTTP 400 can be throttling, expired credentials, or invalid parameters.
        Exit
    EndIf

    $bSuccess = $oResponseBody.Trim()
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not inspect response." & @CRLF)
        Exit
    EndIf

    If ($oResponseBody.StartsWith("{",True) <> True) Then
        ConsoleWrite("Expected a JSON object response." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oResult.LoadSb($oResponseBody)
    If ($bSuccess <> True) Then
        ConsoleWrite("Expected well-formed JSON." & @CRLF)
        Exit
    EndIf

    $oTextCompare.Clear 
    $oTextCompare.SetString($oResult.StringOf("TaskHandle"))
Local $bSameText9 = $oTextCompare.ContentsEqual("",True)
    If (($oResult.JsonTypeOf("TaskHandle") <> 1) Or ($bSameText9 = True)) Then
        ConsoleWrite("Missing or invalid TaskHandle." & @CRLF)
        Exit
    EndIf

    ConsoleWrite("Redrive started. Task handle: " & $oResult.StringOf("TaskHandle") & @CRLF)
    ;  Save the handle privately; use list mode later to inspect progress.
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText10 = $oTextCompare.ContentsEqual("cancel",True)
If ($bSameText10 = True) Then
    $oTextCompare.Clear 
    $oTextCompare.SetString($sTaskHandle)
Local $bSameText11 = $oTextCompare.ContentsEqual("",True)
    $oTextCompare.Clear 
    $oTextCompare.SetString($sTaskHandle)
Local $bSameText12 = $oTextCompare.ContentsEqual("TASK_HANDLE_FROM_START_OR_LIST",True)
    If (($bSameText11 = True) Or ($bSameText12 = True)) Then
        ConsoleWrite("Supply taskHandle from the application before running." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oRest.AddHeader("X-Amz-Target","AmazonSQS.CancelMessageMoveTask")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oBody.UpdateString("TaskHandle",$sTaskHandle)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    ;  EmitSb appends, so clear both builders before each request/page.
    $oRequestBody.Clear 
    $oResponseBody.Clear 
    $bSuccess = $oBody.EmitSb($oRequestBody)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not serialize JSON." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oRest.FullRequestSb("POST","/",$oRequestBody,$oResponseBody)
    If ($bSuccess <> True) Then
        ConsoleWrite("Request did not complete; inspect diagnostics privately." & @CRLF)
        ;  A write or receive may have reached SQS. Do not blindly replay it.
        Exit
    EndIf

    If ($oRest.ResponseStatusCode <> 200) Then
        ConsoleWrite("SQS HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
        ConsoleWrite("AWS request ID: " & $oRest.ResponseHdrByName("x-amzn-RequestId") & @CRLF)
        $bSuccess = $oResult.LoadSb($oResponseBody)
        If (($bSuccess = True) And ($oResult.JsonTypeOf("__type") = 1)) Then
            ConsoleWrite("AWS error type: " & $oResult.StringOf("__type") & @CRLF)
        Else
            ConsoleWrite("AWS error type: " & $oRest.ResponseHdrByName("x-amzn-errortype") & @CRLF)
        EndIf

        ;  Error messages, payloads, receipt handles and signed URLs can be private.
        ;  HTTP 400 can be throttling, expired credentials, or invalid parameters.
        Exit
    EndIf

    $bSuccess = $oResponseBody.Trim()
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not inspect response." & @CRLF)
        Exit
    EndIf

    If ($oResponseBody.StartsWith("{",True) <> True) Then
        ConsoleWrite("Expected a JSON object response." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oResult.LoadSb($oResponseBody)
    If ($bSuccess <> True) Then
        ConsoleWrite("Expected well-formed JSON." & @CRLF)
        Exit
    EndIf

    If ($oResult.JsonTypeOf("ApproximateNumberOfMessagesMoved") <> 2) Then
        ConsoleWrite("Expected approximate moved count." & @CRLF)
        Exit
    EndIf

    ConsoleWrite("Cancellation accepted; messages already moved remain at their destination." & @CRLF)
    ConsoleWrite("Approximate messages moved: " & $oResult.StringOf("ApproximateNumberOfMessagesMoved") & @CRLF)
    Exit
EndIf

$bSuccess = $oBody.UpdateString("SourceArn",$sourceArn)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oBody.UpdateInt("MaxResults",10)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

;  EmitSb appends, so clear both builders before each request/page.
$oRequestBody.Clear 
$oResponseBody.Clear 
$bSuccess = $oBody.EmitSb($oRequestBody)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not serialize JSON." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.FullRequestSb("POST","/",$oRequestBody,$oResponseBody)
If ($bSuccess <> True) Then
    ConsoleWrite("Request did not complete; inspect diagnostics privately." & @CRLF)
    ;  A write or receive may have reached SQS. Do not blindly replay it.
    Exit
EndIf

If ($oRest.ResponseStatusCode <> 200) Then
    ConsoleWrite("SQS HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
    ConsoleWrite("AWS request ID: " & $oRest.ResponseHdrByName("x-amzn-RequestId") & @CRLF)
    $bSuccess = $oResult.LoadSb($oResponseBody)
    If (($bSuccess = True) And ($oResult.JsonTypeOf("__type") = 1)) Then
        ConsoleWrite("AWS error type: " & $oResult.StringOf("__type") & @CRLF)
    Else
        ConsoleWrite("AWS error type: " & $oRest.ResponseHdrByName("x-amzn-errortype") & @CRLF)
    EndIf

    ;  Error messages, payloads, receipt handles and signed URLs can be private.
    ;  HTTP 400 can be throttling, expired credentials, or invalid parameters.
    Exit
EndIf

$bSuccess = $oResponseBody.Trim()
If ($bSuccess <> True) Then
    ConsoleWrite("Could not inspect response." & @CRLF)
    Exit
EndIf

If ($oResponseBody.StartsWith("{",True) <> True) Then
    ConsoleWrite("Expected a JSON object response." & @CRLF)
    Exit
EndIf

$bSuccess = $oResult.LoadSb($oResponseBody)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected well-formed JSON." & @CRLF)
    Exit
EndIf

Local $iResultsType = $oResult.JsonTypeOf("Results")
If (($iResultsType = -1) Or ($iResultsType = 6)) Then
    ConsoleWrite("No recent redrive tasks returned." & @CRLF)
    Exit
EndIf

If ($iResultsType <> 4) Then
    ConsoleWrite("Expected Results array." & @CRLF)
    Exit
EndIf

Local $i = 0
While ($i < $oResult.SizeOfArray("Results"))
    $oResult.I = $i
    $oTextCompare.Clear 
    $oTextCompare.SetString($oResult.StringOf("Results[i].Status"))
Local $bSameText13 = $oTextCompare.ContentsEqual("",True)
    If (($oResult.JsonTypeOf("Results[i].Status") <> 1) Or ($bSameText13 = True)) Then
        ConsoleWrite("Missing or invalid Results[i].Status." & @CRLF)
        Exit
    EndIf

    ConsoleWrite("Status: " & $oResult.StringOf("Results[i].Status") & @CRLF)
    ;  TaskHandle can be absent for tasks that are no longer running.
    If ($oResult.JsonTypeOf("Results[i].TaskHandle") = 1) Then
        ConsoleWrite("Task handle: " & $oResult.StringOf("Results[i].TaskHandle") & @CRLF)
    EndIf

    If ($oResult.JsonTypeOf("Results[i].ApproximateNumberOfMessagesMoved") = 2) Then
        ;  Use text to preserve counts beyond a 32-bit int.
        ConsoleWrite("Approximate moved count: " & $oResult.StringOf("Results[i].ApproximateNumberOfMessagesMoved") & @CRLF)
    EndIf

    If ($oResult.JsonTypeOf("Results[i].ApproximateNumberOfMessagesToMove") = 2) Then
        ConsoleWrite("Approximate total: " & $oResult.StringOf("Results[i].ApproximateNumberOfMessagesToMove") & @CRLF)
    EndIf

    If ($oResult.JsonTypeOf("Results[i].StartedTimestamp") = 2) Then
        ConsoleWrite("Started timestamp: " & $oResult.StringOf("Results[i].StartedTimestamp") & @CRLF)
    EndIf

    ;  FailureReason can contain sensitive details; inspect privately if status is FAILED.
    $i = $i + 1
Wend
ConsoleWrite("Recent redrive tasks inspected. This API returns at most ten recent tasks." & @CRLF)