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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
// StringBuilder compares text by value in every generated language.
final textCompare = CkStringBuilder();
// 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.
final credentials = CkJsonObject();
credentials.strict = true;
try {
credentials.loadFile('qa_data/aws/sqs.json');
} on ChilkatException {
print('Could not load private AWS credentials.');
return;
}
textCompare.clear();
textCompare.setString(credentials.stringOf('access_key'));
final sameText1 = textCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('access_key') != 1) || (sameText1)) {
print('Missing or invalid access_key.');
return;
}
textCompare.clear();
textCompare.setString(credentials.stringOf('secret_key'));
final sameText2 = textCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('secret_key') != 1) || (sameText2)) {
print('Missing or invalid secret_key.');
return;
}
// Set this once to the region containing the queue.
final region = 'us-west-2';
final endpoint = CkStringBuilder();
try {
endpoint.append('sqs.');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
endpoint.append(region);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
endpoint.append('.amazonaws.com');
} on ChilkatException {
print('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.
final queueUrl = credentials.stringOf('queue_url');
textCompare.clear();
textCompare.setString(queueUrl);
final sameText3 = textCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('queue_url') != 1) || (sameText3)) {
print('Missing or invalid queue_url in sqs.json.');
return;
}
final expectedPrefix = CkStringBuilder();
try {
expectedPrefix.append('https://');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
expectedPrefix.append(endpoint.getAsString());
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
expectedPrefix.append('/');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
final queueText = CkStringBuilder();
try {
queueText.append(queueUrl);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
if (!queueText.startsWith(expectedPrefix.getAsString(), true)) {
print('Queue URL must use HTTPS and the configured SQS region.');
return;
}
final aws = CkAuthAws();
aws.accessKey = credentials.stringOf('access_key');
aws.secretKey = credentials.stringOf('secret_key');
aws.region = region;
aws.serviceName = 'sqs';
aws.signatureVersion = 4;
final rest = CkRest();
rest.connectTimeoutMs = 20000;
rest.idleTimeoutMs = 60000;
try {
rest.setAuthAws(aws);
} on ChilkatException {
print('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')) {
if (credentials.jsonTypeOf('session_token') != 1) {
print('session_token must be a string.');
return;
}
textCompare.clear();
textCompare.setString(credentials.stringOf('session_token'));
final sameText4 = textCompare.contentsEqual('', true);
if (!sameText4) {
try {
rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
} on ChilkatException {
print('Could not set the session-token parameter.');
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
final connection = CkSocket();
connection.requireSslCertVerify = true;
connection.maxReadIdleMs = 60000;
connection.maxSendIdleMs = 60000;
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} on ChilkatException {
print('TLS connection failed; inspect diagnostics privately.');
return;
}
// Do not automatically reconnect/replay a write or receive after a lost response.
try {
rest.useConnection(connection, false);
} on ChilkatException {
print('Could not attach the TLS connection.');
return;
}
try {
rest.addHeader('Content-Type', 'application/x-amz-json-1.0');
} on ChilkatException {
print('Could not set the content type.');
return;
}
final body = CkJsonObject();
final result = CkJsonObject();
result.strict = true;
final requestBody = CkStringBuilder();
final responseBody = CkStringBuilder();
try {
rest.addHeader('X-Amz-Target', 'AmazonSQS.SendMessageBatch');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
body.updateString('QueueUrl', queueUrl);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
// Standard queue; fixed small bodies keep this example easy to adapt.
try {
body.updateString('Entries[0].Id', 'm0');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
body.updateString('Entries[0].MessageBody', 'First example message.');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
body.updateString('Entries[1].Id', 'm1');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
body.updateString('Entries[1].MessageBody', 'Second example message.');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
final numEntries = body.sizeOfArray('Entries');
if ((numEntries < 1) || (numEntries > 10)) {
print('A batch must have 1 through 10 entries.');
return;
}
final expected = CkHashtable();
final bodyBytes = CkBinData();
final returnedMd5 = CkStringBuilder();
var totalBytes = 0;
var i = 0;
while (i < numEntries) {
body.i = i;
final entryId = body.stringOf('Entries[i].Id');
if (expected.contains(entryId)) {
print('Batch entry IDs must be unique.');
return;
}
try {
bodyBytes.clear();
} on ChilkatException {
print('Could not prepare the request.');
return;
}
try {
bodyBytes.appendString(body.stringOf('Entries[i].MessageBody'), 'utf-8');
} on ChilkatException {
print('Could not prepare the request.');
return;
}
if ((bodyBytes.numBytes == 0) || (bodyBytes.numBytes > 1048576)) {
print('Message body must be nonempty and at most 1 MiB.');
return;
}
totalBytes += bodyBytes.numBytes;
if (totalBytes > 1048576) {
print('Total batch payload exceeds 1 MiB.');
return;
}
final String md5;
try {
md5 = bodyBytes.getHash('md5', 'hex');
} on ChilkatException {
print('Could not hash body.');
return;
}
try {
expected.addStr(entryId, md5);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
i++;
}
// EmitSb appends, so clear both builders before each request/page.
requestBody.clear();
responseBody.clear();
try {
body.emitSb(requestBody);
} on ChilkatException {
print('Could not serialize JSON.');
return;
}
try {
rest.fullRequestSb('POST', '/', requestBody, responseBody);
} on ChilkatException {
print('Request did not complete; inspect diagnostics privately.');
// A write or receive may have reached SQS. Do not blindly replay it.
return;
}
if (rest.responseStatusCode != 200) {
print('SQS HTTP status: ${rest.responseStatusCode}');
print('AWS request ID: ${rest.responseHdrByName('x-amzn-RequestId')}');
success = true;
try {
result.loadSb(responseBody);
} on ChilkatException {
success = false;
}
if ((success) && (result.jsonTypeOf('__type') == 1)) {
print('AWS error type: ${result.stringOf('__type')}');
} else {
print('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;
}
try {
responseBody.trim();
} on ChilkatException {
print('Could not inspect response.');
return;
}
if (!responseBody.startsWith('{', true)) {
print('Expected a JSON object response.');
return;
}
try {
result.loadSb(responseBody);
} on ChilkatException {
print('Expected well-formed JSON.');
return;
}
final seenResults = CkHashtable();
var resultCount = 0;
var failedCount = 0;
final successfulType = result.jsonTypeOf('Successful');
if ((successfulType != -1) && (successfulType != 6)) {
if (successfulType != 4) {
print('Expected Successful array.');
return;
}
var successfulIndex = 0;
while (successfulIndex < result.sizeOfArray('Successful')) {
result.i = successfulIndex;
textCompare.clear();
textCompare.setString(result.stringOf('Successful[i].Id'));
final sameText5 = textCompare.contentsEqual('', true);
if ((result.jsonTypeOf('Successful[i].Id') != 1) || (sameText5)) {
print('Missing or invalid Successful[i].Id.');
return;
}
final successfulId = result.stringOf('Successful[i].Id');
if (!expected.contains(successfulId)) {
print('Unexpected batch result ID; outcome needs reconciliation.');
return;
}
if (seenResults.contains(successfulId)) {
print('Duplicate batch result ID; outcome needs reconciliation.');
return;
}
try {
seenResults.addInt(successfulId, 1);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
textCompare.clear();
textCompare.setString(result.stringOf('Successful[i].MessageId'));
final sameText6 = textCompare.contentsEqual('', true);
if ((result.jsonTypeOf('Successful[i].MessageId') != 1) || (sameText6)) {
print('Missing or invalid Successful[i].MessageId.');
return;
}
textCompare.clear();
textCompare.setString(result.stringOf('Successful[i].MD5OfMessageBody'));
final sameText7 = textCompare.contentsEqual('', true);
if ((result.jsonTypeOf('Successful[i].MD5OfMessageBody') != 1) || (sameText7)) {
print('Missing or invalid Successful[i].MD5OfMessageBody.');
return;
}
returnedMd5.clear();
try {
returnedMd5.append(result.stringOf('Successful[i].MD5OfMessageBody'));
} on ChilkatException {
print('Could not prepare the request.');
return;
}
final expectedMd5 = expected.lookupStr(successfulId);
if (!returnedMd5.contentsEqual(expectedMd5, false)) {
print('Batch body MD5 mismatch; do not blindly resend.');
return;
}
print('Accepted entry: $successfulId Message ID: ${result.stringOf('Successful[i].MessageId')}');
resultCount++;
successfulIndex++;
}
}
final failedType = result.jsonTypeOf('Failed');
if ((failedType != -1) && (failedType != 6)) {
if (failedType != 4) {
print('Expected Failed array.');
return;
}
var failedIndex = 0;
while (failedIndex < result.sizeOfArray('Failed')) {
result.i = failedIndex;
textCompare.clear();
textCompare.setString(result.stringOf('Failed[i].Id'));
final sameText8 = textCompare.contentsEqual('', true);
if ((result.jsonTypeOf('Failed[i].Id') != 1) || (sameText8)) {
print('Missing or invalid Failed[i].Id.');
return;
}
final failedId = result.stringOf('Failed[i].Id');
if (!expected.contains(failedId)) {
print('Unexpected batch result ID; outcome needs reconciliation.');
return;
}
if (seenResults.contains(failedId)) {
print('Duplicate batch result ID; outcome needs reconciliation.');
return;
}
try {
seenResults.addInt(failedId, 1);
} on ChilkatException {
print('Could not prepare the request.');
return;
}
textCompare.clear();
textCompare.setString(result.stringOf('Failed[i].Code'));
final sameText9 = textCompare.contentsEqual('', true);
if ((result.jsonTypeOf('Failed[i].Code') != 1) || (sameText9)) {
print('Missing or invalid Failed[i].Code.');
return;
}
if (result.jsonTypeOf('Failed[i].SenderFault') != 5) {
print('Missing boolean SenderFault.');
return;
}
print('Failed entry: $failedId Code: ${result.stringOf('Failed[i].Code')}');
print('SenderFault: ${result.boolOf('Failed[i].SenderFault')}');
// SenderFault=false is not a guarantee a retry will succeed. Inspect the error code.
failedCount++;
resultCount++;
failedIndex++;
}
}
if (resultCount != numEntries) {
print('Missing batch results; outcome needs reconciliation.');
return;
}
if (failedCount > 0) {
print('Batch contains failed entries. No automatic retries were made.');
return;
}
print('All batch entries accepted.');
}