AWS Lambda function continues for a bit after context.fail
<p>I have a simple AWS Lambda function that does some validation on images saved to an S3 bucket. I'm using async.waterfall to download the image and process it, but before I even enter the first waterfall function, I do some basic validation on the event data that I am getting from my S3 PutObject trigger, specifically the size information (<code>event.Records[0].s3.object.size</code>). If the event references an image that is greater than my MAX_SIZE, I use <code>context.fail(new Error("Validation error: the file is too big."))</code> to end execution. </p>

<p>This is all working fine, but I notice in my logs that after the error is logged, the function continues to run for a little bit before it is exited. For example, the first function in my async.waterfall call gets called (i.e. a message from that function shows in the log). I even tried adding a <code>context.done(errorMessage)</code> immediately after the context.fail, and it gets executed (i.e. the message I pass in gets logged) along with a few more lines of code. </p>

<p>Is this expected behavior? I could not find any mention of this in the docs. Does the function take a little bit of time to exit or am I misunderstanding the synchronous nature of the code in the handler function that is BEFORE <code>async.waterfall</code>?</p>

<p>Below is some of my code. All the <code>console.log</code> messages that are shown after <code>context.fail</code> get printed to the log, which I wouldn't expect to happen.</p>

<pre><code>exports.handler = function(event, context) {
  console.log('Received event:', JSON.stringify(event, null, 2));

  if (event.Records[0].s3.object.size &gt; MAX_FILE_SIZE) {
    var error = new Error("Validation error: the file is too big.")
    context.fail(error);
  }
  console.log('Event validation complete.')

  var bucket = event.Records[0].s3.bucket.name;
  var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  var fileName = key.split("/")[1];
  var params = {
    Bucket: bucket,
    Key: key
  };
  console.log('Starting processing of the following file: ' + JSON.stringify(params, null, 2));

  async.waterfall([
    function download(callback) {
        // Download the image from S3 into a buffer.
        console.log("Downloading the image from S3...");
        s3.getObject(params, function(err, data) {
            if (err) {
                callback(err);
            } else {
                callback(null, data);
            }
        });
    },
  ...
  ], ...)
}
</code></pre>