0
0
Firebasecloud~5 mins

Custom functions in rules in Firebase - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom functions in rules
O(n)
Understanding Time Complexity

When using custom functions in Firebase security rules, it's important to know how the number of times these functions run affects performance.

We want to understand how the work grows as more data or checks happen.

Scenario Under Consideration

Analyze the time complexity of this Firebase rule using a custom function.

function isOwner(userId) {
  return request.auth.uid == userId;
}

match /documents/{docId} {
  allow read: if isOwner(resource.data.ownerId);
}
    

This rule checks if the user requesting data is the owner by calling a custom function.

Identify Repeating Operations

Look at what happens each time a request is checked.

  • Primary operation: The custom function isOwner is called once per request.
  • How many times: Exactly once for each document read request.
How Execution Grows With Input

As the number of read requests grows, the number of function calls grows the same way.

Input Size (n)Approx. Api Calls/Operations
1010 calls to isOwner
100100 calls to isOwner
10001000 calls to isOwner

Pattern observation: The number of function calls grows directly with the number of requests.

Final Time Complexity

Time Complexity: O(n)

This means the work grows in a straight line with the number of requests checked.

Common Mistake

[X] Wrong: "The custom function runs only once no matter how many requests come in."

[OK] Correct: Each request triggers the function separately, so the total work grows with requests.

Interview Connect

Understanding how custom functions scale helps you design rules that stay fast as your app grows.

Self-Check

What if the custom function called another function inside it? How would that affect the time complexity?