Amazon SQS: Receive Messages with Long Polling
See more Amazon SQS Examples
Make one long poll for up to five messages (SQS allows 1–10) and iterate every returned message. WaitTimeSeconds=20 reduces empty polling; the HTTP read timeout is longer. No messages is a normal result and does not prove the queue is permanently empty. The code requests current MessageSystemAttributeNames instead of deprecated AttributeNames, plus custom attributes.
The 60-second visibility timeout starts when messages are received, not when each loop iteration begins. Choose batch size and visibility for actual processing time; ChangeMessageVisibility can extend processing time or release a delivery. This inspection example prints bodies, verifies body MD5, and deletes nothing; messages become eligible for redelivery. Real consumers should commit their work before deleting and handle duplicates idempotently. Message IDs, delivery receipt handles, counts and millisecond timestamps remain strings. Keep real payloads and receipt handles private.
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:ReceiveMessage. Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.
Chilkat AutoIt Downloads
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.ReceiveMessage")
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
$bSuccess = $oBody.UpdateInt("MaxNumberOfMessages",5)
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
$bSuccess = $oBody.UpdateInt("WaitTimeSeconds",20)
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
$bSuccess = $oBody.UpdateInt("VisibilityTimeout",60)
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
$bSuccess = $oBody.UpdateString("MessageSystemAttributeNames[0]","ApproximateReceiveCount")
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
$bSuccess = $oBody.UpdateString("MessageSystemAttributeNames[1]","SentTimestamp")
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
$bSuccess = $oBody.UpdateString("MessageAttributeNames[0]","All")
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
; Rest and Socket read timeouts are 60 seconds, longer than this 20-second poll.
; 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 $iMessagesType = $oResult.JsonTypeOf("Messages")
If (($iMessagesType = -1) Or ($iMessagesType = 6)) Then
ConsoleWrite("No messages returned by this poll." & @CRLF)
Exit
EndIf
If ($iMessagesType <> 4) Then
ConsoleWrite("Expected Messages array." & @CRLF)
Exit
EndIf
Local $iNumMessages = $oResult.SizeOfArray("Messages")
If ($iNumMessages = 0) Then
ConsoleWrite("No messages returned by this poll." & @CRLF)
Exit
EndIf
$oDigest = ObjCreate("Chilkat.Crypt2")
$oDigest.HashAlgorithm = "md5"
$oDigest.Charset = "utf-8"
$oDigest.EncodingMode = "hex"
$oReturnedMd5 = ObjCreate("Chilkat.StringBuilder")
Local $i = 0
While ($i < $iNumMessages)
$oResult.I = $i
If ($oResult.JsonTypeOf("Messages[i]") <> 3) Then
ConsoleWrite("Expected a message object." & @CRLF)
Exit
EndIf
$oTextCompare.Clear
$oTextCompare.SetString($oResult.StringOf("Messages[i].MessageId"))
Local $bSameText5 = $oTextCompare.ContentsEqual("",True)
If (($oResult.JsonTypeOf("Messages[i].MessageId") <> 1) Or ($bSameText5 = True)) Then
ConsoleWrite("Missing or invalid Messages[i].MessageId." & @CRLF)
Exit
EndIf
$oTextCompare.Clear
$oTextCompare.SetString($oResult.StringOf("Messages[i].ReceiptHandle"))
Local $bSameText6 = $oTextCompare.ContentsEqual("",True)
If (($oResult.JsonTypeOf("Messages[i].ReceiptHandle") <> 1) Or ($bSameText6 = True)) Then
ConsoleWrite("Missing or invalid Messages[i].ReceiptHandle." & @CRLF)
Exit
EndIf
$oTextCompare.Clear
$oTextCompare.SetString($oResult.StringOf("Messages[i].Body"))
Local $bSameText7 = $oTextCompare.ContentsEqual("",True)
If (($oResult.JsonTypeOf("Messages[i].Body") <> 1) Or ($bSameText7 = True)) Then
ConsoleWrite("Missing or invalid Messages[i].Body." & @CRLF)
Exit
EndIf
$oTextCompare.Clear
$oTextCompare.SetString($oResult.StringOf("Messages[i].MD5OfBody"))
Local $bSameText8 = $oTextCompare.ContentsEqual("",True)
If (($oResult.JsonTypeOf("Messages[i].MD5OfBody") <> 1) Or ($bSameText8 = True)) Then
ConsoleWrite("Missing or invalid Messages[i].MD5OfBody." & @CRLF)
Exit
EndIf
Local $sMessageId = $oResult.StringOf("Messages[i].MessageId")
Local $sReceiptHandle = $oResult.StringOf("Messages[i].ReceiptHandle")
Local $sMessageBody = $oResult.StringOf("Messages[i].Body")
Local $sLocalMd5 = $oDigest.HashStringENC($sMessageBody)
If ($oDigest.LastMethodSuccess <> True) Then
ConsoleWrite("Could not calculate body MD5." & @CRLF)
Exit
EndIf
$oReturnedMd5.Clear
$bSuccess = $oReturnedMd5.Append($oResult.StringOf("Messages[i].MD5OfBody"))
If ($bSuccess <> True) Then
ConsoleWrite("Could not prepare the request." & @CRLF)
Exit
EndIf
If ($oReturnedMd5.ContentsEqual($sLocalMd5,False) <> True) Then
ConsoleWrite("Body MD5 mismatch; do not process or delete this message." & @CRLF)
Exit
EndIf
ConsoleWrite("Message ID: " & $sMessageId & @CRLF)
; This body display is for demonstration. Keep real message contents out of shared logs.
ConsoleWrite("Body: " & $sMessageBody & @CRLF)
If ($oResult.JsonTypeOf("Messages[i].Attributes.ApproximateReceiveCount") = 1) Then
ConsoleWrite("Approximate receive count: " & $oResult.StringOf("Messages[i].Attributes.ApproximateReceiveCount") & @CRLF)
EndIf
If ($oResult.JsonTypeOf("Messages[i].Attributes.SentTimestamp") = 1) Then
; Epoch milliseconds stay strings; a 32-bit int would overflow.
ConsoleWrite("Sent timestamp (milliseconds): " & $oResult.StringOf("Messages[i].Attributes.SentTimestamp") & @CRLF)
EndIf
If ($oResult.JsonTypeOf("Messages[i].MessageAttributes.content_type.StringValue") = 1) Then
ConsoleWrite("Content type attribute: " & $oResult.StringOf("Messages[i].MessageAttributes.content_type.StringValue") & @CRLF)
EndIf
; receiptHandle belongs to THIS delivery. Pass it with queueUrl to DeleteMessage
; only after application work succeeds durably. Do not use messageId for deletion.
; This inspection example performs no application work and deletes nothing.
; Visibility is a processing window, not a guarantee against duplicate delivery.
$i = $i + 1
Wend
ConsoleWrite("Messages inspected: " & $iNumMessages & @CRLF)