AWS Builder Center

Implementing JWT auth with a Lambda authorizer, and the caching lesson that followed

I built JWT-based authentication with a custom Lambda authorizer for a personal API project, then hit a latency problem once I simulated more traffic.

For a personal project that didn't need a full external identity provider, I validated JWT tokens directly inside a custom Lambda authorizer in API Gateway .

The first version

The first version validated signature and expiration on every request, calling the authorizer function each time. A successful check returns the standard policy document API Gateway expects: a principal ID, a policy statement allowing execute-api:Invoke on the matching resource ARN, and a small context object (in my case just a tier field set to standard) that gets passed through to the backend.

The latency problem

When I simulated higher traffic against my test API, the extra latency from a fresh authorizer invocation on every call became noticeable, response times roughly doubling from what they were with no authorizer at all.

Adding a cache

Configuring API Gateway's own authorization policy cache , using the token as the cache key for a short window, cut the number of authorizer invocations drastically without meaningfully weakening security, and latency dropped back close to the original.

Handling expired tokens

One detail worth planning for from the start: distinguishing, in the error response, between an invalid token and an expired one, since the expected client behavior differs, one needs a fresh login, the other can just try refreshing the token. Retrofitting that distinction after clients already assume a single generic error means a second round of changes on both sides.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article