Applying Lambda Best Practices for Performance, Reliability and Security
This lesson brings together the Lambda best practices that appear again and again in exam scenarios. Each one addresses a specific performance, cost, reliability or security problem.
Learning outcomes
After completing this lesson, you will be able to:
- Explain why initialisation work belongs outside the handler.
- Explain why configuration and secrets are stored outside the deployment package.
- Identify the retry, timeout and failure-handling settings that make a function reliable.
- Recognise the causes of recursive invocation loops and how Lambda detects them.
Code structure and performance
Lambda runs each function in an execution environment that is created when needed and then reused for many invocations. Code outside the handler runs once, during the initialisation (Init) phase of a new environment, while the handler runs for every invocation. Creating SDK clients, database connections and loaded configuration outside the handler therefore means that every later invocation in that environment reuses them, which removes repeated set-up time from most requests.
The size and structure of a function also affect its performance. Smaller deployment packages load faster during Init, so a function should include only the libraries it needs and import specific SDK clients rather than entire frameworks. Keeping each function focused on one task keeps it small and lets its execution role grant only the permissions that task requires.
Memory and timeout should be chosen deliberately rather than left at the defaults of 128 MB and three seconds. Lambda allocates CPU in proportion to memory, so more memory often makes a function finish so much faster that it costs no more; the open-source Lambda Power Tuning tool measures this trade-off. Running on the arm64 architecture, which uses AWS Graviton processors, gives better price performance for most workloads that do not depend on x86-only libraries.
Performance habits
Configuration and secrets
A function's code should be the same in every environment, so that the artifact tested is the artifact released. Values that differ between environments, such as table names, API endpoints and feature flags, are supplied from outside: through environment variables, AWS Systems Manager Parameter Store or AWS AppConfig.
Secrets, such as database passwords and API keys, need more protection. They belong in AWS Secrets Manager or in Parameter Store SecureString parameters, never in code or in plain-text environment variables, which anyone who can view the function's configuration can read. Because fetching a secret on every invocation adds latency and cost, the function should cache it, for example with the AWS Parameters and Secrets Lambda Extension or Powertools, and refresh it periodically so that rotated values are picked up.
Each function should also have its own execution role with only the permissions it needs, rather than sharing one broad role between many functions. A narrow role limits what an attacker could do if the function were compromised.
Reliability
Reliable functions are designed on the assumption that events can be repeated, can fail and can arrive in bursts. Because every invocation model can deliver an event more than once, handlers must be idempotent, as the lesson Making Functions Idempotent to Handle Duplicate Events explains. Failed events must not be lost silently: asynchronous invocations should have an on-failure destination or a dead-letter queue, and functions that process SQS or stream batches should report partial batch failures so that only the failed records are retried.
Lambda can scale much faster than the systems it calls. A sudden burst of thousands of concurrent invocations can exhaust a relational database's connections or a third-party API's rate limit. Reserved concurrency caps how many copies of a function run at once, RDS Proxy pools database connections, and an SQS queue between producers and the function absorbs bursts so they are processed at a steady rate.
Finally, an execution environment can be discarded at any time, so its memory and its /tmp directory are caches, not storage. Anything that must persist between invocations belongs in a service such as DynamoDB or Amazon S3.
Which practice fixes it?
Avoiding recursive loops
A function that writes to the resource that triggers it, such as an S3 bucket or SQS queue, can invoke itself without end and generate large bills. Lambda's recursive loop detection stops some loops involving SQS, SNS, S3 and Lambda after about 16 iterations, but the design should prevent them: write output to a different bucket or prefix, and filter triggers by prefix or suffix.
A thumbnail function that breaks the rules
Reviewing a function before release
A reviewer checks a new image-processing function against the best practices before it is released:
| Finding | Change |
|---|---|
| The S3 client is created inside the handler | Move it to initialisation code |
Thumbnails are written back to the uploads/ prefix that triggers the function | Write them to thumbnails/ to prevent a recursive loop |
| Memory is the 128 MB default and the timeout 3 seconds | Measure with Power Tuning; settle on 1,024 MB and 30 seconds |
| Failed events are not captured | Add an on-failure destination |
The role has s3:* on all buckets | Limit it to GetObject on uploads/* and PutObject on thumbnails/* |
Each change addresses a different risk: latency, runaway cost, timeouts, lost events and excessive permissions.
Why should SDK clients and database connections be created outside the handler function?
Show answer
Code outside the handler runs once, when the execution environment initialises. Warm invocations then reuse the client or connection instead of creating it for every request, which reduces latency and cost.
Exam Tips
Remember for the exam
- Initialise clients and connections outside the handler to speed up warm invocations.
- Break an infinite S3-trigger loop by writing output to a different bucket or prefix.
- Set memory and timeout deliberately rather than relying on the defaults.
- Every Lambda handler should be idempotent.