Auth state change listeners in Supabase - Time & Space Complexity
When using auth state change listeners, it is important to understand how the number of listeners affects performance.
We want to know how the work grows as more listeners are added or triggered.
Analyze the time complexity of setting up and triggering auth state change listeners.
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
console.log('Auth event:', event);
// handle session update
});
// Later, when auth state changes, all listeners are called
// For example, user signs in or out
This code sets up a listener that runs a callback whenever the authentication state changes.
Look at what happens repeatedly when auth state changes.
- Primary operation: Calling each registered auth state change listener callback.
- How many times: Once per listener for every auth state change event.
As the number of listeners increases, the number of callback calls grows directly with it.
| Number of Listeners (n) | Approx. Callback Calls per Event |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: Each auth event triggers all listeners, so the work grows linearly with the number of listeners.
Time Complexity: O(n)
This means the time to handle an auth state change grows directly with the number of listeners registered.
[X] Wrong: "Adding more listeners won't affect performance because they run independently."
[OK] Correct: Each listener callback runs one after another on every auth event, so more listeners mean more work and longer handling time.
Understanding how event listeners scale helps you design responsive apps and manage resources well, a key skill in cloud and frontend development.
What if we batch multiple auth events before notifying listeners? How would that change the time complexity?