Aarmora
Aarmora

Reputation: 1153

Second event makes first event complete

I have a Lambda function that does the following:

  1. Gets records from DynamoDB
  2. Creates a CSV file with fs.writeFile from those records and saves it to /tmp/xxx
  3. Emails the CSV file

I'm seeing very unexpected behavior. I trigger an event to this function and the code returns successfully but logs stop right before creating the CSV file.

If I trigger a second event, I suddenly see the logs for the first event complete when the file is created and the email is sent. CloudWatch shows different AWS RequestIds. Something was too weird so I added my own, custom request id. And...the custom request id for the first event showed up only when the second event was triggered! I put it in the subject line and when I trigger the second event, the email is sent with the first request id.

What am I missing here? See logs:

enter image description here

It does seem to hit this pause on file creation. Maybe I'm handling the callback incorrectly? Or maybe it's not blocking the code completion. It doesn't explain why the second request would finish the first (it's scary to me that this happens).

Here is the file save code.

 try {
                console.log('About to create file', 'Request Id:', requestId);
                fs.writeFile(filePath, csv, async (err) => {
                    if (err) {
                        console.log('An error on file creation', err);

                        const response = {
                            statusCode: 500,
                            body: JSON.stringify({ message: 'An error on file creation' })
                        };

                        return response;
                    }
                    console.log('File created. Request Id: ', requestId);

Upvotes: 0

Views: 21

Answers (1)

Aarmora
Aarmora

Reputation: 1153

Okay, so it was related to me not blocking the save file. I wrapped it in a promise and the function worked as expected.

It still doesn't explain why the second event is what finished the first one. This doesn't make any sense to me.

Upvotes: 1

Related Questions