๐ช๐ต๐ ๐๐ช๐ง ๐๐ ๐ถ๐๐๐: ๐ง๐ต๐ฒ ๐ฅ๐ฒ๐ฎ๐น ๐ก๐๐บ๐ฏ๐ฒ๐ฟ๐
I used JWT in every project. I knew how to use it. I did not know why it existed. I stopped watching tutorials. I looked at the numbers.
The speed of operations:
- JWT signing: 5ms
- DB query: 50ms
- Bcrypt: 100ms
Most apps used sessions before JWT. The server stores a session in a database. The browser sends a cookie. The server looks up the session in the database. This takes 50ms per request. 10,000 users create 10,000 database calls per second. Your database slows down. It becomes a single point of failure.
Some think about using bcrypt for every request. Bcrypt takes 100ms on purpose. It stops brute force attacks. But 1,000 users need 100 seconds of compute per second. Your server crashes.
JWT solves this with math. A JWT has three parts:
- Header: The algorithm.
- Payload: Your data.
- Signature: Proof of integrity.
The server re-computes the signature. It takes 5ms. No database lookup. No network call.
Warning: the payload is public. The payload is open to everyone. Avoid putting passwords in the payload. The signature only proves the data is not modified.
JWTs have one weakness. Logging people out is hard. Sessions are easy to delete from a database. JWTs last until they expire.
Engineers fix this with:
- Short expiry times.
- Refresh tokens.
- Redis blacklists.
Knowing the syntax is not engineering. Engineering is understanding the why. The numbers explain the tool.