Skip to main content

Keycloak HTTP 431 "Request header fields too large"

· 10 min read
GR Patil
Phase Two

HTTP 431 in a Keycloak deployment means one thing: the access token in the Authorization header, or the cookie carrying it, has grown past a header limit somewhere in the request path. The limit is almost never Keycloak's. Measured on Keycloak 26.8.2, Keycloak itself accepts 64 KiB of request headers before it answers 431 — several times more than the proxies and application servers around it. So the component that returned the 431 tells you where to look, and the token size tells you what to fix. Both are two minutes of measurement, and both are below.

Every number here was measured on 2026-11-30 against Keycloak 26.8.2 (Quarkus 3.40.1.1) with the versions named in each table.

Which component returned the 431?​

Nothing in a request path agrees on the limit, and — more useful — they do not agree on the status code either. Sending one oversized Cookie header at each of these, in stock configuration:

ReceiverVersionFirst rejected atStatus
Keycloak26.8.265,472 B of total request headers431
Node.js (Express, Next.js, oauth2 middleware)24.2216,327 B of total request headers431
nginx1.29.88,181 B in one header line400
Apache httpd2.4.718,192 B in one header line400
Tomcat11.0.298,192 B in one header line400
Traefik3.6.25not reached at 1.2 MB—

Two things fall out of that table. A 431 is already a narrow diagnosis: of the receivers above, only Keycloak and Node.js emit it, so if there is a Node-based BFF, Next.js route handler or oauth2 middleware anywhere in the path, start there. If your headers really are over 64 KiB and the 431 body is empty, it was Keycloak. And nginx, httpd and Tomcat return 400, not 431 — if someone reports a 400 Bad Request that only happens for a few users, it is the same root cause with a different status code, and the per-header limit is half what Node.js allows in total.

Traefik is the trap in the other direction: it forwarded a 1.2 MB header without complaint, so a gateway that looks healthy is often just passing the problem to whatever is behind it.

Measure the token before you change anything​

Guessing which claim is large wastes an afternoon. This script asks the admin API for every client in a realm, mints a token for one user against each client that has Direct Access Grants enabled, and reports the size of the token and its largest claims:

kc-token-size.py
import base64, getpass, json, sys, urllib.parse, urllib.request

BASE, REALM, USER, PASSWORD = sys.argv[1].rstrip("/"), sys.argv[2], sys.argv[3], sys.argv[4]

def post(path, form, token=None):
headers = {"Content-Type": "application/x-www-form-urlencoded"}
if token:
headers["Authorization"] = "Bearer " + token
req = urllib.request.Request(BASE + path, urllib.parse.urlencode(form).encode(), headers)
return json.loads(urllib.request.urlopen(req).read())

def get(path, token):
req = urllib.request.Request(BASE + path, headers={"Authorization": "Bearer " + token})
return json.loads(urllib.request.urlopen(req).read())

def claims(jwt):
body = jwt.split(".")[1]
return json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))

admin = post("/realms/master/protocol/openid-connect/token",
{"client_id": "admin-cli", "grant_type": "password",
"username": input("admin user: "),
"password": getpass.getpass("admin password: ")})["access_token"]

print(f"{'client':28} {'access tok':>10} {'Authorization':>14} largest claims")
for client in sorted(get(f"/admin/realms/{REALM}/clients", admin), key=lambda c: c["clientId"]):
if not client.get("directAccessGrantsEnabled"):
continue
form = {"client_id": client["clientId"], "grant_type": "password",
"username": USER, "password": PASSWORD, "scope": "openid"}
if not client.get("publicClient"):
form["client_secret"] = get(
f"/admin/realms/{REALM}/clients/{client['id']}/client-secret", admin)["value"]
token = post(f"/realms/{REALM}/protocol/openid-connect/token", form)["access_token"]
sizes = {k: len(json.dumps(v, separators=(",", ":"))) for k, v in claims(token).items()}
top = ", ".join(f"{k} {v:,}B" for k, v in sorted(sizes.items(), key=lambda kv: -kv[1])[:3])
print(f"{client['clientId']:28} {len(token):>9,}B {len(token) + 22:>13,}B {top}")

Run it against the realm and the user who is getting the 431:

$ python3 kc-token-size.py https://auth.example.com my-realm alice
client access tok Authorization largest claims
admin-cli 841B 863B jti 45B, aud 42B, iss 36B
app 16,803B 16,825B groups 8,401B, realm_access 3,270B, resource_access 78B
legacy-portal 5,622B 5,644B realm_access 3,270B, resource_access 78B, jti 45B
reports-api 1,087B 1,109B jti 45B, sub 38B, iss 36B

Same realm, same user, four clients, and a 15× spread. That spread is the answer: the problem is per-client configuration, not the user and not the server. Clients without Direct Access Grants are skipped — there is no non-interactive way to mint a token for them — so for those, read the claim sizes out of a token copied from the browser instead.

Why the token grew: groups and roles​

The user above is in 200 groups. Adding them one at a time, with a Group Membership mapper configured with full group path on, the access token grows in a straight line:

GroupsAccess tokengroups claimRefresh token
01,322 B2 B678 B
101,897 B421 B678 B
252,737 B1,051 B678 B
504,137 B2,101 B678 B
1006,937 B4,201 B678 B
20012,537 B8,401 B678 B

That is 56 bytes of access token per group, for a 38-character group path — the JSON string plus the 33% Base64 expansion the JWT encoding adds on top. Realm roles behave the same way: granting the same user 100 realm roles added 4,532 bytes, taking the token to 16,803 B.

Two things that do not grow are worth knowing, because they rule out whole theories:

  • The refresh token stays at 678 B at every group count. If a refresh call works and an API call fails, token size is the reason.
  • Keycloak's own session cookies stay small. For this user, after a browser login with 200 groups and 100 roles: KEYCLOAK_IDENTITY 570 B, KEYCLOAK_SESSION 64 B, KC_AUTH_SESSION_HASH 66 B. A 431 on a Keycloak URL is therefore someone else's cookie on the same domain — typically an application session cookie holding the access token, which middleware like oauth2-proxy splits into numbered chunks that the browser then sends back together.

Four ways to shrink the token​

Each of these was measured on the same user, changing one setting at a time:

ChangeBeforeAfterWhat it costs you
Full group path off12,537 B9,870 B (−21%)Leaf names only, which is ambiguous when two parents have a child of the same name
Full scope allowed off on the client16,803 B (100 realm roles granted)12,271 B (−27%)You now add the roles the client actually needs to its scope, explicitly
Group Membership mapper out of the access token, kept in the ID token and userinfo12,537 B1,322 B (−89%)The resource server has to call /userinfo or introspection for group data
Lightweight access token on the client12,537 B750 B (−94%)Strips sub, aud and every mapper that has not opted in with lightweight.claim, so every service reading a claim must be audited first

Take them in that order. The first two are reversible settings changes. The third is the one that actually solves the problem for a group-heavy realm, and it is the right default: group membership is authorization data that a resource server can look up, and it does not belong in a header on every request. The fourth is the largest win and the largest change, and the trade-off is real — a lightweight access token dropped even the explicitly configured groups mapper in our run, which is exactly its design. Our protocol mappers field guide covers the lightweight.claim audit and which mappers emit what; roles, composite roles and groups covers restructuring the membership itself, which is the durable fix when a user is in 200 groups because the group tree is doing the work roles should be doing.

When raising the limit is the right answer​

Sometimes the token is as small as it can be and a receiver's limit is simply too low. Keycloak's own limit is a Quarkus setting rather than a kc.sh option, so it is set in conf/quarkus.properties:

conf/quarkus.properties
quarkus.http.limits.max-header-size=128K

or as an environment variable, which is the practical form in a container — note the QUARKUS_ prefix, not KC_:

QUARKUS_HTTP_LIMITS_MAX_HEADER_SIZE=128K

Both forms were verified on 26.8.2 in start-dev and in production start mode, with no kc.sh build step needed. Quarkus documents max-header-size as "the maximum length of all headers" and defaults it to 20K; Keycloak raises that, which is why 64 KiB is the figure measured above and why this knob is usually the last one you need. It really is a total budget rather than a per-header one: four headers of 20,000 B each were rejected, three were accepted.

The equivalents elsewhere, for the receivers in the first table: large_client_header_buffers 4 16k in nginx, LimitRequestFieldSize in httpd, maxHttpRequestHeaderSize on the Tomcat connector, and --max-http-header-size=32768 for Node.js. Raise all of them or none — a path is only as wide as its narrowest hop, and the component that rejects after a change is the next one along.

One limit you cannot raise: browsers cap an individual cookie at about 4 KB, which is why session middleware chunks. Beyond roughly 8 KB of session state, shrinking the token is the only direction left.

Stop it recurring​

Token size drifts upward one mapper at a time, and nobody notices until a user joins the group that crosses the line. Give each client a byte budget and assert it on every change to the realm, the same way the Keycloak production checklist treats the rest of the server config:

token-budget.sh
#!/usr/bin/env bash
set -euo pipefail
BUDGET=${BUDGET:-6000}
TOKEN=$(curl -sf -d "client_id=$CLIENT" -d "username=$USERNAME" -d "password=$PASSWORD" \
-d grant_type=password -d scope=openid \
"$KC_URL/realms/$REALM/protocol/openid-connect/token" |
sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p')
SIZE=${#TOKEN}
echo "$CLIENT access token: ${SIZE} bytes (budget ${BUDGET})"
[ "$SIZE" -le "$BUDGET" ] || { echo "::error::access token for $CLIENT is ${SIZE} bytes, over the ${BUDGET}-byte budget"; exit 1; }

Set the budget to half the narrowest limit in the path — 6,000 bytes is a reasonable default when there is an nginx in front — and run it against a test user who belongs to the most groups. It fails on the commit that adds the mapper, rather than in production on the day someone joins their fortieth group.


A 431 is a short debugging session once you know it is a size problem and not an auth problem: find the receiver that produced it, measure the token, then shrink the token rather than widening every hop. If you would rather not own the limit on every hop, Phase Two runs managed Keycloak with a 30-day Starter trial from $149/month. Staying self-hosted is the right call for plenty of teams — Keycloak 502 Bad Gateway behind a reverse proxy covers the response-side version of the same squeeze, and the securing applications docs cover where the token ends up once it is the right size.