You want to increase a numeric field likes in a Firestore document by 1 without overwriting other fields. Which code snippet correctly performs this atomic increment?
const docRef = firestore.collection('posts').doc('post1'); // Which option correctly increments 'likes' by 1?
Use Firestore's atomic increment operation to avoid race conditions.
Option D uses FieldValue.increment(1) which atomically increases the likes field without overwriting other fields. Options A and B assume you have the current value locally, which can cause race conditions. Option D overwrites the entire document, which is not desired.
In Firebase Realtime Database, which method correctly increments a numeric value at path /counters/visits atomically?
const ref = firebase.database().ref('/counters/visits');
// Choose the correct increment methodUse a transaction to safely update values in Realtime Database.
Option C uses a transaction function that reads the current value and increments it atomically. Options B and C try to read and write without atomicity, risking race conditions. Option C is invalid as increment is not a Realtime Database method.
You expect very high traffic incrementing a counter in Firestore. Which architecture best avoids contention and throttling?
Think about how to reduce write contention on a single document.
Option B shards the counter across multiple documents to distribute writes, reducing contention and throttling. Option B risks contention on a single document. Option B delays increments but still writes to one document. Option B causes contention due to repeated read-write cycles.
Which Firestore security rule snippet correctly allows increments on a likes field but prevents arbitrary overwrites?
match /posts/{postId} {
allow update: if ... ;
}Ensure only the likes field changes and it increments by exactly 1.
Option A checks that only the likes field changes and that it increments by exactly 1. Option A allows any increase but not restricting other fields. Option A does not restrict other fields. Option A restricts fields but not the increment logic.
You need to implement a view counter that increments thousands of times per second in Firebase. Which approach is best to ensure accuracy, scalability, and minimal cost?
Consider write limits and cost efficiency for very high write rates.
Option A shards counters to distribute writes and uses Cloud Functions to aggregate counts, balancing scalability and cost. Option A risks contention and throttling. Option A faces similar contention issues. Option A is costly and inefficient for counting.