I have gone back and forth on this issue several times.
On one hand, you could argue, a repository's single responsibility is to manage the persistent state of an entity, and the consuming application is the one that knows whether it will accept a stale value or not in exchange for performance.
However, if you are dealing with an out of process cache, and many different applications/servers all need that same cached value, putting the caching code in the repository is a convenient place for, and would help avoid cache duplication. Since there is, at that point a single cache acting as a single source of truth, and acting as a buffer for the DB, it seems more appropriate for a repository to contain caching code.
Does caching code belong in a repository?
What about specifically an out of process cache (such as redis) acting as a buffer to the database?
If caching code does not belong in a repository, where should it reside if many desperate pieces of code need that same value?
Decorator
, e.g. you have aFooDao
interface which is implemented byDatabaseFooDao
andRedisFooDao
, the latter delegating to the former if the value is not in cache. Whether the caching should be present at the data access level or at the domain level depends on what you cache, in my opinion. – Vincent Savard Aug 9 '17 at 18:20