Extension Review: Funky Async Extension
Do you ever find your self needing to build an API endpoint on lambda that executes some code after your lambda handler has finished running?
Maybe you have done this where your API lambda function just immediately invokes another lambda function. Maybe you hook up a step function directly to an http endpoint. Maybe your pockets are deep enough to use API Gateway v1 and utilize the X-Amz-Invocation-Type
header.
What if I told you it is possible to use an API Gateway v2 API and still perform an async task with lambda?
Bare with me on this “review” because this is an extension I built myself and I am currently using in a production. I probably haven’t made the code super pretty or robust enough for public consumption but I still thought it would be fun to share.
This extension leverages AWS Lambda’s extensions API to execute an ASYNC_HANDLER
after your lambda sends its final response.
Allow me to demonstrate with a cartoon 👇
As you can see
- Our client makes a request
- The lambda tells the async handler to start
- The lambda returns a response to the client
- The async handler finishes the work
How could I try this for myself?
Take a look at my repo for this extension
If you take a look at the serverless.yml
file there are three examples.
longRunning
- This function demonstrates an async handler that runs after a typical HTTP API would be required to return a response. It is also using theproxy
handler included with the async extension layer that will take care of passing theevent
andcontext
object to the async handler.customResponse
- This function demonstrates an async handler that uses the built in layerproxy
handler and customizes the response message.customHandler
- This function demonstrates a custom handler paired with anASYNC_HANDLER
. This also demonstrates how to use thesendArgs
method exposed by our layer.
TL;DR
If you include this extension and set your main handler to /opt/proxy.handler
then set an environment variable for the ASYNC_HANDLER
that points to your normal lambda handler function.
Limitions
This extension is written using nodejs and is referencing the async handler using require. So as it stands right now this extension would only really work with a nodejs lambda.
Also this extension may or may not work out of the box with some build tools. It will technically work but you may need to set the ASYNC_HANDLER
path to the output file path in the build directory.
Conclusion
Lol maybe I am being a little cheeky calling this a “review”. I don’t think I can actually review someething I built myself so maybe I should ask that you review it for me and leave some feedback in the comments or on GitHub. 😉
Feel free to try out this extension for yourself and let me know what you think. I plan to make this a public extension at some point so you don’t have to build/distribute the layer on your own but in the meantime feel free to use the layer code as you please. 😎