How do I correctly add cache information for breadcrumb parts? Visiting a node Foobar a breadcrumb gets created which adds the parent menu structure like so:

$currentPluginId = $menu_link-&gt;getPluginId();
$trailIds = $this-&gt;menuActiveTrail-&gt;getActiveTrailIds('main');

foreach (array_reverse($trailIds) as $key =&gt; $value) {
  if ($value &amp;&amp; $value !== $currentPluginId) {
    // @todo add cache per item
    $instance = $menu_link_manager-&gt;createInstance($value);
    $breadcrumb-&gt;addLink(
      new Link(
        $instance-&gt;getTitle(),
        $instance-&gt;getUrlObject()
      )
    );
  }
}

$breadcrumb-&gt;addCacheContexts(['route.menu_active_trails:main']);


So the breadcrumb looks like:


  Home > John Doe > Foobar


But if the node/ menu item of John Doe changes, the breadcrumb for Foobar stays the same.

dpm($instance-&gt;getUrlObject()-&gt;getRouteName());
dpm($instance-&gt;getUrlObject()-&gt;getRouteParameters());


gives me: 


  entity.node.canonical


and


  array(
      [node] => 25 )


How can I use that for adding each breadcrumb part as cache context/ tag?
Look at \Drupal\book\BookBreadcrumbBuilder::build() for an example. You'll want to add the cacheability metadata (or at minimum the cache tags) of the node/menu item John Doe.

So:

$breadcrumb-&gt;addCacheableDependency($entity);




You could have easily figured this out yourself: you're building a \Drupal\Core\Breadcrumb\Breadcrumb object… which implements RefinableCacheableDependencyInterface, and that interface lists all things related to cacheability.

I highly recommend you read https://www.drupal.org/developing/api/8/cache and all documentation it points to.