0
0
Firebasecloud~5 mins

Transaction basics in Firebase - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Transaction basics
O(n)
Understanding Time Complexity

When using transactions in Firebase, it's important to know how the time to complete changes as more data is involved.

We want to understand how the number of reads and writes inside a transaction affects its execution time.

Scenario Under Consideration

Analyze the time complexity of this Firebase transaction code.

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

This code reads a document, updates a count field, and writes it back inside a transaction.

Identify Repeating Operations

Look at the main actions inside the transaction.

  • Primary operation: One read (get) and one write (update) on the document.
  • How many times: Each transaction run does these operations once per document involved.
How Execution Grows With Input

As the number of documents involved grows, the transaction does more reads and writes.

Input Size (n documents)Approx. Api Calls/Operations
11 read + 1 write
1010 reads + 10 writes
100100 reads + 100 writes

Pattern observation: The number of operations grows directly with the number of documents involved.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of documents read and written in the transaction.

Common Mistake

[X] Wrong: "Transactions always take the same time no matter how many documents they touch."

[OK] Correct: Each document read and write adds work, so more documents mean more time.

Interview Connect

Understanding how transaction time grows helps you design efficient data updates and shows you can reason about cloud operations clearly.

Self-Check

"What if the transaction reads multiple documents but only writes to one? How would the time complexity change?"