I have the following schema in my app
/
users/
user1/
username: "mike",
totalFollowers: 500190,
lastPosts: {
post1: { images: [], totalLikes: 191200, date: ... },
post2: { images: [], totalLikes: 71137, date: ... },
...
post10: { images: [], totalLikes: 59301, date: ... }
}
posts/
user1/
userPosts/
post1/
images: [],
totalLikes: 191200,
date: ...
...
post637/
images: [],
totalLikes: 15029,
date: ...
as you can see, I am denormalizing some data, the last 10 user posts. So, when a user uploads a post, I have to run a transaction, as follows:
function uploadPost(postId, postOwnerId) {
const postId = uuidv4();
const postsRef = firestore
.collection("posts")
.doc(postOwnerId)
.collection("userPosts")
.doc(postId);
const userRef = firestore.collection("users").doc(postOwnerId);
return firestore.runTransaction(async (transaction) => {
// Get the post owner data
const postOwnerData = await getUserData(postOwnerId, transaction);
...
}
just in order to:
1. Delete the current oldest post from the user's lastPosts map
2. Add the new post to it
Also, when a user likes a post, I will need a transaction too, because it will necessary to:
1. Read the user's lastPosts map to check if it contains the liked post
2. Synchronize the lastPosts' post with the post doc's totalLikes
I am afraid of not being scalable at all. As you can see, when uploading or liking a post, I will need to read the user doc, in order to get the most up-to-date lastPosts field. But... as I am not using distributed counters for totalLikes and totalFollowers (seems too expensive for me), I think that, if for example, 5 of the 11 counters that the doc has are updated multiple times in a short period (5 seconds), my transactions will fail.
Is it right? Should I avoid the denormalization of the lastPosts in order to get a good scalability?
Note: I am only storing the last 10 posts because my UI paginates the user posts 10 by 10, and having the most recent user posts attached to the user doc would save me 10 reads each time someone visits his/her profile