title: Google Cloud Kubernetes - Load Balancer session affinity with Cloudflare
body: <h2>Background</h2>
  
  <p>I have web application which deployed to deployment with multiple pods. The deployment is exposed to the internet with kubernetes service with external IP. </p>
  
  <p>The external IP exposed to the world via Cloudflare:</p>
  
  <pre><code>Client ---&gt; Cloudflare ---&gt; k8 service ---&gt; pod
  </code></pre>
  
  <p>This web application needs to be defined with sticky sessions. So I patched my service with <code>sessionAffinity: ClientIP</code>, like this:</p>
  
  <pre><code>kubectl patch service MYSERVICE  -p '{"spec":{"sessionAffinity":"ClientIP"}}'
  </code></pre>
  
  <p>I checked it on development environment and found that the session affinity is not working well. </p>
  
  <h2>Investigation</h2>
  
  <p>I looked for the problem with the sticky sessions. Then I found that Cloudflare caller IP can be changed from time to time - randomly. This will redirect all the users to another pod - exactly what Sticky Session should solve.</p>
  
  <p>So, the problem is that my Loadbalancer service redirect traffic according to Cloudflare IP and it random.</p>
  
  <h2>Possible solutions</h2>
  
  <ol>
  <li>I found that it may be possible to loadbalance traffic according to
  Cookie. Founded this <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/configure-backend-service#setting_generated_cookie_affinity" rel="nofollow noreferrer">source</a>. But it using advanced Kubernetes
  components, like BackendService and Ingress, that needs to be
  well-defined. Do you have more simple solution?</li>
  <li>Cloudflare attaching the real client IP to the request in headers. Is this possible to define the loadbalancing to look on this header and redirect the traffic according to it's value?</li>
  </ol>