Cache query results
https://github.com/strongloop/loopback-datasource-juggler/pull/812#issuecomment-178478203 describes the following use case:
Our API is starting to have huge traffic and to gain perfomance, we need to implement a cache system. To do that, we want to use the operation hooks (Example):
Model.observe('access', function (context, cb) {
// check the cache
// short-cirtcuit to cb(null, cached) when found
});
Model.observe('all_loaded', function (context, cb) {
// update the cache
});
Implementing a good caching solution is difficult, as there are many edge case to handle correctly. For example, should findOrCreate use the cached data too? findById? How should we invalidate the cached data, do we want WRITE operations like create to invalidate records, or is it enough to use a time-based invalidation, where cache records expire after a given time interval, and thus clients may receive stale data?
I think LoopBack should provide a built-in caching mechanism with hooks for customizing cache fetch & update, possibly with components providing implementations of these hooks for common caching backends (in-memory, memcache, redis, etc.)
At the moment, a caching layer can be implemented at strong-remoting level (see https://github.com/strongloop/loopback-datasource-juggler/pull/812#issuecomment-180427291) or by changing the find method (https://github.com/strongloop/loopback-datasource-juggler/pull/812#issuecomment-185104939).
Hi @bajtos
I like the idea with the base cached model :-) But we will not be able to cache native model like ACLs, RoleMapping, ... These models are requested for each REST Calls and the perfs will really increase with caching.
So maybe improve PersistedModel with cache layer and provide the option cache: true in the model.json
{
"_meta": {
"sources": [
"./node_modules/loopback/common/models",
"loopback/common/models",
"loopback/server/models"
]
},
"User": {
"dataSource": "db",
"public": false
},
"ACL": {
"dataSource": "db",
"public": true,
"cache": true
}
}
I like the idea with the base cached model :-)
I am glad to hear that :)
But we will not be able to cache native model like ACLs, RoleMapping, ... These models are requested for each REST Calls and the perfs will really increase with caching.
That's a very valid point. In that case I am proposing to use a mixin-based approach.
// server/mixins/cache-queries.js
module.exports = function(Model, options) {
// wait until the datasource defined `find` method
CachedModel.on('dataAccessConfigured', function() {
var Model = this;
Model._findLive = CachedModel.find;
Model.find = function(filter,...,cb) {
var cached = // check the cache
if (cached)
cb(null, cached);
else
Model._findLive(filter,...,cb);
};
});
};
Now I am not sure if loopback-boot supports applying mixins via server/model-config.json file. As a workaround, one can setup this mixin via a boot script.
// server/boot/cache.js
var cacheQueries = require('../mixins/cache-queries.js');
module.exports = function(app) {
cacheQueries(app.models.ACL);
cacheQueries(app.models.RoleMapping);
// etc.
};
I can imagine this two bits of code can be neatly wrapped in a reusable component which I imagine will be configured as follows:
// server/component-config.json
{
"loopback-component-cache-queries": {
"models": ["ACL", "RoleMapping"],
"store": "memory"
}
}
So maybe improve PersistedModel with cache layer and provide the option cache: true in the model.json
Yes, I think we should eventually implement something like that. I am not sure if cache:true would be enough, as we may need to configure the cache backend (in-memory, redis, etc.). This configuration will allow users to cache the data cross-process when running the app in a cluster of node processes.
loopback-component-cache-queries would be great.
We can add a Cache model linked to in-memory/redis/... datasource ?
Another point we shoud consider :
To keep some data integrity, we should also override in the mixin the WRITE methods. That will allow to clean the data in the cache.
To keep some data integrity, we should also override in the mixin the WRITE methods. That will allow to clean the data in the cache.
You can subscribe to "after save" and "after delete" hooks, they are perfectly suited for that.
Hi @bajtos , I tried to use
// server/boot/cache.js
var cacheQueries = require('../mixins/cache-queries.js');
module.exports = function(app) {
cacheQueries(app.models.ACL);
cacheQueries(app.models.RoleMapping);
};
and
// server/mixins/cache-queries.js
module.exports = function(Model, options) {
console.log("Cache for: " + Model.modelName);
// wait until the datasource defined `find` method
Model.on('dataAccessConfigured', function() {
console.log("dataAccessConfigured");
});
};
but seems dataAccessConfigured event is not emitted.
We can see the boot (cache.js) was executed. But the event dataAccessConfigured was not triggered for the Model.on()
INFO strong-agent v2.0.3 profiling app 'lexacl' pid '30880'
INFO strong-agent[30880] started profiling agent
INFO supervisor reporting metrics to internal:
supervisor running without clustering (unsupervised)
Cache for: ACL Cache for: RoleMapping
INFO strong-agent not profiling, agent metrics requires a valid license. Please contact [email protected] for assistance. Web server listening at: http://0.0.0.0:3000 Browse your REST API at http://0.0.0.0:3000/explorer
Could you please advise if I'm doing any wrong initialization or what I'm missing?
Thanks.
@bajtos Has there been any movement here? :) I would love to contribute if it is a WIP.
Has there been any movement here? :) I would love to contribute if it is a WIP.
Very little. Recently, we created a KeyValueModel with in-memory and Redis connectors. The new feature is not documented yet, but you can learn about it from https://github.com/strongloop/loopback/issues/2525 and other linked issues/pull requests.
You are welcome to try to build a caching layer using this new feature! I am recommending you to start a new project (npm package) that will provide the caching feature, either as a mixin configurable via common/models/my-model.json or as a component configurable via server/component-config.json. This way you stay fully in control of your code & project.
@bajtos Thanks for being descriptive! I was going through the thread and the new KV model but I am following doubts! I started working on a caching solution similar to the mentioned below:
Model.observe('access', function (context, cb) {
// check the cache using KV model
// short-cirtcuit to cb(null, cached) when found
});
Model.observe('all_loaded', function (context, cb) {
// update the cache to KV model
});
How do I handle edge case like to handle correctly? For example, should findOrCreate use the cached data too? findById? Even in case of 'update' operation the access hook will get executed and eventually get short circuited. How do I solve it? Is there a way I can get the method name in the context variable passed to the hooks?
I see that I can use 'remote' hooks to solve the issue but I have some logic residing in boot scripts and apparently 'remote' hooks don't work for boot script code.
Thanks in advance
@sreerajkrishnank Yeah, I think the proposal of using operation hooks was not a good one. Have you considered the newer one (described e.g. in https://github.com/strongloop/loopback/issues/2076#issuecomment-185149122 but also in https://github.com/strongloop/loopback-datasource-juggler/pull/812#issuecomment-185104939), where the caching layer overrides individual DAO methods? That gives your better control of how to handle caching for each individual operation.
Is there a way I can get the method name in the context variable passed to the hooks?
No, operation hooks were intentionally designed in this way. See https://github.com/strongloop/loopback-datasource-juggler/issues/397
For example, should findOrCreate use the cached data too?
The way how findOrCreate is implemented now:
- If your connector provides optimized/atomic implementation, then your caching layer can decide whether and how to cache this method.
- If your connector does not provide optimized implementation, juggler will fall back to
find+create. In this case, the caching offindwill be triggered. I think it should be possible to define a newoptionsproperty to avoid that.
As for findById, it calls find under the hood, so it will use the same caching scheme as find. I don't know whether that's a good or a bad thing.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.
TypeError: context.end is not a function at D:\Workspace_for_cache\SpeedUp\common\mixins\cache-mixin.js:24:36 at notifySingleObserver (D:\Workspace_for_cache\SpeedUp\node_modules\loopback-datasource-juggler\lib\observer.js:160:24)
i am getting this error while using the above method to cache can you help me with this @bajtos