Can AWS Lambda functions call other Lambda functions? If so, how?

Instruction: Describe the process and considerations for invoking one AWS Lambda function from another.

Context: This question explores a candidate's understanding of building interconnected, serverless architectures using AWS Lambda. It tests their knowledge of Lambda functions' invocation types and the implications of synchronous vs. asynchronous calls.

Updated

Official answer

Yes. A function can call the Lambda Invoke API through an SDK. The caller needs permission to invoke the approved target; cross-account invocation also requires the applicable target resource policy. Prefer a configured version or alias over an arbitrary function name supplied by an untrusted request.

This Node.js ES module uses the packaged @aws-sdk/client-lambda dependency. Configure the handler as index.handler for index.mjs, and set TARGET_FUNCTION_ARN to an approved target alias ARN:

import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";

const client = new LambdaClient({});

export async function handler(event) {
  const target = process.env.TARGET_FUNCTION_ARN;
  if (!target) throw new Error("Missing target configuration");
  if (!event || typeof event.orderId !== "string" ||
      event.orderId.trim() === "") {
    throw new Error("orderId must be a nonempty string");
  }
  const result = await client.send(new InvokeCommand({
    FunctionName: target,
    InvocationType: "Event",
    Payload: Buffer.from(JSON.stringify({ orderId: event.orderId }))
  }));
  if (result.StatusCode !== 202) {
    throw new Error("Invocation was not accepted");
  }
  return { accepted: true, orderId: event.orderId };
}

Event waits for the API to accept asynchronous work, not for the target to finish. Configure target retries/failure capture and make processing idempotent; a network error can leave acceptance uncertain. The returned object is an invocation result, not an API Gateway proxy-response envelope.

With RequestResponse, the caller waits for completion and must inspect FunctionError and the returned payload as well as API failures. An HTTP 200 from Invoke does not necessarily mean the handler succeeded. Nested synchronous calls add waiting time and cost. Use a queue or Step Functions when buffering or explicit orchestration is more suitable, and prevent recursive invocation loops.

Invoke API, Node.js SDKv3 handler

Related Questions