Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active April 1, 2021 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/6b82bdef94af6bec982b62ebadb6587e to your computer and use it in GitHub Desktop.
Save crazy4groovy/6b82bdef94af6bec982b62ebadb6587e to your computer and use it in GitHub Desktop.
Cache stampede (JavaScript)
// Basically, store a promise for a key, and return that promise for its key, until the async job is done.
const refPromises = {};
const workflowWithOneCacheMiss = async (key) => {
const dataFromCache = await getCache(key);
if (dataFromCache !== undefined) {
return dataFromCache;
}
if (!refPromises[key]) {
refPromises[key] = new Promise(async (resolve, reject) => {
const dataFromDb = await getDataFromDb(key);
await setCache(key, dataFromDb);
delete refPromises[key]; // required only if cached value can become "stale"
resolve(dataFromDb);
});
}
return refPromises[key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment