Lambda Deep Dive Basics
Six examples to get comfortable managing and running a Lambda function from an SDK - four basic and two intermediate.
Busca en todas las páginas de la documentación
Six examples to get comfortable managing and running a Lambda function from an SDK - four basic and two intermediate.
Each example shows the same operation in both Python (boto3) and TypeScript (AWS SDK for JavaScript v3). By the end you can push new code, retune a function's resources, and invoke it both ways while reading back its result and logs.
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-lambda (Node.js 18+).aws configure, environment variables, or an IAM role - the SDK finds them automatically.my-func and IAM permissions for lambda:UpdateFunctionCode, lambda:UpdateFunctionConfiguration, lambda:GetFunctionConfiguration, and lambda:InvokeFunction.A synchronous (RequestResponse) invoke runs the function and returns its output on the same call.
# --- Python (boto3) ---
import boto3, json
lam = boto3.client("lambda")
resp = lam.invoke(
FunctionName="my-func",
InvocationType="RequestResponse",
Payload=json.dumps({"name": "Ada"}).encode(),
)
result = json.loads(resp["Payload"].read())
print(resp["StatusCode"], result)// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const lam = new LambdaClient({});
const resp = await lam.send(new InvokeCommand({
FunctionName: "my-func",
InvocationType: "RequestResponse",
Payload: new TextEncoder().encode(JSON.stringify({ name: "Ada" })),
}));
const result = JSON.parse(new TextDecoder().decode(resp.Payload));
console.log(resp.StatusCode, result);StatusCode is 200 for a completed synchronous invoke.Payload is a streaming body in boto3 (.read()) and a Uint8Array in SDK v3 (TextDecoder).json.loads / JSON.parse - the SDK gives you bytes, not a string.Related: Lambda's Execution Model for SDK Callers - why synchronous invokes pay cold-start latency inline.
An asynchronous (Event) invoke queues the payload and returns immediately, letting Lambda run and retry it for you.
# --- Python (boto3) ---
import boto3, json
lam = boto3.client("lambda")
resp = lam.invoke(
FunctionName="my-func",
InvocationType="Event",
Payload=json.dumps({"job": "resize", "id": 42}).encode(),
)
print(resp["StatusCode"]) # 202 - accepted, not yet run// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const lam = new LambdaClient({});
const resp = await lam.send(new InvokeCommand({
FunctionName: "my-func",
InvocationType: "Event",
Payload: new TextEncoder().encode(JSON.stringify({ job: "resize", id: 42 })),
}));
console.log(resp.StatusCode); // 202 - accepted, not yet runStatusCode is 202: Lambda accepted the event but has not run it yet.Change memory, timeout, and environment variables without touching the code.
# --- Python (boto3) ---
import boto3
lam = boto3.client("lambda")
lam.update_function_configuration(
FunctionName="my-func",
MemorySize=512, # MB, 128-10240
Timeout=30, # seconds, max 900
Environment={"Variables": {"LOG_LEVEL": "info"}},
)// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, UpdateFunctionConfigurationCommand } from "@aws-sdk/client-lambda";
const lam = new LambdaClient({});
await lam.send(new UpdateFunctionConfigurationCommand({
FunctionName: "my-func",
MemorySize: 512, // MB, 128-10240
Timeout: 30, // seconds, max 900
Environment: { Variables: { LOG_LEVEL: "info" } },
}));MemorySize also grants proportionally more CPU, so it can speed up compute-bound functions.Environment.Variables replaces the whole map - include existing keys you want to keep.LastUpdateStatus: InProgress.Timeout caps a single invocation; the hard maximum is 900 seconds (15 minutes).Ship a new deployment package from a local ZIP.
# --- Python (boto3) ---
import boto3
lam = boto3.client("lambda")
with open("function.zip", "rb") as f:
lam.update_function_code(
FunctionName="my-func",
ZipFile=f.read(),
Publish=True, # also cut an immutable version
)// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, UpdateFunctionCodeCommand } from "@aws-sdk/client-lambda";
import { readFileSync } from "node:fs";
const lam = new LambdaClient({});
await lam.send(new UpdateFunctionCodeCommand({
FunctionName: "my-func",
ZipFile: readFileSync("function.zip"),
Publish: true, // also cut an immutable version
}));ZipFile takes the raw bytes of the package; for large artifacts pass S3Bucket/S3Key instead.Publish: true publishes a new numbered version from the updated code in one step.ImageUri rather than ZipFile.Pending while the new code is deployed.Related: Versions, Aliases & Traffic Shifting - what
Publish: truegives you and how to route to it.
Ask Lambda to return the last chunk of logs and check whether the function itself failed.
# --- Python (boto3) ---
import boto3, base64, json
lam = boto3.client("lambda")
resp = lam.invoke(
FunctionName="my-func",
InvocationType="RequestResponse",
LogType="Tail", # include last 4 KB of logs
Payload=json.dumps({"name": "Ada"}).encode(),
)
if "FunctionError" in resp:
print("handler failed:", resp["FunctionError"])
print(base64.b64decode(resp["LogResult"]).decode())// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const lam = new LambdaClient({});
const resp = await lam.send(new InvokeCommand({
FunctionName: "my-func",
InvocationType: "RequestResponse",
LogType: "Tail", // include last 4 KB of logs
Payload: new TextEncoder().encode(JSON.stringify({ name: "Ada" })),
}));
if (resp.FunctionError) console.log("handler failed:", resp.FunctionError);
console.log(Buffer.from(resp.LogResult ?? "", "base64").toString());LogType: "Tail" returns LogResult, base64-encoded, holding the last 4 KB of logs.FunctionError is set (Unhandled or Handled) when the handler throws - even though the HTTP call itself succeeded.200 status with a FunctionError is a successful invoke of a failing function - check both.LogType only applies to synchronous invokes.Config and code updates are eventually consistent; wait for Active/Successful before the next step.
# --- Python (boto3) ---
import boto3
lam = boto3.client("lambda")
lam.update_function_configuration(FunctionName="my-func", MemorySize=1024)
waiter = lam.get_waiter("function_updated_v2")
waiter.wait(FunctionName="my-func") # returns when LastUpdateStatus is Successful
print("update applied")// --- TypeScript (AWS SDK v3) ---
import {
LambdaClient,
UpdateFunctionConfigurationCommand,
waitUntilFunctionUpdatedV2,
} from "@aws-sdk/client-lambda";
const lam = new LambdaClient({});
await lam.send(new UpdateFunctionConfigurationCommand({ FunctionName: "my-func", MemorySize: 1024 }));
const r = await waitUntilFunctionUpdatedV2({ client: lam, maxWaitTime: 120 }, { FunctionName: "my-func" });
if (r.state !== "SUCCESS") throw new Error(`update not applied: ${r.state}`);
console.log("update applied");function_updated_v2 waiter polls GetFunctionConfiguration until LastUpdateStatus is Successful.ResourceConflictException.waitUntilFunctionUpdatedV2 returns a state object; branch on SUCCESS instead of catching.function_active_v2 / waitUntilFunctionActiveV2 for newly created functions.200. An asynchronous (Event) invoke returns 202, and a DryRun returns 204. The status reflects the invoke itself, not whether your handler logic succeeded.
Check for FunctionError in the response. If present (Unhandled or Handled), the handler failed even though the HTTP call returned 200. The payload then holds the error object.
The SDKs return the raw response body. boto3 gives a streaming body you .read(); SDK v3 gives a Uint8Array you decode with TextDecoder. Then json.loads / JSON.parse it.
Set LogType: "Tail" on a synchronous invoke to get the last 4 KB in LogResult, base64-encoded. For full history, read the function's CloudWatch Logs group.
Only the fields you pass, but structured fields like Environment.Variables are replaced wholesale. Merge in the keys you want to keep before sending.
Yes. Pass Publish: true to update_function_code, and Lambda publishes a new immutable version from the new code without a separate PublishVersion call.
The previous change is still applying. Wait with the function_updated_v2 waiter until LastUpdateStatus is Successful, then issue the next update.
Timeout is up to 900 seconds (15 minutes). Memory ranges from 128 MB to 10,240 MB, and CPU scales with it.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 23 jul 2026