AWS Lambda Interview Questions and Answers
Learn AWS Lambda with production-ready interview questions covering Lambda architecture, triggers, execution environments, cold starts, concurrency, retries, permissions, VPC access, monitoring, deployment, pricing, and best practices.
Module Navigation
Previous: Serverless Basics QA | Parent: Serverless Learning Path | Next: Azure Functions QA
Introduction
AWS Lambda is a serverless compute service that runs application code in response to events without requiring developers to provision or manage servers.
Developers upload code, configure an event source, assign permissions, and define runtime settings. AWS Lambda manages the underlying infrastructure, operating system, execution environment, scaling, availability, and much of the operational lifecycle.
Lambda is commonly used for:
- REST APIs
- File processing
- Event-driven applications
- Scheduled jobs
- Queue consumers
- Stream processing
- Notifications
- Infrastructure automation
- Security remediation
- Lightweight microservices
Lambda works especially well with other AWS services such as Amazon API Gateway, Amazon S3, Amazon SQS, Amazon SNS, Amazon EventBridge, Amazon DynamoDB, Amazon Kinesis, and AWS Step Functions.
What Is AWS Lambda?
AWS Lambda is an event-driven compute service that executes code when a configured event occurs.
Examples of Lambda triggers include:
- HTTP request through API Gateway
- Object upload to Amazon S3
- Message arrival in Amazon SQS
- Event published to Amazon EventBridge
- Record added to a DynamoDB stream
- Event received from Amazon Kinesis
- Notification published to Amazon SNS
- Scheduled EventBridge rule
- Direct SDK invocation
- Application Load Balancer request
The function runs only when invoked and scales automatically based on workload demand.
Basic AWS Lambda Architecture
flowchart LR
Client[Client Application] --> APIGateway[Amazon API Gateway]
APIGateway --> Lambda[AWS Lambda]
Lambda --> DynamoDB[(Amazon DynamoDB)]
Lambda --> S3[(Amazon S3)]
Lambda --> SQS[Amazon SQS]
Lambda --> SNS[Amazon SNS]
Lambda --> CloudWatch[Amazon CloudWatch]
AWS Lambda Request Flow
sequenceDiagram
participant User
participant API as API Gateway
participant Lambda as AWS Lambda
participant DB as DynamoDB
participant Logs as CloudWatch Logs
User->>API: Send HTTP request
API->>Lambda: Invoke function
Lambda->>DB: Read or update item
DB-->>Lambda: Return result
Lambda->>Logs: Write logs and metrics
Lambda-->>API: Return response
API-->>User: HTTP response
Core AWS Lambda Components
| Component | Description |
|---|---|
| Function | Deployed application code |
| Runtime | Language execution environment |
| Handler | Entry method called by Lambda |
| Trigger | AWS service or event that invokes the function |
| Execution role | IAM role used by the function |
| Event source mapping | Polling configuration for queues and streams |
| Layer | Reusable dependencies or shared code |
| Version | Immutable snapshot of function configuration and code |
| Alias | Named pointer to a Lambda version |
| Destination | Target for asynchronous invocation results |
| Dead-letter queue | Stores failed asynchronous events |
Supported Runtime Model
AWS Lambda supports managed runtimes for popular programming languages and custom runtimes for other technologies.
Common runtime categories include:
- Java
- Python
- Node.js
- .NET
- Go
- Ruby
- Custom runtime
- Container image deployment
The selected runtime influences:
- Startup time
- Memory usage
- Deployment package size
- Framework compatibility
- Cold-start performance
- Maintenance strategy
Lambda Handler
The handler is the entry point AWS Lambda calls when a function is invoked.
A handler generally receives:
- Event data
- Runtime context
- Metadata about the invocation
Example Java handler:
package com.codewithvenu.lambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import java.util.Map;
public class GreetingHandler
implements RequestHandler<Map<String, String>, Map<String, String>> {
@Override
public Map<String, String> handleRequest(
Map<String, String> event,
Context context) {
String name = event.getOrDefault("name", "Guest");
context.getLogger().log("Processing request for: " + name);
return Map.of(
"message", "Hello, " + name,
"requestId", context.getAwsRequestId()
);
}
}
The handler should remain focused and delegate complex business logic to reusable service classes.
Lambda Execution Environment
When a function is invoked, Lambda runs it inside an isolated execution environment.
A simplified lifecycle is:
flowchart LR
Request[Invocation Request] --> Create{Environment Available?}
Create -->|No| Initialize[Create Execution Environment]
Create -->|Yes| Reuse[Reuse Existing Environment]
Initialize --> InitCode[Run Initialization Code]
InitCode --> Handler[Invoke Handler]
Reuse --> Handler
Handler --> Response[Return Result]
Response --> Freeze[Freeze Environment]
The environment may be reused for future invocations.
This means resources initialized outside the handler may be reused, including:
- SDK clients
- HTTP clients
- Database connection pools
- Configuration values
- Cached metadata
However, applications must not assume that the environment will always be reused.
Initialization Phase and Invocation Phase
Initialization Phase
During initialization, Lambda:
- Starts the runtime
- Loads function code
- Loads dependencies
- Runs static initialization
- Initializes framework components
- Creates resources declared outside the handler
Invocation Phase
During invocation, Lambda:
- Passes the event to the handler
- Executes business logic
- Returns the result
- Captures logs and metrics
Initialization work should be minimized because it directly affects cold-start latency.
Cold Start and Warm Start
Cold Start
A cold start occurs when Lambda must create a new execution environment.
Cold-start latency may include:
- Runtime startup
- Code download
- Dependency loading
- Framework initialization
- Network-interface initialization
- Application startup logic
Warm Start
A warm start occurs when Lambda reuses an initialized environment.
flowchart TD
Event[Incoming Event] --> Check{Warm Environment?}
Check -->|Yes| Invoke[Invoke Handler]
Check -->|No| Start[Start Runtime]
Start --> Load[Load Code and Dependencies]
Load --> Init[Run Initialization]
Init --> Invoke
Invoke --> Result[Return Result]
Reducing Lambda Cold Starts
Cold-start impact can be reduced by:
- Reducing deployment-package size
- Removing unused dependencies
- Selecting an efficient runtime
- Avoiding heavy initialization
- Reusing clients outside the handler
- Reducing framework startup overhead
- Allocating appropriate memory
- Using provisioned concurrency for latency-sensitive workloads
- Avoiding unnecessary VPC dependencies
- Using optimized Java deployment approaches
For Java workloads, developers may consider:
- Lightweight frameworks
- Lazy initialization
- Ahead-of-time compilation
- Smaller dependency graphs
- Provisioned concurrency
- SnapStart where supported and suitable
Lambda Invocation Types
AWS Lambda supports different invocation models.
| Invocation Type | Behavior | Typical Use |
|---|---|---|
| Synchronous | Caller waits for response | API Gateway, direct invocation |
| Asynchronous | Event is queued and processed later | S3, SNS, EventBridge |
| Poll-based | Lambda polls an event source | SQS, Kinesis, DynamoDB Streams |
Synchronous Invocation
In synchronous invocation, the calling service waits for Lambda to return a response.
sequenceDiagram
participant Client
participant API
participant Lambda
Client->>API: Request
API->>Lambda: Synchronous invoke
Lambda-->>API: Response
API-->>Client: Response
The caller usually handles failures and retry behavior.
Common synchronous sources include:
- API Gateway
- Application Load Balancer
- Lambda Function URL
- Direct SDK invocation
Asynchronous Invocation
In asynchronous invocation, Lambda accepts the event and processes it later.
flowchart LR
Producer[Event Producer] --> Queue[Lambda Internal Event Queue]
Queue --> Function[Lambda Function]
Function --> Success[Success Destination]
Function --> Failure[Failure Destination or DLQ]
The Lambda service manages retry behavior.
Common asynchronous event sources include:
- Amazon S3
- Amazon SNS
- Amazon EventBridge
Because retries may occur, functions should be idempotent.
Poll-Based Invocation
For certain event sources, Lambda uses event source mappings to poll for records.
Common poll-based sources include:
- Amazon SQS
- Amazon Kinesis Data Streams
- Amazon DynamoDB Streams
- Amazon Managed Streaming for Apache Kafka
- Self-managed Apache Kafka
flowchart LR
Queue[Amazon SQS] --> Mapping[Event Source Mapping]
Mapping --> Lambda[Lambda Function]
Lambda --> Database[(Database)]
Lambda --> DLQ[Dead-Letter Queue]
Lambda reads batches of records and invokes the function with those records.
Event Source Mapping
An event source mapping connects Lambda to a polling-based source.
Configuration may include:
- Batch size
- Maximum batching window
- Concurrency controls
- Starting position
- Retry behavior
- Failure handling
- Record filtering
- Partial batch responses
The event source mapping is managed independently from the Lambda function code.
AWS Lambda Concurrency
Concurrency is the number of Lambda invocations running at the same time.
If ten requests are executing simultaneously, the function is using approximately ten concurrent executions.
flowchart LR
Events[Incoming Events] --> LambdaService[Lambda Service]
LambdaService --> F1[Execution 1]
LambdaService --> F2[Execution 2]
LambdaService --> F3[Execution 3]
LambdaService --> FN[Execution N]
Concurrency affects:
- Scaling
- Throttling
- Database connections
- Downstream capacity
- Cost
- Latency
Types of Lambda Concurrency
Unreserved Concurrency
The function uses concurrency from the account's shared regional pool.
Reserved Concurrency
Reserved concurrency:
- Reserves capacity for a function
- Limits the maximum concurrency of that function
- Protects other functions from resource exhaustion
- Can intentionally throttle a function
Provisioned Concurrency
Provisioned concurrency keeps a configured number of environments initialized and ready.
It is useful for:
- Latency-sensitive APIs
- Java applications
- Predictable traffic
- Critical production workloads
It increases cost because initialized capacity remains allocated.
Concurrency Protection Architecture
flowchart LR
Producers[Multiple Producers] --> SQS[Amazon SQS]
SQS --> Mapping[Event Source Mapping]
Mapping --> Lambda[AWS Lambda]
Lambda --> Database[(Relational Database)]
Control[Reserved or Maximum Concurrency] --> Lambda
Using queues and concurrency limits prevents Lambda from overwhelming downstream systems.
Lambda Scaling Considerations
Lambda can scale quickly, but dependent systems may not.
Potential downstream bottlenecks include:
- Relational databases
- Third-party APIs
- Legacy mainframes
- File systems
- External payment systems
- Rate-limited services
Protection strategies include:
- Reserved concurrency
- Event-source maximum concurrency
- Amazon SQS buffering
- Rate limiting
- Circuit breakers
- Exponential backoff
- Amazon RDS Proxy
- Batch processing
Lambda Memory and CPU
Lambda allows developers to configure memory for a function.
CPU, network, and other resources generally increase with memory allocation.
Increasing memory can:
- Reduce execution time
- Improve framework startup
- Improve CPU-intensive processing
- Reduce cold-start duration
- Sometimes reduce total cost by shortening execution
The cheapest memory setting is not always the most cost-effective setting.
Performance testing should determine the optimal balance.
Lambda Timeout
Each Lambda function has a configured execution timeout.
The function is terminated if processing exceeds that limit.
Timeouts should be configured based on:
- Expected processing time
- External API latency
- Database operations
- Retry strategy
- User-facing response requirements
- Upstream timeout limits
For long-running processes, consider:
- AWS Step Functions
- AWS Fargate
- AWS Batch
- Amazon ECS
- Amazon EKS
Lambda Environment Variables
Environment variables store runtime configuration such as:
- Environment name
- Feature flags
- Table names
- Queue URLs
- Log levels
- Service endpoints
Sensitive values should not be stored as plain environment variables when dedicated secret-management services are more appropriate.
Use:
- AWS Secrets Manager
- AWS Systems Manager Parameter Store
- AWS KMS encryption
- IAM-based access
AWS Lambda Layers
A Lambda layer is a package containing shared libraries, dependencies, runtime components, or common code.
Layers can be used for:
- Shared utility libraries
- Logging libraries
- Security libraries
- Custom runtimes
- Monitoring agents
- Common SDK components
flowchart LR
Layer[Shared Lambda Layer] --> FunctionA[Function A]
Layer --> FunctionB[Function B]
Layer --> FunctionC[Function C]
Layers reduce duplication, but excessive shared layers can make dependency management harder.
Lambda Versions and Aliases
Version
A version is an immutable snapshot of:
- Function code
- Configuration
- Dependencies
- Runtime settings
Alias
An alias is a named pointer to a Lambda version.
Examples:
devteststageprod
flowchart LR
Alias[Production Alias] --> V1[Version 1]
Alias --> V2[Version 2]
Aliases support controlled traffic shifting between versions.
Lambda Deployment Strategies
Common deployment strategies include:
- All-at-once deployment
- Canary deployment
- Linear deployment
- Blue-green deployment
- Alias-based weighted routing
Example canary deployment:
flowchart LR
Users[Incoming Traffic] --> Alias[Production Alias]
Alias -->|90 Percent| V1[Version 1]
Alias -->|10 Percent| V2[Version 2]
If the new version is stable, traffic is gradually shifted to it.
AWS Lambda Permissions
Lambda uses two major permission models.
Execution Role
The execution role defines what the Lambda function can access.
Examples:
- Read an S3 object
- Write to DynamoDB
- Publish to SNS
- Read a secret
- Send a message to SQS
Resource-Based Policy
A resource-based policy defines who or what can invoke the Lambda function.
Examples:
- API Gateway
- Amazon S3
- Amazon SNS
- Another AWS account
Lambda Security Architecture
flowchart LR
Trigger[Event Source] --> Policy[Resource-Based Policy]
Policy --> Lambda[AWS Lambda]
Lambda --> Role[IAM Execution Role]
Role --> DynamoDB[(DynamoDB)]
Role --> S3[(S3)]
Role --> Secrets[Secrets Manager]
The function should receive only the minimum permissions required.
Lambda Inside a VPC
Lambda can connect to resources inside an Amazon VPC.
Common use cases include access to:
- Amazon RDS
- Amazon ElastiCache
- Private EC2 services
- Internal load balancers
- Private endpoints
- On-premises systems through VPN or Direct Connect
flowchart LR
Lambda[AWS Lambda] --> PrivateSubnet[Private Subnet]
PrivateSubnet --> RDS[(Amazon RDS)]
PrivateSubnet --> Cache[(ElastiCache)]
PrivateSubnet --> InternalAPI[Internal API]
VPC-enabled functions require correct:
- Subnet configuration
- Security groups
- Route tables
- NAT access where required
- VPC endpoints
- DNS settings
Internet Access from a VPC-Connected Lambda
Connecting Lambda to a public subnet does not automatically provide public internet access.
A typical private architecture uses:
flowchart LR
Lambda[AWS Lambda] --> PrivateSubnet[Private Subnet]
PrivateSubnet --> NAT[NAT Gateway]
NAT --> Internet[Internet]
PrivateSubnet --> Endpoint[VPC Endpoint]
Endpoint --> AWSService[AWS Service]
VPC endpoints should be used where practical to access AWS services privately and reduce dependency on NAT gateways.
Lambda and Relational Databases
Lambda can rapidly create many concurrent database connections.
This may overwhelm relational databases.
Recommended patterns include:
- Reuse connections across warm invocations
- Limit function concurrency
- Use Amazon RDS Proxy
- Use connection pooling carefully
- Buffer requests through SQS
- Use shorter transactions
- Monitor connection count
- Avoid creating a new connection per record
flowchart LR
Lambda1[Lambda Instance 1] --> Proxy[Amazon RDS Proxy]
Lambda2[Lambda Instance 2] --> Proxy
Lambda3[Lambda Instance 3] --> Proxy
Proxy --> RDS[(Amazon RDS)]
Lambda Error Handling
Error handling depends on the invocation type.
Synchronous
The caller receives the error and typically decides whether to retry.
Asynchronous
Lambda retries failed events according to service behavior and configuration. Failed events can be sent to:
- Dead-letter queue
- Failure destination
- Amazon SQS
- Amazon SNS
- EventBridge
Stream-Based
Failed records can block progress if not handled correctly.
Possible strategies include:
- Bisecting batches
- Limiting retry attempts
- Setting maximum record age
- Using failure destinations
- Applying partial batch failure handling
Retry and Failure Flow
flowchart TD
Event[Incoming Event] --> Lambda[Lambda Invocation]
Lambda --> Success{Successful?}
Success -->|Yes| Complete[Complete]
Success -->|No| Retry[Retry]
Retry --> Limit{Retry Limit Reached?}
Limit -->|No| Lambda
Limit -->|Yes| Failure[Failure Destination or DLQ]
Failure --> Alert[Alert Operations Team]
Failure --> Replay[Investigate and Replay]
Dead-Letter Queues vs Destinations
| Dead-Letter Queue | Lambda Destination |
|---|---|
| Stores failed asynchronous events | Routes successful or failed invocation records |
| Common targets are SQS or SNS | Targets include SQS, SNS, Lambda, and EventBridge |
| Contains original event | Includes invocation context and result details |
| Primarily for failure handling | Supports success and failure workflows |
Idempotency
Lambda functions should be idempotent because the same event may be delivered more than once.
An idempotent operation safely handles duplicate events without creating duplicate business outcomes.
Example:
flowchart LR
Event[Order Event with Event ID] --> Lambda[Order Lambda]
Lambda --> Check{Event Already Processed?}
Check -->|Yes| Return[Return Existing Result]
Check -->|No| Process[Process Order]
Process --> Store[Store Event ID and Result]
Common idempotency techniques include:
- Unique event IDs
- DynamoDB conditional writes
- Idempotency tables
- Database uniqueness constraints
- Request tokens
- Transactional state updates
Lambda Logging and Monitoring
AWS Lambda integrates with Amazon CloudWatch.
Common monitoring data includes:
- Invocation count
- Duration
- Error count
- Throttles
- Concurrent executions
- Iterator age
- Dead-letter queue messages
- Provisioned concurrency usage
- Initialization duration
Important Lambda Metrics
| Metric | Purpose |
|---|---|
| Invocations | Total function executions |
| Duration | Function execution time |
| Errors | Failed executions |
| Throttles | Invocations rejected due to concurrency limits |
| ConcurrentExecutions | Current parallel executions |
| IteratorAge | Delay when processing stream records |
| DeadLetterErrors | Failures while sending to a DLQ |
| ProvisionedConcurrencySpilloverInvocations | Requests that exceeded provisioned capacity |
| Init Duration | Time spent initializing a new environment |
Distributed Tracing
AWS X-Ray or compatible observability platforms can trace a request across:
- API Gateway
- Lambda
- DynamoDB
- SQS
- SNS
- Other AWS services
flowchart LR
Client --> APIGateway
APIGateway --> Lambda
Lambda --> DynamoDB
Lambda --> SQS
APIGateway --> Trace[Distributed Trace]
Lambda --> Trace
DynamoDB --> Trace
SQS --> Trace
Correlation IDs should be propagated across service boundaries.
Lambda Function URLs
A Lambda Function URL provides a dedicated HTTP endpoint for a Lambda function.
It can be useful for:
- Simple webhooks
- Internal HTTP services
- Lightweight APIs
- Prototypes
API Gateway may be preferred when advanced capabilities are needed, such as:
- Request transformation
- Usage plans
- API keys
- Complex authorization
- Rate limiting
- API lifecycle management
- Multiple routes
- Detailed gateway policies
Lambda Packaging Options
AWS Lambda supports:
ZIP Deployment Package
Contains function code and dependencies.
Best for:
- Smaller applications
- Standard runtimes
- Fast deployments
Container Image
Packages the function as a container image.
Best for:
- Larger dependencies
- Custom runtimes
- Existing container workflows
- Specialized native libraries
Lambda container images still run within the Lambda execution model. They are not equivalent to continuously running ECS containers.
Lambda Pricing Considerations
Lambda cost commonly depends on:
- Number of requests
- Execution duration
- Memory allocation
- Provisioned concurrency
- Ephemeral storage configuration
- Data transfer
- Connected AWS services
- Logging and tracing
The full architecture cost may also include:
- API Gateway
- CloudWatch Logs
- SQS
- SNS
- DynamoDB
- EventBridge
- NAT Gateway
- RDS Proxy
- Step Functions
Serverless cost evaluation should consider the entire request flow.
Production Use Case: Order Processing
A retail application receives customer orders through API Gateway.
flowchart TB
Client[Web or Mobile Client] --> API[Amazon API Gateway]
API --> OrderLambda[Order Lambda]
OrderLambda --> Orders[(DynamoDB Orders Table)]
OrderLambda --> Queue[Amazon SQS]
Queue --> PaymentLambda[Payment Lambda]
PaymentLambda --> PaymentAPI[Payment Provider]
PaymentLambda --> EventBridge[Amazon EventBridge]
EventBridge --> InventoryLambda[Inventory Lambda]
EventBridge --> NotificationLambda[Notification Lambda]
NotificationLambda --> SNS[Amazon SNS]
Queue --> DLQ[Dead-Letter Queue]
OrderLambda --> CloudWatch[CloudWatch]
PaymentLambda --> CloudWatch
InventoryLambda --> CloudWatch
Processing Flow
- Customer submits an order.
- API Gateway validates and forwards the request.
- Order Lambda validates the payload.
- Order data is stored in DynamoDB.
- A message is sent to SQS.
- Payment Lambda processes the queued order.
- Successful payment publishes an EventBridge event.
- Inventory and notification functions process the event independently.
- Failures are sent to a dead-letter queue.
- Logs, metrics, alarms, and traces are collected.
Interview Questions and Answers
1. What is AWS Lambda?
Answer
AWS Lambda is a serverless compute service that runs code in response to events without requiring developers to provision or manage servers.
AWS manages:
- Infrastructure
- Runtime execution
- Scaling
- Availability
- Operating-system maintenance
- Execution-environment lifecycle
Developers manage application code, permissions, configuration, data, monitoring, and error handling.
2. How does AWS Lambda work internally?
Answer
When an event invokes a function:
- Lambda receives the event.
- It checks for an available execution environment.
- If none exists, Lambda creates a new environment.
- The runtime and code are initialized.
- The handler receives the event.
- The function processes the request.
- The result is returned or passed to another service.
- Logs and metrics are generated.
- The environment may be frozen and reused.
Multiple environments are created when concurrency increases.
3. What is the difference between synchronous and asynchronous Lambda invocation?
Answer
In synchronous invocation, the caller waits for the function response.
Examples:
- API Gateway
- Application Load Balancer
- Direct SDK invocation
In asynchronous invocation, the event is accepted and processed later.
Examples:
- Amazon S3
- Amazon SNS
- Amazon EventBridge
Asynchronous invocations may be retried automatically, so handlers should be idempotent.
4. What is a Lambda cold start?
Answer
A cold start occurs when Lambda creates a new execution environment before invoking the handler.
Cold-start time can include:
- Starting the runtime
- Loading code
- Loading dependencies
- Initializing frameworks
- Establishing network resources
- Running application initialization
Cold starts can be reduced through smaller packages, efficient runtimes, lighter frameworks, optimized initialization, appropriate memory, and provisioned concurrency.
5. What is the difference between reserved concurrency and provisioned concurrency?
Answer
Reserved concurrency controls how many concurrent executions a function can use and reserves that amount from the account pool.
Provisioned concurrency keeps a specified number of execution environments initialized and ready to reduce cold-start latency.
| Reserved Concurrency | Provisioned Concurrency |
|---|---|
| Controls maximum concurrency | Pre-initializes execution environments |
| Protects downstream systems | Reduces startup latency |
| Reserves account capacity | Adds additional cost |
| Can intentionally throttle | Supports latency-sensitive workloads |
6. How does Lambda process SQS messages?
Answer
Lambda uses an event source mapping to poll Amazon SQS.
The process is:
- Lambda polls the queue.
- It retrieves a batch of messages.
- The batch is passed to the function.
- On successful processing, messages are removed.
- On failure, messages become visible again after the visibility timeout.
- After repeated failures, messages may be moved to a dead-letter queue.
Functions should support idempotency and partial batch failure handling where appropriate.
7. How do you secure an AWS Lambda function?
Answer
A Lambda function should be secured using:
- Least-privilege execution roles
- Resource-based invocation policies
- Input validation
- Secrets Manager or Parameter Store
- Encryption at rest and in transit
- Private networking where required
- Dependency scanning
- CloudTrail audit logging
- CloudWatch monitoring
- Reserved concurrency
- API authentication and authorization
Each function should have only the permissions needed for its responsibility.
8. How do you connect Lambda to a relational database safely?
Answer
Recommended practices include:
- Reuse connections across warm invocations
- Use Amazon RDS Proxy
- Limit Lambda concurrency
- Avoid opening a connection for every record
- Configure appropriate timeouts
- Use short transactions
- Monitor database connections
- Buffer traffic through SQS
- Store credentials in Secrets Manager
Without controls, Lambda scaling can exhaust database connections.
9. How do you handle Lambda failures?
Answer
Failure handling depends on the invocation model.
Recommended controls include:
- Retry policies
- Exponential backoff
- Dead-letter queues
- Lambda destinations
- CloudWatch alarms
- Idempotent processing
- Partial batch responses
- Maximum event age
- Replay procedures
- Correlation IDs
Failures should be observable, recoverable, and safe to retry.
10. When should AWS Lambda not be used?
Answer
Lambda may not be the best choice for:
- Long-running workloads
- Applications requiring persistent processes
- Specialized operating-system access
- Large in-memory applications
- Constant high-utilization workloads
- Highly customized networking
- Workloads exceeding Lambda execution limits
- Applications requiring stable local state
- Extremely latency-sensitive workloads without acceptable mitigation
Containers, ECS, EKS, Fargate, EC2, or AWS Batch may be better alternatives.
Common Interview Follow-Up Questions
- What is Lambda provisioned concurrency?
- What is Lambda SnapStart?
- How does Lambda scale?
- What is an event source mapping?
- How do partial batch responses work with SQS?
- What is the difference between a DLQ and a Lambda destination?
- How do Lambda layers work?
- What is the difference between a version and an alias?
- How do you perform canary deployment with Lambda?
- How do you troubleshoot Lambda timeout issues?
- How do you reduce Lambda cost?
- How do Lambda Function URLs differ from API Gateway?
- How do you access Secrets Manager from Lambda?
- How do you trace Lambda requests?
- How do you prevent Lambda from overwhelming a database?
Common Mistakes
Assigning Administrator Permissions
Lambda execution roles should not use broad permissions such as full administrative access.
Creating Clients Inside the Handler
SDK clients, HTTP clients, and reusable connections should generally be initialized outside the handler when safe.
Ignoring Duplicate Events
Asynchronous systems can deliver the same event more than once.
Missing Timeout Alignment
Lambda, API Gateway, database, and HTTP-client timeouts should be aligned.
Logging Secrets
Tokens, passwords, payment details, and personal information should never be logged.
Using Unlimited Concurrency
Uncontrolled scaling can overload downstream databases and APIs.
Ignoring Dead-Letter Queues
Failed asynchronous messages need a recovery path.
Deploying Large Frameworks Unnecessarily
Heavy frameworks can increase cold-start time and memory use.
Opening New Database Connections for Every Request
This can exhaust database capacity during traffic spikes.
Treating Lambda as a Long-Running Server
Lambda is designed for event-based, bounded execution rather than continuously running processes.
AWS Lambda Best Practices
- Keep handlers small and focused.
- Separate business logic from Lambda-specific code.
- Initialize reusable clients outside the handler.
- Make functions stateless.
- Implement idempotency.
- Apply least-privilege IAM permissions.
- Store secrets in Secrets Manager.
- Encrypt sensitive data.
- Configure bounded retries.
- Use dead-letter queues or destinations.
- Protect downstream systems using concurrency controls.
- Use SQS to absorb traffic spikes.
- Monitor errors, throttles, concurrency, and duration.
- Use distributed tracing and correlation IDs.
- Optimize memory through performance testing.
- Minimize deployment-package size.
- Use aliases and versions for controlled releases.
- Test failure, retry, and recovery scenarios.
- Review CloudWatch Logs retention.
- Evaluate the total architecture cost.
Troubleshooting AWS Lambda
Function Times Out
Check:
- External API latency
- Database query duration
- Network routing
- DNS resolution
- Deadlocks
- Timeout configuration
- VPC NAT access
- Excessive initialization
Function Is Throttled
Check:
- Account concurrency
- Reserved concurrency
- Event-source concurrency
- Traffic spikes
- Downstream limits
SQS Messages Are Reprocessed
Check:
- Visibility timeout
- Function timeout
- Partial batch failures
- Idempotency
- Retry count
- DLQ configuration
Lambda Cannot Access the Internet
Check:
- Private subnet routes
- NAT gateway
- Security groups
- Network ACLs
- DNS settings
- VPC endpoints
High Cold-Start Latency
Check:
- Runtime choice
- Package size
- Framework startup
- Initialization code
- VPC configuration
- Memory setting
- Provisioned concurrency
Quick Revision
| Topic | Key Point |
|---|---|
| AWS Lambda | Event-driven serverless compute service |
| Handler | Function entry point |
| Trigger | Service or event that invokes Lambda |
| Execution role | Permissions used by Lambda |
| Resource policy | Controls who can invoke Lambda |
| Cold start | Initialization of a new environment |
| Warm start | Reuse of an initialized environment |
| Reserved concurrency | Reserves and limits concurrency |
| Provisioned concurrency | Pre-initializes environments |
| Event source mapping | Polls queues and streams |
| Layer | Shared dependencies and code |
| Version | Immutable function snapshot |
| Alias | Named pointer to a version |
| DLQ | Stores failed events |
| Destination | Routes success or failure results |
| Idempotency | Safe duplicate-event processing |
| RDS Proxy | Manages database connections |
| CloudWatch | Logs, metrics, and alarms |
Key Takeaways
- AWS Lambda runs event-driven code without requiring direct server management.
- Lambda supports synchronous, asynchronous, and poll-based invocation models.
- Execution environments may be reused, but applications must remain stateless.
- Cold starts can be reduced through optimized initialization, smaller deployments, appropriate memory, and provisioned concurrency.
- Concurrency must be controlled to protect databases and downstream services.
- Event handlers should be idempotent because duplicate delivery can occur.
- IAM roles, resource policies, encryption, secret management, and input validation are essential security controls.
- CloudWatch, distributed tracing, alarms, dead-letter queues, and destinations provide production observability and recovery.
- Lambda is ideal for APIs, event processing, automation, scheduled workloads, and short-running services.
- Long-running or continuously utilized workloads may be better suited to containers or other AWS compute services.