<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kleber Rocha on Medium]]></title>
        <description><![CDATA[Stories by Kleber Rocha on Medium]]></description>
        <link>https://medium.com/@klinuxk?source=rss-5d0fefc99b04------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UuzcLF3PNKntTnU_swefTA.jpeg</url>
            <title>Stories by Kleber Rocha on Medium</title>
            <link>https://medium.com/@klinuxk?source=rss-5d0fefc99b04------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:50:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@klinuxk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Keycloak: Remote persistent sessions]]></title>
            <link>https://klinuxk.medium.com/keycloak-remote-persistent-sessions-9e0a279632d2?source=rss-5d0fefc99b04------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0a279632d2</guid>
            <category><![CDATA[infinispan]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Kleber Rocha]]></dc:creator>
            <pubDate>Tue, 25 May 2021 17:52:42 GMT</pubDate>
            <atom:updated>2021-06-08T18:15:17.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADUTnfFRiVoqUNEsJ3o6Mg.png" /></figure><blockquote><strong>Disclaimer</strong>: Este artigo foi feito para ajudar outros engenheiros a criar um sistema mais robusto de autenticação com o <strong>Keycloak</strong>, e também abrir uma thread até mesmo para discutir esta solução e até criar um processo melhor.</blockquote><p>Keycloak é uma ferramenta opensource para <strong>SSO</strong>, com ele você pode usar os principais protocolos para autenticação e autorização, como, <strong>OAuth2</strong> e <strong>SAML</strong>.</p><p>O <strong>Keycloak</strong> tem ótimas features para atender grande parte das necessidades que temos hoje na engenharia pra cuidar da autenticação e autorização, não vamos entrar em detalhes do que o <strong>Keycloak</strong> pode fazer ou não, pois isso tomaria bastante tempo, isso pode ser visto na documentação do produto, acesse o site do <strong>Keycloak</strong> para maiores informações: <a href="https://www.keycloak.org/documentation">https://www.keycloak.org/documentation</a></p><h4>Detalhando o problema</h4><p>O Keycloak gerencia todas as suas sessões usando o <strong>Infinispan </strong>(<a href="https://infinispan.org/">https://infinispan.org/</a>) embarcado, o <strong>Keycloak</strong> cria alguns caches in-memory para ter maior performance, em vez de gerenciar tudo em um banco de dados, quando você está rodando o <strong>Keycloak</strong> em produção, você pode fazer a persistência das sessões entre os nós do cluster, por exemplo, setar as definições dos caches do cluster com o <strong>owners</strong> igual ao número de nós do seu Cluster.</p><blockquote>&lt;distributed-cache name=”sessions” owners=”3&quot;/&gt;</blockquote><p>No exemplo acima, o cache usa o modelo distribuído, veja a documentação quais são os modelos de cache no Infinispan: <a href="https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#cache_modes-configuring">https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#cache_modes-configuring</a>, você pode configurar isso diretamente nos arquivos de configuração <strong>standard.xml</strong>, <strong>standard-ha.xml</strong> ou<strong> domain.xml</strong>. Se você usa o Keycloak em docker, kubernetes você pode só setar as váriaveis de ambientes abaixo:</p><p>CACHE_OWNERS_COUNT=3<br>CACHE_OWNERS_AUTH_SESSIONS_COUNT=3</p><p>Você pode olhar melhor a documentação aqui (<a href="https://github.com/keycloak/keycloak-containers/blob/13.0.1/server/README.md#replication-and-fail-over">https://github.com/keycloak/keycloak-containers/blob/13.0.1/server/README.md#replication-and-fail-over</a>)</p><p>Com isso você já tem um sistema com alta-disponibilidade, quando não se pode perder sessões, em aplicações críticas por exemplo, se sua aplicação não tem impacto, por exemplo se reiniciar todos os nós por alguma falha ou algo não previsto, e seu usuário poder fazer o login novamente sem isso causar grandes problemas, a configuração default do Keycloak já vai atender você, este documento é direcionado para quem tem aplicações críticas que isso não pode acontecer. Na documentação do <strong>Keycloak</strong> você pode ver a dica sobre esta configuração:</p><blockquote>The number of owners recommended is really dependent on your deployment. If you do not care if users are logged out when a node goes down, then one owner is good enough and you will avoid replication.</blockquote><p>Os caches importantes aqui são os listados abaixo, você pode ver isso descrito na documentação do próprio Keycloak, na parte de replicação do cache entre sites (<a href="https://www.keycloak.org/docs/latest/server_installation/index.html#crossdc-mode">https://www.keycloak.org/docs/latest/server_installation/index.html#crossdc-mode</a>).</p><blockquote>sessions<br>work<br>offlineSessions<br>clientSessions<br>offlineClientSessions<br>loginFailures<br>actionTokens</blockquote><h4>Detalhando a solução</h4><p>Como nosso ambiente não pode ter este tipo de situação, temos que nos previnir inclusive de falhas que não podemos controlar, e caso todo o ambiente reinicie, precisamos ter de volta todas as sessões de volta.<br>Em nosso ambiente, usamos tudo em Kubernetes, mas tudo issoé possível configurar também em um ambiente usando VMs ou BareMetal.</p><p>Com isso pegamos a solução de replicação entre sites, e incluimos somente um infinispan remoto, que pode ou não ser replicado entre sites, vai depender de sua necessidade, e criamos uma persistência em disco dos caches usando o RoksDB(<a href="https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#rocksdb_cache_store">https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#rocksdb_cache_store</a>), eleé muito mais performático que usar um SQL por exemplo, que também é uma solução possível (<a href="https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#jdbc_cache_store">https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#jdbc_cache_store</a>), mas em nosso ambiente a persistência via JDBC não se comportou muito bem, não foi muito performática, principalmente na hora de fazer o <strong>preload</strong> do banco para memória, ou, você pode usar a persistência em arquivo simples (<a href="https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#sfs_cache_store">https://infinispan.org/docs/12.1.x/titles/configuring/configuring.html#sfs_cache_store</a>), preferimos não seguir com esta configuração, justamente por ser um arquivo simples, e conter todo indice no próprio arquivo, o que poderia ser um problema de performance e ter outras consequências, você pode se perguntar se não teria outra maneira de fazer esta persistência, como um <strong>Redis</strong>, infelizmente, oficialmente não temos este suporte, tinham alguns plugins da comunidade que suportava o <strong>Redis</strong>, <strong>MongoDB</strong>, <strong>Cassandra, </strong>etc. Mas algumas soluções pararam o suporte na versão 9 do Infinspan. Você pode olhar aqui essa informação (<a href="https://infinispan.org/cache-store-implementations">https://infinispan.org/cache-store-implementations</a>).</p><blockquote>The following cache stores are developed and maintained independently of the Infinispan release cycle, so they might not be aligned with the latest version of the Cache Store SPI.</blockquote><p>Como diz na documentação da página, estes <strong>caches stores</strong> podem não estar totalmente compátiveis com o Infinispan.</p><p>Abaixo podemos ver como foi feita a topologia da nossa solução para ter este tipo de funcionalidade, termos o HA dos caches, e também persistir os caches em disco, e caso de perda de todos os Pods e assim recuperar as sessões depois de um reboot total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYKblBpGzkxcZEckx-U-_Q.png" /><figcaption>Keycloak Deploy Topology</figcaption></figure><p>Como pode ser visto na imagem, temos o cluster de <strong>Keycloak</strong>, e também um cluster de <strong>Infinispan</strong>, e este cluster, tem seus caches persistidos em disco usando o <a href="https://rocksdb.org/"><strong>RocksDB</strong></a>, o <strong>RocksDB</strong> tem suporte oficial no Infinipan e tem uma ótima <strong>performance</strong>, além de suportar <strong>compressão</strong>, e uma performance muito boa pra fazer o <strong>preload</strong>. Ou seja, carregar o que temos em disco para a mémoria do Infinipan.</p><h4>Setup</h4><p>Para fazer esta configuração você pode escolher algumas maneiras de configurar o <strong>Keycloak</strong>, você pode fazer isso configurando o arquivo do cluster que deseja usar e subir junto com a imagem do <strong>Keycloak</strong>, ou configurar tudo isso via script como o exemplo abaixo:</p><pre>embed-server — server-config=standalone-ha.xml — std-out=echo<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=sessions:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=authenticationSessions:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=offlineSessions:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=clientSessions:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=offlineClientSessions:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=loginFailures:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>/subsystem=infinispan/cache-container=keycloak/distributed-cache=actionTokens:write-attribute(name=owners, value=${env.CACHE_OWNERS:3})<br>run-batch<br>stop-embedded-server</pre><blockquote>Este exemplo acima, é um exemplo simples de como manipular a configuraçãdo do <strong>Keycloak</strong> sem precisar editar os arquivos <strong>standalone.xml</strong> ou<strong> standalone-ha.xml </strong>ou <strong>domain.xml</strong>.</blockquote><p><strong>Keycloak</strong></p><p>Para fazer a instalação do <strong>Keycloak</strong>, usamos o helm chart da <a href="https://github.com/codecentric/helm-charts/tree/master/charts/keycloak"><strong>Codecentric</strong></a>, este chart é bem detalhado e tem uma ótima documentação de como instalar seu ambiente, não iremos cobrir aqui a instalação do <strong>Keycloak</strong> pois demandaria muito do documento, o intuíto deste documento é tratar a persistência das sessões.</p><p><strong>Infinispan</strong></p><p>Para fazer a instalação do <strong>Infinispan</strong>, usamos o <strong>Infinispan-Operator</strong>, também tem uma documentação bem detalhada e de fácil entendimento.</p><blockquote>O operator tem algumas limitações neste projeto, por exemplo para manipular annotations para o Ingress por exemplo, tem uma <a href="https://github.com/infinispan/infinispan-operator/issues/1060">issue</a> aberta pra isso. Para corrigir alguns destas limitações, somente aplicar um patch depois de instalado no que precisa ser corrigido, por exemplo no ingress, ou no statefulset.</blockquote><p>Instalar o <strong>infinispan-operator</strong>, baixe o manifesto<strong> </strong><a href="https://raw.githubusercontent.com/infinispan/infinispan-operator/2.1.3.Final/deploy/operator-install.yaml"><strong>operator-install.ayml</strong></a> e instale com o comando abaixo:</p><pre>kubectl apply -f operator-install.yaml -n infinispan</pre><p>Uma vez o ambiente configurado, e rodando, você precisa configurar os caches no <strong>Infinispan</strong> para poder configurar o <strong>Keycloak</strong>, abaixo segue um exempo de criação de um cluster via <strong>Operator</strong> e a criação dos caches.</p><p><strong><em>cluster.yaml</em></strong></p><pre>apiVersion: infinispan.org/v1<br>kind: Infinispan<br>metadata:<br>  name: infinispan-cluster<br>  namespace: infinispan<br>spec:<br>  replicas: 3<br>  service:<br>    type: DataGrid<br>    container:<br>      storage: <strong>100Gi</strong><br>      ephemeralStorage: <strong>false</strong><br>  autoscale:<br>    maxMemUsagePercent: 80<br>    minMemUsagePercent: 40<br>    maxReplicas: 5<br>    minReplicas: 3<br>  security:<br>    endpointAuthentication: <strong>false</strong><br>    endpointEncryption:<br>      type: <strong>None</strong><br>  container:<br>    extraJvmOpts: &quot;-XX:NativeMemoryTracking=summary&quot;<br>    cpu: <strong>&quot;1000m&quot;</strong><br>    memory:<strong> 3Gi</strong><br>  expose:<br>    type: <strong>Route</strong><br>    host: <strong>cache.example.com</strong><br>  logging:<br>    categories:<br>      org.infinispan: info<br>      org.jgroups: info<br>  affinity:outbound-socket-binding<br>    podAntiAffinity:<br>      preferredDuringSchedulingIgnoredDuringExecution:<br>        - weight: 100<br>          podAffinityTerm:<br>            labelSelector:<br>              matchLabels:<br>                app: infinispan-pod<br>                clusterName: infinispan-cluster<br>                infinispan_cr: infinispan-cluster<br>            topologyKey: &quot;kubernetes.io/hostname&quot;</pre><p>O exemplo acima cria um cluster simples somente para demonstração do nosso documento, veja que setamos a memória dos pods em 3Gi, com esta informação o <strong>Operator</strong> faz um cálculo de quanto será usado para o <strong>-Xmx</strong> do heap do <strong>Infinispan</strong>, com este arquivo criado, é somente aplicar o deploy:</p><blockquote>Veja que colocamos o valor para <strong>false</strong> em <strong>ephemeralStorage</strong>, faça isso se não quiser perder dados, caso contrário, o <strong>Infinispan</strong> mata o disco.</blockquote><pre>kubectl apply -f cluster.yaml -n infinispan</pre><p>Quando o cluster estiver rodando, agora podemos criar todos os caches para o ambiente do <strong>Keycloak</strong>.</p><p><strong><em>caches.yaml</em></strong></p><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-sessions<br>spec:<br>  clusterName: infinispan-cluster<br>  name: sessions<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;sessions&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-work<br>spec:<br>  clusterName: infinispan-cluster<br>  name: work<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;work&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-client-sessions<br>spec:<br>  clusterName: infinispan-cluster<br>  name: clientSessions<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;clientSessions&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-offline-sessions<br>spec:<br>  clusterName: infinispan-cluster<br>  name: offlineSessions<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;offlineSessions&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-offline-client-sessions<br>spec:<br>  clusterName: infinispan-cluster<br>  name: offlineClientSessions<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;offlineClientSessions&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-action-tokens<br>spec:<br>  clusterName: infinispan-cluster<br>  name: actionTokens<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;actionTokens&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><pre>---<br>apiVersion: infinispan.org/v2alpha1<br>kind: Cache<br>metadata:<br>  name: keycloak-login-failures<br>spec:<br>  clusterName: infinispan-cluster<br>  name: loginFailures<br>  template: &lt;infinispan&gt;&lt;cache-container statistics=&quot;true&quot;&gt;&lt;metrics gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;&lt;distributed-cache name=&quot;loginFailures&quot; statistics=&quot;true&quot; mode=&quot;SYNC&quot; remote-timeout=&quot;30000&quot; owners=&quot;3&quot;&gt;&lt;state-transfer timeout=&quot;600000&quot; /&gt;&lt;locking concurrency-level=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;&lt;encoding media-type=&quot;application/x-jboss-marshalling&quot;/&gt;&lt;persistence&gt;&lt;rocksdb-store preload=&quot;true&quot; fetch-state=&quot;true&quot;&gt;&lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;&lt;write-behind/&gt;&lt;property name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;&lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;&lt;property name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;&lt;/rocksdb-store&gt;&lt;/persistence&gt;&lt;/distributed-cache&gt;&lt;/cache-container&gt;&lt;/infinispan&gt;</pre><p>Agora é só aplicar os caches no cluster.</p><pre>kubectl apply -f caches.yaml -n infinispan</pre><p>Neste arquivo acima, falamos para o operator criar todos os caches necessários para o <strong>Keycloak</strong>, agora vamos descrever o que esta sendo feito aqui, para consultar os parâmetros use a documentação em <a href="https://docs.jboss.org/infinispan/12.1/configdocs/infinispan-config-12.1.html"><strong>cofiguration</strong></a>.</p><pre>&lt;infinispan&gt;<br>  &lt;<strong>cache-container</strong> statistics=&quot;true&quot;&gt;<br>    &lt;<strong>metrics</strong> gauges=&quot;true&quot; histograms=&quot;true&quot; /&gt;<br>    &lt;<strong>distributed-cache</strong> name=&quot;loginFailures&quot; <strong>statistics</strong>=&quot;true&quot; mode=&quot;SYNC&quot; <strong>remote-timeout</strong>=&quot;30000&quot; <strong>owners</strong>=&quot;3&quot;&gt;<br>      &lt;<strong>state-transfer</strong> timeout=&quot;600000&quot; /&gt;<br>      &lt;<strong>locking</strong> <strong>concurrency-level</strong>=&quot;1000&quot; acquire-timeout=&quot;15000&quot; /&gt;<br>      &lt;<strong>encoding</strong> media-type=&quot;application/x-jboss-marshalling&quot;/&gt;<br>      &lt;<strong>persistence</strong>&gt;<br>        &lt;<strong>rocksdb-store</strong> <strong>preload</strong>=&quot;true&quot; fetch-state=&quot;true&quot;&gt;<br>          &lt;expiration path=&quot;rocksdb/expired&quot;/&gt;&lt;compression type=&quot;NONE&quot;/&gt;<br>          &lt;<strong>write-behind</strong>/&gt;<br>          &lt;<strong>property</strong> name=&quot;data.write_buffer_size&quot;&gt;128MB&lt;/property&gt;<br>          &lt;property name=&quot;data.max_write_buffer_number&quot;&gt;3&lt;/property&gt;<br>         &lt;<strong>property</strong> name=&quot;data.min_write_buffer_number_to_merge&quot;&gt;2&lt;/property&gt;<br>        &lt;/rocksdb-store&gt;<br>      &lt;/persistence&gt;<br>    &lt;/distributed-cache&gt;<br>  &lt;/cache-container&gt;<br>&lt;/infinispan&gt;</pre><p>Declaramos no arquivo, cada cache que será necessário para o Keycloak, colocamos o <strong>cache-container</strong>, com suporte a estatistícas, e criamos o cache em modo distribuído (<strong>distributed-cache</strong>), caso você vá usar o modo de replicação entre sites, você deve configurar o cache em modo <strong>replicaticated-cache, </strong>mas o modo replication tem seus penaltis quando o assunto é performance para escrita, mas isso depende muito do seu setup, se não estiver falando em milhões de sessões, talvez isso não seja um problema, abaixo segue uma imagem com as características de cada modo de cache:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Cubzs1pPlnqdiBFLeuGjJQ.png" /><figcaption>outbound-socket-bindingCache mode</figcaption></figure><p>Definimos o <strong>remote-timeout</strong> para <strong>30000 </strong>ms (30 segundos), o valor padrão dependendo do tamanho do seu ambiente não seja o bastante, no nosso caso funcionou bem os 30000 ms, definimos o modo distribuido com 3 <strong>owners,</strong> ou seja, as entradas do cache será distribuída em pelo menos 3 servers. o <strong>state-transfer</strong> foi configurado para <strong>600000</strong> ms (10 minutos), o valor padrão <strong>240000</strong> não funcionou bem em nosso ambiente. Definimos o locking com um <strong>concurrency-level </strong>em <strong>1000</strong>, em nosso ambiente este valor foi bem apropriado, o valor default é <strong>32</strong>, olhe a documentação do <strong>Infinispan</strong> para entender melhor este parâmetro, a documentação diz o seguinte:</p><blockquote>Concurrency level for lock containers. Adjust this value according to the number of concurrent threads interacting with Infinispan.</blockquote><p>Em <strong>encoding</strong> somente definimos o encode das entradas que serão armazenadas no cache.</p><p>Em <strong>persistence</strong> é onde criamos nossa persistência em disco de nossos caches, veja que criamos uma entrada como <strong>rocksdb-store</strong>, definimos se ele vai fazer o <strong>preload</strong> quando for reiniciado, ou seja, fazer a carga do que está armazenado em disco para a memória, também definimos o <strong>write-behind</strong> para escrita em modo assíncrono, e definimos algumas properties para melhorar a performance do <strong>RocksDB</strong>.</p><p>Você pode verificar como estão seus caches no console do infinispan, assim ver os status dos caches e as estatísticas de cada um, no nosso exemplo, por simplicidade, não colocamos nem autenticação e nem utilização de TLS diratemente no <strong>Infinispan</strong>, só para efeito de simplicidade, então em nosso exemplo usamos o endereço de Route (<strong>cache.example.com</strong>), ou seja, de <strong>Ingress</strong> no <strong>Kubernetes</strong>, no caso do <strong>Openshift</strong> seria criado um route, vamos ver como estão nossos caches, acesse o endereço que você forneceu, no nosso caso aquié <a href="http://cache.example.com.]"><strong>http://cache.example.com</strong>.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhC4JTB0j2zNL3rwS1iVQg.png" /><figcaption>Caches list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSEkiNOHOGvMqdGIUmgatg.png" /><figcaption>Cache Global Statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ychnmTONNrVWj2Ou8wdr5g.png" /><figcaption>Cluster Status</figcaption></figure><p>Como podemos ver, temos nossos caches configurados em modo <strong>distributed-cache</strong>, e também com o status de <strong>persisted</strong>.</p><p>Na segunda imagem podemos ver as estatísticas globais do nosso ambiente, também é possível ter a estatísticas de cada cache, basta somente selecionar o cache e clicar na aba <strong>statistics</strong> do cache.</p><p>E o status dos nós do cluster, se o cluster está saudável ou com algum problema, no nosso caso temos os 3 nós dentro do cluster.</p><p>Todas estas estátisticas,é possível obter também no prometheus e monitorar também no Grafana, abaixo segue exemplo dos caches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptHtSQDanaAKSmJqyILDig.png" /><figcaption>Infinispan Grafana</figcaption></figure><h4>Keycloak Configuration</h4><p>Com o <strong>Infinispan</strong> pronto e configurado, podemos agora configurar o <strong>Keycloak</strong> para usar o <strong>remote-store </strong>das definições dos caches, aqui no exemplo iremos demonstrar como ficam os caches diretamente no XML de configuração do <strong>Keycloak</strong>, lembrando que você pode fazer esta configuração também por scripts em vez de editar e manipular os arquivos XML.</p><pre><strong># Caches</strong></pre><pre>&lt;<strong>distributed-cache</strong> name=&quot;<strong>sessions</strong>&quot; owners=&quot;1&quot;&gt;<br><strong>  &lt;remote-store cache=&quot;sessions&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;false&quot; shared=&quot;true&quot;&gt;<br>    &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>    &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/distributed-cache&gt;</pre><pre>&lt;<strong>distributed-cache</strong> name=&quot;<strong>offlineSessions</strong>&quot; owners=&quot;1&quot;&gt;<br><strong>  &lt;remote-store cache=&quot;offlineSessions&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;false&quot; shared=&quot;true&quot;&gt;<br>      &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>      &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/distributed-cache&gt;</pre><pre>&lt;<strong>distributed-cache</strong> name=&quot;<strong>clientSessions</strong>&quot; owners=&quot;1&quot;&gt;<br>  <strong>&lt;remote-store cache=&quot;clientSessions&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;false&quot; shared=&quot;true&quot;&gt;<br>    &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>    &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/distributed-cache&gt;</pre><pre>&lt;<strong>distributed-cache</strong> name=&quot;<strong>offlineClientSessions</strong>&quot; owners=&quot;1&quot;&gt;<br><strong>  &lt;remote-store cache=&quot;offlineClientSessions&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;false&quot; shared=&quot;true&quot;&gt;<br>    &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>    &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/distributed-cache&gt;</pre><pre>&lt;<strong>distributed-cache</strong> name=&quot;<strong>loginFailures</strong>&quot; owners=&quot;1&quot;&gt;<br>  <strong>&lt;remote-store cache=&quot;loginFailures&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;false&quot; shared=&quot;true&quot;&gt;<br>    &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>    &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/distributed-cache&gt;</pre><pre>&lt;d<strong>istributed-cache</strong> name=&quot;<strong>actionTokens</strong>&quot; owners=&quot;1&quot;&gt;<br>  &lt;heap-memory size=&quot;-1&quot;/&gt;<br>  &lt;expiration max-idle=&quot;-1&quot; interval=&quot;300000&quot;/&gt;<br> <strong> &lt;remote-store cache=&quot;actionTokens&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;true&quot; shared=&quot;true&quot;&gt;<br>    &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>    &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/distributed-cache&gt;<br>                <br>&lt;<strong>replicated-cache</strong> name=&quot;<strong>work</strong>&quot;&gt;<br><strong>  &lt;remote-store cache=&quot;work&quot; remote-servers=&quot;remote-cache&quot; passivation=&quot;false&quot; fetch-state=&quot;false&quot; purge=&quot;false&quot; preload=&quot;false&quot; shared=&quot;true&quot;&gt;<br>    &lt;property name=&quot;rawValues&quot;&gt;true&lt;/property&gt;<br>    &lt;property name=&quot;marshaller&quot;&gt;org.keycloak.cluster.infinispan.KeycloakHotRodMarshallerFactory&lt;/property&gt;<br>  &lt;/remote-store&gt;</strong><br>&lt;/replicated-cache&gt;</pre><pre><strong># socket-binding-group name=&quot;standard-sockets&quot;</strong></pre><pre>&lt;<strong>outbound-socket-binding</strong> name=&quot;<strong>remote-cache</strong>&quot;&gt;<br>  &lt;remote-destination host=&quot;${env.INFINISPAN_CLUSTER_ADDRESS:localhost}&quot; port=&quot;${remote.cache.port:11222}&quot;/&gt;<br>&lt;/outbound-socket-binding&gt;<br> </pre><p>No arquivo que usamos para manipular, no caso o<strong> standalone-ha.xml</strong>, alteramos as definições dos caches, esta em negrito a parte do <strong>remote-store</strong>, onde definimos que o <strong>Keycloak</strong> irá usar este Infinispan como um store remoto, ou seja criando assim uma persistência das entradas dos caches em um <strong>Infinispan remoto</strong>, vale lembrar que nesta configuração, os caches continuam valendo também no <strong>Infinispan embarcado</strong> do próprio Keycloak, não estgamos fazendo um cache remoto somente, também temos que criar uma entrada <strong>outbound-socket-binding</strong> em <strong>socket-binding-group </strong>para definir o endereço do Infinispan remoto, em nosso caso tudo é passado por váriaveis de ambiente, mas esta váriavel de ambiente está mapeado para <strong>infinispan-cluster.infinispan.svc</strong>, pronto agora você pode inciar o <strong>Keycloak</strong> com acesso ao cluster do Infinispan.</p><p>Como teste, crie várias sessões no <strong>Keycloak</strong>, e reiniciei todos os pods simultaneamente para ver se as sessões são recuperadas após e restart dos PODs, o <strong>Keycloak</strong> tem o plugin para monitorar via <strong>prometheus</strong>, você pode ver o plugin neste <a href="https://github.com/aerogear/keycloak-metrics-spi">link</a>. Exemplo abaixo da monitoração do <strong>Keycloak</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muLCz1nrSpO7ZY7mylDf1A.png" /><figcaption>Keycloak Grafana Infra</figcaption></figure><h3>Conclusão</h3><p>Espero que isso ajude os engenheiros que usam o <strong>Keycloak</strong> a criar um ambiente, quando necessário mais resiliente as falhas que podemos ter, também ajude em discussões sobre este assunto, o <strong>Keycloak</strong> é uma ferramenta poderosa, e estou aberto a receber críticas e ajuda sobre este documento, fique a vontade para ajudar ou fazer críticas construtivas, acredito que isso faça todos nós engenheiros crescerem e aprendermos cada dia mais.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0a279632d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>