Best way to move messages off DLQ in Amazon SQS?

Amazon Web-ServicesAmazon Sqs

Amazon Web-Services Problem Overview

What is the best practice to move messages from a dead letter queue back to the original queue in Amazon SQS?

Would it be

  1. Get message from DLQ
  2. Write message to queue
  3. Delete message from DLQ

Or is there a simpler way?

Also, will AWS eventually have a tool in the console to move messages off the DLQ?

Amazon Web-Services Solutions

Solution 1 - Amazon Web-Services

Here is a quick hack. This is definitely not the best or recommended option.

  1. Set the main SQS queue as the DLQ for the actual DLQ with Maximum Receives as 1.
  2. View the content in DLQ (This will move the messages to the main queue as this is the DLQ for the actual DLQ)
  3. Remove the setting so that the main queue is no more the DLQ of the actual DLQ

Solution 2 - Amazon Web-Services

There are a few scripts out there that do this for you:

# install
npm install replay-aws-dlq;

# use
npx replay-aws-dlq [source_queue_url] [dest_queue_url]
# compile:

# use
sqsmover -s [source_queue_url] -d [dest_queue_url] 

Solution 3 - Amazon Web-Services

On Dec 1 2021 AWS released the ability to redrive messages from a DLQ back to the source queue(or custom queue).

> With dead-letter queue redrive to source queue, you can simplify and enhance your error-handling workflows for standard queues.

DLQ redrive


Introducing Amazon Simple Queue Service dead-letter queue redrive to source queues

Solution 4 - Amazon Web-Services

Don't need to move the message because it will come with so many other challenges like duplicate messages, recovery scenarios, lost message, de-duplication check and etc.

Here is the solution which we implemented -

Usually, we use the DLQ for transient errors, not for permanent errors. So took below approach -

  1. Read the message from DLQ like a regular queue #####Benefits
    • To avoid duplicate message processing
    • Better control on DLQ- Like I put a check, to process only when the regular queue is completely processed.
    • Scale up the process based on the message on DLQ
  2. Then follow the same code which regular queue is following.
  3. More reliable in case of aborting the job or the process got terminated while processing (e.g. Instance killed or process terminated)
- Code reusability
- Error handling
- Recovery and message replay

3. Extend the message visibility so that no other thread process them.

- Avoid processing same record by multiple threads.

4. Delete the message only when either there is a permanent error or successful.

- Keep processing until we are getting a transient error.

Solution 5 - Amazon Web-Services

That looks like your best option. There is a possibility that your process fails after step 2. In that case you'll end up copying the message twice, but you application should be handling re-delivery of messages (or not care) anyway.

Solution 6 - Amazon Web-Services

I wrote a small python script to do this, by using boto3 lib:

conf = {
  "sqs-access-key": "",
  "sqs-secret-key": "",
  "reader-sqs-queue": "",
  "writer-sqs-queue": "",
  "message-group-id": ""

import boto3
client = boto3.client(
        aws_access_key_id       = conf.get('sqs-access-key'),
        aws_secret_access_key   = conf.get('sqs-secret-key')

while True:
	messages = client.receive_message(QueueUrl=conf['reader-sqs-queue'], MaxNumberOfMessages=10, WaitTimeSeconds=10)

	if 'Messages' in messages:
		for m in messages['Messages']:
			ret = client.send_message( QueueUrl=conf['writer-sqs-queue'], MessageBody=m['Body'], MessageGroupId=conf['message-group-id'])
			client.delete_message(QueueUrl=conf['reader-sqs-queue'], ReceiptHandle=m['ReceiptHandle'])
		print('Queue is currently empty or messages are invisible')

you can get this script in this link

this script basically can move messages between any arbitrary queues. and it supports fifo queues as well as you can supply the message_group_id field.

Solution 7 - Amazon Web-Services


import boto3
import sys
import Queue
import threading

work_queue = Queue.Queue()

sqs = boto3.resource('sqs')

from_q_name = sys.argv[1]
to_q_name = sys.argv[2]
print("From: " + from_q_name + " To: " + to_q_name)

from_q = sqs.get_queue_by_name(QueueName=from_q_name)
to_q = sqs.get_queue_by_name(QueueName=to_q_name)

def process_queue():
    while True:
        messages = work_queue.get()

        bodies = list()
        for i in range(0, len(messages)):
            bodies.append({'Id': str(i+1), 'MessageBody': messages[i].body})


        for message in messages:
            print("Coppied " + str(message.body))

for i in range(10):
     t = threading.Thread(target=process_queue)
     t.daemon = True

while True:
    messages = list()
    for message in from_q.receive_messages(


Solution 8 - Amazon Web-Services

DLQ comes into play only when the original consumer fails to consume message successfully after various attempts. We do not want to delete the message since we believe we can still do something with it (maybe attempt to process again or log it or collect some stats) and we do not want to keep encountering this message again and again and stop the ability to process other messages behind this one.

DLQ is nothing but just another queue. Which means we would need to write a consumer for DLQ that would ideally run less frequently (compared to original queue) that would consume from DLQ and produce message back into the original queue and delete it from DLQ - if thats the intended behavior and we think original consumer would be now ready to process it again. It should be OK if this cycle continues for a while since we now also get an opportunity to manually inspect and make necessary changes and deploy another version of original consumer without losing the message (within the message retention period of course - which is 4 days by default).

Would be nice if AWS provides this capability out of the box but I don't see it yet - they're leaving this to the end user to use it in way they feel appropriate.

Solution 9 - Amazon Web-Services

There is a another way to achieve this without writing single line of code. Consider your actual queue name is SQS_Queue and the DLQ for it is SQS_DLQ. Now follow these steps:

  1. Set SQS_Queue as the dlq of SQS_DLQ. Since SQS_DLQ is already a dlq of SQS_Queue. Now, both are acting as the dlq of the other.
  2. Set max receive count of your SQS_DLQ to 1.
  3. Now read messages from SQS_DLQ console. Since message receive count is 1, it will send all the message to its own dlq which is your actual SQS_Queue queue.

Solution 10 - Amazon Web-Services

We use the following script to redrive message from src queue to tgt queue:


usage: python -s {source queue name} -t {target queue name}

This script is used to redrive message in (src) queue to (tgt) queue

The solution is to set the Target Queue as the Source Queue's Dead Letter Queue.
Also set Source Queue's redrive policy, Maximum Receives to 1. 
Also set Source Queue's VisibilityTimeout to 5 seconds (a small period)
Then read data from the Source Queue.

Source Queue's Redrive Policy will copy the message to the Target Queue.
import argparse
import json
import boto3
sqs = boto3.client('sqs')

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--src', required=True,
                        help='Name of source SQS')
    parser.add_argument('-t', '--tgt', required=True,
                        help='Name of targeted SQS')

    args = parser.parse_args()
    return args

def verify_queue(queue_name):
    queue_url = sqs.get_queue_url(QueueName=queue_name)
    return True if queue_url.get('QueueUrl') else False

def get_queue_attribute(queue_url):
    queue_attributes = sqs.get_queue_attributes(

    return queue_attributes

def main():
    args = parse_args()
    for q in [args.src, args.tgt]:
        if not verify_queue(q):
            print(f"Cannot find {q} in AWS SQS")

    src_queue_url = sqs.get_queue_url(QueueName=args.src)['QueueUrl']

    target_queue_url = sqs.get_queue_url(QueueName=args.tgt)['QueueUrl']
    target_queue_attributes = get_queue_attribute(target_queue_url)

    # Set the Source Queue's Redrive policy
    redrive_policy = {
        'deadLetterTargetArn': target_queue_attributes['QueueArn'],
        'maxReceiveCount': '1'
            'VisibilityTimeout': '5',
            'RedrivePolicy': json.dumps(redrive_policy)

    # read all messages
    num_received = 0
    while True:
            resp = sqs.receive_message(

            num_message = len(resp.get('Messages', []))
            if not num_message:

            num_received += num_message
        except Exception:
    print(f"Redrive {num_received} messages")

    # Reset the Source Queue's Redrive policy
            'VisibilityTimeout': '30',
            'RedrivePolicy': ''

if __name__ == "__main__":

Solution 11 - Amazon Web-Services

AWS Lambda solution worked well for us -

Detailed instructions:


Deployed with a click and another click to start the redrive!

Solution 12 - Amazon Web-Services

Here is also the script (written in Typescript) to move the messages from one AWS queue to another one. Maybe it will be useful for someone.

import {
} from '@aws-sdk/client-sqs'

const AWS_REGION = 'eu-west-1'
const AWS_ACCOUNT = '12345678901'

const DLQ = `https://sqs.${AWS_REGION}${AWS_ACCOUNT}/dead-letter-queue`
const QUEUE = `https://sqs.${AWS_REGION}${AWS_ACCOUNT}/queue`

const loadMessagesFromDLQ = async () => {
    const client = new SQSClient({region: AWS_REGION})
    const command = new ReceiveMessageCommand({
        QueueUrl: DLQ,
        MaxNumberOfMessages: 10,
        VisibilityTimeout: 60,
    const response = await client.send(command)

    console.log('---------LOAD MESSAGES----------')
    console.log(`Loaded: ${response.Messages?.length}`)
    console.log(JSON.stringify(response, null, 4))
    return response

const sendMessagesToQueue = async (entries: Array<{Id: string, MessageBody: string}>) => {
    const client = new SQSClient({region: AWS_REGION})
    const command = new SendMessageBatchCommand({
        QueueUrl: QUEUE,
        Entries: => ({...entry, DelaySeconds: 10})),
        // [
        // {
        //     Id: '',
        //     MessageBody: '',
        //     DelaySeconds: 10
        // }
        // ]
    const response = await client.send(command)
    console.log('---------SEND MESSAGES----------')
    console.log(`Send: Successful - ${response.Successful?.length}, Failed: ${response.Failed?.length}`)
    console.log(JSON.stringify(response, null, 4))

const deleteMessagesFromQueue = async (entries: Array<{Id: string, ReceiptHandle: string}>) => {
    const client = new SQSClient({region: AWS_REGION})
    const command = new DeleteMessageBatchCommand({
        QueueUrl: DLQ,
        Entries: entries,
        // [
        //     {
        //         "Id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        //         "ReceiptHandle": "someReceiptHandle"
        //     }
        // ]
    const response = await client.send(command)
    console.log('---------DELETE MESSAGES----------')
    console.log(`Delete: Successful - ${response.Successful?.length}, Failed: ${response.Failed?.length}`)
    console.log(JSON.stringify(response, null, 4))

const run = async () => {
    const dlqMessageList = await loadMessagesFromDLQ()

    if (!dlqMessageList || !dlqMessageList.Messages) {
        console.log('There is no messages in DLQ')

    const sendMsgList: any = => ({ Id: msg.MessageId, MessageBody: msg.Body}))
    const deleteMsgList: any = => ({ Id: msg.MessageId, ReceiptHandle: msg.ReceiptHandle}))

    await sendMessagesToQueue(sendMsgList)
    await deleteMessagesFromQueue(deleteMsgList)


P.S. The script is with room for improvement, but anyway might be useful.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt DellView Question on Stackoverflow
Solution 1 - Amazon Web-ServicesRajkumarView Answer on Stackoverflow
Solution 2 - Amazon Web-ServicesUlad KasachView Answer on Stackoverflow
Solution 3 - Amazon Web-ServicesFrostyOnionView Answer on Stackoverflow
Solution 4 - Amazon Web-ServicesAshView Answer on Stackoverflow
Solution 5 - Amazon Web-ServicesDaveView Answer on Stackoverflow
Solution 6 - Amazon Web-ServiceslinehrrView Answer on Stackoverflow
Solution 7 - Amazon Web-ServicesBrian DilleyView Answer on Stackoverflow
Solution 8 - Amazon Web-Servicesrd2View Answer on Stackoverflow
Solution 9 - Amazon Web-ServicesPriyanka AgarwalView Answer on Stackoverflow
Solution 10 - Amazon Web-ServicesmenrfaView Answer on Stackoverflow
Solution 11 - Amazon Web-ServicesvisrahaneView Answer on Stackoverflow
Solution 12 - Amazon Web-ServiceselbikView Answer on Stackoverflow