keyshade icon indicating copy to clipboard operation
keyshade copied to clipboard

API: Cache user for optimized authentication

Open rajdip-b opened this issue 9 months ago • 0 comments

Description

keyshade uses stateless cookie-based authentication to let users in. In the long run, this will impose a strain on our database since we will have over 100qps. To optimize this, we would like to cache our user data during authentication.

Solution

In auth.guard.ts, if the authentication is successful, we fetch the user details and set it in the current session. We would also like to cache this data. We will be using the key structure user-<userId>.

  • Import Redis in auth.guard.ts:
    @Inject(REDIS_CLIENT) readonly redisClient: {
        publisher: RedisClientType
    },
    
  • Try to fetch the user from redis by the user-<userId>. If it's null, fetch from the database by email.
  • JSON.stringify() the data retrieved, and set it in cache as userId -> userObject(stringified)
  • In user.serviec.ts, whenever a user is updated, fetch the cached user, and update the value of the cache.

Additional context

Relevant files can be found in auth and user module.

rajdip-b avatar May 11 '24 18:05 rajdip-b