Search code examples
c#amazon-web-servicesamazon-s3aws-lambdaamazon-sqs

How to handle an SQS event that's triggered by S3?


I have an S3 bucket that dispatches a message to an SQS queue whenever an object is added. That SQS queue in return triggers a Lambda which attempts to retrieve that recently added object using its key.

The FunctionHandler method in in my Lambda looks something like this:

public async Task FunctionHandler(S3EventNotification evnt, ILambdaContext context) {
    // evnt.Records[0].S3 is null
}

Am I handling the right event here? The reason I'm handling S3EventNotification is because when I inspected the messages inside the SQS queue, their contents corresponded to the S3EventNotification event type (see documentation here). Yet for some reason the properties I'm trying to access are null.

If I try to handle an SQSEvent instead, there's no way for me to get the object key which I need in order to be able to grab the corresponding object from my S3 bucket.

Any ideas?


Solution

  • You probably want to handle an SQSEvent here. I believe in each event.records you will have the body property which will hold the original S3 event. It might need some serialisation.

    Something like:

    public class Function
    {
        public string Handler(SQSEvent sqsEvent)
        {
            foreach (var record in sqsEvent.Records)
            {
                // record.Body has your S3 event
            }
        }
    }
    

    Out of interest, have you considered going straight from S3 -> EventBridge -> Lambda? That way you skip the SQS Queue.