In case anyone else sees this: AWS documentation recommends checking that the number of messages in a queue is zero for several minutes straight before considering that queue empty. This is due to the distributed nature of SQS and because these metrics are approximate.
To confirm that a queue is empty (AWS CLI, AWS API)
Stop all producers from sending messages.
Repeatedly run one of the following commands:
Observe the metrics for the following attributes:
ApproximateNumberOfMessagesDelayed
ApproximateNumberOfMessagesNotVisible
ApproximateNumberOfMessages
When all of them are 0
for several minutes, the queue is empty.
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/confirm-queue-is-empty.html
You can have your hosts check the number of messages in the queue every few seconds for several minutes and keep track of how long the queue has been continuously empty. Once you confirm the queue is empty, you can run the required job.
Alternatively, if you are using a FIFO queue with a single message group and know beforehand which message from the producer will be the last one, you can add a message attribute that marks that message as the last one.
ReceiveMessageRequest
,ApproximateNumberOfMessages
andApproximateNumberOfMessagesNotVisible
along with Long Polling to determine if the queue is empty or not. If the result ofReceiveMessageRequest
isnull
&&
ApproximateNumberOfMessages == 0
&&
ApproximateNumberOfMessagesNotVisible==0
, then can I be sure that there would be no message left in the queue? – Bunnie