The 'security rules are not filters' concept of googles firebase/firestore is a great concept that a lot more (realtime) apps should follow. It tremendously increases scalability and reduces server load.
Here is why:
What does it mean?
'...Cloud Firestore evaluates a query against its potential result set instead of the actual field values for all of your documents. If a query could potentially return documents that the client does not have permission to read, the entire request fails...'
This basically means that the client is responsible to set up it's queries the way that it only requests data that it's actually allowed to load. This saves the server from having to check the permissions for every single change to the data.
If security rules would really act as filters, every client could possible subscribe to changes for a collection and the server would have to save every subscription in any kind of list and iterate over this list everytime the collection gets changed. It needs to check if the changed data still match the security rule and only if this is the case send the changes over to the client.
When the concept of 'security rules are not filters' is applied, the server checks the security rule against the query when the client tries to subscribe to data and only accepts it if the check passes. If not, the subscription doesn't even get established. This way the server only has to broadcast changes to clients that he knows they have permission.
Let's have a look at a simple example:
The first query assumes that the server does the filtering and just queries for all documents. It offloads all the work to the server even if it's clear that it only can load documents which are owned by the authenticated user.
The second query directly specifies that it only wants to receive documents that the authenticated user owns. That way, the server just needs to check the permissions when the subscription gets established.
Of course this is just a rough overview and doesn't consider changes in values that need to trigger a security rule recheck.
I will give a simple example of how the server could possibly implement this kind of security check in another thread.
Happy coding everyone!
If you like this kind of short tips and tricks, follow me on twitter. I'm posting a lot of them there.