Caching Code Example

Suppose a client or middleware wishes to read data. They will first try to read a key-value-pair (KVP) from Bluzelle's cache. If the KVP is not yet in Bluzelle's cache, that is a "miss", and the client/middleware will fall back to requesting this data from the database directly. The database here is considered the "origin". This usage pattern of Bluzelle+DB is called cache-aside.

We will show you how to implement the cache-aside pattern in JavaScript.

For more information, please refer to Bluzelle's JavaScript API.

Setup

Begin by initializing the Bluzelle client in your code:

const bz = await bluzelle({
public_pem: 'MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE9bpzn2nMBJUndlgsbDH5II5zboGWq3DCfv0alLYUdPBqYIy0atSU5QuckupktqPebw28y/ZZ38k0MVfCQrYE5g==',
private_pem: 'MHQCAQEEIBWT/Vz7ZAxqkaBxXhjKEXfteiERFMNf2QqM7PxuXDOwoAcGBSuBBAAKoUQDQgAE9bpzn2nMBJUndlgsbDH5II5zboGWq3DCfv0alLYUdPBqYIy0atSU5QuckupktqPebw28y/ZZ38k0MVfCQrYE5g=='
});

The Read Pattern

We wish to read a record from the Bluzelle cache and fall back to our existing database.

try {
return await bz.read(key);
}
catch(e)
{
const value = await db.get(key);
await bz.update(key, value);
return value;
}

The Write Pattern

When writing records, write both to the cache and to the database.

await db.put(key, value)
await bz.update(key, value)

AWS Lambda Integration

Below is a sample implementation of a cache-aside pattern for AWS Lambda.

const { bluzelle } = require('bluzelle');
const bz = await bluzelle({
public_pem: 'MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE9bpzn2nMBJUndlgsbDH5II5zboGWq3DCfv0alLYUdPBqYIy0atSU5QuckupktqPebw28y/ZZ38k0MVfCQrYE5g==',
private_pem: 'MHQCAQEEIBWT/Vz7ZAxqkaBxXhjKEXfteiERFMNf2QqM7PxuXDOwoAcGBSuBBAAKoUQDQgAE9bpzn2nMBJUndlgsbDH5II5zboGWq3DCfv0alLYUdPBqYIy0atSU5QuckupktqPebw28y/ZZ38k0MVfCQrYE5g=='
});
const db = {} // Initialize database connection
exports.handler = async function(event, context) {
const key = event.path;
if(event.httpMethod === 'GET') {
return get(key);
}
if(event.httpMethod === 'POST') {
const value = event.body;
return post(key, value);
}
return new Error('HTTP method must be GET or POST');
};
const get = async key => {
try {
return await bz.read(key);
}
catch(e)
{
const value = await db.get(key);
await bz.update(key, value);
return value;
}
};
const post = async (key, value) => {
await db.put(key, value)
await bz.update(key, value)
};