Currently I am working at a simple session handling within a Cloud Function as Dialogflow fulfillment. In my script, I keep various variables, either entered by the user or acquired from external APIs. To handle sessions, I save the variable data inside a Firestore database. However, when two different users are communicating with the bot at the same time, the sessions are still overwriting each other's variables which leads to broken conversations.
Right now, I have the following workflow:
- when an intent is detected, look for existing session data in Firestore (the Dialogflow session ID given by the external trigger is used as storage key)
- if there is already any data, load the variable data into the global variables inside the script
- process the intent's code based on the loaded variables
- generate an output to the user based on the variables
- after
agent.add(...)
, save the data back to the Firestore database
For me, this still looks logical. Also, loading and saving to the database is tested and works as intended. But somehow, if two or more users communicate at the same time, the data is overwritten in between. How can I prevent this? And shouldn't Cloud Functions be able to "scale" by themselves, which for me implies that the functions are working for a thousand users at one time without any race conditions?