Last active
April 1, 2021 14:45
-
-
Save crazy4groovy/6b82bdef94af6bec982b62ebadb6587e to your computer and use it in GitHub Desktop.
Cache stampede (JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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