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

Amazon SQS: Send a Batch and Handle Partial Failures

See more Amazon SQS Examples

Send two standard-queue messages in one request, using short request-local IDs m0 and m1 to correlate results. A batch supports 1–10 entries and a total payload of at most 1 MiB. This example counts UTF-8 body bytes and verifies every successful body MD5. It sends no custom attributes; add their sizes to the accounting if you extend it.

HTTP 200 may include both Successful and Failed arrays. A Hashtable detects unknown, duplicate or missing result IDs. Report failures by Id, Code and SenderFault; retry only appropriate failed entries with bounded backoff. Do not repeat successful sends after a partial result. A lost response leaves the outcome uncertain, and standard queues do not deduplicate retries automatically. Batch request Id is distinct from SQS MessageId.

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 IAM action: sqs:SendMessage (also authorizes SendMessageBatch). Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.

AWS SendMessageBatch reference

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

;  StringBuilder compares text by value in every generated language.
$oTextCompare = ObjCreate("Chilkat.StringBuilder")
;  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 $bSameText1 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($bSameText1 = True)) Then
    ConsoleWrite("Missing or invalid access_key." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($oCredentials.StringOf("secret_key"))
Local $bSameText2 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($bSameText2 = 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

;  Use the exact QueueUrl returned by CreateQueue, GetQueueUrl, or ListQueues.
;  This example targets a standard commercial regional endpoint, not a custom endpoint.
Local $sQueueUrl = $oCredentials.StringOf("queue_url")
$oTextCompare.Clear 
$oTextCompare.SetString($sQueueUrl)
Local $bSameText3 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("queue_url") <> 1) Or ($bSameText3 = True)) Then
    ConsoleWrite("Missing or invalid queue_url in sqs.json." & @CRLF)
    Exit
EndIf

$oExpectedPrefix = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oExpectedPrefix.Append("https://")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

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

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

$oQueueText = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oQueueText.Append($sQueueUrl)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

If ($oQueueText.StartsWith($oExpectedPrefix.GetAsString(),True) <> True) Then
    ConsoleWrite("Queue URL must use HTTPS and the configured SQS region." & @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 $bSameText4 = $oTextCompare.ContentsEqual("",True)
    If ($bSameText4 <> 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.SendMessageBatch")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

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

;  Standard queue; fixed small bodies keep this example easy to adapt.
$bSuccess = $oBody.UpdateString("Entries[0].Id","m0")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oBody.UpdateString("Entries[0].MessageBody","First example message.")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oBody.UpdateString("Entries[1].Id","m1")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oBody.UpdateString("Entries[1].MessageBody","Second example message.")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

Local $iNumEntries = $oBody.SizeOfArray("Entries")
If (($iNumEntries < 1) Or ($iNumEntries > 10)) Then
    ConsoleWrite("A batch must have 1 through 10 entries." & @CRLF)
    Exit
EndIf

$oExpected = ObjCreate("Chilkat.Hashtable")
$oBodyBytes = ObjCreate("Chilkat.BinData")
$oReturnedMd5 = ObjCreate("Chilkat.StringBuilder")
Local $iTotalBytes = 0
Local $i = 0
While ($i < $iNumEntries)
    $oBody.I = $i
Local $sEntryId = $oBody.StringOf("Entries[i].Id")
    If ($oExpected.Contains($sEntryId) = True) Then
        ConsoleWrite("Batch entry IDs must be unique." & @CRLF)
        Exit
    EndIf

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

    $bSuccess = $oBodyBytes.AppendString($oBody.StringOf("Entries[i].MessageBody"),"utf-8")
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    If (($oBodyBytes.NumBytes = 0) Or ($oBodyBytes.NumBytes > 1048576)) Then
        ConsoleWrite("Message body must be nonempty and at most 1 MiB." & @CRLF)
        Exit
    EndIf

    $iTotalBytes = $iTotalBytes + $oBodyBytes.NumBytes
    If ($iTotalBytes > 1048576) Then
        ConsoleWrite("Total batch payload exceeds 1 MiB." & @CRLF)
        Exit
    EndIf

Local $sMd5 = $oBodyBytes.GetHash("md5","hex")
    If ($oBodyBytes.LastMethodSuccess <> True) Then
        ConsoleWrite("Could not hash body." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oExpected.AddStr($sEntryId,$sMd5)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    $i = $i + 1
Wend
;  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

$oSeenResults = ObjCreate("Chilkat.Hashtable")
Local $iResultCount = 0
Local $iFailedCount = 0
Local $iSuccessfulType = $oResult.JsonTypeOf("Successful")
If (($iSuccessfulType <> -1) And ($iSuccessfulType <> 6)) Then
    If ($iSuccessfulType <> 4) Then
        ConsoleWrite("Expected Successful array." & @CRLF)
        Exit
    EndIf

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

Local $successfulId = $oResult.StringOf("Successful[i].Id")
        If ($oExpected.Contains($successfulId) <> True) Then
            ConsoleWrite("Unexpected batch result ID; outcome needs reconciliation." & @CRLF)
            Exit
        EndIf

        If ($oSeenResults.Contains($successfulId) = True) Then
            ConsoleWrite("Duplicate batch result ID; outcome needs reconciliation." & @CRLF)
            Exit
        EndIf

        $bSuccess = $oSeenResults.AddInt($successfulId,1)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

        $oTextCompare.Clear 
        $oTextCompare.SetString($oResult.StringOf("Successful[i].MessageId"))
Local $bSameText6 = $oTextCompare.ContentsEqual("",True)
        If (($oResult.JsonTypeOf("Successful[i].MessageId") <> 1) Or ($bSameText6 = True)) Then
            ConsoleWrite("Missing or invalid Successful[i].MessageId." & @CRLF)
            Exit
        EndIf

        $oTextCompare.Clear 
        $oTextCompare.SetString($oResult.StringOf("Successful[i].MD5OfMessageBody"))
Local $bSameText7 = $oTextCompare.ContentsEqual("",True)
        If (($oResult.JsonTypeOf("Successful[i].MD5OfMessageBody") <> 1) Or ($bSameText7 = True)) Then
            ConsoleWrite("Missing or invalid Successful[i].MD5OfMessageBody." & @CRLF)
            Exit
        EndIf

        $oReturnedMd5.Clear 
        $bSuccess = $oReturnedMd5.Append($oResult.StringOf("Successful[i].MD5OfMessageBody"))
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

Local $sExpectedMd5 = $oExpected.LookupStr($successfulId)
        If ($oReturnedMd5.ContentsEqual($sExpectedMd5,False) <> True) Then
            ConsoleWrite("Batch body MD5 mismatch; do not blindly resend." & @CRLF)
            Exit
        EndIf

        ConsoleWrite("Accepted entry: " & $successfulId & " Message ID: " & $oResult.StringOf("Successful[i].MessageId") & @CRLF)
        $iResultCount = $iResultCount + 1
        $iSuccessfulIndex = $iSuccessfulIndex + 1
    Wend
EndIf

Local $iFailedType = $oResult.JsonTypeOf("Failed")
If (($iFailedType <> -1) And ($iFailedType <> 6)) Then
    If ($iFailedType <> 4) Then
        ConsoleWrite("Expected Failed array." & @CRLF)
        Exit
    EndIf

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

Local $sFailedId = $oResult.StringOf("Failed[i].Id")
        If ($oExpected.Contains($sFailedId) <> True) Then
            ConsoleWrite("Unexpected batch result ID; outcome needs reconciliation." & @CRLF)
            Exit
        EndIf

        If ($oSeenResults.Contains($sFailedId) = True) Then
            ConsoleWrite("Duplicate batch result ID; outcome needs reconciliation." & @CRLF)
            Exit
        EndIf

        $bSuccess = $oSeenResults.AddInt($sFailedId,1)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

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

        If ($oResult.JsonTypeOf("Failed[i].SenderFault") <> 5) Then
            ConsoleWrite("Missing boolean SenderFault." & @CRLF)
            Exit
        EndIf

        ConsoleWrite("Failed entry: " & $sFailedId & " Code: " & $oResult.StringOf("Failed[i].Code") & @CRLF)
        ConsoleWrite("SenderFault: " & $oResult.BoolOf("Failed[i].SenderFault") & @CRLF)
        ;  SenderFault=false is not a guarantee a retry will succeed. Inspect the error code.
        $iFailedCount = $iFailedCount + 1
        $iResultCount = $iResultCount + 1
        $iFailedIndex = $iFailedIndex + 1
    Wend
EndIf

If ($iResultCount <> $iNumEntries) Then
    ConsoleWrite("Missing batch results; outcome needs reconciliation." & @CRLF)
    Exit
EndIf

If ($iFailedCount > 0) Then
    ConsoleWrite("Batch contains failed entries. No automatic retries were made." & @CRLF)
    Exit
EndIf

ConsoleWrite("All batch entries accepted." & @CRLF)