Cache Moleculer Action Responses with MemoryCache
Enable Moleculer's built-in MemoryCache for action responses, verify hits with ctx.meta.$cached, and manage single-node limits.
29 Dec 2025, 23:33 UTC

You have a Moleculer action that runs a database query or calls an external API, and the same request arrives repeatedly with identical arguments. Each call repeats the work even though the result rarely changes. Adding an external cache such as Redis is one option, but it introduces infrastructure you may not need yet.
Takeaway: Moleculer includes a built-in MemoryCache connector. Enable it on the broker, add a cache option to the action schema, and check ctx.meta.$cached to tell whether a response came from memory or was computed fresh. The cache lives in a single Node.js process and is lost on restart.
Desired outcome
Repeated calls to a Moleculer action with the same arguments return the stored response without re-running the handler, using only in-process memory. After the TTL elapses, the next call computes a fresh result.
Prerequisites
- A Node.js project with Moleculer installed.
- A broker file you can edit and restart.
- No external cache service is required for MemoryCache.
Install the dependency
Run this in the project root with normal filesystem permissions:
npm install moleculer
This modifies package.json and node_modules. Review the change before committing it in production.
Enable MemoryCache on the broker
Set cache: true when creating the ServiceBroker. Moleculer then uses the default in-process MemoryCache connector.
const { ServiceBroker } = require('moleculer');
const broker = new ServiceBroker({
cache: true,
});
You can also write { type: 'Memory' }. The connector keeps entries in the current process only; it does not share data with other nodes or survive a restart.
Mark an action as cacheable
Add a cache option to the action schema. Use ttl to set the expiration in milliseconds and keys to list the parameter names that form the cache key.
broker.createService({
name: 'posts',
actions: {
getPost: {
cache: {
ttl: 60000,
keys: ['id'],
},
async handler(ctx) {
console.log('fetching fresh post', ctx.params.id);
return { id: ctx.params.id, title: 'Hello' };
},
},
},
});
If you omit keys, Moleculer builds the key from the action parameters according to its default behavior. Explicit keys make it easier to reason about which arguments produce a cache hit.
Verify cache behavior
Run this diagnostic script in the same project as your broker:
const { ServiceBroker } = require('moleculer');
const broker = new ServiceBroker({ cache: true });
broker.createService({
name: 'demo',
actions: {
getItem: {
cache: { ttl: 5000, keys: ['id'] },
async handler(ctx) {
console.log('handler executed for id:', ctx.params.id);
console.log('served from cache:', ctx.meta.$cached === true);
return { id: ctx.params.id, value: Date.now() };
},
},
},
});
await broker.start();
await broker.call('demo.getItem', { id: 1 });
await broker.call('demo.getItem', { id: 1 });
await broker.call('demo.getItem', { id: 2 });
await broker.stop();
Expected checks:
- The first call with
{ id: 1 }runs the handler and logsserved from cache: false. - The second call with
{ id: 1 }skips the handler and logsserved from cache: true. - The call with
{ id: 2 }runs the handler again because the cache key differs. - With a short
ttl, waiting past the expiry and calling again runs the handler once more.
Inside a handler, ctx.meta.$cached is true when Moleculer returns a stored response. You can use that flag to skip logging, metrics, or other work that should happen only on fresh computation.
Inspect and evict cache entries
In a test or REPL, confirm the connector type:
console.log(broker.cache.constructor.name); // expect MemoryCache
To clear all in-process entries manually:
await broker.cache.clean();
This evicts stored responses immediately. Use it during development or after correcting bad data, but remember it affects every cached action on that node.
Limitations and recovery
- MemoryCache is local to one Node.js process. Sibling instances and other nodes do not see its entries. Use RedisCache or another connector for shared multi-node caching.
- Restarting the process clears the cache.
- Do not cache actions with side effects or non-deterministic output; callers may receive stale results and errors can be hidden.
- High-cardinality cache keys or a missing TTL can cause unbounded memory growth in long-running services.
Rollback
Enabling caching changes runtime behavior. To roll back, remove cache: true from the broker options and the cache option from the affected action schema, then restart the process. A restart also clears any entries already held in MemoryCache.
Practical check after rollback: call the same action twice with identical arguments and confirm the handler log appears on both calls.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.