I want to build a simple e-commerce application that lets users buy different digital products. I also want to track every user’s total purchase value and get their percentage as a top buyer (Basically ranking based on total money spent).
So a user who spent a total of $50k would have a lower percentage as a top buyer than someone who spent a total of $100.
This is just like OnlyFans, how creators can showcase their percentage as top creators.
Question: How would I derive and store this data in Cloud Firestore, I can easily get the total amount spent by a user but to get their percentage is a bit tricky.
My Opinion: I could simply create a cron job that runs every week or month and would calculate and update every user’s rank but I feel that would be expensive if the app scales and cloud Firestore’s transactions are limited to 500 writes.
2
Answers
If you are concerned with write count, I strongly believe you should have just one object in Firestore that contains a hashtable of everyone’s rank:
Either when a transaction occurs, or as a separate process outside of the context of a transaction, run a process that reads everyone’s spending, and recalculate the rank, and update this hashtable with the new ranks.
If you only update this document periodically, also consider caching the ranks so that your application doesn’t have to go back to Firestore to get the new data.
If you are considered with read count, you could create a second hashtable of users and their spending, instead of inside of each client record:
You should be able to perform a merge update to just update the content with just the hash table entry you need to update.
If you want to store the percentage of a user, then I think that is more appropriate to store that data in the Realtime Database rather than in Firestore. Or maybe you can store the total a user has spent, and then calculate the percentage in your application code.
It’s true, you can create a document that can hold all those percentages or the total spent, but please note that you’re limited to 1 MiB. So the Realtime Database schema might look like this:
Now, each time a user buys something simply increment the value using:
Here are the Swift API docs for FieldValue.increment() and the Firebase official documentation.
So in this case, there is nothing you need to pay when you update that number. You’ll only have to pay when you read that value. So in my opinion, there is no need to create a cron job. However, if you need to schedule some operations in Realtime Database, you can consider using Cloud Scheduler, which allows you to schedule HTTP requests or Cloud Pub/Sub messages to the Cloud Functions for Firebase that you deploy.