Skip to content

Commit e0ce832

Browse files
authored
Merge pull request #204 from aws/maxday/feat-pre-poll-multiple-next
feat: multi-pending /next polling for multi-concurrent mode
2 parents 620bd7e + 5ee205b commit e0ce832

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
@@ -442,12 +442,15 @@ describe("Runtime", () => {
442442
beforeEach(async () => {
443443
// Set AWS_LAMBDA_MAX_CONCURRENCY to ensure InvokeStoreMulti is used
444444
process.env.AWS_LAMBDA_MAX_CONCURRENCY = "1";
445+
// Use polling count of 1 for existing tests (they test handler concurrency, not multi-pending)
446+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "1";
445447
InvokeStore._testing?.reset?.();
446448
invokeStore = await InvokeStore.getInstanceAsync();
447449
});
448450

449451
afterEach(() => {
450452
delete process.env.AWS_LAMBDA_MAX_CONCURRENCY;
453+
delete process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT;
451454
InvokeStore._testing?.reset();
452455
});
453456
it("should process invocations concurrently", async () => {
@@ -938,6 +941,202 @@ describe("Runtime", () => {
938941
});
939942
});
940943
});
944+
945+
describe("[multi-pending]", () => {
946+
beforeEach(async () => {
947+
process.env.AWS_LAMBDA_MAX_CONCURRENCY = "32";
948+
InvokeStore._testing?.reset?.();
949+
await InvokeStore.getInstanceAsync();
950+
});
951+
952+
afterEach(() => {
953+
delete process.env.AWS_LAMBDA_MAX_CONCURRENCY;
954+
delete process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT;
955+
InvokeStore._testing?.reset();
956+
});
957+
958+
it("should fire pollingCount /next calls at startup", async () => {
959+
// GIVEN
960+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "4";
961+
// All calls hang (simulating RAPID holding /next connections)
962+
const mockRapidClient = {
963+
nextInvocation: vi.fn().mockImplementation(() => {
964+
return new Promise(() => {});
965+
}),
966+
postInvocationResponse: vi.fn(async () => {}),
967+
postInvocationError: vi.fn(async () => {}),
968+
postInitError: vi.fn(async () => {}),
969+
} as unknown as RAPIDClient;
970+
971+
const handler: BufferedHandler = async () => "done";
972+
973+
const runtime = Runtime.create({
974+
rapidClient: mockRapidClient,
975+
handler,
976+
isMultiConcurrent: true,
977+
});
978+
979+
// WHEN
980+
runtime.start();
981+
await vi.advanceTimersByTimeAsync(10);
982+
983+
// THEN - exactly 4 calls issued (all pending, no resolutions)
984+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(4);
985+
});
986+
987+
it("should respect AWS_LAMBDA_NODEJS_POLLING_COUNT env var", async () => {
988+
// GIVEN
989+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "2";
990+
const mockRapidClient = {
991+
nextInvocation: vi.fn().mockImplementation(() => {
992+
return new Promise(() => {}); // all hang
993+
}),
994+
postInvocationResponse: vi.fn(async () => {}),
995+
postInvocationError: vi.fn(async () => {}),
996+
postInitError: vi.fn(async () => {}),
997+
} as unknown as RAPIDClient;
998+
999+
const handler: BufferedHandler = async () => "done";
1000+
1001+
const runtime = Runtime.create({
1002+
rapidClient: mockRapidClient,
1003+
handler,
1004+
isMultiConcurrent: true,
1005+
});
1006+
1007+
// WHEN
1008+
runtime.start();
1009+
await vi.advanceTimersByTimeAsync(10);
1010+
1011+
// THEN - only 2 calls issued
1012+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(2);
1013+
});
1014+
1015+
it("should replenish /next after invocation resolves", async () => {
1016+
// GIVEN
1017+
vi.useRealTimers();
1018+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "2";
1019+
const resolvers: Array<(value: unknown) => void> = [];
1020+
1021+
const mockRapidClient = {
1022+
nextInvocation: vi.fn().mockImplementation(() => {
1023+
return new Promise((resolve) => {
1024+
resolvers.push(resolve);
1025+
});
1026+
}),
1027+
postInvocationResponse: vi.fn(async () => {}),
1028+
postInvocationError: vi.fn(async () => {}),
1029+
postInitError: vi.fn(async () => {}),
1030+
} as unknown as RAPIDClient;
1031+
1032+
const handler: BufferedHandler = async () => "done";
1033+
1034+
const runtime = Runtime.create({
1035+
rapidClient: mockRapidClient,
1036+
handler,
1037+
isMultiConcurrent: true,
1038+
});
1039+
1040+
// WHEN - start: 2 pending
1041+
runtime.start();
1042+
await new Promise((r) => setTimeout(r, 10));
1043+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(2);
1044+
expect(resolvers.length).toBe(2);
1045+
1046+
// Resolve one - should trigger replenishment
1047+
resolvers[0]({
1048+
bodyJson: JSON.stringify({ key: "value" }),
1049+
headers: {
1050+
"lambda-runtime-aws-request-id": "test-id-1",
1051+
"lambda-runtime-deadline-ms": "1234567890",
1052+
"lambda-runtime-invoked-function-arn": "test:arn",
1053+
},
1054+
});
1055+
await new Promise((r) => setTimeout(r, 10));
1056+
1057+
// THEN - 2 initial + 1 replenishment = 3
1058+
expect(mockRapidClient.nextInvocation).toHaveBeenCalledTimes(3);
1059+
});
1060+
1061+
it("should not exceed pollingCount pending calls", async () => {
1062+
// GIVEN
1063+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "3";
1064+
let concurrentPending = 0;
1065+
let maxConcurrentPending = 0;
1066+
let invocationCount = 0;
1067+
1068+
const mockRapidClient = {
1069+
nextInvocation: vi.fn().mockImplementation(() => {
1070+
invocationCount++;
1071+
concurrentPending++;
1072+
maxConcurrentPending = Math.max(
1073+
maxConcurrentPending,
1074+
concurrentPending,
1075+
);
1076+
1077+
if (invocationCount >= 10) {
1078+
return new Promise(() => {}); // throttle
1079+
}
1080+
1081+
return new Promise((resolve) => {
1082+
setTimeout(() => {
1083+
concurrentPending--;
1084+
resolve({
1085+
...baseMockInvocation,
1086+
headers: {
1087+
...baseMockInvocation.headers,
1088+
"lambda-runtime-aws-request-id": `test-id-${invocationCount}`,
1089+
},
1090+
});
1091+
}, 10);
1092+
});
1093+
}),
1094+
postInvocationResponse: vi.fn(async () => {}),
1095+
postInvocationError: vi.fn(async () => {}),
1096+
postInitError: vi.fn(async () => {}),
1097+
} as unknown as RAPIDClient;
1098+
1099+
const handler: BufferedHandler = async () => "done";
1100+
1101+
const runtime = Runtime.create({
1102+
rapidClient: mockRapidClient,
1103+
handler,
1104+
isMultiConcurrent: true,
1105+
});
1106+
1107+
// WHEN
1108+
await startAndTickRuntime(runtime, 100);
1109+
1110+
// THEN - pending never exceeded 3
1111+
expect(maxConcurrentPending).toBeLessThanOrEqual(3);
1112+
});
1113+
1114+
it("should dispatch all handlers without capping in-flight", async () => {
1115+
// GIVEN
1116+
process.env.AWS_LAMBDA_NODEJS_POLLING_COUNT = "2";
1117+
let handlersDispatched = 0;
1118+
1119+
const mockRapidClient = createMockRapidClient(8); // allow 7 invocations
1120+
1121+
const handler: BufferedHandler = async () => {
1122+
handlersDispatched++;
1123+
await new Promise((resolve) => setTimeout(resolve, 100));
1124+
return "done";
1125+
};
1126+
1127+
const runtime = Runtime.create({
1128+
rapidClient: mockRapidClient,
1129+
handler,
1130+
isMultiConcurrent: true,
1131+
});
1132+
1133+
// WHEN
1134+
await startAndTickRuntime(runtime, 50);
1135+
1136+
// THEN - all resolved invocations dispatched (no cap)
1137+
expect(handlersDispatched).toBeGreaterThanOrEqual(2);
1138+
});
1139+
});
9411140
});
9421141

9431142
const baseMockInvocation: InvocationRequest = {
@@ -966,7 +1165,7 @@ function createMockRapidClient(
9661165
return {
9671166
nextInvocation: vi.fn().mockImplementation(() => {
9681167
invocationCount++;
969-
if (invocationCount == throttleAt) {
1168+
if (throttleAt > 0 && invocationCount >= throttleAt) {
9701169
return new Promise(() => {});
9711170
}
9721171
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({
@@ -76,9 +81,32 @@ export class Runtime {
7681
private async processMultiConcurrent(
7782
processor: InvokeProcessor,
7883
): Promise<void> {
84+
const pollingCount = getPollingCount();
85+
log.vvverbose(`Multi-concurrent polling count: ${pollingCount}`);
86+
87+
const pendingNextCalls = new Set<Promise<EventAndContext>>();
88+
89+
// Fill initial pending /next calls
90+
while (pendingNextCalls.size < pollingCount) {
91+
pendingNextCalls.add(this.lifecycle.next());
92+
}
93+
7994
while (true) {
80-
const { context, event } = await this.lifecycle.next();
95+
// Wait for any pending /next to return with an invocation
96+
const resolved = await Promise.race(
97+
[...pendingNextCalls].map((p) =>
98+
p.then((result) => ({ promise: p, result })),
99+
),
100+
);
101+
102+
// Remove the resolved promise from tracking
103+
pendingNextCalls.delete(resolved.promise);
104+
105+
// Replenish: fire replacement /next BEFORE dispatching handler
106+
pendingNextCalls.add(this.lifecycle.next());
81107

108+
// Dispatch handler via setImmediate (fire-and-forget)
109+
const { context, event } = resolved.result;
82110
setImmediate(async () => {
83111
await this.runWithInvokeContext(
84112
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)