Skip to main content

Cache

Overview

The purpose of this component is to provide a cache implementation for a number of selected cache providers. Currently the cache component supports the following engines:

  • Hybrid - Utilizes both the memory and Redis cache, see below for more info
  • In Memory - Utilizes node-cache to provide an in-memory cache.
  • Redis - Utilizes ioredis to provide a redis cache.

The cache componwnt is initialised on startup and the engine used is defined in the configuration document.

In local dev we use in-memory only for simplicity, all other environments use the Hybrid cache.

Hybrid Cache

The purpose of the hybrid cache is to maximise performance and reduce database load. This works by using Redis as a longer lasting cache and in-memory as a very short lived (2 minutes) cache.

Its important to note that because the memory cache is replicated across each web server cache invalidation messages will only be executed on the server that handles the invalidation API call, redis is obviously shared so a cache invalidationmessage will invalidate the redis cache for all servers. This means even after a cache invalidation message has been processed some cache keys on some servers may be act3ive until the memory cache expires, hence the short cache expiry time for the memory cache.

The hybrid cache will attempt to locate an item from memory cache, if its not found it will look in redis cache if its not found in redis it will retrieve the item from the database and cache it in redis for the specified time and in the memory cache for 2 minutes.

A put request to hybrid cache will write the item to memory cache and redis cache

Usage

  1. Set the cache variables in the configuration.ts file to choose the engine you wish to use.
  2. Import the cache implementation using the following code:
import { cache } from '@hectare/platform.components.cache'

...

await cache.set(...)
await cache.get(...)

Note: The imported cache is a singleton and will load the desired cache implementation at runtime.

See the ICache interface for a list of public functions that can be used.

Redis - Local Testing

If you wish to use the Redis cache implementation, you must be running an instance of Redis on your local environment. The easiest way to achieve this is by using the Docker Redis Image.

docker pull redis
docker run --network=host -p 6379:6379 redis