ealeng

Episode 50 of 55 · Security

Sessions vs JWTs: a banned user kept access for up to 5 minutes, and rotating a password early failed none

Twenty logged-in users were banned at once. With server-side sessions, none got another answer. With five-minute JWTs, all twenty kept being served, the last for 300 seconds, because a token is checked without a lookup and nothing in that check can see a ban. Checking a token's signature cost 0.014 ms per request, a Redis lookup 0.085 to 0.098 ms, and an authorization service 0.32 to 0.40 ms. Rotating a database password at half its 15-second lease failed no requests in ten switches; waiting for a failure lost 22.

Lab 20 · Security, Auth and Multi-Tenancy12 min read
Video transcript8:02

0:00Cold open

0:01

I banned twenty logged-in users at once. With sessions, not one of them got another answer.

0:08

With five-minute tokens, all twenty kept working. The last one, for three hundred seconds.

0:16

Then I made the database password change every fifteen seconds. Switched late, twenty-two requests failed. Switched early, none.

0:26

So how do you take access back? And what does each check cost?

0:32Intro

0:33

Hands-on system design, part fifty.

0:37

Today: banning a user, what each check costs, and changing a password without anyone noticing.

0:44Meet Lucía

0:45

I’m Lucía, a platform engineer. After you log in, each request carries proof of who you are. One kind is a session: a random id the server looks up in a shared store, Redis.

0:59

The other is a signed token, a JWT: who you are and an expiry time, signed by the server, so any change breaks the signature. To check it, the server checks the signature and the clock. It looks nothing up.

1:14

Tokens are kept short-lived, and come with a refresh token: a longer-lived one the server keeps a record of, used only to get a new short one.

1:25

Think of a hotel. A session is a room key the door checks with the front desk. A token is a wristband with a printed date: the guards only read the date. And a ban list: the guard phones the desk anyway.

1:4001 · What you need

1:42

To run it yourself: Docker, for the service and everything around it. Redis, a login server, an authorization service, a proxy, Vault and Postgres.

1:53

The quick tests need none of them, and pass in a couple of seconds. No cloud, nothing to pay for.

2:0102 · The ban

2:03

The test: twenty users logged in. An admin bans all twenty, and each keeps calling the API, the service’s web interface.

2:13

With sessions, the ban deletes their sessions, and no user got another answer. The same with a token plus a ban list, where every request also asks Redis: is this user banned?

2:26

With five-minute tokens, the ban cancels the refresh tokens. But all twenty kept being served. The first was cut off after fourteen seconds, the last after three hundred.

2:39

That spread is my test’s doing: I logged them in fifteen seconds apart, so their tokens were of every age. Each worked until its own expiry.

2:5103 · Still served

2:52

Here are the twenty, one bar each: how long each banned user kept being served.

2:59

Twelve thousand three hundred thirty-seven calls answered for banned users. That number is my test’s pace, about four calls a second each. A busier client gets more.

3:11

The rule: the worst case is the token’s whole lifetime. With tokens of every age, half of it on average.

3:20

And the refresh tokens were dead: none of the twenty got a new token. Revoking it stops the next token, not the one already out.

3:29

With one-hour tokens, the last was cut off after almost the full hour; its token was a minute and a half old. I didn’t wait an hour: I moved the app’s clock forward, after checking that the shortcut gave the same answer as really waiting five minutes.

3:4704 · In code

3:49

In code, a session is a lookup: get it from Redis. Not there, no user.

3:55

A token is a check: verify the signature and the expiry. No lookup at all.

4:02

The ban list adds one line: ask Redis if this user is banned. That’s the very lookup the token was meant to avoid.

4:1105 · The cost

4:13

So what does each check cost? I timed many requests of each kind. Checking a token’s signature: about a hundredth of a millisecond.

4:23

A session, or a ban list: one trip to Redis, here on one laptop, about nine hundredths of a millisecond, six or seven times the token check.

4:34

Asking an authorization service, from part forty-eight, a separate service that answers “may this user open this?”, with its own cache off: about four tenths. More than twice a whole request with no check.

4:48

A small cache in the app, a memory of recent answers kept ten seconds, brings that back to almost nothing. The price: a permission you take away can keep working for up to ten seconds.

5:0206 · Between services

5:04

Services prove who they are too, with a certificate: an ID card signed by an authority both trust. Mutual TLS is the encryption behind https, with both sides showing a card. A proxy in front, Envoy, lets in only the gateway.

5:22

On a kept-open connection: about a quarter of a millisecond, barely more than unencrypted.

5:29

With a new connection for every request: a little over a millisecond, more than four times as long. That’s mostly the handshake, the opening exchange where the cards are checked. So keep connections open.

5:43

And the three wrong callers, with no certificate, one from another authority, and another service’s, were all refused in the handshake.

5:5407 · The password

5:55

Last: the database password. A fixed one in a config file never changes, so a leaked file gives it away for good. The fix is swapping in a new one regularly, called rotating.

6:08

Vault, a service that keeps secrets, can hand out a fresh password on a short lease, here fifteen seconds; when it runs out, Vault deletes that login and cuts its connections. Waiting for a failure before fetching a new one: twenty-two requests failed, out of fifteen thousand.

6:27

They failed at every expiry, every fifteen seconds. About four each time, on average, probably the requests on the four connections Vault cut.

6:38

Switching at half the lease instead, ten switches, and not one failed request. Typically a fifth of a millisecond slower than the fixed password; one run, so it may be noise.

6:5108 · In code

6:53

In code: sleep for half of what’s left of the lease. Then open a new pool, four database connections kept open and shared, with the new credentials.

7:04

Point new requests at it, and close the old pool once its last queries finish. Nobody meets a dead connection.

7:13Back to Lucía

7:15

So, three lessons.

7:17

If the server never looks a token up, it can’t take it back before it expires. Keep it short, or add the lookup.

7:26

The check is cheap; the trip across the network is the cost. A cache saves it, and delays every change by up to its length.

7:35

And switch a secret before its deadline, not after the first failure.

7:41

Next time: SLOs and error budgets. How much failure is allowed, and who decides.

7:48

For today: ask how fast you can take it back.Lucía: How fast can I take it back?

7:53Summary

7:54

Short tokens or a lookup, cache with care, and rotate before the deadline.

Key takeaways

  • ✓A server-side session is looked up in Redis (a fast shared store) on every request, so when 20 logged-in users were banned at once, none of them got another answer: 0 served after the ban, and the ban deleted their sessions.
  • ✓A JWT (a signed token the server checks without a lookup) stays valid until its expiry time, so with 5-minute tokens all 20 banned users kept being served for 12,337 calls: the first was cut off after 14 seconds, the median after 157 seconds and the last after 300 seconds.
  • ✓Revoking the refresh tokens (the longer-lived tokens used only to get a new short one) stopped renewal, since none of the 20 got a new token after the ban, but it could not stop a token already issued, so the worst case is the token's whole lifetime and, with tokens of every age, about half of it on average.
  • ✓Per request in the app, checking a token's signature cost 0.014 ms at p50 (the median of 3,000 requests), a Redis session lookup 0.085 ms and a token plus a ban-list lookup 0.098 ms, six to seven times the token check; an authorization service call with its cache off cost 0.32 to 0.40 ms, and a 10-second app cache brought it to 0.001 ms, at the price of a removed permission working for up to 10 seconds.
  • ✓Mutual TLS, where both sides show a certificate, cost 0.262 ms at p50 on a connection kept open, against 0.228 ms for plain HTTP through the same proxy, but 1.163 ms when every request opened a new connection, so connections should be kept open.
  • ✓Rotating the database password at half of its 15-second lease, with a new pool of four connections opened before the old one closed, failed 0 of 15,170 requests over ten rotations, while the naive version that fetched a new password only after a failure lost 22 requests at five expiries.

Twenty logged-in users were banned at once. With server-side sessions, none of them got another answer. With five-minute JWTs, all twenty kept being served, the last for 300 seconds. This chapter is about why the two designs differ, what each check costs on every request, and how to change a database password without failing a request. The examples come from Lab 20 (Security, Auth and Multi-Tenancy) of the system design labs. Three scripts are used: 04_revocation.py runs the ban, 05_check_cost.py times each check, and 06_rotation.py rotates the database password under load. Each result is one recorded run on an Apple M4 Max with Docker Desktop (16 virtual CPUs), with everything in containers on one laptop. The README puts scripts 01 to 06 at about 30 minutes.

Two kinds of proof

After a login, each request carries proof of who is calling. There are two common kinds.

A session is a random id. The server keeps the record behind it in Redis, a fast shared store, and looks that record up on every request. Deleting the record ends the session at once.

A JWT (JSON Web Token) is a signed statement: who the user is, and an expiry time, written into the token as the exp field. The server signs it when it issues the token. On each request it checks the signature and the clock, and looks nothing up. Any change to the token breaks the signature, so it cannot be forged. Because the check needs no lookup, the server cannot take the token back before it expires.

Tokens are therefore kept short-lived and come with a refresh token: a longer-lived one the server keeps a record of, used only to get a new short-lived token.

Think of a hotel. A session is a room key that the door checks with the front desk. A token is a wristband with a printed date: the guard reads the date and does not phone anyone. A ban list is the guard phoning the desk on every check, which brings back the lookup the wristband was meant to avoid.

A ban, and how long it takes

The test logs in 20 users, one every 15 seconds, so that their tokens are of every age. Then an admin bans all twenty, and each keeps calling the API. Every design is run on the same 20 users.

Design Cut off, fastest Median Slowest Users served after the ban Calls served to banned users Refresh worked
Session next request next request next request 0 0 not applicable
JWT + ban list next request next request next request 0 0 0 of 20
JWT, 5 min (real time) 14 s 157 s 300 s 20 12,337 0 of 20
JWT, 5 min (clock moved) 7.5 s 150 s 292.5 s 20 2,000 clock steps 0 of 20
JWT, 1 hour (clock moved) 90 s 30 min 58.5 min 20 2,000 clock steps 0 of 20

"JWT + ban list" is a JWT that is also checked against a list of banned users in Redis on every request. "Clock moved" means the script advanced the app's clock instead of waiting an hour. The lab checked that shortcut on the 5-minute case: the clock-moved median was 150 seconds against 157 seconds for the real wait, and the longest was 292.5 seconds against 300.

For sessions and the ban list, the script printed times of 7 to 20 ms, but those were its 10 ms polling interval, so the measure that counts is "served after the ban": none.

The 5-minute JWT row shows the rule. The first banned user was cut off after 14 seconds because its token was almost expired; the last was cut off at 300 seconds because its token had just been issued. Each token worked until its own expiry, and the refresh tokens were dead, so no banned user got a new one. The worst case is the whole token lifetime, and with tokens of every age the typical case is about half of it. For the 1-hour token the same reasoning holds: a token that is cut off at 3,510 seconds was 90 seconds old at the ban, so that user had about a minute and a half of access left.

Revoking the refresh token therefore stops the next token, not the one already out. Choosing a token lifetime is choosing how long a banned user may stay.

Try it · Banned, and still servedRecorded: 04_revocation.json, 20 users, one ban

The ban revokes the refresh tokens, but tokens already issued keep working until they expire.

Each user, seconds after the ban, scale 0 to 300 s (the token's lifetime)

Bars are sorted from the shortest to the longest. The tallest bar is the last user, cut off at 5.0 min; the token's lifetime is 5.0 min.

Users served after the ban
20 of 20
Calls served to banned users
12,337
Refresh worked after the ban
0 of 20
Median, real or clock-moved
2.6 min

Real-time run: 20 logins 15 s apart, so the tokens were of every age. Calls are the test's own polling (about four a second per user).

Whether a check is a lookup

In code, a session is a lookup: fetch the record from Redis, and if it is not there, there is no user. A token is a check: verify the signature and the expiry, with no network trip. A ban list adds one line, a lookup asking whether this user is banned, which is the very trip a token was supposed to avoid.

The script 05_check_cost.py times each of these per request. It sends 3,000 requests for each row and reads the time the app itself reports for its check in a response header called Server-Timing. Here are the values at the median (p50):

Check Its own time at p50 Note
Our JWT, HS256 signature 0.014 ms HS256 signs and checks with one shared secret
Keycloak token, RS256 signature 0.071 ms RS256 signs with a private key and checks with a public key; Keycloak is the identity provider the lab uses
Session, Redis lookup 0.085 ms six times the token check
JWT + ban list, Redis lookup 0.098 ms seven times the token check
OpenFGA, one direct permission, cache off 0.32 ms OpenFGA is an authorization service that answers "may this user do this to that object?"
OpenFGA, group, folder, then document, cache off 0.402 ms a three-step walk through the relationships
The app's own 10-second cache in front of OpenFGA 0.001 ms a memory of recent answers, kept for up to 10 seconds

A whole request with no check at all took 0.153 ms at p50, so the authorization service, uncached, cost more than twice the rest of the request. The in-process numbers show the same ordering: verifying our token took 4.2 microseconds, and a single Redis GET took 77 microseconds.

The price of the cache is staleness. A permission that is removed can keep working for up to 10 seconds, which is the same trade as the ban list's opposite: the cache saves the trip and delays every change by up to its length.

Try it · What each check costsRecorded: 05_check_cost.json, p50 over 3,000 requests
Our JWT (HS256 signature)
signature and expiry, no lookup
0.014 ms
Keycloak token (RS256, keys cached)
public-key signature, cached keys
0.071 ms
Session (Redis GET)
one round trip to Redis
0.085 ms
JWT + ban list (Redis EXISTS)
one round trip to Redis
0.098 ms
OpenFGA, direct tuple, no cache
OpenFGA's part
0.32 ms
OpenFGA, group, folder, doc, no cache
three-hop walk, OpenFGA's part
0.40 ms
App's 10 s cache in front of OpenFGA (hit)
memory of recent answers
0.001 ms
A whole request, no check
0.153 ms
Redis session vs token
6 to 7x
App cache hit
0.001 ms

The token check is the app's own Server-Timing auth time. The authorization service's bars are OpenFGA's part of the request, with its cache off unless named. The cache row is the app's 10 s memory of recent answers, so a permission removed can keep working for up to 10 s.

Services proving who they are

Services can prove who they are too. A certificate is an ID card signed by an authority that both sides trust. Mutual TLS, or mTLS, is the encryption behind https with both sides showing a card. The lab puts Envoy, a proxy, in front of the orders service and lets in only the gateway.

Through Envoy, at p50:

  • Plain HTTP on a reused connection: 0.228 ms. Mutual TLS on a reused connection: 0.262 ms. The encryption cost barely anything once the connection was open.
  • Plain HTTP on a new connection for each request: 0.346 ms. Mutual TLS on a new connection for each request: 1.163 ms, 4.4 times the reused case. Most of that is the handshake, the opening exchange where the certificates are checked. Connection pools and long-lived connections make mutual TLS affordable.

Three wrong callers were refused in the handshake, before any HTTP reached the app: one with no certificate, one with a certificate from another authority, and one holding a valid certificate for a different service. The gateway's certificate got a 200.

Rotating a password without a failure

A fixed database password in a config file never changes, so a leaked file gives access away for good. The fix is to hand out short-lived credentials and replace them regularly. Vault, a secrets service, does this with a lease: a time-limited grant. In the lab, Vault creates a new database login for each lease, and when the lease ends, it removes that login and ends its connections. The lease is 15 seconds here so the test covers several rotations; production leases last hours.

06_rotation.py sends 200 requests a second for 75 seconds through a pool of four Postgres connections, a set of database connections kept open and shared. It runs three ways:

Password source Rotations Failed requests Seconds with failures p50 p99
Static, never changes 0 0 of 15,170 none 1.75 ms 4.33 ms
Vault, naive 5 22 of 15,170 14, 29, 44, 59, 74 1.76 ms 4.46 ms
Vault, graceful 10 0 of 15,170 none 1.93 ms 4.73 ms

The naive version fetched credentials once and fetched again only after a query failed. At each 15-second expiry, Vault cut the connections that were in use, and about four requests failed before the app noticed. The number is an average of 22 over five expiries, and the lab did not save the count per expiry.

The graceful version switches at half the lease. It fetches new credentials, opens a new pool of four connections, sends new requests to it, and closes the old pool once its last queries finish, all before Vault revokes the old login. No request ever meets a dead connection. The cost was about 0.18 ms at p50 (1.93 against 1.75 ms), from opening connections while serving. That is one run, so the difference may be noise.

The order is the lesson: the old credential may end only after the new pool is open.

The workflow and the results

To run it yourself, the lab needs Docker. The three scripts are:

  • 04_revocation.py (about 12 minutes): the 20 users under each design, including the 5-minute real-time run that waits out the full five minutes.
  • 05_check_cost.py (about 2 minutes): the check table and the mutual TLS table, plus the three refused clients.
  • 06_rotation.py (about 4 minutes): the three password sources under load.

The lab's own checklist asks the same questions: what each check costs per request, how fast each design can be revoked, and how to rotate a database password without an outage. The answers above are the lab's recorded values, and the widgets show them as recorded.

Caveats

  • One recorded run per row. Each row comes from one run on one laptop. The clock-moved rows are a shortcut the lab checked against one real-time run; the 1-hour row has no real-time run to check it against.
  • Calls are not a rate. The 12,337 calls to banned users depend on the test's own polling, about four a second per user. A busier client would make more calls, and the lab does not give a rate for real traffic.
  • The 14-to-300-second spread is by design. The logins were 15 seconds apart, so the tokens were of every age. The median of about half the lifetime is a property of that spread, not a measured property of a real system.
  • Signing-key rotation was not tested. The app can fetch a new public key when a token names a key it does not have yet, which is the idea behind rotating a JWT signing key. No script changes a signing key while users are logged in, so "rotating signing secrets without logging everyone out" is not something this lab measured. The chapter's rotation results are for database passwords only.
  • Rotation at a 15-second lease with a pool of four. Production leases are hours long, and the lab's README expects more failures per expiry with a bigger pool or more traffic. That was not measured.
  • Check costs are p50 on one laptop. The p99 figures are in the results but not narrated here. Redis, the authorization service and the app shared one machine, so a real network would add its own time, and no check was measured under load.
  • Not covered: logout as a separate flow, a stolen token used before the ban, a cache's behaviour under concurrent permission changes, and any service in another region.

The checklist

  1. Decide how fast a ban must work. A check that never looks anything up cannot see a ban, so either keep the token lifetime short or add a lookup and pay for it on every request.
  2. Read the token lifetime as the longest a banned user may stay. The lab's 5-minute token allowed up to 300 seconds; its 1-hour token allowed up to 58.5 minutes.
  3. Price every check per request. A signature check costs microseconds, a Redis lookup costs a round trip, and an authorization service call costs more again, so cache with a stated staleness.
  4. Keep connections open. Mutual TLS on a reused connection cost 0.262 ms, against 1.163 ms when each request opened a new one.
  5. Rotate a secret before its lease ends. The new credential must be in place before the old one is removed, and the old one must drain.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A banned user holds a JWT that expires in 4 minutes, and the refresh token has been revoked. Can that user still call the API during those 4 minutes?

  2. 2.Which check costs a round trip to another server on every request?

  3. 3.The naive rotation lost 22 requests over five expiries, and the graceful one lost none. What did the graceful version do differently?

Check your understanding

Try each question before opening its answer.

Why did the 20 banned users with sessions get no answer, while the 20 with 5-minute JWTs kept being served for up to 300 seconds?

A session is looked up in Redis on every request, and the ban deleted the record, so the next request found nothing. A JWT is checked by its signature and its expiry time with no lookup, so nothing in the check could see the ban. The token worked until it expired, and the refresh tokens had been revoked, so no banned user got a new one.

The app's 10-second cache made an authorization check cost 0.001 ms instead of 0.32 to 0.40 ms. What did that cost?

A permission that was removed can keep working for up to 10 seconds, because the app answers from its memory of recent answers rather than asking the authorization service again. The cache saves the trip, and it delays every change by up to its length.

Why is a mutual TLS connection that is reused barely slower than plain HTTP, while one that opens for every request is over four times slower?

On a reused connection, the certificates were checked once, when it opened, and each request then costs only the encryption: 0.262 ms against 0.228 ms for plain HTTP. A new connection repeats the handshake, where both certificates are checked, so every request paid for it: 1.163 ms, 4.4 times the reused case.

The naive rotation lost 22 requests at five expiries. Why does switching at half the lease lose none?

Because the new pool is open before the old credentials expire. New requests go to the new pool, and the old one is closed only after its last queries finish, so no request ever uses a connection that Vault has already cut. The naive version waited for a failure, so each expiry cut the connections in use before the app fetched new credentials.

The full track, with its sections in order, is on the System design index.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.