Rule syntax and structure in Firebase - Time & Space Complexity
When working with Firebase security rules, it's important to know how the time to check these rules changes as your data grows.
We want to understand how the rule checking time grows when more data or conditions are involved.
Analyze the time complexity of this Firebase rule checking sequence.
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read: if request.auth.uid == userId;
}
}
}
This rule allows a user to read only their own user document by checking the user ID.
Look at what happens each time a read request is made.
- Primary operation: Checking if the authenticated user ID matches the document ID.
- How many times: Once per read request on a user document.
Each read request checks only one document's ID against the user ID.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 checks (one per document read) |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of read requests.
Time Complexity: O(n)
This means the time to check rules grows linearly with the number of read requests.
[X] Wrong: "The rule check happens once for all documents at once, so time stays the same no matter how many reads happen."
[OK] Correct: Each read request triggers a separate rule check for that document, so time grows with the number of reads.
Understanding how rule checks scale helps you design secure and efficient Firebase apps, a skill valued in real projects.
"What if the rule included a query that checked multiple documents? How would the time complexity change?"