Something that threw me for a long time about AWS Lambda was the idea about memory passing.

It's really a simple thing, but for some reason it just took me a while to understand.
I remember when someone first told me that an AWS Lambda function could have a memory leak.

I'm like: What? How?

Doesn't it just create like a "whole new environment" for each function?
Turns out, that was a fairly naive way to look at it. Because (sadly) AWS Lambda isn't as magical as my mind had made out.
The reality is, since AWS Lambda is just pretty much containers under the hood, it all makes sense.

Every time a request comes in, AWS Lambda creates a new container. Those containers LIVE ON until AWS decides to kill them.
And importantly, what this means is that memory can jump between AWS Lambda functions.

Which, yes, in a negative scenario can create issues like memory leaks, and mutations in your future lambda functions.
But, sharing memory is also super useful for other things.

Well, I mean, sharing state between anything: functions, lambda functions, microservices is a dance with the devil.
But, one example that worked well for me, was implementing the idea of log events. A log event is like a regular log, but you load it up with lots of context over the request life cycle and dump it out at the end.
And because AWS Lambda has 1 request on an AWS Lambda at a time, you can put this up in your memory, and push to it for the lifetime of the AWS Lambda.
BUT.

And here's the BUT.

You MUST then clean up after yourself.
If you leave things in memory, they'll start affecting subsequent invocations, and quite frankly, this is a nightmare.

AWS Lambda is awesome when treated like functional programming. Pass stuff in, get stuff out.
The more you leave things "lying about", the more likely you are to bump into issues.
Essentially there's two things to wrap your head around:

- It's 1 request per function, so your AWS Lambda won't be "doing other things" whilst you've got one request on the go, unlike a server
- Your containers hang around, so whatever you shove in temp, or in memory stays.
When you wrap your head around this, another big piece in the AWS Lambda puzzle falls into place.

For me, it took a while.

Hopefully for you, it won't take as long 😂
You can follow @loujaybee.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.