Amazon SQS: Delete a Batch of Processed Deliveries
See more Amazon SQS Examples
Load 1–10 latest receipt handles from a private sqs-processed.json file and assign request-local string IDs. Include only deliveries whose application work committed successfully and whose handles belong to the configured queue. The file is input to this demonstration, not a durable acknowledgment mechanism: do not reuse it after the handles expire or newer deliveries arrive.
Match each successful or failed result to its request ID, even when HTTP status is 200. Duplicate, unknown or missing results are not treated as complete success. An old receipt handle can be accepted without deleting the newest delivery. Keep handles private, retry only suitable failures, and retain idempotent processing. No receive call or automatic deletion of unprocessed messages occurs.
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:DeleteMessage (also authorizes DeleteMessageBatch). Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.
AWS DeleteMessageBatch reference
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkHashtableW.h>
void ChilkatSample(void)
{
bool success = false;
// StringBuilder compares text by value in every generated language.
CkStringBuilderW textCompare;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the SQS operation.
CkJsonObjectW credentials;
credentials.put_Strict(true);
success = credentials.LoadFile(L"qa_data/aws/sqs.json");
if (success != true) {
wprintf(L"Could not load private AWS credentials.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"access_key"));
bool sameText1 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"access_key") != 1) || (sameText1 == true)) {
wprintf(L"Missing or invalid access_key.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"secret_key"));
bool sameText2 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"secret_key") != 1) || (sameText2 == true)) {
wprintf(L"Missing or invalid secret_key.\n");
return;
}
// Set this once to the region containing the queue.
const wchar_t *region = L"us-west-2";
CkStringBuilderW endpoint;
success = endpoint.Append(L"sqs.");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = endpoint.Append(region);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = endpoint.Append(L".amazonaws.com");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
// Use the exact QueueUrl returned by CreateQueue, GetQueueUrl, or ListQueues.
// This example targets a standard commercial regional endpoint, not a custom endpoint.
const wchar_t *queueUrl = credentials.stringOf(L"queue_url");
textCompare.Clear();
textCompare.SetString(queueUrl);
bool sameText3 = textCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"queue_url") != 1) || (sameText3 == true)) {
wprintf(L"Missing or invalid queue_url in sqs.json.\n");
return;
}
CkStringBuilderW expectedPrefix;
success = expectedPrefix.Append(L"https://");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedPrefix.Append(endpoint.getAsString());
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expectedPrefix.Append(L"/");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
CkStringBuilderW queueText;
success = queueText.Append(queueUrl);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
if (queueText.StartsWith(expectedPrefix.getAsString(),true) != true) {
wprintf(L"Queue URL must use HTTPS and the configured SQS region.\n");
return;
}
CkAuthAwsW aws;
aws.put_AccessKey(credentials.stringOf(L"access_key"));
aws.put_SecretKey(credentials.stringOf(L"secret_key"));
aws.put_Region(region);
aws.put_ServiceName(L"sqs");
aws.put_SignatureVersion(4);
CkRestW rest;
rest.put_ConnectTimeoutMs(20000);
rest.put_IdleTimeoutMs(60000);
success = rest.SetAuthAws(aws);
if (success != true) {
wprintf(L"Could not configure AWS signing.\n");
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(L"session_token") == true) {
if (credentials.JsonTypeOf(L"session_token") != 1) {
wprintf(L"session_token must be a string.\n");
return;
}
textCompare.Clear();
textCompare.SetString(credentials.stringOf(L"session_token"));
bool sameText4 = textCompare.ContentsEqual(L"",true);
if (sameText4 != true) {
success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
if (success != true) {
wprintf(L"Could not set the session-token parameter.\n");
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
CkSocketW connection;
connection.put_RequireSslCertVerify(true);
connection.put_MaxReadIdleMs(60000);
connection.put_MaxSendIdleMs(60000);
success = connection.Connect(endpoint.getAsString(),443,true,20000);
if (success != true) {
wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
return;
}
// Do not automatically reconnect/replay a write or receive after a lost response.
success = rest.UseConnection(connection,false);
if (success != true) {
wprintf(L"Could not attach the TLS connection.\n");
return;
}
success = rest.AddHeader(L"Content-Type",L"application/x-amz-json-1.0");
if (success != true) {
wprintf(L"Could not set the content type.\n");
return;
}
CkJsonObjectW body;
CkJsonObjectW result;
result.put_Strict(true);
CkStringBuilderW requestBody;
CkStringBuilderW responseBody;
success = rest.AddHeader(L"X-Amz-Target",L"AmazonSQS.DeleteMessageBatch");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = body.UpdateString(L"QueueUrl",queueUrl);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
// Populate only after the corresponding application work has committed.
// File shape: {"receipt_handles":["LATEST_HANDLE_1","LATEST_HANDLE_2"]}
CkJsonObjectW processed;
processed.put_Strict(true);
success = processed.LoadFile(L"qa_data/aws/sqs-processed.json");
if (success != true) {
wprintf(L"Could not load processed-delivery handles.\n");
return;
}
if (processed.JsonTypeOf(L"receipt_handles") != 4) {
wprintf(L"Expected receipt_handles array.\n");
return;
}
int numEntries = processed.SizeOfArray(L"receipt_handles");
if ((numEntries < 1) || (numEntries > 10)) {
wprintf(L"Supply 1 through 10 processed receipt handles.\n");
return;
}
CkHashtableW expected;
CkHashtableW seenHandles;
CkStringBuilderW idText;
int i = 0;
while ((i < numEntries)) {
processed.put_I(i);
body.put_I(i);
const wchar_t *receiptHandle = processed.stringOf(L"receipt_handles[i]");
textCompare.Clear();
textCompare.SetString(receiptHandle);
bool sameText5 = textCompare.ContentsEqual(L"",true);
if ((processed.JsonTypeOf(L"receipt_handles[i]") != 1) || (sameText5 == true)) {
wprintf(L"Expected a nonempty receipt handle.\n");
return;
}
if (seenHandles.Contains(receiptHandle) == true) {
wprintf(L"Duplicate receipt handle in input.\n");
return;
}
success = seenHandles.AddInt(receiptHandle,1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
idText.Clear();
success = idText.Append(L"m");
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = idText.AppendInt(i);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
const wchar_t *entryId = idText.getAsString();
success = body.UpdateString(L"Entries[i].Id",entryId);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = body.UpdateString(L"Entries[i].ReceiptHandle",receiptHandle);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
success = expected.AddInt(entryId,1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
i = i + 1;
}
// EmitSb appends, so clear both builders before each request/page.
requestBody.Clear();
responseBody.Clear();
success = body.EmitSb(requestBody);
if (success != true) {
wprintf(L"Could not serialize JSON.\n");
return;
}
success = rest.FullRequestSb(L"POST",L"/",requestBody,responseBody);
if (success != true) {
wprintf(L"Request did not complete; inspect diagnostics privately.\n");
// A write or receive may have reached SQS. Do not blindly replay it.
return;
}
if (rest.get_ResponseStatusCode() != 200) {
wprintf(L"SQS HTTP status: %d\n",rest.get_ResponseStatusCode());
wprintf(L"AWS request ID: %s\n",rest.responseHdrByName(L"x-amzn-RequestId"));
success = result.LoadSb(responseBody);
if ((success == true) && (result.JsonTypeOf(L"__type") == 1)) {
wprintf(L"AWS error type: %s\n",result.stringOf(L"__type"));
}
else {
wprintf(L"AWS error type: %s\n",rest.responseHdrByName(L"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 != true) {
wprintf(L"Could not inspect response.\n");
return;
}
if (responseBody.StartsWith(L"{",true) != true) {
wprintf(L"Expected a JSON object response.\n");
return;
}
success = result.LoadSb(responseBody);
if (success != true) {
wprintf(L"Expected well-formed JSON.\n");
return;
}
CkHashtableW seenResults;
int resultCount = 0;
int failedCount = 0;
int successfulType = result.JsonTypeOf(L"Successful");
if ((successfulType != -1) && (successfulType != 6)) {
if (successfulType != 4) {
wprintf(L"Expected Successful array.\n");
return;
}
int successfulIndex = 0;
while ((successfulIndex < result.SizeOfArray(L"Successful"))) {
result.put_I(successfulIndex);
textCompare.Clear();
textCompare.SetString(result.stringOf(L"Successful[i].Id"));
bool sameText6 = textCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"Successful[i].Id") != 1) || (sameText6 == true)) {
wprintf(L"Missing or invalid Successful[i].Id.\n");
return;
}
const wchar_t *successfulId = result.stringOf(L"Successful[i].Id");
if (expected.Contains(successfulId) != true) {
wprintf(L"Unexpected batch result ID; outcome needs reconciliation.\n");
return;
}
if (seenResults.Contains(successfulId) == true) {
wprintf(L"Duplicate batch result ID; outcome needs reconciliation.\n");
return;
}
success = seenResults.AddInt(successfulId,1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
wprintf(L"Deleted entry: %s\n",successfulId);
resultCount = resultCount + 1;
successfulIndex = successfulIndex + 1;
}
}
int failedType = result.JsonTypeOf(L"Failed");
if ((failedType != -1) && (failedType != 6)) {
if (failedType != 4) {
wprintf(L"Expected Failed array.\n");
return;
}
int failedIndex = 0;
while ((failedIndex < result.SizeOfArray(L"Failed"))) {
result.put_I(failedIndex);
textCompare.Clear();
textCompare.SetString(result.stringOf(L"Failed[i].Id"));
bool sameText7 = textCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"Failed[i].Id") != 1) || (sameText7 == true)) {
wprintf(L"Missing or invalid Failed[i].Id.\n");
return;
}
const wchar_t *failedId = result.stringOf(L"Failed[i].Id");
if (expected.Contains(failedId) != true) {
wprintf(L"Unexpected batch result ID; outcome needs reconciliation.\n");
return;
}
if (seenResults.Contains(failedId) == true) {
wprintf(L"Duplicate batch result ID; outcome needs reconciliation.\n");
return;
}
success = seenResults.AddInt(failedId,1);
if (success != true) {
wprintf(L"Could not prepare the request.\n");
return;
}
textCompare.Clear();
textCompare.SetString(result.stringOf(L"Failed[i].Code"));
bool sameText8 = textCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"Failed[i].Code") != 1) || (sameText8 == true)) {
wprintf(L"Missing or invalid Failed[i].Code.\n");
return;
}
if (result.JsonTypeOf(L"Failed[i].SenderFault") != 5) {
wprintf(L"Missing boolean SenderFault.\n");
return;
}
wprintf(L"Failed entry: %s Code: %s\n",failedId,result.stringOf(L"Failed[i].Code"));
wprintf(L"SenderFault: %d\n",result.BoolOf(L"Failed[i].SenderFault"));
// SenderFault=false is not a guarantee a retry will succeed. Inspect the error code.
failedCount = failedCount + 1;
resultCount = resultCount + 1;
failedIndex = failedIndex + 1;
}
}
if (resultCount != numEntries) {
wprintf(L"Missing batch results; outcome needs reconciliation.\n");
return;
}
if (failedCount > 0) {
wprintf(L"Batch contains failed entries. No automatic retries were made.\n");
return;
}
wprintf(L"All batch entries accepted.\n");
}