What is the best way to persist user sessions in Keycloak?

Viewed 1063

I'm using a standalone Keycloak server. I have created one realm and a user inside that realm. When I log in the user and restart keycloak server, the session gets lost.

I am aware that keycloak saves user sessions data in Infinispan. But is there any way I can save/persist this user session data?

Or shall I create multiple nodes cluster and replicate the keycloak session data?

Please suggest what's best.

1 Answers

We also have this problem.

So far I think there are 2 solutions, neither of them is perfect:

1. Keep sessions in infinispan

You can use external infinispan instance as described in the docs. This is cumbersome because you need to keep an external infinispan instance.

If you don't want to use an external infinispan instance, you can set CACHE_OWNERS_COUNT in the docker image >=2. This will rebalance the cache between nodes and will make sure that an entry is saved in at lease CACHE_OWNERS_COUNT nodes. If you have many sessions (>1Million) you will run out of memory and the startup time will increase substantially because the cache needs to be rebalanced at each deploy.

Another issue is that you would loose the sessions when updating the infinispan instance.

2. Use offline sessions

Offline sessions are kept in the db and some of them are kept in the offline_sessions_cache. You can limit the number of offline sessions keycloak keeps in memory and stop preloading offline session for faster startup as described here.

This also has drawbacks:

  • SSO will not work after the server is restarted
  • You cannot change any offline session notes

I think there are some PRs in keycloak to have a persistent session store build in so please keep an eye on the progress on the keycloak Github page

Related