Search code examples
djangocachingdjango-rest-frameworkredisauth-token

Django caching simple auth token


I have an app which uses Django DRF with simple AuthToken, Postgres for database and Redis for caching.

I am trying to reduce the number of calls to my DB and one of most common action is SELECT on AuthToken table. In fact, it needs to be called for every request on a protected endpoint to verify the permission of the user.

We could reduce the number of calls to our DB by caching the token of users in Redis as {user_id: token}.

Assuming we set a decent expiration for the key and that we invalidate it in case of revoked token AuthToken, is caching the auth token an anti-pattern? Is there any security issue I should be concerned about?


Solution

    • If you don't want to have DB lookups you can use JWT. JWT is using cryptography to check token.
    • If you want to stay with DRF token you can cache it, but it will add complexity to your code. Do you see a huge impact on DB performance with these queries?
    • If you decide to cache the token, please remember to secure the Redis.
    • I'm using DRF token in my boilerplate and Django+React articles. I like it this way because it keeps code/flow simple.