Synchronous and asynchronous invocation of AWS Lambda functions with support for different invocation types, response streaming, and detailed control over execution parameters.
Invokes a Lambda function synchronously and returns the response directly.
class InvokeCommand {
constructor(input: InvokeCommandInput);
}
interface InvokeCommandInput {
/** The name or ARN of the Lambda function, version, or alias */
FunctionName: string;
/** Choose from the following options (RequestResponse - default, Event, DryRun) */
InvocationType?: InvocationType;
/** Set to Tail to include the execution log in the response (only for RequestResponse) */
LogType?: LogType;
/** Up to 3,583 bytes of base64-encoded data about the invoking client to pass to the function */
ClientContext?: string;
/** The JSON that you want to provide to your Lambda function as input */
Payload?: Uint8Array;
/** Specify a version or alias to invoke a published version of the function */
Qualifier?: string;
}
interface InvokeCommandOutput {
/** The HTTP status code is in the 200 range for a successful request */
StatusCode?: number;
/** If present, indicates that an error occurred during function execution */
FunctionError?: string;
/** The last 4 KB of the execution log, which is base64-encoded */
LogResult?: string;
/** The response from the function, or an error object */
Payload?: Uint8Array;
/** The version of the function that executed */
ExecutedVersion?: string;
}Usage Example:
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const client = new LambdaClient({ region: "us-east-1" });
// Synchronous invocation
const command = new InvokeCommand({
FunctionName: "my-function",
InvocationType: "RequestResponse",
LogType: "Tail",
Payload: JSON.stringify({
key1: "value1",
key2: "value2"
})
});
const response = await client.send(command);
// Parse the response
const result = JSON.parse(new TextDecoder().decode(response.Payload));
console.log('Function result:', result);
// Check for errors
if (response.FunctionError) {
console.error('Function error:', response.FunctionError);
}
// View logs if requested
if (response.LogResult) {
const logs = Buffer.from(response.LogResult, 'base64').toString();
console.log('Execution logs:', logs);
}Invokes a function asynchronously using Event invocation type.
// Asynchronous invocation
const asyncCommand = new InvokeCommand({
FunctionName: "my-function",
InvocationType: "Event",
Payload: JSON.stringify({ message: "Process this later" })
});
const asyncResponse = await client.send(asyncCommand);
// Response will have StatusCode 202 for acceptedInvokes a Lambda function with a streaming response, allowing for real-time data processing.
class InvokeWithResponseStreamCommand {
constructor(input: InvokeWithResponseStreamCommandInput);
}
interface InvokeWithResponseStreamCommandInput {
/** The name or ARN of the Lambda function, version, or alias */
FunctionName: string;
/** Use one of the following options (BUFFERED - default, RESPONSE_STREAM) */
InvokeMode?: InvokeMode;
/** Set to Tail to include the execution log in the response */
LogType?: LogType;
/** Up to 3,583 bytes of base64-encoded data about the invoking client to pass to the function */
ClientContext?: string;
/** The JSON that you want to provide to your Lambda function as input */
Payload?: Uint8Array;
/** Specify a version or alias to invoke a published version of the function */
Qualifier?: string;
}
interface InvokeWithResponseStreamCommandOutput {
/** The HTTP status code is in the 200 range for a successful request */
StatusCode?: number;
/** The version of the function that executed */
ExecutedVersion?: string;
/** The stream of response payload chunks from the function */
EventStream?: InvokeWithResponseStreamResponseEvent;
}Usage Example:
import { LambdaClient, InvokeWithResponseStreamCommand } from "@aws-sdk/client-lambda";
const client = new LambdaClient({ region: "us-east-1" });
const command = new InvokeWithResponseStreamCommand({
FunctionName: "my-streaming-function",
InvokeMode: "RESPONSE_STREAM",
Payload: JSON.stringify({ prompt: "Generate a story" })
});
const response = await client.send(command);
// Process streaming response
if (response.EventStream) {
for await (const event of response.EventStream) {
if ('PayloadChunk' in event && event.PayloadChunk) {
const chunk = new TextDecoder().decode(event.PayloadChunk.Payload);
process.stdout.write(chunk);
}
if ('InvokeComplete' in event) {
console.log('\nStreaming complete');
break;
}
}
}Legacy asynchronous invocation method (deprecated in favor of InvokeCommand with Event type).
class InvokeAsyncCommand {
constructor(input: InvokeAsyncCommandInput);
}
interface InvokeAsyncCommandInput {
/** The name or ARN of the Lambda function */
FunctionName: string;
/** The JSON that you want to provide to your Lambda function as input */
InvokeArgs: Uint8Array;
}
interface InvokeAsyncCommandOutput {
/** The HTTP status code is in the 200 range for a successful request */
Status?: number;
}Configures options for asynchronous invocation including retry attempts and destination routing.
class PutFunctionEventInvokeConfigCommand {
constructor(input: PutFunctionEventInvokeConfigCommandInput);
}
interface PutFunctionEventInvokeConfigCommandInput {
/** The name or ARN of the Lambda function, version, or alias */
FunctionName: string;
/** A version number or alias name */
Qualifier?: string;
/** The maximum number of times to retry when the function returns an error */
MaximumRetryAttempts?: number;
/** The maximum age of a request that Lambda sends to a function for processing */
MaximumEventAgeInSeconds?: number;
/** A destination for events after they have been sent to a function for processing */
DestinationConfig?: DestinationConfig;
}
class UpdateFunctionEventInvokeConfigCommand {
constructor(input: UpdateFunctionEventInvokeConfigCommandInput);
}
interface UpdateFunctionEventInvokeConfigCommandInput {
/** The name or ARN of the Lambda function, version, or alias */
FunctionName: string;
/** A version number or alias name */
Qualifier?: string;
/** The maximum number of times to retry when the function returns an error */
MaximumRetryAttempts?: number;
/** The maximum age of a request that Lambda sends to a function for processing */
MaximumEventAgeInSeconds?: number;
/** A destination for events after they have been sent to a function for processing */
DestinationConfig?: DestinationConfig;
}
class GetFunctionEventInvokeConfigCommand {
constructor(input: GetFunctionEventInvokeConfigCommandInput);
}
interface GetFunctionEventInvokeConfigCommandInput {
/** The name or ARN of the Lambda function, version, or alias */
FunctionName: string;
/** A version number or alias name */
Qualifier?: string;
}
class DeleteFunctionEventInvokeConfigCommand {
constructor(input: DeleteFunctionEventInvokeConfigCommandInput);
}
interface DeleteFunctionEventInvokeConfigCommandInput {
/** The name or ARN of the Lambda function, version, or alias */
FunctionName: string;
/** A version number or alias name */
Qualifier?: string;
}
class ListFunctionEventInvokeConfigsCommand {
constructor(input: ListFunctionEventInvokeConfigsCommandInput);
}
interface ListFunctionEventInvokeConfigsCommandInput {
/** The name or ARN of the Lambda function */
FunctionName: string;
/** Specify the pagination token that's returned by a previous request to retrieve the next page of results */
Marker?: string;
/** The maximum number of configurations to return */
MaxItems?: number;
}Configure recursion detection to prevent infinite loops in Lambda functions.
class PutFunctionRecursionConfigCommand {
constructor(input: PutFunctionRecursionConfigCommandInput);
}
interface PutFunctionRecursionConfigCommandInput {
/** The name or ARN of the Lambda function */
FunctionName: string;
/** The function's recursion configuration */
RecursionConfig: RecursionConfig;
}
class GetFunctionRecursionConfigCommand {
constructor(input: GetFunctionRecursionConfigCommandInput);
}
interface GetFunctionRecursionConfigCommandInput {
/** The name or ARN of the Lambda function */
FunctionName: string;
}
interface GetFunctionRecursionConfigCommandOutput {
/** The function's recursion configuration */
RecursionConfig?: RecursionConfig;
}enum InvocationType {
/** Invoke the function synchronously and wait for the response */
RequestResponse = "RequestResponse",
/** Invoke the function asynchronously */
Event = "Event",
/** Validate parameters and access permissions without running the function */
DryRun = "DryRun"
}
enum LogType {
/** Don't return logs */
None = "None",
/** Return the last 4 KB of logs */
Tail = "Tail"
}
enum InvokeMode {
/** Buffer the response until the function completes */
BUFFERED = "BUFFERED",
/** Stream the response as the function executes */
RESPONSE_STREAM = "RESPONSE_STREAM"
}
interface DestinationConfig {
/** The destination configuration for successful invocations */
OnSuccess?: OnSuccess;
/** The destination configuration for failed invocations */
OnFailure?: OnFailure;
}
interface OnSuccess {
/** The Amazon Resource Name (ARN) of the destination resource */
Destination?: string;
}
interface OnFailure {
/** The Amazon Resource Name (ARN) of the destination resource */
Destination?: string;
}
interface RecursionConfig {
/** If you set to Allow, Lambda doesn't take any action when a recursive loop is detected */
RecursiveLoop?: RecursiveLoop;
}
enum RecursiveLoop {
Allow = "Allow",
Terminate = "Terminate"
}
interface FunctionEventInvokeConfig {
/** The date and time that the configuration was last updated */
LastModified?: Date;
/** The Amazon Resource Name (ARN) of the function */
FunctionArn?: string;
/** The maximum number of times to retry when the function returns an error */
MaximumRetryAttempts?: number;
/** The maximum age of a request that Lambda sends to a function for processing */
MaximumEventAgeInSeconds?: number;
/** A destination for events after they have been sent to a function for processing */
DestinationConfig?: DestinationConfig;
}
interface InvokeWithResponseStreamResponseEvent {
/** A chunk of the streamed response payload */
PayloadChunk?: {
Payload?: Uint8Array;
};
/** An error that occurred during streaming */
InvokeComplete?: {
ErrorCode?: string;
ErrorDetails?: string;
LogResult?: string;
};
}When invoking Lambda functions, several types of errors can occur:
Function Errors:
Service Errors:
Usage Example with Error Handling:
import { LambdaClient, InvokeCommand, LambdaServiceException } from "@aws-sdk/client-lambda";
const client = new LambdaClient({ region: "us-east-1" });
try {
const command = new InvokeCommand({
FunctionName: "my-function",
Payload: JSON.stringify({ data: "test" })
});
const response = await client.send(command);
if (response.FunctionError) {
// Handle function-level errors
console.error(`Function error (${response.FunctionError}):`,
new TextDecoder().decode(response.Payload));
} else {
// Process successful response
const result = JSON.parse(new TextDecoder().decode(response.Payload));
console.log('Success:', result);
}
} catch (error) {
if (error instanceof LambdaServiceException) {
// Handle service-level errors
console.error(`Service error: ${error.name} - ${error.message}`);
} else {
// Handle other errors
console.error('Unexpected error:', error);
}
}