Working with Asynchronous Events

Here, you'll learn how to handle asynchronous calls and store output while using AWS Lambda functions.

The Lambda interface is always the same, regardless of the event source or type. The conversion function will expect the same two parameters as all your Lambda functions so far:

  • the event
  • the context object

But unlike everything else we’ve done so far in the course, the Lambda function won’t be able to just return the result back to the client. That’s because S3 invokes the Lambda function in the background, separate from the client request going through API Gateway.

Synchronous and asynchronous calls #

AWS Lambda functions support two types of call, synchronous and asynchronous:

  • Synchronous calls expect the caller to wait until the Lambda function completes. The function reports the result directly to the caller. API Gateway uses this method.

  • Asynchronous calls complete immediately, and the Lambda function keeps running in the background. The function can’t send the result directly to the caller (it’s ‘fire and forget’). S3 and most other platform services use this method.

Storing the output with asynchronous calls #

With asynchronous calls, the function also needs to be responsible for storing the output somewhere. The usual way to achieve this is to somehow correlate outputs with inputs, for example including the target output location in the event parameters, or deriving the result location from inputs. In this case, an easy solution for that would be to use a different bucket for results and store the output using the same key as the input. Buckets are effectively namespaces for files, and two different files can have the same keys in different buckets. You’ll just need to tell the function the name of the result bucket. For that, you can use an environment variable. You can create a new file for the main Lambda function, for example, index.js, in the conversion function source directory.

Get hands-on with 1200+ tech skills courses.