feat(lambdaweb): scale environments per endpoint and apply maxEnvironments and rateLimit (#5785)

* feat(lambdaweb): scale environments per endpoint and apply maxEnvironments and rateLimit

Each endpoint keeps its own pool of environments, as on AWS. An
environment takes up to the revision's maxConcurrencyPerEnvironment
requests at once, the least busy one first so requests rotate, and a
request that finds every environment full starts another or waits for
one that is starting. At maxEnvironments the request gets the 429 page
with Platform.EndpointMaxEnvThrottle. A rateLimit admits a burst of up
to rateLimit requests refilled at rateLimit per second and refuses the
rest with Platform.EndpointRequestThrottle. Both pages were recorded
against AWS.

Part of #5699

* fix(lambdaweb): key environment pools by endpoint creation and let a new revision take an idle slot

A recreated endpoint gets a new domain, so it no longer reuses the
environments of the deleted one. At maxEnvironments an idle environment
of another revision is stopped to make room. Empty pools are dropped.
The burst in the Docker test now arrives at once, so a slow runner still
goes past the rate.

* fix(lambdaweb): keep the rate limiter clock monotonic and drop refilled buckets

A bucket untouched for a second is full, so it is dropped. A clock read
that lands behind the bucket no longer takes tokens back.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-16 07:10:39 -04:00
1 parent 3cb1643d30
commit 832f1008bb
9 files changed
+499 -69

No files matched your search

@@ -18,7 +18,17 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -50,6 +60,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {
const [host, port] = process.env.AWS_LAMBDA_HTTP_ENDPOINT.split(':');
http.createServer((req, res) => {
if (req.url.startsWith('/slow')) { setTimeout(() => res.end('late'), 8000); return; }
if (req.url.startsWith('/wait')) { setTimeout(() => res.end('waited'), 3000); return; }
if (req.url.startsWith('/stream')) {
res.writeHead(200, {'content-type': 'text/plain'});
let i = 0;
@@ -181,7 +192,97 @@ class LambdaWebDataPlaneDockerIntegrationTest {
assertNotEquals(logStream, after.header("lambda-web-logstream"), "a new environment serves the next request");
}
@Test
@Timeout(240)
void environmentsScaleUpToMaxEnvironmentsAndTheRateLimitThrottles() throws Exception {
String domain = createFunction(30, 1);
given().contentType("application/json").body("{\"scalingConfig\": {\"maxEnvironments\": 2}}")
.when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")
.then().statusCode(202);
// One request per environment: two run, the rest are refused, as recorded on AWS.
List<String> responses = parallel(5, () -> raw("GET /wait HTTP/1.1\r\nHost: " + domain
+ "\r\nConnection: close\r\n\r\n"));
long served = responses.stream().filter(response -> response.startsWith("HTTP/1.1 200 ")).count();
List<String> throttled = responses.stream().filter(response -> response.startsWith("HTTP/1.1 429 ")).toList();
assertEquals(2, served, String.join("\n----\n", responses));
assertEquals(3, throttled.size(), String.join("\n----\n", responses));
for (String response : throttled) {
assertTrue(response.contains("\r\nlambda-web-error-type: Platform.EndpointMaxEnvThrottle\r\n"), response);
assertTrue(response.contains("<p>Request rate exceeded. Please try again later.</p>"), response);
}
// Requests one after another rotate over the two environments.
Set<String> logStreams = new HashSet<>();
for (int i = 0; i < 4; i++) {
logStreams.add(given().header("Host", domain).when().get("/status/200")
.then().statusCode(200).extract().header("lambda-web-logstream"));
}
assertEquals(2, logStreams.size(), logStreams.toString());
// A new revision takes the place of an idle environment of the old one.
String revisionId = given().contentType("application/json")
.body("""
{"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "%s.zip"}},
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": 30}}
""".formatted(BUCKET, functionName, ROLE))
.when().post(BASE + "/web-functions/" + functionName + "/revisions")
.then().statusCode(202)
.extract().path("revisionId");
String moved = given().header("Host", domain).when().get("/status/200")
.then().statusCode(200).extract().header("lambda-web-logstream");
assertTrue(moved.contains("[" + revisionId + "]"), moved);
logStreams.add(moved);
// A recreated endpoint shares no environment or rate with the deleted one.
String endpoints = BASE + "/web-functions/" + functionName + "/endpoints";
given().when().delete(endpoints + "/dev").then().statusCode(204);
String recreated = given().contentType("application/json")
.body("{\"endpointName\": \"dev\", \"endpointType\": \"HomeRegion\","
+ " \"authType\": \"ApplicationManaged\", \"autoDeploymentMode\": \"LatestRevision\","
+ " \"throttleConfig\": {\"rateLimit\": 100}}")
.when().put(endpoints)
.then().statusCode(202)
.extract().path("domainName");
String fresh = given().header("Host", recreated).when().get("/status/200")
.then().statusCode(200).extract().header("lambda-web-logstream");
assertFalse(logStreams.contains(fresh), fresh + " " + logStreams);
// Requests that all arrive at once are only admitted up to the rate.
int count = 200;
CyclicBarrier together = new CyclicBarrier(count);
List<String> burst = parallel(count, () -> raw("GET /status/200 HTTP/1.1\r\nHost: " + recreated
+ "\r\nConnection: close\r\n\r\n", together));
List<String> limited = burst.stream().filter(response -> response.startsWith("HTTP/1.1 429 ")).toList();
assertFalse(limited.isEmpty(), "a burst well past the rate is throttled");
for (String response : limited) {
assertTrue(response.contains("\r\nlambda-web-error-type: Platform.EndpointRequestThrottle\r\n"), response);
}
}
private static List<String> parallel(int count, Callable<String> call) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(count);
try {
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < count; i++) {
futures.add(pool.submit(call));
}
List<String> results = new ArrayList<>();
for (Future<String> future : futures) {
results.add(future.get(60, TimeUnit.SECONDS));
}
return results;
} finally {
pool.shutdownNow();
}
}
private String createFunction(int timeoutSeconds) throws IOException {
return createFunction(timeoutSeconds, 64);
}
private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment) throws IOException {
functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());
@@ -192,19 +293,29 @@ class LambdaWebDataPlaneDockerIntegrationTest {
"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "%s.zip"}},
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s", "timeoutSeconds": %d,
"maxConcurrencyPerEnvironment": %d,
"environmentVariables": {"CUSTOM": "yes"}}},
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
""".formatted(functionName, BUCKET, functionName, ROLE, timeoutSeconds))
""".formatted(functionName, BUCKET, functionName, ROLE, timeoutSeconds,
maxConcurrencyPerEnvironment))
.when().put(BASE + "/web-functions")
.then().statusCode(202)
.extract().path("endpoint.domainName");
}
/** Sends one raw HTTP/1.1 request with {@code Connection: close} and reads until the server closes. */
private static String raw(String request) throws IOException {
private static String raw(String request) throws Exception {
return raw(request, null);
}
/** As {@link #raw(String)}, sent once every party of {@code together} has connected. */
private static String raw(String request, CyclicBarrier together) throws Exception {
try (Socket socket = new Socket("localhost", RestAssured.port)) {
socket.setSoTimeout(30_000);
if (together != null) {
together.await(30, TimeUnit.SECONDS);
}
OutputStream out = socket.getOutputStream();
out.write(request.getBytes(StandardCharsets.US_ASCII));
out.flush();
@@ -51,7 +51,7 @@ class LambdaWebDataPlaneIntegrationTest {
}
@Test
void aDisabledEndpointAnswersBeforeAnyEnvironmentStarts() {
void aDisabledEndpointAnswersBeforeAnyEnvironmentStarts() throws IOException {
String functionName = "dp-disabled-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(functionName);
given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 0}}")
@@ -65,9 +65,40 @@ class LambdaWebDataPlaneIntegrationTest {
.body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.ENDPOINT_DISABLED,
response.header("lambda-web-request-id"))));
// The page keeps the connection, as on AWS. A body sent after it is skipped and the next request is served.
try (Socket socket = new Socket("localhost", RestAssured.port)) {
socket.setSoTimeout(10_000);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
out.write(("POST /upload HTTP/1.1\r\nHost: " + domain + "\r\nContent-Length: 5\r\n\r\n")
.getBytes(StandardCharsets.US_ASCII));
out.flush();
String first = readUntil(in, "</html>");
assertTrue(first.startsWith("HTTP/1.1 503 "), first);
assertTrue(first.contains("\r\nconnection: keep-alive\r\n"), first);
out.write(("hello" + "GET /next HTTP/1.1\r\nHost: " + domain + "\r\nConnection: close\r\n\r\n")
.getBytes(StandardCharsets.US_ASCII));
out.flush();
String second = new String(in.readAllBytes(), StandardCharsets.UTF_8);
assertTrue(second.startsWith("HTTP/1.1 503 "), second);
assertTrue(second.contains("\r\nlambda-web-error-type: Platform.EndpointDisabled\r\n"), second);
}
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
}
private static String readUntil(InputStream in, String end) throws IOException {
StringBuilder read = new StringBuilder();
while (!read.toString().endsWith(end)) {
int next = in.read();
if (next < 0) {
break;
}
read.append((char) next);
}
return read.toString();
}
@Test
void httpOneDotZeroIsRefused() throws IOException {
String response = raw("GET / HTTP/1.0\r\nHost: " + UNKNOWN_HOST + "\r\n\r\n");
@@ -23,6 +23,8 @@ class LambdaWebErrorPagesTest {
assertEquals(228, length(LambdaWebErrorPages.TIMEOUT_LISTEN_ERROR));
assertEquals(228, length(LambdaWebErrorPages.INIT_CODE_ERROR));
assertEquals(228, length(LambdaWebErrorPages.RUNTIME_EXIT));
assertEquals(237, length(LambdaWebErrorPages.ENDPOINT_MAX_ENV_THROTTLE));
assertEquals(237, length(LambdaWebErrorPages.ENDPOINT_REQUEST_THROTTLE));
assertEquals(180, LambdaWebErrorPages.MALFORMED_REQUEST_HTML.getBytes(StandardCharsets.UTF_8).length);
}
@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.services.lambdaweb;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LambdaWebRateLimiterTest {
private final AtomicLong now = new AtomicLong();
private final LambdaWebRateLimiter limiter = new LambdaWebRateLimiter(now::get);
@Test
void aBurstUpToTheRatePassesAndTheNextRequestIsThrottled() {
assertEquals(100, admitted("ep", 100, 150));
}
@Test
void theBucketRefillsAtTheRatePerSecond() {
assertEquals(100, admitted("ep", 100, 100));
assertFalse(limiter.tryAcquire("ep", 100));
now.addAndGet(TimeUnit.MILLISECONDS.toNanos(500));
assertEquals(50, admitted("ep", 100, 80));
now.addAndGet(TimeUnit.SECONDS.toNanos(10));
assertEquals(100, admitted("ep", 100, 150), "the bucket holds at most one second of requests");
}
@Test
void endpointsHaveTheirOwnBucketsAndANewRateStartsAFullOne() {
assertEquals(100, admitted("a", 100, 100));
assertTrue(limiter.tryAcquire("b", 100));
assertFalse(limiter.tryAcquire("a", 100));
assertEquals(200, admitted("a", 200, 250));
}
@Test
void aClockReadOutOfOrderTakesNoTokensBack() {
now.set(1_000);
assertTrue(limiter.tryAcquire("ep", 2));
now.set(0);
assertTrue(limiter.tryAcquire("ep", 2));
assertFalse(limiter.tryAcquire("ep", 2));
}
@Test
void bucketsThatRefilledAreDropped() {
assertEquals(100, admitted("a", 100, 100));
assertTrue(limiter.tryAcquire("b", 100));
assertEquals(2, limiter.size());
now.addAndGet(TimeUnit.SECONDS.toNanos(1));
assertTrue(limiter.tryAcquire("c", 100));
assertEquals(1, limiter.size());
assertEquals(100, admitted("a", 100, 150));
}
private int admitted(String endpoint, int rate, int requests) {
int admitted = 0;
for (int i = 0; i < requests; i++) {
if (limiter.tryAcquire(endpoint, rate)) {
admitted++;
}
}
return admitted;
}
}