Lambda via SDK Best Practices
These are the defaults every Lambda integration should set explicitly, not leave to chance.
Busque em todas as páginas da documentação
These are the defaults every Lambda integration should set explicitly, not leave to chance.
Walk the list once now, then use it as a review checklist before shipping code that deploys, invokes, triggers, or tunes a function via the SDK.
$LATEST. Publish an immutable version and point an alias (prod) at it; $LATEST changes the instant you touch the draft.Publish: true to update_function_code so the version snapshots the exact code you shipped, with no race.function_updated_v2 waiter until LastUpdateStatus is Successful; back-to-back updates raise ResourceConflictException.RoutingConfig.AdditionalVersionWeights, watch per-version metrics, then promote.Publish and route through an alias, not the mutable draft.
# --- Python (boto3) ---
import boto3
lam = boto3.client("lambda")
with open("function.zip", "rb") as f:
v = lam.update_function_code(FunctionName="my-func", ZipFile=f.read(), Publish=True)["Version"]
lam.update_alias(FunctionName="my-func", Name="prod", FunctionVersion=v)// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, UpdateFunctionCodeCommand, UpdateAliasCommand } from "@aws-sdk/client-lambda";
import { readFileSync } from "node:fs";
const lam = new LambdaClient({});
const { Version } = await lam.send(new UpdateFunctionCodeCommand({
FunctionName: "my-func", ZipFile: readFileSync("function.zip"), Publish: true,
}));
await lam.send(new UpdateAliasCommand({ FunctionName: "my-func", Name: "prod", FunctionVersion: Version! }));MemorySize also scales CPU, so more memory can be both faster and cheaper per invoke - measure it.Timeout to the work; do not leave a long default that hides hangs (max 900 seconds).RequestResponse when you need the result; Event for fire-and-forget with Lambda-managed retries.FunctionError on sync invokes. A 200 with FunctionError set is a failed handler - inspect the payload..read()); SDK v3 returns a Uint8Array (TextDecoder).Invoke from AWS callers, URLs from HTTP callers. Do not wrap the SDK just to hit a Function URL, and do not expose Invoke to non-AWS clients.Distinguish a failed call from a failed handler.
# --- Python (boto3) ---
resp = lam.invoke(FunctionName="my-func:prod", InvocationType="RequestResponse", Payload=b"{}")
if "FunctionError" in resp:
raise RuntimeError(resp["Payload"].read().decode())// --- TypeScript (AWS SDK v3) ---
import { InvokeCommand } from "@aws-sdk/client-lambda";
const resp = await lam.send(new InvokeCommand({ FunctionName: "my-func:prod", Payload: new TextEncoder().encode("{}") }));
if (resp.FunctionError) throw new Error(new TextDecoder().decode(resp.Payload));FunctionResponseTypes: ["ReportBatchItemFailures"] on stream/queue mappings so only failed records retry.BisectBatchOnFunctionError, a retry/age limit, and an OnFailure destination so one record cannot stall a shard.BatchSize and MaximumBatchingWindowInSeconds.PutFunctionConcurrency to guarantee capacity or cap a runaway function within the account limit.PutProvisionedConcurrencyConfig, sized to baseline, and poll until READY.AuthType. A NONE URL needs an AddPermission with FunctionUrlAuthType="NONE"; keep the two in sync.AWS_IAM for Function URLs. Use NONE only for genuinely public endpoints, and authenticate inside the handler.Principal and SourceArn rather than allowing *.GetFunctionConfiguration.LogType: "Tail" on synchronous invokes and base64-decode LogResult for the last 4 KB.TracingConfig to see downstream latency.ResponseMetadata.RequestId (boto3) / $metadata.requestId (SDK v3) for support and tracing.Do not point production at $LATEST. Publish an immutable version and route a prod alias to it, so callers get a fixed snapshot and rollback is one UpdateAlias away.
Config and code changes are eventually consistent. Issuing another update before the last one finishes raises ResourceConflictException. Use the function_updated_v2 waiter until LastUpdateStatus is Successful.
Deliberately, by measuring. MemorySize also sets CPU, so raising it often lowers duration - and sometimes total cost. Do not leave the default; test a few sizes against real load.
The HTTP status covers the invoke; FunctionError covers your code. A 200 response with FunctionError set means the handler threw. Always check both on synchronous invokes.
Partial-batch failure reporting (ReportBatchItemFailures). Without it, one failed record retries the whole batch and reprocesses records that already succeeded.
Reserve concurrency to guarantee or cap how many environments a function may use. Provision concurrency to pre-warm environments for a latency-critical path. They solve different problems and combine.
Prefer AWS_IAM. If you must use NONE, add the matching public permission, authenticate inside the handler, and remove the public statement the moment you tighten auth.
Outside the handler, at init time. Clients, connections, and config loaded there are reused by warm invocations, so you pay the cost once per environment rather than per request.
Size provisioned concurrency to your baseline and use Application Auto Scaling to raise it at peak and lower it off-peak. Delete the config when a function no longer needs warm capacity.
Environment variables are returned in plaintext by GetFunctionConfiguration to anyone with read access. Reference Secrets Manager or SSM Parameter Store and fetch at runtime instead.
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 atualização: 23 de jul. de 2026