Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

Amazon SQS: Purge a Queue (Deletes All Messages)

See more Amazon SQS Examples

Destructive operation: PurgeQueue removes available and in-flight messages while retaining the queue and its configuration. Deleted messages cannot be recovered. The code defaults to purgeConfirmed=false and sends no request until you deliberately enable it.

Purge can take up to 60 seconds. Messages sent during that window may also be deleted. Stop or coordinate producers and consumers, verify the target account/region/queue, and wait at least 60 seconds before resuming traffic. PurgeQueueInProgress indicates a purge request within the preceding 60 seconds; it is not a successful second purge. HTTP 200 confirms acceptance, not completion. The JSON protocol returns an empty body; an empty JSON object is also accepted by this example.

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:PurgeQueue. Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.

AWS PurgeQueue reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
textCompare: HCkStringBuilder;
purgeConfirmed: Boolean;
credentials: HCkJsonObject;
sameText1: Boolean;
sameText2: Boolean;
region: PWideChar;
endpoint: HCkStringBuilder;
queueUrl: PWideChar;
sameText3: Boolean;
expectedPrefix: HCkStringBuilder;
queueText: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
sameText4: Boolean;
connection: HCkSocket;
body: HCkJsonObject;
result: HCkJsonObject;
requestBody: HCkStringBuilder;
responseBody: HCkStringBuilder;

begin
success := False;

//  StringBuilder compares text by value in every generated language.
textCompare := CkStringBuilder_Create();
//  DESTRUCTIVE: removes available AND in-flight messages from the entire queue.
//  Confirm the account/region/queue, and stop producers/consumers as appropriate.
purgeConfirmed := False;
if (purgeConfirmed <> True) then
  begin
    Memo1.Lines.Add('Purge disabled. Review the target queue and set purgeConfirmed to true deliberately.');
    Exit;
  end;
//  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.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/sqs.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private AWS credentials.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'access_key'));
sameText1 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (sameText1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'secret_key'));
sameText2 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (sameText2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
//  Set this once to the region containing the queue.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
success := CkStringBuilder_Append(endpoint,'sqs.');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,region);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'.amazonaws.com');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
//  Use the exact QueueUrl returned by CreateQueue, GetQueueUrl, or ListQueues.
//  This example targets a standard commercial regional endpoint, not a custom endpoint.
queueUrl := CkJsonObject__stringOf(credentials,'queue_url');
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,queueUrl);
sameText3 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'queue_url') <> 1) or (sameText3 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid queue_url in sqs.json.');
    Exit;
  end;
expectedPrefix := CkStringBuilder_Create();
success := CkStringBuilder_Append(expectedPrefix,'https://');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkStringBuilder_Append(expectedPrefix,CkStringBuilder__getAsString(endpoint));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkStringBuilder_Append(expectedPrefix,'/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
queueText := CkStringBuilder_Create();
success := CkStringBuilder_Append(queueText,queueUrl);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
if (CkStringBuilder_StartsWith(queueText,CkStringBuilder__getAsString(expectedPrefix),True) <> True) then
  begin
    Memo1.Lines.Add('Queue URL must use HTTPS and the configured SQS region.');
    Exit;
  end;
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'sqs');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  end;
//  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 (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
      begin
        Memo1.Lines.Add('session_token must be a string.');
        Exit;
      end;
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'session_token'));
    sameText4 := CkStringBuilder_ContentsEqual(textCompare,'',True);
    if (sameText4 <> True) then
      begin
        success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set the session-token parameter.');
            Exit;
          end;
      end;
  end;
//  Supply a Socket to explicitly enable TLS certificate verification.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
//  Do not automatically reconnect/replay a write or receive after a lost response.
success := CkRest_UseConnection(rest,connection,False);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach the TLS connection.');
    Exit;
  end;
success := CkRest_AddHeader(rest,'Content-Type','application/x-amz-json-1.0');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set the content type.');
    Exit;
  end;

body := CkJsonObject_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
requestBody := CkStringBuilder_Create();
responseBody := CkStringBuilder_Create();
success := CkRest_AddHeader(rest,'X-Amz-Target','AmazonSQS.PurgeQueue');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
success := CkJsonObject_UpdateString(body,'QueueUrl',queueUrl);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
//  EmitSb appends, so clear both builders before each request/page.
CkStringBuilder_Clear(requestBody);
CkStringBuilder_Clear(responseBody);
success := CkJsonObject_EmitSb(body,requestBody);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not serialize JSON.');
    Exit;
  end;
success := CkRest_FullRequestSb(rest,'POST','/',requestBody,responseBody);
if (success <> True) then
  begin
    Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
    //  A write or receive may have reached SQS. Do not blindly replay it.
    Exit;
  end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('SQS HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
    success := CkJsonObject_LoadSb(result,responseBody);
    if ((success = True) and (CkJsonObject_JsonTypeOf(result,'__type') = 1)) then
      begin
        Memo1.Lines.Add('AWS error type: ' + CkJsonObject__stringOf(result,'__type'));
      end
    else
      begin
        Memo1.Lines.Add('AWS error type: ' + CkRest__responseHdrByName(rest,'x-amzn-errortype'));
      end;
    //  Error messages, payloads, receipt handles and signed URLs can be private.
    //  HTTP 400 can be throttling, expired credentials, or invalid parameters.
    Exit;
  end;
//  DeleteMessage and PurgeQueue normally return an empty HTTP body.
//  Also accept an empty JSON object; never require XML for this protocol.
if (CkStringBuilder_getLength(responseBody) > 0) then
  begin
    success := CkStringBuilder_Trim(responseBody);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not inspect response.');
        Exit;
      end;
    if (CkStringBuilder_StartsWith(responseBody,'{',True) <> True) then
      begin
        Memo1.Lines.Add('Expected a JSON object response.');
        Exit;
      end;
    success := CkJsonObject_LoadSb(result,responseBody);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected well-formed JSON.');
        Exit;
      end;
    if (CkJsonObject_getSize(result) <> 0) then
      begin
        Memo1.Lines.Add('Unexpected fields in the empty-result response.');
        Exit;
      end;
  end;
Memo1.Lines.Add('Purge request accepted. Wait at least 60 seconds before resuming queue traffic.');
//  Acceptance is not completion. Messages sent during the purge may also be deleted.
//  Do not send another purge within 60 seconds; PurgeQueueInProgress is an error.

CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkStringBuilder_Dispose(expectedPrefix);
CkStringBuilder_Dispose(queueText);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(body);
CkJsonObject_Dispose(result);
CkStringBuilder_Dispose(requestBody);
CkStringBuilder_Dispose(responseBody);