UserStorageProvider SPI instantiated twice for a login flow (each with multiple get user calls)

My UserStorageProvider SPI is backed by an API. When I login with an application (confidential client+authcode flow). I am seeing the provider instantiated twice in a single login with multiple calls to getUserByUserName and GetUserByUserId. This results in my API be called 5 times in the first instantiation of the SPI and 3 times in the second. I’m not importing users into KC. What strategy or changes should I look at to reduce the number of API calls? Is this normal behavior? It seem like it may be from the SO post although it is old: java - Keycloak User Storage SPI Authentication Flow - Stack Overflow. Thanks!

I am having a similar issue and was looking to see what if anything I was doing wrong to better leverage the user cache.

I still end up with two calls to the backend via the provider getUserById and GetUserByUsername, but you can reduce the overall number a bit by including a local map/cache in your provider, storing the user model there for the life of the provider/transaction. That helped me a bit even though I still cannot get it down to one call just yet

You could introduce the secondary cache at the component level. (The primary cache would be Keycloak.)

I do something similar – a component performance boost – in the SPI listed below. I use a pool of datasource connections. In your case, you’d pass a component map of users to the Provider’s constructor which is called by create(). You might include a “last session” as part of this map’s key to decide whether or not to make new API calls.

Note that I’m caching the whole component too. This will only be re-created if the component configuration changes. A re-created component would clear the API cache entirely.

bekwam-jdbc-user-storage-spi