Search code examples
expresshttpserverlessnetlify

are FaaS Serverless Variables Reliable?


I'm writing an API that is provided through the FaaS Serverless service of Netlify. To transfer Data Between Requests, I stored data on a temporary variable outside function declaration as it's useble by many functions instances, but I noticed some errors while doing so.

I tried to test it and would like to confirm my ideas.

I create an temporary variable let value = 1;

Created an Express Server that is wrapped by serverless-http that is provived as handler to Netlify. I created one route /modify for adding 1 to value and setted a timeout to wait one second before the function timeout - to simulate the time that would take to get the data to retrieve to the user. I created another route /getVal to print value on Netlify Console.

→ After executing modify and waiting a little, but not long enough for the function to finish, the value before the modification is rendered → However, at a seemingly random frequency, the rendered value is not the previous one, but the initial 1. If I change the initial value to 0, the value printed is 0 instead.

**- The seemingly random return of the initial value from the shared variable means that these shared variables aren't reliable? **

- Does the values shared among functions instances - modified by afunctions - change just after the modifier function ended?


Solution

  • This is one of the features of serverless architectures. There is no permanent server on which state can be stored. Depending on a number of factors, when you invoke your endpoint a second or third time, you might find that the endpoint executes on the same server, or an entirely new one with fresh state.

    You should not attempt to store mutable global state in the globals of your function code. The state may or may not persist between function invocations. This makes it unreliable. If you need to store state, then connect the function to a database or other external storage service.