Amazon SQS API Guide

Amazon Simple Queue Service (SQS) stores messages until an application receives and processes them. Producers send messages to a queue; consumers receive them, perform the work, and delete the successfully processed deliveries. This guide explains that workflow and links to 18 complete examples using signed Chilkat.Rest requests.

Before making requests

The examples require Chilkat 11.6.0 or later and an unlocked library. They use AWS Signature Version 4 with a regional SQS endpoint and do not require an AWS SDK. Set the region in the code to match the queue. The examples use commercial endpoints such as sqs.us-west-2.amazonaws.com; other AWS partitions and custom endpoints require corresponding changes.

Each example explicitly reads a private qa_data/aws/sqs.json file. Supply current IAM credentials, preferably short-lived role credentials. Temporary credentials require their session token as well as the access key and secret key. The examples do not automatically discover AWS profiles, obtain role credentials, or refresh expired credentials. Keep the file outside public web content and source control.

{
  "access_key": "YOUR_ACCESS_KEY",
  "secret_key": "YOUR_SECRET_KEY",
  "session_token": "YOUR_SESSION_TOKEN",
  "queue_url": "https://sqs.us-west-2.amazonaws.com/123456789012/ExampleQueue"
}

Omit session_token only when the credentials do not have one. Queue-specific examples read queue_url; queue creation and discovery do not require it. The dead-letter configuration example also needs dlq_url. Use the exact URLs returned by SQS and retain their case. Configure IAM permissions for the chosen operations and queues; a credential's existence does not establish permission.

How SQS requests map to Chilkat.Rest

The examples use SQS's AWS JSON protocol: POST a JSON body to the regional endpoint's root path, and identify the operation with a header such as X-Amz-Target: AmazonSQS.SendMessage. The queue URL is a JSON request field for queue-specific operations, not the POST path. The older Query/XML protocol is still supported, but these examples use JSON. See AWS JSON request format.

Building and checking a signed SQS request
RequirementChilkat implementation
SigningSet AuthAws.AccessKey, SecretKey, Region, ServiceName = "sqs", and SignatureVersion = 4, then call Rest.SetAuthAws.
Temporary credentialsThe examples add X-Amz-Security-Token with Rest.AddQueryParam, which includes it in the signed query. Keep signed URLs and detailed request diagnostics private.
HTTPSEnable Socket.RequireSslCertVerify, connect with TLS on port 443, and attach the connection with Rest.UseConnection.
Operation headersAdd Content-Type: application/x-amz-json-1.0 and the operation-specific X-Amz-Target using Rest.AddHeader.
Body and requestBuild inputs with JsonObject, serialize with EmitSb, and call Rest.FullRequestSb("POST", "/", requestBody, responseBody). Clear reused builders first: EmitSb appends.
ResponseCheck transport completion and Rest.ResponseStatusCode separately. Parse JSON with JsonObject.Strict enabled and check required fields. Operations with no response fields can return an empty HTTP body.

A completed HTTP exchange is not necessarily a successful SQS operation. Batch operations need per-entry checks even with HTTP 200. A disconnected response can leave the outcome unknown; these examples disable automatic reconnection for writes and receives to avoid replaying a request whose result was lost. Read-only queue listing permits reconnection.

Keep identifiers distinct

Identifiers used by the examples
ValuePurpose
Queue URLIdentifies the queue for sending, receiving, attributes, deletion, and most other queue operations.
Queue ARNIdentifies the resource in IAM and dead-letter policies and in message movement requests. Read it with GetQueueAttributes.
MessageIdIdentifies a message returned by SQS. It is not sufficient to delete a delivery.
ReceiptHandleIdentifies a particular receipt of a message. Use the latest handle for deletion or visibility changes.
Batch entry IdA request-local string used to match each Successful or Failed result to its input.
FIFO group and deduplication IDsApplication-supplied values controlling ordering groups and duplicate-send suppression. They are separate from MessageId.

Keep IDs, ARNs, URLs, receipt handles, and pagination tokens as strings. FIFO sequence numbers can exceed 64 bits; the examples also preserve large returned counts and timestamps as text. See SQS queue and message identifiers.

Queues and Configuration

Use Resolve a Queue URL by Name when the application already knows the name. Supply the optional owner's account ID for authorized access to another account's queue. Use List Queues with Pagination to discover queues in your account and region, optionally by name prefix. It follows NextToken, detects repeated tokens, and reports incomplete enumeration if its demonstration page bound is reached.

Read Queue Attributes and Approximate Counts obtains the ARN, configuration, and approximate message counts. Available, delayed, and in-flight counts describe different states; they are eventually consistent and cannot prove that all processing has finished. The code enumerates the string-valued attribute map and accepts unfamiliar attribute names.

The standard-queue creation example configures visibility, long polling, SQS-managed encryption, and a 1 MiB maximum message size. Wait at least one second before using a newly created queue. An existing queue with the same name and matching attributes can return its existing URL; conflicting attributes cause an error.

The update example offers separate modes for processing settings, retention, and a customer-managed KMS key. Queue attribute values are JSON strings, even when they represent numbers or booleans. Most updates can take up to 60 seconds to propagate; retention changes can take up to 15 minutes. Reducing retention can expire existing messages. Changing encryption does not remove the need for the old key to read messages already encrypted with it. See SetQueueAttributes.

Sending and Receiving Messages

A message has a text body and can have custom attributes with declared data types. SQS supports bodies up to 1 MiB, subject to the queue's configured limit and attribute size overhead. Measure UTF-8 bytes, not character count. The send and receive examples verify the returned body MD5; they do not calculate the separate message-attribute MD5.

Send a Batch and Handle Partial Failures sends two messages and matches responses by entry Id, without relying on response order. A batch allows up to ten entries and a combined payload of at most 1 MiB. HTTP 200 can contain both Successful and Failed entries. The example detects missing, duplicate, and unexpected result IDs and verifies successful body hashes. Retry only suitable failed entries; resending successful standard-queue messages can create duplicates. See SendMessageBatch.

Receive Messages with Long Polling asks for up to five messages, waits up to 20 seconds, and applies a 60-second visibility timeout. A response can contain fewer messages or none. The client read timeout must be longer than the polling wait. Every returned message is inspected; the example deliberately does not delete messages before application processing has succeeded. See AWS long-polling guidance.

FIFO Queues

Choose a FIFO queue when messages need ordered processing within each group. Its name ends in .fifo, and its FifoQueue attribute is true. Queue type cannot be changed in place. Independent groups allow concurrent processing; a single group establishes one ordering sequence.

The creation example disables content-based deduplication, so each send supplies an explicit MessageDeduplicationId along with MessageGroupId. Persist the group, body, and deduplication ID for a logical message. Reuse them when retrying that same send, and choose a new deduplication ID for new work. The example's constant ID demonstrates one send and should not be used for every message.

SQS suppresses duplicate sends with the same deduplication ID within its five-minute deduplication interval. A retry after that window can create another message. If content-based deduplication is enabled instead, its hash uses the body, not custom attributes. Consumer work must still tolerate a message being delivered again after visibility expires; queue deduplication is not a transaction with the application's database. See FIFO identifiers and deduplication.

Message Processing and Acknowledgment

Receiving a message temporarily hides it from other receives. It does not remove the message. The normal sequence is: receive, process, commit the application's work, then delete using the latest receipt handle. If work fails or the consumer stops before deletion, the message becomes available again after its visibility timeout. Design processing so that a repeated delivery does not repeat an already committed effect.

Extend or Release Message Visibility sets 120 seconds from the change request, or zero to release the delivery. Extend before the current timeout expires. The maximum remaining visibility is bounded by 12 hours from the original receive; another extension does not restart that clock. Stop local work before releasing a message so another consumer can safely receive it. The change applies to this delivery, not the queue default or later receipts. See SQS visibility timeout.

The single-delete example requires an explicitly supplied processed-delivery handle. The batch version reads 1–10 latest handles from a private qa_data/aws/sqs-processed.json file containing a receipt_handles array. That file is demonstration input, not a permanent acknowledgment record. Do not reuse stale handles. An old handle can be accepted without deleting the newest delivery. Batch deletion checks each result independently; HTTP 200 alone does not acknowledge every entry.

Dead-Letter Queues

A dead-letter queue (DLQ) holds messages that repeatedly fail processing. Use two existing queues in the same account and region. The configuration example reads their ARNs and checks that both queues have the same type. It sets a DLQ RedriveAllowPolicy permitting this source, then a source RedrivePolicy with the DLQ ARN and maxReceiveCount of five. Both policy values are serialized JSON strings inside the Attributes map.

These updates are separate operations. A failure on the second write leaves the first change in place. Inspect both policies after propagation and include every intended source before replacing a shared DLQ's allow policy. Choose retention and receive count for the application; standard-queue DLQ retention should exceed source retention. Moving messages out of a FIFO sequence can affect end-to-end ordering. See Using dead-letter queues.

Start, Inspect, and Cancel Dead-Letter Redrive moves messages back for processing after the underlying failure has been fixed. Its default mode lists up to ten recent tasks. Start mode requests ten messages per second, returning messages to their original queues or to a specified same-type destination. Cancel mode requires a running task handle; cancellation does not undo messages already moved.

This redrive feature supports DLQs whose sources are SQS queues. Only one movement task can be active per source DLQ. Redriven messages receive new message IDs and enqueue times and can interleave with newly produced messages. The example performs one selected operation per run, not an automatic polling loop. Recent task results are not a complete audit history. See AWS redrive behavior and permissions.

Tags and Queue Maintenance

Queue tags help organize resources and can participate in access policies. They are distinct from message attributes. The tag example lists tags by default, adds or updates two named keys in add mode, and removes only those keys in remove mode. It handles literal tag names containing dots and preserves unrelated tags.

Purge and deletion are destructive and disabled by default. Verify the account, region, and exact queue before enabling either example. Coordinate producers and consumers before running it.

Purge a Queue removes messages, including in-flight messages, while keeping the queue. It can take up to 60 seconds, and messages sent during that interval can also be removed. Wait at least 60 seconds before another purge; deleted messages cannot be recovered through SQS. See PurgeQueue.

Delete a Queue Deliberately removes the queue and its contents. Deletion can take up to 60 seconds, and requests during that interval can appear to succeed even though their messages will be lost with the queue. Wait at least 60 seconds before creating a queue with the same name. An accepted delete response does not establish that deletion has already finished. See DeleteQueue.

Permissions, errors, and retries

Grant only the needed IAM actions on the relevant queues. Action names do not always match the API name: SendMessageBatch uses sqs:SendMessage, and DeleteMessageBatch uses sqs:DeleteMessage. ListQueues requires resource *. Redrive needs its task action plus access to read and remove messages from the DLQ and send to destinations, as applicable; encrypted queues can also require KMS permissions. See SQS API permissions reference.

On failure, record the operation, HTTP status, AWS error type, and request ID. Check the signing region, endpoint, clock, session token, and policies before retrying. Some throttling and credential errors use HTTP 400. Use bounded backoff with jitter for retryable failures, replace expired credentials, and reconcile uncertain writes before replaying them. Keep message bodies, receipt handles, credentials, and signed request URLs out of public logs.