Zend certified PHP/Magento developer

Set cookie not working with varnish

I’ve created the following observer method that sets a cookie:

       if ($this->_cookieManager->getCookie(self::COOKIE_NAME)) {
            $this->_cookieManager->deleteCookie(
                self::COOKIE_NAME,
                $this->_cookieMetadataFactory
                    ->createCookieMetadata()
                    ->setPath('/')
                    ->setDomain(null)
            );
        }

        $metadata = $this->_cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration(self::COOKIE_DURATION)
            ->setPath('/')
            ->setDomain(null);

        $this->_cookieManager->setPublicCookie(
            self::COOKIE_NAME,
            $mediumValue,
            $metadata
        );

It observes the event controller_action_predispatch to run on all pages.
This code works perfectly when Varnish is disabled, but when I enable varnish, this code no longer sets the new cookie.