Adding custom variable to twig's html.html.twig which is not cachable
Ok - so to write your own extension see this answer, refeer to the twig tweak module. Or follow this article, that's it's content adapted to session (using a funcition) - like twig tweak, but different form the linked answer:

In this exemple, we built an extension du display a Drupal block directly from a twig template :

{{ session_var('my_var_name') }}


To to it, you must create a custom Drupal module. You can use the Drupal console to easily create your module.

In your module folder, frist create a new class in in a src subfolder :

For exemple : src/MyTwigExtension.php

&lt;?php
namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'session_var';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('session_var', 
        array($this, 'session_var'),
        array('is_safe' =&gt; array('html')
      )),
  }

  public function session_var($key) {
    return \Session-&gt;get($key);
  }

}


In a second time you must register your extension as service : 

Create a service configuration file 

# src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }


And you are done :-)

You can now enable your module and use your Twig extension.



The simple workaround could look like this in twig:

{% app.session.get('cart')|length %}