urbanplatform / django-keycloak-auth

Middleware to allow authorization using Keycloak and Django for django-rest-framework (DRF). This package should only be used in projects starting from scratch, since it overrides the users' management.
MIT License
32 stars 14 forks source link

Add caching to JWT decoding #18

Closed moritz89 closed 2 years ago

moritz89 commented 2 years ago

The decoding of JWTs is 'relatively' expensive and called about 5 times per request. Caching the request results in almost a 10x speed up. Caching the call also reduces the total call by almost 20%. Therefore, it would be impactful to add a cache to the function. In order not to cache an expired token, the cache would be given a time-to-live (TTL). Here, even a 60 second cache time would have significant benefits.

I would propose adding the ttl_cache decorator from cachetools.

Graph of the cache timings:

timings

Zoomed graph without the first requests:

timings_zoom

Data and graph source:

timings.ods

The timings were recorded with the following function:

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        print(f"took: {(te - ts) * 1000} ms")
        return result

    return wrap