Noticed an interesting behavior, and was wondering what the best practice might be for managing connections given how Lambda is invoked (and seemingly copied?), and managing database how one closes database connections.
In a single script I have, I was instantiating connections with this logic:
- There's a connection object that's initially set to null.
- When some routines are invoked, if the object is null, it is instantiated/connected.
- When the script is "done", we call the mysql.end() on that connection object.
Doing this works great in a single Lambda invocation. The script would quit (rather than timeout), and its connections were tidily removed.
An issue, however, occurs when two AWS Gateway calls invoke the same Lambda function.
Seems state and everything are copied over? The result is a stale mysql object with a non-null connection, on which .end() was called. You can't enqueue queries after .end() was called - so the first gateway invocation succeeds, but subsequent gateway invocations fail.
If I remove all calls to mysql.end(), the connection issue goes away, but, the Lambda script now times out (30 seconds) rather than neatly quitting.
What's the solve for this kind of situation on Lambda?
via Saeven
No comments:
Post a Comment