How to use OrmLiteAuthRepository with caching?

I am using the OrmLiteAuthRepository to authenticate access to endpoints and the performance difference is significant. Without authentication responses return ~25ms and with authentication ~165ms. I am assuming that the sessions are hitting the SQL Server database on every request which is why the performance is decreased so much.

I need to persist the users (in my case 3rd party services using ApiKeys). However, is there a way to cache the UserAuth and ApiKey data in memory to speed things back up without having to create a custom iAuthRepository?

The OrmLiteAuthRepository just persists the UserAuth tables in an RDBMS, ServiceStack’s Sessions are instead stored in the registered ICacheClient Caching Provider.

If you’re using the API Key AuthProvider for authentication then that would hit the RDBMS to fetch the key which it gets by Primary Key, but then it needs to access the RDBMS again to setup the Users Session.

I’ll see if I can add an option to cache they Key + Users Session to skip repopulating the Users Session on subsequent requests, but then this would mean the User Session would be populated with stale data so would need to be a short cache.

FYI I’ve added a SessionCacheDuration feature in ApiKeyAuthProvider which will cache the Users Session in-between API Requests with the same key in this commit which you can enable with:

Plugins.Add(new AuthFeature(...,
    new IAuthProvider[] {
        new ApiKeyAuthProvider(AppSettings) {
            SessionCacheDuration = TimeSpan.FromMinutes(10),
        }
    }));

Which should subsequent API Key requests down to 1 DB call to fetch and validate the API Key + 1 Cache Hit to restore the Users Session which if you’re using the default in-memory Cache will mean it only has 1 I/O call for the DB request.

This feature is available from v4.5.5 that’s now available on MyGet.