jpadilla / pyjwt

JSON Web Token implementation in Python
https://pyjwt.readthedocs.io
MIT License
5.08k stars 679 forks source link

Mention performance reasons for passing RSAPrivateKey to encode #733

Closed dmahr1 closed 2 years ago

dmahr1 commented 2 years ago

My employer is currently using PyJWT in production for signing URLs. As part of some routine performance monitoring and profiling, I discovered that this signing method was consuming a disproportionate amount of time - even more than the wall clock time of communicating with the database. The icicle plot below shows how most of the time was spent in the load_pem_private_key() method within the cryptography library. image

I resolved the issue by manually instantiating the RSAPrivateKey object and passing that to jwt.encode(). As a result, RSAAlgorithm.prepare_key() returns immediately rather than instantiating a new RSAPrivateKey. Otherwise, the CPU-intensive RSA_check_key primality test would be needlessly rerun on every call to encode().

It looks like there's some discussion in #602 about changing the type hinting to make this usage more official. In the meantime, a stopgap is to make mention of the performance benefits of passing an RSAPrivateKey object in the Usage Examples page of the documentation.

734

dmahr1 commented 2 years ago

@auvipy Thanks for the approval! Closing this issue.