When does Moleculer's built-in cacher invalidate entries after the underlying data changes?
0 reputation · 12 Jul 2023, 02:20 UTC
0 reputation · 12 Jul 2023, 02:20 UTC
I'm designing a Moleculer service where several actions are wrapped with the built-in cacher, and I'm trying to pin down exactly when a cached action response stops being served. Assume a recent Moleculer 0.14.x release with the default in-memory cacher.
My understanding is that the cacher keys entries from the action name plus params, and that a TTL controls expiry. What is unclear to me is the relationship between TTL-based expiry and explicit invalidation: if the underlying data store is updated through a different service (or outside the broker entirely), does the cacher have any mechanism to notice, or does it keep serving the old response until the TTL elapses or a manual clean occurs?
I also see references to cache invalidation via events and to wildcard key cleaning, but the documented behavior around which keys get cleared, and whether that differs between the memory cacher and a distributed backend like Redis, is ambiguous to me.
cacher.clean calls, or is there any automatic reaction to data changes?In Moleculer 0.14.x the built‑in cacher removes a cached action result only when one of the following happens:
this.broker.cacher.clean(key) or a clear event is broadcast.cacher.clean() call without a key (clears all entries).There is no automatic invalidation that listens to changes in an external data store. If another service updates the data, the cacher will keep returning the old response until one of the above mechanisms triggers.
When a service emits an event like cache.clear, the broker distributes it to all nodes. Each node’s cacher receives the event and deletes every key that matches the supplied pattern. The pattern is a simple glob – * matches any sequence of characters, ? matches a single character. It is not a regular expression.
Example:
this.broker.emit('cache.clear', 'user.*');
All keys that start with user. will be removed. Wildcard matching is performed by the cacher implementation, so the same syntax applies to both the in‑memory and Redis backends.
clean command issued on any node deletes the key from the Redis database, so every node sees the updated state immediately (subject to network latency).ttl (e.g., 60 s) on the action that reads the data.emit('cache.clear', 'actionName.*') where actionName is the cached action’s name.Do you already set a ttl on the cached actions? If not, the entries will never expire automatically. If you rely on the default (no TTL), you must use explicit clean or events to keep the cache fresh.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.