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 Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoCrypt2.h>
BOOL success = NO;
// StringBuilder compares text by value in every generated language.
CkoStringBuilder *textCompare = [[CkoStringBuilder alloc] init];
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the SQS operation.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/sqs.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load private AWS credentials.");
return;
}
[textCompare Clear];
[textCompare SetString: [credentials StringOf: @"access_key"]];
BOOL sameText1 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || (sameText1 == YES)) {
NSLog(@"%@",@"Missing or invalid access_key.");
return;
}
[textCompare Clear];
[textCompare SetString: [credentials StringOf: @"secret_key"]];
BOOL sameText2 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || (sameText2 == YES)) {
NSLog(@"%@",@"Missing or invalid secret_key.");
return;
}
// Set this once to the region containing the queue.
NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
success = [endpoint Append: @"sqs."];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [endpoint Append: region];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [endpoint Append: @".amazonaws.com"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
// Use the exact QueueUrl returned by CreateQueue, GetQueueUrl, or ListQueues.
// This example targets a standard commercial regional endpoint, not a custom endpoint.
NSString *queueUrl = [credentials StringOf: @"queue_url"];
[textCompare Clear];
[textCompare SetString: queueUrl];
BOOL sameText3 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[credentials JsonTypeOf: @"queue_url"] intValue] != 1) || (sameText3 == YES)) {
NSLog(@"%@",@"Missing or invalid queue_url in sqs.json.");
return;
}
CkoStringBuilder *expectedPrefix = [[CkoStringBuilder alloc] init];
success = [expectedPrefix Append: @"https://"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [expectedPrefix Append: [endpoint GetAsString]];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [expectedPrefix Append: @"/"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
CkoStringBuilder *queueText = [[CkoStringBuilder alloc] init];
success = [queueText Append: queueUrl];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
if ([queueText StartsWith: [expectedPrefix GetAsString] caseSensitive: YES] != YES) {
NSLog(@"%@",@"Queue URL must use HTTPS and the configured SQS region.");
return;
}
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = [credentials StringOf: @"access_key"];
aws.SecretKey = [credentials StringOf: @"secret_key"];
aws.Region = region;
aws.ServiceName = @"sqs";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
success = [rest SetAuthAws: aws];
if (success != YES) {
NSLog(@"%@",@"Could not configure AWS signing.");
return;
}
// 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 HasMember: @"session_token"] == YES) {
if ([[credentials JsonTypeOf: @"session_token"] intValue] != 1) {
NSLog(@"%@",@"session_token must be a string.");
return;
}
[textCompare Clear];
[textCompare SetString: [credentials StringOf: @"session_token"]];
BOOL sameText4 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (sameText4 != YES) {
success = [rest AddQueryParam: @"X-Amz-Security-Token" value: [credentials StringOf: @"session_token"]];
if (success != YES) {
NSLog(@"%@",@"Could not set the session-token parameter.");
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
return;
}
// Do not automatically reconnect/replay a write or receive after a lost response.
success = [rest UseConnection: connection autoReconnect: NO];
if (success != YES) {
NSLog(@"%@",@"Could not attach the TLS connection.");
return;
}
success = [rest AddHeader: @"Content-Type" value: @"application/x-amz-json-1.0"];
if (success != YES) {
NSLog(@"%@",@"Could not set the content type.");
return;
}
CkoJsonObject *body = [[CkoJsonObject alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
CkoStringBuilder *requestBody = [[CkoStringBuilder alloc] init];
CkoStringBuilder *responseBody = [[CkoStringBuilder alloc] init];
success = [rest AddHeader: @"X-Amz-Target" value: @"AmazonSQS.ReceiveMessage"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateString: @"QueueUrl" value: queueUrl];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateInt: @"MaxNumberOfMessages" value: [NSNumber numberWithInt: 5]];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateInt: @"WaitTimeSeconds" value: [NSNumber numberWithInt: 20]];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateInt: @"VisibilityTimeout" value: [NSNumber numberWithInt: 60]];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateString: @"MessageSystemAttributeNames[0]" value: @"ApproximateReceiveCount"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateString: @"MessageSystemAttributeNames[1]" value: @"SentTimestamp"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
success = [body UpdateString: @"MessageAttributeNames[0]" value: @"All"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
// Rest and Socket read timeouts are 60 seconds, longer than this 20-second poll.
// EmitSb appends, so clear both builders before each request/page.
[requestBody Clear];
[responseBody Clear];
success = [body EmitSb: requestBody];
if (success != YES) {
NSLog(@"%@",@"Could not serialize JSON.");
return;
}
success = [rest FullRequestSb: @"POST" uriPath: @"/" requestBody: requestBody responseBody: responseBody];
if (success != YES) {
NSLog(@"%@",@"Request did not complete; inspect diagnostics privately.");
// A write or receive may have reached SQS. Do not blindly replay it.
return;
}
if ([rest.ResponseStatusCode intValue] != 200) {
NSLog(@"%@%d",@"SQS HTTP status: ",[rest.ResponseStatusCode intValue]);
NSLog(@"%@%@",@"AWS request ID: ",[rest ResponseHdrByName: @"x-amzn-RequestId"]);
success = [result LoadSb: responseBody];
if ((success == YES) && ([[result JsonTypeOf: @"__type"] intValue] == 1)) {
NSLog(@"%@%@",@"AWS error type: ",[result StringOf: @"__type"]);
}
else {
NSLog(@"%@%@",@"AWS error type: ",[rest ResponseHdrByName: @"x-amzn-errortype"]);
}
// Error messages, payloads, receipt handles and signed URLs can be private.
// HTTP 400 can be throttling, expired credentials, or invalid parameters.
return;
}
success = [responseBody Trim];
if (success != YES) {
NSLog(@"%@",@"Could not inspect response.");
return;
}
if ([responseBody StartsWith: @"{" caseSensitive: YES] != YES) {
NSLog(@"%@",@"Expected a JSON object response.");
return;
}
success = [result LoadSb: responseBody];
if (success != YES) {
NSLog(@"%@",@"Expected well-formed JSON.");
return;
}
int messagesType = [[result JsonTypeOf: @"Messages"] intValue];
if ((messagesType == -1) || (messagesType == 6)) {
NSLog(@"%@",@"No messages returned by this poll.");
return;
}
if (messagesType != 4) {
NSLog(@"%@",@"Expected Messages array.");
return;
}
int numMessages = [[result SizeOfArray: @"Messages"] intValue];
if (numMessages == 0) {
NSLog(@"%@",@"No messages returned by this poll.");
return;
}
CkoCrypt2 *digest = [[CkoCrypt2 alloc] init];
digest.HashAlgorithm = @"md5";
digest.Charset = @"utf-8";
digest.EncodingMode = @"hex";
CkoStringBuilder *returnedMd5 = [[CkoStringBuilder alloc] init];
int i = 0;
while ((i < numMessages)) {
result.I = [NSNumber numberWithInt: i];
if ([[result JsonTypeOf: @"Messages[i]"] intValue] != 3) {
NSLog(@"%@",@"Expected a message object.");
return;
}
[textCompare Clear];
[textCompare SetString: [result StringOf: @"Messages[i].MessageId"]];
BOOL sameText5 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"Messages[i].MessageId"] intValue] != 1) || (sameText5 == YES)) {
NSLog(@"%@",@"Missing or invalid Messages[i].MessageId.");
return;
}
[textCompare Clear];
[textCompare SetString: [result StringOf: @"Messages[i].ReceiptHandle"]];
BOOL sameText6 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"Messages[i].ReceiptHandle"] intValue] != 1) || (sameText6 == YES)) {
NSLog(@"%@",@"Missing or invalid Messages[i].ReceiptHandle.");
return;
}
[textCompare Clear];
[textCompare SetString: [result StringOf: @"Messages[i].Body"]];
BOOL sameText7 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"Messages[i].Body"] intValue] != 1) || (sameText7 == YES)) {
NSLog(@"%@",@"Missing or invalid Messages[i].Body.");
return;
}
[textCompare Clear];
[textCompare SetString: [result StringOf: @"Messages[i].MD5OfBody"]];
BOOL sameText8 = [textCompare ContentsEqual: @"" caseSensitive: YES];
if (([[result JsonTypeOf: @"Messages[i].MD5OfBody"] intValue] != 1) || (sameText8 == YES)) {
NSLog(@"%@",@"Missing or invalid Messages[i].MD5OfBody.");
return;
}
NSString *messageId = [result StringOf: @"Messages[i].MessageId"];
NSString *receiptHandle = [result StringOf: @"Messages[i].ReceiptHandle"];
NSString *messageBody = [result StringOf: @"Messages[i].Body"];
NSString *localMd5 = [digest HashStringENC: messageBody];
if (digest.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not calculate body MD5.");
return;
}
[returnedMd5 Clear];
success = [returnedMd5 Append: [result StringOf: @"Messages[i].MD5OfBody"]];
if (success != YES) {
NSLog(@"%@",@"Could not prepare the request.");
return;
}
if ([returnedMd5 ContentsEqual: localMd5 caseSensitive: NO] != YES) {
NSLog(@"%@",@"Body MD5 mismatch; do not process or delete this message.");
return;
}
NSLog(@"%@%@",@"Message ID: ",messageId);
// This body display is for demonstration. Keep real message contents out of shared logs.
NSLog(@"%@%@",@"Body: ",messageBody);
if ([[result JsonTypeOf: @"Messages[i].Attributes.ApproximateReceiveCount"] intValue] == 1) {
NSLog(@"%@%@",@"Approximate receive count: ",[result StringOf: @"Messages[i].Attributes.ApproximateReceiveCount"]);
}
if ([[result JsonTypeOf: @"Messages[i].Attributes.SentTimestamp"] intValue] == 1) {
// Epoch milliseconds stay strings; a 32-bit int would overflow.
NSLog(@"%@%@",@"Sent timestamp (milliseconds): ",[result StringOf: @"Messages[i].Attributes.SentTimestamp"]);
}
if ([[result JsonTypeOf: @"Messages[i].MessageAttributes.content_type.StringValue"] intValue] == 1) {
NSLog(@"%@%@",@"Content type attribute: ",[result StringOf: @"Messages[i].MessageAttributes.content_type.StringValue"]);
}
// 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;
}
NSLog(@"%@%d",@"Messages inspected: ",numMessages);