jperasmus / stale-while-revalidate-cache

Storage-agnostic and configurable stale-while-revalidate cache helper for any function, for any JavaScript environment.
MIT License
62 stars 5 forks source link

Can this be used in a distributed environment e.g. Kubernetes? #2

Closed benknight closed 2 years ago

benknight commented 2 years ago

I'm assuming the answer is no. But assume I'm deploying a Node application on Kubernetes and memcached for storage. Each Node server instance have its own SWR function and so I think would not be able to coordinate with SWR functions running on other nods as far as determine cache status?

jperasmus commented 2 years ago

Hi @benknight It should definitely work using a single Memcached instance as storage source. This library gives you an optional storage config option that you can set when you instantiate it, so depending on the client library you are using for your Memcached setup, it would look something like this:

const MemcachedClient = require('some-memcached-library')
const { createStaleWhileRevalidateCache } = require('stale-while-revalidate-cache')

// Instantiate your Memcached client as you normally do
const memcached = new MemcachedClient()

// Here you configure how cached values should be stored and retrieved from your Memcached instance.
// The only important parts are that you give it a `getItem` and `setItem` method that returns a Promise
const storage = {
    async getItem(cacheKey: string) {
      return memcached.get(cacheKey)
    },
    async setItem(cacheKey: string, cacheValue: any) {
      await memcached.set(cacheKey, cacheValue)
    },
  }

// Now instantiate SWR cache with your custom `storage`
const swr = createStaleWhileRevalidateCache({
  storage
})

Hope this helps!