Webserver: per-CUD cap on in-flight requests, enforced only while the pool is saturated (429)

Author: tamassolteszCreated Sep 18, 2026Updated Sep 24, 2026
Labelsagent-wip

Unit 1. Add a configurable ceiling on how many request threads a single connection URI domain (CUD) may hold at the same time on a core, so one tenant cannot exhaust the shared Tomcat pool (max_server_pool_size) for everyone else on the same core. The ceiling is a FAIR-SHARE rule, not a quota: it is enforced only while the pool is saturated; on an idle core a tenant may exceed it freely. Full design: agent-plans PLAN-015.

Config key (src/main/java/io/supertokens/config/CoreConfig.java): max_concurrent_requests_per_cud, int, default 0 = no cap. Annotate @EnvName("MAX_CONCURRENT_REQUESTS_PER_CUD"), @JsonProperty, @ConfigDescription, @NotConflictingInConnectionUriDomain (all tenants of a CUD must carry the same value). Add it to PROTECTED_CONFIGS (SaaS customers must not be able to raise their own share). Validation in normalizeAndValidate: < 0 → InvalidConfigException; > the base config's max_server_pool_size → InvalidConfigException. Add the template entry to config.yaml and devConfig.yaml.

Second key, base config only: concurrency_cap_reserved_pool_percent, int, default 25, @ConfigYamlOnly, @EnvName("CONCURRENCY_CAP_RESERVED_POOL_PERCENT"), validated 1..100. Meaning: the share of max_server_pool_size kept free for tenants under their cap. Derive at load saturationThreshold = max_server_pool_size - floor(max_server_pool_size * percent / 100) (200 threads, 25 % → enforce at 150 in flight). 100 = always enforce (a hard cap). The threshold MUST be below the pool size: our hook runs on a Tomcat thread, and once every thread is busy new connections queue in the acceptor where nothing of ours runs.

Limiter (new src/main/java/io/supertokens/webserver/ConcurrencyLimiter.java): a ResourceDistributor.SingletonResource keyed by the CUD's base tenant (new TenantIdentifier(cud, null, null)), created lazily like utils/RateLimiter.getInstance. State is one AtomicInteger inFlight per CUD plus ONE process-wide AtomicInteger of all requests in flight on this core. The cap is read per request from Config.getConfig(tenantIdentifier, main).getMaxConcurrentRequestsPerCud() and the threshold from the base config, so a live config reload applies to the next request with no state migration. Do NOT use a Semaphore (cannot be resized while permits are out). tryAcquire(limit, saturationThreshold): increment BOTH counters first; if limit > 0 && mine > limit && global > saturationThreshold roll both back and return false; else return true. release(): decrement both. Count even when unlimited (unlimited CUDs still contribute to saturation and to stats). No hysteresis: a tenant above its cap when saturation starts keeps the threads it holds and is only refused NEW ones until it drops below the cap or the pool is idle enough again.

Hook (src/main/java/io/supertokens/webserver/WebserverAPI.java, service()): right after tenantIdentifier = getTenantIdentifierWithoutVerifying(req) and BEFORE checkIPAccess / assertThatAPIKeyCheckPasses (a saturated tenant must not spend a thread on those either). On rejection: Retry-After: 1, sendTextResponse(429, "Too many concurrent requests for this tenant", resp), return. Wrap the whole existing try/catch in try { … } finally { limiter.release(); } so every exit path (incl. QuitProgramException and the 500 fallback) releases. Exempt ONLY the real /hello servlet (HelloAPI, liveness probe) from the CAP — it is still counted in the global in-flight counter like any request; NotFoundOrHelloAPI and everything else, including /.well-known/jwks.json, is counted and capped. If Config.getConfig throws TenantOrAppNotFoundException, skip the limiter (the existing 400 path handles it).

SDK behaviour on 429 — verified 2026-09-17 on master of all three SDKs, no SDK change needed. Node 24.0.3 (lib/ts/querier.ts:668), Python 0.31.3 (querier.py:515) and Go 0.26.0 (querier.go:589) all retry a 429 from the core up to 5 times per URL with a fixed delay of 10 + 250 × attempt ms (10, 260, 510, 760, 1010 ms; ~2.5 s total), then raise the generic "SuperTokens core threw an error … status code: 429" error. Retry-After is ignored by all three (informational only). So a tenant briefly over its cap self-heals from the SDK's side; a tenant saturated for >2.5 s surfaces as an SDK error on the customer's backend, which is the intended signal (today it is a 504 from the ALB after 10 s).

Tests (src/test/java/io/supertokens/test/webserver/ConcurrencyLimiterTest.java): requests must be slow to hold threads — add a Main.isTesting-gated test servlet (/test/slow?ms=) registered in Webserver only when testing. Then: (0) NOT saturated: cap 2, max_server_pool_size 10, reserve 25 % (threshold 8), three parallel slow requests on the capped CUD → all three 200 (the cap alone never rejects); (1) saturated: fill the pool to the threshold with slow requests from ANOTHER CUD, then three parallel slow requests on the capped CUD → two 200, one 429 with Retry-After, ProcessState.CONCURRENT_REQUEST_LIMIT_HIT recorded; with concurrency_cap_reserved_pool_percent: 100 the same three requests give two 200 / one 429 with no filler traffic (hard-cap mode); (2) isolation: CUD A over its cap under saturation, CUD B under its cap still 200; (3) release on error path (a request that throws) → both counters back to 0, next request accepted; (4) live reload: raise the cap via the multitenancy API → next request sees it; lower it below in-flight under saturation → rejects until drained; (5) no cap set → max_server_pool_size parallel slow requests all 200; (6) /hello 200 while saturated; (7) validation: negative, above pool size, and differing values across two tenants of one CUD are rejected; concurrency_cap_reserved_pool_percent outside 1..100 is rejected and it is not settable per tenant; (8) protected: setting the cap via the multitenancy API without the SaaS secret is rejected when supertokens_saas_secret is configured; (9) after a burst of rejections and all requests finishing, BOTH counters are back at 0.

Release plumbing: new ProcessState.PROCESS_STATE.CONCURRENT_REQUEST_LIMIT_HIT; do NOT bump version in build.gradle (release prepare does it); add one line to CHANGELOG.md under the topmost unreleased section (create ## [Unreleased] at the top if the head section is already released): "Adds max_concurrent_requests_per_cud (SaaS-protected, 0 = off) and concurrency_cap_reserved_pool_percent (base config, default 25): once the request pool has less than the reserved share of free threads, a connection URI domain above its cap gets 429 immediately instead of a thread; below that, no request is ever rejected."

BASE BRANCH: cut your worktree from the head of origin/12.3 and open the PR with --base 12.3. State "Base: 12.3" in the PR body. Do not target master or dev.

Plan: PLAN-015

Source: supertokens/supertokens-core