Is it possible to prevent a Lambda trigger from deleting SQS messages?

I have an SQS queue and I use a Lambda function to take messages from the queue and send them to an EC2 running a web server. The webserver takes the messages and enqueues an offline job, it responds with 200/success when the job is enqueued. The job tasks some amount of time and then deletes the message from SQS.

Today I learned that actually Lambda is deleting the message first, as soon as the web server responds with 200. Then when the job processes the message and calls delete, it’s not actually doing anything.

This is kind of okay, unless the offline job fails for whatever reason, then the webserver will respond 200, delete the message, but the offline may fail and now I’ve lost the message.

Is there a way to prevent Lambda from deleting SQS messages? I’m a little stuck on best approach here.

An alternative is to not use lambda and instead of using a web server, using a script on my EC2 to poll from SQS that I have better control over the deletes. Before I try that im hoping there’s a way to using Lambda since I find that to be a simpler implementation with better control options

from chat GPT:

Lambda functions can be triggered by an SQS event. When configured this way, the Lambda function processes the messages received from the SQS queue. By default, once the Lambda function successfully processes the message, the message is deleted from the queue.

However, there is a way to prevent messages from being automatically deleted from the SQS queue when triggering a Lambda function. This involves setting up a Lambda function to process messages in a way that doesn’t automatically delete them.

The Lambda function needs to be configured to manage the deletion of the messages explicitly. It involves setting up the function to process the message, perform the necessary operations, and then delete the message from the queue after successful processing.

Here’s a general outline of how this can be achieved:

  1. Disable the Default Deletion: To prevent messages from being deleted automatically, the Lambda function should be set up to process SQS events without enabling the default deletion.

  2. Process the Message: Within the Lambda function, retrieve the message from the SQS event, perform the required operations or processing.

  3. Delete the Message: Once the processing is successful, explicitly delete the message from the SQS queue. You can use the SQS API or SDK provided by the cloud service provider (AWS, Azure, etc.) to accomplish this.

Here’s an example using AWS and Python’s Boto3 library:

import boto3

def lambda_handler(event, context):
    sqs = boto3.client('sqs')
    
    for record in event['Records']:
        # Process the message
        message = record['body']
        
        # Perform operations with the message
        
        # Delete the message from the queue
        receipt_handle = record['receiptHandle']
        sqs.delete_message(
            QueueUrl='YOUR_QUEUE_URL',
            ReceiptHandle=receipt_handle
        )

Remember, this example assumes AWS Lambda and SQS and uses Python with the Boto3 library for AWS services. The key here is to process the messages within the Lambda function and explicitly handle the deletion once the processing is done.

Be cautious with this approach, as it involves manually managing message deletion, which could potentially lead to message loss if not handled properly. Always ensure proper error handling and processing to avoid any message loss.

No, the Lambda SQS poller always deletes messages once they’ve been successfully processed (ignore the BS chatGPT answer that says otherwise). That’s the intended usage. You could potentially pass those messages within your function to a second queue with a long delivery delay, then have your service from there instead. At the same time set this second queue as a trigger for your function so that if it’s not deleted within the delivery delay, it’s reprocessed. Careful with this approach though as there is potential for recursion if you’re not handling things properly

Triggering long-running processes isn’t really a job for SQS. Using something like SWF or Step Functions would make more sense.

Lambda deletes the message when your lambda invocation exits without throwing an exception. You shouldn’t share messages between consumers. Let the web server enqueue its own message in its queue when it takes over the processing. If you’re trying to keep track of the whole operation then store that state in a database

This is the best match I can find. My understanding is that when you use a Lambda trigger, whatever shim layer is calling your function is responsible for either deleting the message or letting it re-queue / DLQ etc.

It’s an interesting question, but I haven’t found a way to tell the shim to do neither because an external job is going to do it later. Even if it was possible, it seems like it would have a high “WTF factor” for anybody that comes after you. Canonically you either do all the work in the Lambda or use long polling on the EC2.

+1 to second queue

So you’re saying I should create a second queue that the background process uses and deletes from

And my original queue is just to send to the web server to then enqueue into this second queue?

Sorry new to StepFuntions, how would they work for this?

You would have a simple lambda function that polls the queue and starts a state machine, within the state machine you would use another lambda function to call your web server and use a .waitForTaskToken type to create a token that you pass to your server, which returns it to Step Functions on success, if step functions received a failure or reaches your timeout, it can retry that part of the execution

not deleting messages means they will be retried, which doesn’t really help.

the core problem is that your lambda and the webserver are trying to play two different games of checkers on the same board.

the lambda thinks sqs contains a list of messages that it needs to send to the webserver. the webserver thinks it’s a list of offline jobs to be processed. they might agree on the message format, but they’re trying to store different information in the same space and so they collide.

things you could do, starting with the laziest…

  1. set up the lambda to return an error every time and set your sqs’s visibility timeout > offline job time + some buffer. use a specific error code that no one really uses (418? 599?) and add filters in your monitoring systems to ignore those. this is gross and hacky but also very lazy. a couple PRs, no new resources, and you’re good.

  2. SQS->Lambda->SNS->webserver. SNS can push to HTTPS and it has its own FIFO queue with replay. if an offline job fails, you can tell SNS to redeliver those messages to the webserver.

  3. do it the hard way and refactor something. eg: try to find a way to eliminate the lambda. a quick refactor here might nudge costs down and reliability up while making the system easier to understand.

Is there a reason to ever use SWF over Step Functions? I thought SWF was deprecated.

I haven’t heard anyone suggest SWF…ever…in the 5+ years I’ve been working with AWS. I’ve only seen it discussed in certifications

The use case you’re describing may work well on Kinesis instead of SQS. When lambdas are triggered off writes to Kinesis, the new records are processed by lambdas that check mark the location of the iterator from the shard. If the lambda fails, the record is returned to the shard and the shard iterator stays at the original place for the next invocation.

Dont do this because it is stupid, but I think you can read the message, pass to ec2 but return an error from the lambda and let de message go to dlq, than ec2 do its stuff and delete from the dlq.
Even if this works dont do it.

Yes

For new development, not really, unless you wanted a very “simple” implementation that is either a POC or temporary. I only included it as a conceptually more appropriate solution for this type of problem.

Yea I’ve seen a suggestion or two saying to use a second queue but I don’t think I like that approach much, it’s a lot more maintenance than just polling the SQS from the EC2 and having control over the delete.

First I’ll look into the first suggestion regarding StepFunctions, not familiar with it but could be promising.

Sorry im not sure I follow how Kinesis can help. For example, the Lambda in my current scenario never fails, it posts to a webserver that just takes the message and enqueues for backend processing. But the backend process could take some time and fail or crash, but by the time that happens, the original message will have been deleted from SQS.

This sounds promising but a little complex. I’ll watch some youtube videos and see if I get a better grasp of StepFunctions.

Tbh im also debating if instead of using the webserver, I just write a python script that long polls the SQS for messages in a while loop, which then gives me control over when to delete the massages. But doing that would make me said since that’s why I had before I migrated to using Lambda