Realtime Database security rules in Firebase - Time & Space Complexity
When using Realtime Database security rules, it is important to understand how the time to check permissions grows as your data grows.
We want to know how the number of rule checks changes when more data is accessed or written.
Analyze the time complexity of security rule checks for reading a list of items.
{
"rules": {
"items": {
"$itemId": {
".read": "auth != null",
".write": "auth != null && data.child('owner').val() == auth.uid"
}
}
}
}
This rule allows authenticated users to read any item and write only if they own it.
When a client reads multiple items, the database checks the read rule for each item.
- Primary operation: Evaluating the read rule for each item requested.
- How many times: Once per item in the list being read.
Each additional item read requires one more rule check, so the total checks grow as the number of items grows.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 rule checks |
| 100 | 100 rule checks |
| 1000 | 1000 rule checks |
Pattern observation: The number of rule checks increases directly with the number of items read.
Time Complexity: O(n)
This means the time to check security rules grows linearly with the number of items accessed.
[X] Wrong: "Security rules are checked once per request, no matter how many items are read."
[OK] Correct: Each item read triggers its own rule check, so more items mean more checks.
Understanding how security rule checks scale helps you design efficient and secure database access patterns.
"What if the read rule included a condition that checks a parent node instead of each item? How would the time complexity change?"