Skip to content

Commit 5ee205b

Browse files
trivenaymaxday
authored andcommitted
Multi-pending /next polling for multi-concurrent mode
Pre-poll (2*detectedCpus+1) /next calls at startup to improve burst absorption
1 parent 1114b37 commit 5ee205b

8 files changed

Lines changed: 306 additions & 19 deletions

File tree

‎Dockerfile.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ RUN mkdir -p /build && \
2222
tar xzf /tmp/deps.tar.gz -C /build && \
2323
ls -R /build/deps
2424

25-
# Copy bare config
26-
COPY package.json package-lock.json tsconfig.json eslint.config.js vitest.config.js vitest.setup.ts /app/
25+
# Copy dependency manifests and bare config
26+
COPY package.json package-lock.json tsconfig.json eslint.config.js vitest.config.js vitest.setup.ts /app/
2727

2828
WORKDIR /app
2929

‎src/client/rapid-client.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
RetryOptions,
1818
DEFAULT_RETRY_OPTIONS,
1919
calculateBackoffDelay,
20+
getPollingCount,
2021
} from "../utils/index.js";
2122

2223
import { StreamOptions } from "../context/types.js";
@@ -71,7 +72,7 @@ export class RAPIDClient {
7172
this.nativeClient = nativeClient;
7273
this.agent = new this.httpClient.Agent({
7374
keepAlive: true,
74-
maxSockets: 1,
75+
maxSockets: isMultiConcurrent ? getPollingCount() : 1,
7576
});
7677
this.useAlternativeClient = shouldUseAlternativeClient();
7778
this.isMultiConcurrent = isMultiConcurrent;

‎src/context/constants.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,7 @@ export const CALLBACK_ERROR_NODEJS22 =
3939

4040
export const CALLBACK_ERROR_NODEJS24_ABOVE =
4141
"ERROR: AWS Lambda has removed support for callback-based function handlers starting with Node.js 24. You need to modify this function to use a supported handler signature to use Node.js 24 or later. For more information see https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html.";
42+
43+
// Number of concurrent /next calls to keep pending in multi-concurrent mode.
44+
// Override via AWS_LAMBDA_NODEJS_POLLING_COUNT env var.
45+
export const DEFAULT_POLLING_COUNT = 4;

‎src/runtime/runtime.test.ts‎

Lines changed: 200 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,12 +418,15 @@ describe("Runtime", () => {
418418
beforeEach(async () => {
419419
// Set AWS_LAMBDA_MAX_CONCURRENCY to ensure InvokeStoreMulti is used
420420
process.env.AWS_LAMBDA_MAX_CONCURRENCY = "1";
421+
// Use polling count of 1 for existing tests (they test handler concurrency, not multi-pending)
422+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "1";
421423
InvokeStore._testing?.reset?.();
422424
invokeStore = await InvokeStore.getInstanceAsync();
423425
});
424426

425427
afterEach(() => {
426428
delete process.env.AWS_LAMBDA_MAX_CONCURRENCY;
429+
delete process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT;
427430
InvokeStore._testing?.reset();
428431
});
429432
it("should process invocations concurrently", async () => {
@@ -875,6 +878,202 @@ describe("Runtime", () => {
875878
});
876879
});
877880
});
881+
882+
describe("[multi-pending]", () => {
883+
beforeEach(async () => {
884+
process.env.AWS_LAMBDA_MAX_CONCURRENCY = "32";
885+
InvokeStore._testing?.reset?.();
886+
await InvokeStore.getInstanceAsync();
887+
});
888+
889+
afterEach(() => {
890+
delete process.env.AWS_LAMBDA_MAX_CONCURRENCY;
891+
delete process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT;
892+
InvokeStore._testing?.reset();
893+
});
894+
895+
it("should fire pollingCount /next calls at startup", async () => {
896+
// GIVEN
897+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "4";
898+
// All calls hang (simulating RAPID holding /next connections)
899+
const mockRapidClient = {
900+
nextInvocation: vi.fn().mockImplementation(() => {
901+
return new Promise(() => {});
902+
}),
903+
postInvocationResponse: vi.fn(async () => {}),
904+
postInvocationError: vi.fn(async () => {}),
905+
postInitError: vi.fn(async () => {}),
906+
} as unknown as RAPIDClient;
907+
908+
const handler: BufferedHandler = async () => "done";
909+
910+
const runtime = Runtime.create({
911+
rapidClient: mockRapidClient,
912+
handler,
913+
isMultiConcurrent: true,
914+
});
915+
916+
// WHEN
917+
runtime.start();
918+
await vi.advanceTimersByTimeAsync(10);
919+
920+
// THEN - exactly 4 calls issued (all pending, no resolutions)
921+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(4);
922+
});
923+
924+
it("should respect AWS_LAMBDA_NODEJS_POLLING_COUNT env var", async () => {
925+
// GIVEN
926+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "2";
927+
const mockRapidClient = {
928+
nextInvocation: vi.fn().mockImplementation(() => {
929+
return new Promise(() => {}); // all hang
930+
}),
931+
postInvocationResponse: vi.fn(async () => {}),
932+
postInvocationError: vi.fn(async () => {}),
933+
postInitError: vi.fn(async () => {}),
934+
} as unknown as RAPIDClient;
935+
936+
const handler: BufferedHandler = async () => "done";
937+
938+
const runtime = Runtime.create({
939+
rapidClient: mockRapidClient,
940+
handler,
941+
isMultiConcurrent: true,
942+
});
943+
944+
// WHEN
945+
runtime.start();
946+
await vi.advanceTimersByTimeAsync(10);
947+
948+
// THEN - only 2 calls issued
949+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(2);
950+
});
951+
952+
it("should replenish /next after invocation resolves", async () => {
953+
// GIVEN
954+
vi.useRealTimers();
955+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "2";
956+
const resolvers: Array<(value: unknown) => void> = [];
957+
958+
const mockRapidClient = {
959+
nextInvocation: vi.fn().mockImplementation(() => {
960+
return new Promise((resolve) => {
961+
resolvers.push(resolve);
962+
});
963+
}),
964+
postInvocationResponse: vi.fn(async () => {}),
965+
postInvocationError: vi.fn(async () => {}),
966+
postInitError: vi.fn(async () => {}),
967+
} as unknown as RAPIDClient;
968+
969+
const handler: BufferedHandler = async () => "done";
970+
971+
const runtime = Runtime.create({
972+
rapidClient: mockRapidClient,
973+
handler,
974+
isMultiConcurrent: true,
975+
});
976+
977+
// WHEN - start: 2 pending
978+
runtime.start();
979+
await new Promise((r) => setTimeout(r, 10));
980+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(2);
981+
expect(resolvers.length).toBe(2);
982+
983+
// Resolve one - should trigger replenishment
984+
resolvers[0]({
985+
bodyJson: JSON.stringify({ key: "value" }),
986+
headers: {
987+
"lambda-runtime-aws-request-id": "test-id-1",
988+
"lambda-runtime-deadline-ms": "1234567890",
989+
"lambda-runtime-invoked-function-arn": "test:arn",
990+
},
991+
});
992+
await new Promise((r) => setTimeout(r, 10));
993+
994+
// THEN - 2 initial + 1 replenishment = 3
995+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(3);
996+
});
997+
998+
it("should not exceed pollingCount pending calls", async () => {
999+
// GIVEN
1000+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "3";
1001+
let concurrentPending = 0;
1002+
let maxConcurrentPending = 0;
1003+
let invocationCount = 0;
1004+
1005+
const mockRapidClient = {
1006+
nextInvocation: vi.fn().mockImplementation(() => {
1007+
invocationCount++;
1008+
concurrentPending++;
1009+
maxConcurrentPending = Math.max(
1010+
maxConcurrentPending,
1011+
concurrentPending,
1012+
);
1013+
1014+
if (invocationCount >= 10) {
1015+
return new Promise(() => {}); // throttle
1016+
}
1017+
1018+
return new Promise((resolve) => {
1019+
setTimeout(() => {
1020+
concurrentPending--;
1021+
resolve({
1022+
...baseMockInvocation,
1023+
headers: {
1024+
...baseMockInvocation.headers,
1025+
"lambda-runtime-aws-request-id": `test-id-${invocationCount}`,
1026+
},
1027+
});
1028+
}, 10);
1029+
});
1030+
}),
1031+
postInvocationResponse: vi.fn(async () => {}),
1032+
postInvocationError: vi.fn(async () => {}),
1033+
postInitError: vi.fn(async () => {}),
1034+
} as unknown as RAPIDClient;
1035+
1036+
const handler: BufferedHandler = async () => "done";
1037+
1038+
const runtime = Runtime.create({
1039+
rapidClient: mockRapidClient,
1040+
handler,
1041+
isMultiConcurrent: true,
1042+
});
1043+
1044+
// WHEN
1045+
await startAndTickRuntime(runtime, 100);
1046+
1047+
// THEN - pending never exceeded 3
1048+
expect(maxConcurrentPending).toBeLessThanOrEqual(3);
1049+
});
1050+
1051+
it("should dispatch all handlers without capping in-flight", async () => {
1052+
// GIVEN
1053+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "2";
1054+
let handlersDispatched = 0;
1055+
1056+
const mockRapidClient = createMockRapidClient(8); // allow 7 invocations
1057+
1058+
const handler: BufferedHandler = async () => {
1059+
handlersDispatched++;
1060+
await new Promise((resolve) => setTimeout(resolve, 100));
1061+
return "done";
1062+
};
1063+
1064+
const runtime = Runtime.create({
1065+
rapidClient: mockRapidClient,
1066+
handler,
1067+
isMultiConcurrent: true,
1068+
});
1069+
1070+
// WHEN
1071+
await startAndTickRuntime(runtime, 50);
1072+
1073+
// THEN - all resolved invocations dispatched (no cap)
1074+
expect(handlersDispatched).toBeGreaterThanOrEqual(2);
1075+
});
1076+
});
8781077
});
8791078

8801079
const baseMockInvocation: InvocationRequest = {
@@ -902,7 +1101,7 @@ function createMockRapidClient(
9021101
return {
9031102
nextInvocation: vi.fn().mockImplementation(() => {
9041103
invocationCount++;
905-
if (invocationCount == throttleAt) {
1104+
if (throttleAt > 0 && invocationCount >= throttleAt) {
9061105
return new Promise(() => {});
9071106
}
9081107
return Promise.resolve({

‎src/runtime/runtime.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,15 @@ import {
66
StreamingHandler,
77
UserHandler,
88
} from "./types.js";
9+
import { EventAndContext } from "../context/types.js";
910
import { InvokeStore, InvokeStoreBase } from "@aws/lambda-invoke-store";
1011
import { LifecycleManager } from "./lifecycle-manager.js";
1112
import { BufferedInvokeProcessor } from "./buffered-invoke-processor.js";
1213
import { StreamingInvokeProcessor } from "./streaming-invoke-processor.js";
14+
import { logger } from "../logging/verbose-log.js";
15+
import { getPollingCount } from "../utils/env.js";
16+
17+
const log = logger("RUNTIME");
1318

1419
export class Runtime {
1520
public static create({
@@ -75,9 +80,32 @@ export class Runtime {
7580
private async processMultiConcurrent(
7681
processor: InvokeProcessor,
7782
): Promise<void> {
83+
const pollingCount = getPollingCount();
84+
log.vvverbose(`Multi-concurrent polling count: ${pollingCount}`);
85+
86+
const pendingNextCalls = new Set<Promise<EventAndContext>>();
87+
88+
// Fill initial pending /next calls
89+
while (pendingNextCalls.size < pollingCount) {
90+
pendingNextCalls.add(this.lifecycle.next());
91+
}
92+
7893
while (true) {
79-
const { context, event } = await this.lifecycle.next();
94+
// Wait for any pending /next to return with an invocation
95+
const resolved = await Promise.race(
96+
[...pendingNextCalls].map((p) =>
97+
p.then((result) => ({ promise: p, result })),
98+
),
99+
);
100+
101+
// Remove the resolved promise from tracking
102+
pendingNextCalls.delete(resolved.promise);
103+
104+
// Replenish: fire replacement /next BEFORE dispatching handler
105+
pendingNextCalls.add(this.lifecycle.next());
80106

107+
// Dispatch handler via setImmediate (fire-and-forget)
108+
const { context, event } = resolved.result;
81109
setImmediate(async () => {
82110
await this.runWithInvokeContext(
83111
context.awsRequestId,

‎src/utils/env.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { HEADERS } from "../context/index.js";
22
import { InvokeHeaders } from "../context/types.js";
3+
import { DEFAULT_POLLING_COUNT } from "../context/constants.js";
34
import {
45
LogFormat,
56
LOG_FORMAT,
@@ -35,6 +36,60 @@ export function isMultiConcurrentMode(): boolean {
3536
return process.env["AWS_LAMBDA_MAX_CONCURRENCY"] !== undefined;
3637
}
3738

39+
// Default polling count is 4. Override via AWS_LAMBDA_NODEJS_POLLING_COUNT.
40+
// Capped at AWS_LAMBDA_MAX_CONCURRENCY to prevent excessive connections to RAPID.
41+
export function getPollingCount(): number {
42+
const maxConcurrency = parseInt(
43+
process.env["AWS_LAMBDA_MAX_CONCURRENCY"] || "0",
44+
10,
45+
);
46+
const envValue = process.env["AWS_LAMBDA_NODEJS_POLLING_COUNT"];
47+
if (envValue) {
48+
const parsed = parseInt(envValue, 10);
49+
if (!parsed || parsed <= 0) {
50+
console.warn(
51+
`Invalid AWS_LAMBDA_NODEJS_POLLING_COUNT="${envValue}", using default ${DEFAULT_POLLING_COUNT}`,
52+
);
53+
return DEFAULT_POLLING_COUNT;
54+
}
55+
if (maxConcurrency > 0 && parsed > maxConcurrency) {
56+
console.warn(
57+
`AWS_LAMBDA_NODEJS_POLLING_COUNT=${parsed} exceeds MC=${maxConcurrency}, capping`,
58+
);
59+
return maxConcurrency;
60+
}
61+
return parsed;
62+
}
63+
return DEFAULT_POLLING_COUNT;
64+
}
65+
66+
// Override via AWS_LAMBDA_NODEJS_WORKER_COUNT.
67+
// Capped at AWS_LAMBDA_MAX_CONCURRENCY to prevent spawning more workers than MC.
68+
export function getWorkerCountFromEnv(): number | undefined {
69+
const envValue = process.env["AWS_LAMBDA_NODEJS_WORKER_COUNT"];
70+
if (!envValue) return undefined;
71+
72+
const parsed = parseInt(envValue, 10);
73+
if (!parsed || parsed <= 0) {
74+
console.warn(
75+
`Invalid AWS_LAMBDA_NODEJS_WORKER_COUNT="${envValue}", ignoring`,
76+
);
77+
return undefined;
78+
}
79+
80+
const maxConcurrency = parseInt(
81+
process.env["AWS_LAMBDA_MAX_CONCURRENCY"] || "0",
82+
10,
83+
);
84+
if (maxConcurrency > 0 && parsed > maxConcurrency) {
85+
console.warn(
86+
`AWS_LAMBDA_NODEJS_WORKER_COUNT=${parsed} exceeds MC=${maxConcurrency}, capping`,
87+
);
88+
return maxConcurrency;
89+
}
90+
return parsed;
91+
}
92+
3893
export function moveXRayHeaderToEnv(headers: InvokeHeaders) {
3994
if (!isMultiConcurrentMode()) {
4095
if (headers[HEADERS.X_RAY_TRACE_ID]) {

0 commit comments

Comments
 (0)