0
0
Firebasecloud~5 mins

Transaction read-then-write pattern in Firebase - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Transaction read-then-write pattern
O(n)
Understanding Time Complexity

When using Firebase transactions, we want to know how the time to complete changes as we work with more data.

We ask: How does the number of reads and writes grow when we update data inside a transaction?

Scenario Under Consideration

Analyze the time complexity of the following operation sequence.

const docRef = firestore.doc('items/item1');
firestore.runTransaction(async (transaction) => {
  const doc = await transaction.get(docRef);
  const currentCount = doc.data().count || 0;
  transaction.update(docRef, { count: currentCount + 1 });
});

This code reads a document's current count and then updates it inside a transaction to add one.

Identify Repeating Operations

Identify the API calls, resource provisioning, data transfers that repeat.

  • Primary operation: One read (get) and one write (update) inside the transaction.
  • How many times: Each transaction attempt does one read and one write; retries may repeat these.
How Execution Grows With Input

Each transaction reads and writes one document regardless of data size.

Input Size (n)Approx. Api Calls/Operations
1010 reads + 10 writes (one per transaction)
100100 reads + 100 writes
10001000 reads + 1000 writes

Pattern observation: The number of operations grows linearly with the number of transactions.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly in proportion to how many transactions you run.

Common Mistake

[X] Wrong: "The transaction reads once and then updates many documents at the same time, so it's constant time."

[OK] Correct: Each transaction reads and writes only the documents it touches. If you update many documents, each requires its own read and write, so time grows with the number of documents.

Interview Connect

Understanding how transactions scale helps you design reliable apps that handle data safely and efficiently.

Self-Check

"What if the transaction updated multiple documents instead of one? How would the time complexity change?"