0
0
Supabasecloud~5 mins

Caching strategies in Supabase

Choose your learning style9 modes available
Introduction

Caching helps store data temporarily to make apps faster and reduce work on servers.

When your app shows the same data many times quickly.
When you want to reduce how often your database is asked for data.
When users expect fast loading times on your app.
When you want to save money by using fewer server resources.
Syntax
Supabase
cache.set(key, value, { ttl: seconds })
cache.get(key)
cache.delete(key)

cache.set saves data with a time limit (ttl).

cache.get retrieves saved data if it is still valid.

Examples
Saves user data for 60 seconds.
Supabase
cache.set('user_123', {name: 'Anna'}, { ttl: 60 })
Gets the saved user data if it is still in cache.
Supabase
const user = cache.get('user_123')
Removes the user data from cache immediately.
Supabase
cache.delete('user_123')
Sample Program

This example shows a simple cache using JavaScript Map. It stores user data for 30 seconds to avoid repeated database calls.

Supabase
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = 'https://xyzcompany.supabase.co'
const supabaseKey = 'public-anonymous-key'
const supabase = createClient(supabaseUrl, supabaseKey)

// Simple cache object
const cache = new Map()

// Function to set cache with TTL
function cacheSet(key, value, ttl) {
  cache.set(key, { value, expires: Date.now() + ttl * 1000 })
}

// Function to get cache
function cacheGet(key) {
  const cached = cache.get(key)
  if (!cached) return null
  if (Date.now() > cached.expires) {
    cache.delete(key)
    return null
  }
  return cached.value
}

async function getUser(userId) {
  const cachedUser = cacheGet(userId)
  if (cachedUser) {
    console.log('Returning cached user')
    return cachedUser
  }

  const { data, error } = await supabase
    .from('users')
    .select('*')
    .eq('id', userId)
    .single()

  if (error) {
    console.error('Error fetching user:', error)
    return null
  }

  cacheSet(userId, data, 30) // Cache for 30 seconds
  console.log('Returning fresh user')
  return data
}

// Example usage
(async () => {
  const user1 = await getUser('123')
  console.log(user1)
  const user2 = await getUser('123')
  console.log(user2)
})()
OutputSuccess
Important Notes

Always set a time limit (TTL) to avoid stale data.

Clear cache when data changes to keep it fresh.

Use caching wisely to balance speed and accuracy.

Summary

Caching stores data temporarily to speed up apps.

Use TTL to control how long data stays in cache.

Check cache first before asking the database.