I’m building an order system on Google Cloud using Firestore. I have one Firestore database and multiple servers handling orders by location. Each branch starts daily orders from 1, resetting each day.
How can I set up sequential order numbers using Firestore and Google Cloud? Any code examples or tips? Implementation should always be sequential and without gaps.
Note: Order number is needed and will be saved in other collections in addition to orders collection
2
Answers
Using sequential ID’s is not recommended for Firestore there is a post about this topic and some suggestions: Firestore generated key versus custom key in a collection?
The limitation regarding sequential IDs refers to document IDs. If you want to store the order number as a numeric field inside a document, you can go ahead with that, but please note that such a solution is not practical at all. Why? It’s because in order to increment the order number you have to read the last order number first before writing the new one. So instead of paying only for write operation in Firestore, you’ll have to pay a read + a write.
In my opinion, the best option that you have is to store a Firestore timestamp field that has the precision of nanoseconds inside each order. That means that you can order the orders according to that field and achieve the same result. That also means that you don’t have to check the order number or use any transactions.
Edit:
If you really need that sequential order number, then I recommend you store it in Firebase Realtime Database in a schema that looks like this:
To increment the order number, you can simply use increment, which is an atomic operation. To reset the timer, you can use Cloud Scheduler, which allows you to schedule the update of the order number to zero.