I'm building a Firebase project that requires the use of sequential IDs. These IDs must also be short and numeric (ex. 633521).
After reading the documentation I learned that sequential IDs are a performance risk and lead to hotspotting.
The problem is I've already built much of the app's infrastructure using sequential IDs. Here's the code I've written to generate these short numeric ID's:
const generateUniqueId = async (parentId, tries = 1) => {
try {
if (tries > 3) return false;
const zeroPad = (num, places) => String(num).padStart(places, '0');
const id = zeroPad(Math.floor(Math.random() * 999999), 6);
await DB.collection('parent')
.doc(parentId)
.collection('child')
.doc(id)
.create({ id });
return id;
} catch (error) {
if (error.code === 6) {
return await generateUniqueId(parentId, tries + 1);
} else {
return false;
}
}
};
This isn't the most elegant solution, but this was the best I could come up with due to Firebase's lack of support for sequential IDs. Essentially what's happening here is I generate a random 6 digit number, then I check if a document already exists with that number.
But after discovering the inherent risk of sequential ID's I'm wondering if this is still a viable solution (or ever was). Does this need to be refactored or could I get away with a small performance hit in exchange for functionality? The collection size will most likely never exceed a few thousand documents if that matters.
Update:
I simply confused the word "sequential" with "numeric," a very silly mistake while reading the documentation. Somehow I believed numeric IDs could lead to hotspotting, without realizing they needed to be sequential. So there's nothing wrong with the code above. Sorry for the confusion.