Bird
Raised Fist0
Supabasecloud~10 mins

Caching strategies in Supabase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Caching strategies
Client Request
↓
Check Cache
↓
Return
↓
Store in Cache
↓
Return Data
When a client requests data, the system first checks the cache. If data is found (cache hit), it returns immediately. If not (cache miss), it fetches from the database, stores the result in cache, then returns it.
Execution Sample
Supabase
cache = {}
key = 'user:123'
if key in cache:
  data = cache[key]
else:
  data = db_fetch(key)
  cache[key] = data
This code checks if user data is in cache; if not, it fetches from the database and caches it.
Process Table
StepActionCache StateData SourceResult
1Check if 'user:123' in cache{}N/ACache miss
2Fetch 'user:123' from DB{}DatabaseData fetched
3Store 'user:123' data in cache{'user:123': 'UserData'}N/ACache updated
4Return data to client{'user:123': 'UserData'}CacheData returned
5Next request: Check cache{'user:123': 'UserData'}N/ACache hit
6Return cached data{'user:123': 'UserData'}CacheData returned
💡 Execution stops after data is returned to client on cache hit or miss.
Status Tracker
VariableStartAfter Step 2After Step 3After Step 6
cache{}{}{'user:123': 'UserData'}{'user:123': 'UserData'}
dataundefinedUserDataUserDataUserData
Key Moments - 3 Insights
Why do we check the cache before the database?
Checking the cache first (see Step 1 in execution_table) avoids slower database calls if data is already stored, improving speed.
What happens if data is not in the cache?
If cache miss occurs (Step 1), data is fetched from the database (Step 2) and then stored in cache (Step 3) for future requests.
Does the cache update every time we fetch data?
No, the cache updates only on a miss (Step 3). On a hit (Step 5), data is returned directly without updating cache.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the cache state after Step 3?
A{}
Bundefined
C{'user:123': 'UserData'}
D{'user:124': 'UserData'}
💡 Hint
Check the 'Cache State' column in execution_table at Step 3.
At which step does the system fetch data from the database?
AStep 2
BStep 1
CStep 5
DStep 6
💡 Hint
Look at the 'Action' column in execution_table to find when DB fetch happens.
If the cache already contains 'user:123', which step returns data directly from cache?
AStep 2
BStep 5
CStep 3
DStep 1
💡 Hint
Check the 'Result' column for cache hit and data return.
Concept Snapshot
Caching strategies:
- Check cache first for requested data
- If cache hit, return data immediately
- If cache miss, fetch from database
- Store fetched data in cache
- Improves speed by reducing database calls
- Common in cloud apps like Supabase
Full Transcript
Caching strategies help speed up data access by storing data temporarily. When a client asks for data, the system first looks in the cache. If the data is there (cache hit), it returns it quickly. If not (cache miss), it fetches from the database, saves it in the cache, then returns it. This reduces slow database calls and improves performance. The example code shows checking the cache, fetching from the database if needed, and updating the cache. The execution table traces these steps clearly. Key moments include understanding why cache is checked first, what happens on a miss, and when cache updates occur. The quiz tests understanding of cache state and data flow steps.

Practice

(1/5)
1. What is the main purpose of caching in Supabase applications?
easy
A. To store data temporarily and speed up data access
B. To permanently save all user data
C. To delete old data from the database
D. To encrypt data for security

Solution

  1. Step 1: Understand caching basics

    Caching temporarily stores data to avoid repeated database calls.
  2. Step 2: Identify caching purpose in Supabase

    It speeds up app performance by quickly providing stored data.
  3. Final Answer:

    To store data temporarily and speed up data access -> Option A
  4. Quick Check:

    Caching = Temporary storage for speed [OK]
Hint: Caching means temporary storage to speed up access [OK]
Common Mistakes:
  • Thinking caching permanently saves data
  • Confusing caching with encryption
  • Believing caching deletes data
2. Which of the following is the correct way to set a cache TTL (time-to-live) in Supabase client code?
easy
A. cache.set('key', value, { ttl: 300 })
B. cache.set('key', value, ttl=300)
C. cache.set('key', value, timeout: 300)
D. cache.set('key', value, expire: 300)

Solution

  1. Step 1: Review Supabase cache TTL syntax

    Supabase uses an options object with a ttl property to set time-to-live.
  2. Step 2: Match correct syntax

    cache.set('key', value, { ttl: 300 }) uses { ttl: 300 } which is the correct way to specify TTL in seconds.
  3. Final Answer:

    cache.set('key', value, { ttl: 300 }) -> Option A
  4. Quick Check:

    TTL set with { ttl: seconds } object [OK]
Hint: TTL uses { ttl: seconds } object in cache.set [OK]
Common Mistakes:
  • Using ttl=300 instead of { ttl: 300 }
  • Using wrong property names like timeout or expire
  • Passing TTL as a separate argument without object
3. Given this Supabase cache check code:
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'?
medium
A. Cache miss, fetched: [new data]
B. Cache hit: [cached data]
C. Error: cache.get is not a function
D. No output

Solution

  1. Step 1: Check cache.get return value

    If cache has data for 'user_123', cachedData is truthy.
  2. Step 2: Follow code logic on cache hit

    Code logs 'Cache hit:' plus cachedData without fetching from database.
  3. Final Answer:

    Cache hit: [cached data] -> Option B
  4. Quick Check:

    Cache hit logs cached data [OK]
Hint: Cache hit means cachedData exists, logs cache hit [OK]
Common Mistakes:
  • Assuming it fetches from database even if cache exists
  • Confusing cache miss and hit outputs
  • Expecting errors when cache is valid
4. You wrote this code to cache user data but it always fetches from the database:
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?
medium
A. TTL is too short to keep data
B. cache.get syntax is incorrect
C. You never update the cached variable after setting cache
D. Database query is wrong

Solution

  1. Step 1: Analyze variable assignment

    Variable 'cached' is assigned once before cache.set, so it stays null.
  2. Step 2: Understand cache update logic

    After setting cache, 'cached' is not updated to new data, so console.log shows null.
  3. Final Answer:

    You never update the cached variable after setting cache -> Option C
  4. Quick Check:

    cached variable must update after cache.set [OK]
Hint: Update cached variable after cache.set to avoid misses [OK]
Common Mistakes:
  • Assuming cache.set updates cached variable automatically
  • Blaming TTL without checking variable assignment
  • Thinking cache.get syntax is wrong without error
5. You want to optimize a Supabase app by caching user profile data but ensure updates are reflected quickly. Which caching strategy is best?
hard
A. Cache data without TTL and manually clear cache daily
B. Use very long TTL (e.g., 24 hours) to minimize database calls
C. Never cache user profiles to avoid stale data
D. Use short TTL (e.g., 60 seconds) and refresh cache after updates

Solution

  1. Step 1: Consider update frequency and freshness

    User profiles may change, so cache must refresh often to avoid stale data.
  2. Step 2: Choose caching strategy balancing speed and freshness

    Short TTL with cache refresh after updates keeps data fresh and speeds access.
  3. Final Answer:

    Use short TTL (e.g., 60 seconds) and refresh cache after updates -> Option D
  4. Quick Check:

    Short TTL + refresh = fresh and fast cache [OK]
Hint: Short TTL plus refresh keeps cache fresh and fast [OK]
Common Mistakes:
  • Using long TTL causing stale data
  • Avoiding cache entirely losing speed benefits
  • Not refreshing cache after updates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard