Postmark email function works in netlify dev but not on live site

Hey @barrymcgee :wave:t2:

I haven’t seen any code so just speaking in high-level terms here, but Netlify Dev approximates the AWS Lambda runtime; it’s not necessarily a carbon clone. There will be differences. Some of what you’re seeing may be attributed to Lambda spinning up little instances of each Function - when they return the instance is killed. Immediately. Locally in Netlify Dev, all of the functions run in a single instance that persists as long as you’re running netlify dev - it would make sense that if you another function on the stack and return, that function might still get processed.

Fundamentally, Lambda is not designed to allow you to send back a response then keep processing code… for a number of reasons. Note their docs and in particular:

  • Background processes or callbacks that were initiated by your Lambda function and did not complete when the function ended resume if Lambda reuses the execution environment. Make sure that any background processes or callbacks in your code are complete before the code exits.

This just isn’t the design of Lambda.

HOWEVER, if you do want to accomplish something along these lines, I’d suggest you check out Netlify’s new Background Functions (Announcement and Docs). These would allow you to accomplish what you’re trying to do (generally) in a 2-step process.

  1. Have a non-background Function that does your normal logic, kicks off a background job, then responds to the caller (fast)
  2. The background job receives the call from the first function and does the background (slow) work including your various POST requests.

Be aware though, you need to be strategic around what you’re trying to do since the background jobs don’t give you feedback about their status and whether or not they succeeded (which would be the same if Lambda did continue after return anyway) – so you need to take an architectural strategy to where your background job makes changes somewhere to indicate that your task is complete etc. (Or just make your background jobs immutable and repeatable if needed but that doesn’t always work for something like sending emails)

I hope that gives you some brain fodder or ideas / helps!


Jon


EDIT: The conversation continued a bit over on this thread (same premise) so I thought I’d come back and tag it here for those following in the future:

https://answers.netlify.com/t/send-response-before-stopping-function/5016/13

2 Likes