I have a situation where users are watching for an "item" to have "slots" become available. Users will try to fill a slot if possible. I'm new to firebase and am pretty certain that the way I have things set up will not scale. It works with just me testing, but if there are many users I'm thinking it will break.
Currently it's implemented like so:
The "item" is an object on firebase realtime db with an observer set on it. When the observer fires, it checks to see if the "slots" object within that item is full of users or not. If it's full, nothing should happen. If it's not full then the user's id is put within the "slots" object.
Fullness is determined by comparing the current length of the "slots" object with a "maxLength" property/integer attached to the item.
Unfortunately, I'm fairly certain that what will happen is that all users will try to fill the slots at the same time, and they will all detect that the item is not full before any of them actually fill slots. Therefore I will accidentally have more users in the "slots" object than the number in "maxLength". How can I guarantee that won't happen?
Pseudocode of what I have (react native):
const item = firebase.database().ref(`item/`); //the item
const slots = firebase.database().ref(`item/slots`); //slots within the item
item.on('value', (snapshot) => {
let data = snapshot.val();
let keys = data.slots ? Object.keys(data.slots) : [];
let full = keys.length >= data.maxLength ? true : false;
if (!full) {
slots.update({
[user.uid]: true
});
}
});
Realtime DB example looks roughly like:
item {
maxLength: 10,
slots: {
rj6h5f7sd88s7f6sdfs7f7: true, //user
d466df8dfj8dfjd3nkvmdd: true, //another user
// etc.
}
}