I have a few Netlify functions.
I know server-less functions are meant to be stateless, so I use a node module called Memory-cache to save some information which will be shared between these functions.
From the Function log under Netlify’s Functions tab, I can see that
when calling saveSubscription(sub), it does save the subscription to the memory cache, and if I save another one, I can see the both inside the cache; if I save the same subscription, I fetch subscriptions from cache and can detect the duplication.
but when I call showSubscriptions(), from the log panel, I can also see that the subscriptions are always empty.
This makes me thinking that different functions do not share cache momery?
I thought all my functions will be running on a same server.
How could I share the stored subscriptions between functions?
In general we need to think of each run of a Netlify Function (or any AWS Lambda function) as being completely stateless. This includes the in-memory data of the running Node.js process. We can put things in memory and read them out of memory freely but only within the context of that single run. So the saveSubscriptions() may work, but that memory will be erased quickly after that run is over.
AWS Lambda functions are made to not persist memory across runs.
If you need to store data and have it be accessible across different runs (or locations etc.) - you’ll need to use a third party data storage mechanism. Netlify does offer partner add-ons for sites though, and one of those is with FaunaDB - a third party data storage system that behaves similarly to a simple in-memory object cache.