Loading and deleting a cache item I have a render array I'm caching as follows:

$build['friend_link'] = [
  '#type' =&gt; 'item',
  '#markup' =&gt; $link,
  '#cache' =&gt; [
    'keys' =&gt; ['friendship', $user-&gt;id()],
  ],
];


I need to delete this cache when the friendship is invalidated. However, I'm having a lot of troubles with retrieving the cache in order to invalidate it. I'm attempting to use the following code to retrieve the cache item:

$render_cache = \Drupal::cache('render');
$render_cache-&gt;get('friendship:' . $friend-&gt;id()); // id = 4


However, this doesn't work, because the actual cache key in the DB is:

friendship:4:[languages:language_interface]=en:[theme]=bartik:[user.permissions]=80e4ddd871aca07e035f618b532bc75cb7c155caaaedd08a4ae17e5e137ca30f


I tried setting the cache contexts to an empty array:

'#cache' =&gt; [
  'keys' =&gt; ['friendship', $user-&gt;id()],
  'contexts' =&gt; [],
],


But this didn't change the key. So I set the contexts to a value:

'#cache' =&gt; [
  'keys' =&gt; ['friendship', $user-&gt;id()],
  'contexts' =&gt; ['user'],
],


This changed the key to:

friendship:4:[languages:language_interface]=en:[theme]=bartik:[user]=1


So while this does make it potentially easier to build the key manually, it seems like I'm missing something.

I did find RenderCache::createCacheID(), however it's protected so I can't call it.

I'm at a bit of a loss here, is there an API function I'm missing somewhere to retrieve the cache?
What exactly is a "friendship"? You most likely want to use cache tags for invalidation.

One way to do that would be to add the cache tag for the user, then you just have to make sure that you are invalidating that user cache tag. So you add 'tags' =&gt; $user-&gt;getCacheTags(), and when the friendships of a user change, you use Cache::invalidateTags($user-&gt;getCacheTags()). The downside is that this will invalidate too much: It will invalidate all content where the user is displayed, e.g. if he's the author of an article.

You could define your own cache tag; they're really just strings and invalidate just that, e.g. 'tags' =&gt; ['friendships:' . $user-&gt;uid] and then invalidate that.

Cache contexts are for variations of the same cache entry; it's exactly those things you see in the cache key. Having $user-&gt;id() in the cache keys and the user context is practically the same thing. You can do either or the other; you don't need both. (Cache context user and keys just 'friendships' would be the same as what you have now.)