Caching strategies in Supabase - Time & Space Complexity
When using caching with Supabase, we want to know how the number of data fetches changes as requests grow.
We ask: How does caching affect the number of times we call the database?
Analyze the time complexity of fetching user profiles with caching.
// Check if user profile is in cache
const cachedProfile = cache.get(userId);
if (cachedProfile) {
return cachedProfile; // Use cached data
}
// If not cached, fetch from Supabase
const { data, error } = await supabase
.from('profiles')
.select('*')
.eq('id', userId)
.single();
cache.set(userId, data); // Store in cache
return data;
This code tries to get a user profile from cache first, then fetches from Supabase if missing, and stores it in cache.
Look at what happens when many user profiles are requested.
- Primary operation: Database fetch calls to Supabase when cache misses occur.
- How many times: Once per unique user profile not found in cache.
As more unique user profiles are requested, the number of database calls grows with the number of misses.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | Up to 10 database calls if none cached |
| 100 | Up to 100 database calls if none cached |
| 1000 | Up to 1000 database calls if none cached |
Pattern observation: Without cache hits, calls grow linearly with unique requests; with cache hits, calls reduce greatly.
Time Complexity: O(n)
This means the number of database calls grows directly with the number of unique user profiles requested when cache misses happen.
[X] Wrong: "Caching makes the number of database calls constant no matter how many users we request."
[OK] Correct: Cache only helps if data is already stored; new unique requests still cause database calls.
Understanding how caching affects database calls shows you can think about efficiency and user experience in real apps.
"What if we changed the cache to expire every minute? How would the time complexity change when many requests come in quickly?"
Practice
Solution
Step 1: Understand caching basics
Caching temporarily stores data to avoid repeated database calls.Step 2: Identify caching purpose in Supabase
It speeds up app performance by quickly providing stored data.Final Answer:
To store data temporarily and speed up data access -> Option AQuick Check:
Caching = Temporary storage for speed [OK]
- Thinking caching permanently saves data
- Confusing caching with encryption
- Believing caching deletes data
Solution
Step 1: Review Supabase cache TTL syntax
Supabase uses an options object with a ttl property to set time-to-live.Step 2: Match correct syntax
cache.set('key', value, { ttl: 300 }) uses { ttl: 300 } which is the correct way to specify TTL in seconds.Final Answer:
cache.set('key', value, { ttl: 300 }) -> Option AQuick Check:
TTL set with { ttl: seconds } object [OK]
- Using ttl=300 instead of { ttl: 300 }
- Using wrong property names like timeout or expire
- Passing TTL as a separate argument without object
const cachedData = cache.get('user_123');
if (cachedData) {
console.log('Cache hit:', cachedData);
} else {
const data = await supabase.from('users').select('*').eq('id', 123);
cache.set('user_123', data, { ttl: 600 });
console.log('Cache miss, fetched:', data);
}What will be logged if the cache already has data for 'user_123'?
Solution
Step 1: Check cache.get return value
If cache has data for 'user_123', cachedData is truthy.Step 2: Follow code logic on cache hit
Code logs 'Cache hit:' plus cachedData without fetching from database.Final Answer:
Cache hit: [cached data] -> Option BQuick Check:
Cache hit logs cached data [OK]
- Assuming it fetches from database even if cache exists
- Confusing cache miss and hit outputs
- Expecting errors when cache is valid
const cached = cache.get('user_1');
if (!cached) {
const data = await supabase.from('users').select('*').eq('id', 1);
cache.set('user_1', data, { ttl: 300 });
}
console.log(cached);What is the main issue causing the cache miss?
Solution
Step 1: Analyze variable assignment
Variable 'cached' is assigned once before cache.set, so it stays null.Step 2: Understand cache update logic
After setting cache, 'cached' is not updated to new data, so console.log shows null.Final Answer:
You never update the cached variable after setting cache -> Option CQuick Check:
cached variable must update after cache.set [OK]
- Assuming cache.set updates cached variable automatically
- Blaming TTL without checking variable assignment
- Thinking cache.get syntax is wrong without error
Solution
Step 1: Consider update frequency and freshness
User profiles may change, so cache must refresh often to avoid stale data.Step 2: Choose caching strategy balancing speed and freshness
Short TTL with cache refresh after updates keeps data fresh and speeds access.Final Answer:
Use short TTL (e.g., 60 seconds) and refresh cache after updates -> Option DQuick Check:
Short TTL + refresh = fresh and fast cache [OK]
- Using long TTL causing stale data
- Avoiding cache entirely losing speed benefits
- Not refreshing cache after updates
Ready to prove it?
Pass the test and this pattern moves unknown
