Skip to main content

AWS Lambda - Interview Preparation

Total Questions: 316 Levels: Core Fundamentals (100), Intermediate (120), Advanced (80)


Table of Contents​

  1. Core Fundamentals
  2. Intermediate Topics
  3. Advanced Topics

1. Core Fundamentals​

Q1: What is AWS Lambda and how does it work?​

Technical Answer: AWS Lambda is a serverless compute service that runs code in response to events without provisioning servers. It automatically handles compute resources, scaling, and administration.

Execution Model:

  1. Invocation - Event triggers the function
  2. Cold Start - Lambda creates execution environment, initializes runtime
  3. Warm Start - Reuses existing execution environment
  4. Execution - Handler processes event
  5. Cleanup - Environment frozen or terminated

Code Example:

import json

def lambda_handler(event, context):
"""
event: Dict containing trigger data
context: Lambda runtime context object
"""
print(f"Request ID: {context.aws_request_id}")
print(f"Remaining time: {context.get_remaining_time_in_millis()}ms")

body = json.loads(event.get('body', '{}'))
name = body.get('name', 'World')

return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': f'Hello, {name}!'})
}

🔍 Interviewer Notes: Testing serverless concepts, cold vs warm starts, event-driven architecture.

❌ Common Mistakes:

  • Confusing Lambda with EC2
  • Not understanding cold start impact
  • Thinking Lambda shares state between invocations

Q2: What are the different ways to invoke a Lambda function?​

Technical Answer: Lambda supports three invocation models:

  1. Synchronous (RequestResponse) - Caller waits for response
  2. Asynchronous (Event) - Lambda queues and processes later
  3. Poll-based (Stream/DynamoDB/SQS) - Lambda polls source continuously

Code Examples:

import boto3

lambda_client = boto3.client('lambda')

# 1. Synchronous
response = lambda_client.invoke(
FunctionName='my-function',
InvocationType='RequestResponse',
Payload=json.dumps({'key': 'value'})
)
result = json.loads(response['Payload'].read())

# 2. Asynchronous
lambda_client.invoke(
FunctionName='my-function',
InvocationType='Event',
Payload=json.dumps({'key': 'value'})
)

Event Structures:

# API Gateway (Synchronous)
{
"resource": "/users",
"path": "/users",
"httpMethod": "POST",
"body": '{"name": "John"}',
"requestContext": {...}
}

# S3 Event (Asynchronous)
{
"Records": [{
"eventSource": "aws:s3",
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": {"name": "my-bucket"},
"object": {"key": "uploads/file.txt"}
}
}]
}

# SQS Trigger (Poll-based)
{
"Records": [{
"messageId": "12345",
"body": "message content",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:..."
}]
}

🔍 Interviewer Notes: Testing knowledge of event sources and invocation types.

❌ Common Mistakes:

  • Using async when sync needed
  • Not configuring DLQ for async functions
  • Not understanding SQS polling

Q3: What is a Lambda cold start and how to minimize it?​

Technical Answer: Cold start occurs when Lambda initializes a new execution environment - downloading code, starting runtime, running init code.

Optimization Strategies:

import boto3

# ✅ OPTIMIZATION: Initialize OUTSIDE handler
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
s3_client = boto3.client('s3')

def lambda_handler_good(event, context):
# Connection already established
table.put_item(Item={'id': '123', 'name': 'John'})
return {'statusCode': 200}

# ❌ BAD: Initialize INSIDE handler
def lambda_handler_bad(event, context):
dynamodb = boto3.resource('dynamodb') # Cold start every time!
table = dynamodb.Table('Users')
table.put_item(Item={'id': '123', 'name': 'John'})

Provisioned Concurrency:

import boto3

lambda_client = boto3.client('lambda')

# Keep functions warm
lambda_client.put_provisioned_concurrency_config(
FunctionName='my-function',
Qualifier='prod',
ProvisionedConcurrentExecutions=100
)

Cold Start Comparison:

  • Python: ~100-300ms (fastest)
  • Node.js: ~200-500ms
  • Java: ~3-10s (JVM startup)
  • .NET: ~1-3s

🔍 Interviewer Notes: Testing execution model and optimization techniques.

❌ Common Mistakes:

  • Initializing connections inside handler
  • Not using provisioned concurrency for latency-sensitive apps
  • Using Java without provisioned concurrency for sub-second requirements

Q4: How do you handle errors and retries in Lambda?​

Technical Answer: Different retry behaviors per invocation type:

  • Synchronous: No automatic retries by Lambda
  • Asynchronous: 2 automatic retries with exponential backoff
  • Poll-based: Depends on source (SQS retries, Streams retry until success)

Error Handling Implementation:

import json
from botocore.exceptions import ClientError

def lambda_handler(event, context):
try:
result = process_event(event)
return {'statusCode': 200, 'body': json.dumps(result)}

except ClientError as e:
error_code = e.response['Error']['Code']

if error_code == 'ProvisionedThroughputExceededException':
raise # Let Lambda retry for throttling

# Non-retryable errors
return {'statusCode': 400, 'body': json.dumps({'error': str(e)})}

except Exception as e:
print(f"Error: {e}, Event: {json.dumps(event)}")
raise # Triggers retry

DLQ Configuration:

import boto3

lambda_client = boto3.client('lambda')

# Configure DLQ for async invocations
lambda_client.update_function_configuration(
FunctionName='my-function',
DeadLetterConfig={
'TargetArn': 'arn:aws:sqs:us-east-1:123456789:dlq'
}
)

# Modern approach: Lambda Destinations
lambda_client.update_function_configuration(
FunctionName='my-function',
DestinationConfig={
'OnSuccess': {'Destination': 'arn:aws:sqs:...:success-queue'},
'OnFailure': {'Destination': 'arn:aws:sqs:...:failure-queue'}
}
)

Idempotency Pattern:

import boto3
import hashlib

dynamodb = boto3.resource('dynamodb')
idempotency_table = dynamodb.Table('idempotency-keys')

def lambda_handler(event, context):
# Generate idempotency key
idempotency_key = hashlib.sha256(
json.dumps(event, sort_keys=True).encode()
).hexdigest()

# Check if already processed
response = idempotency_table.get_item(
Key={'idempotency_key': idempotency_key}
)
if 'Item' in response:
return response['Item']['result']

# Process and store result
result = process_payment(event)
idempotency_table.put_item(Item={
'idempotency_key': idempotency_key,
'result': result
})

return result

🔍 Interviewer Notes: Testing error patterns, retry mechanisms, and idempotency.

❌ Common Mistakes:

  • Not implementing idempotency for financial transactions
  • Not configuring DLQs for async functions
  • Swallowing exceptions that should trigger retries

Q5: What are Lambda layers and when to use them?​

Technical Answer: Lambda layers are ZIP archives containing libraries, runtimes, or dependencies for code reuse and smaller deployment packages.

Layer Structure:

layer_content.zip
├── python/lib/python3.9/site-packages/
│ ├── requests/
│ └── numpy/

Creating and Using Layers:

import boto3

lambda_client = boto3.client('lambda')

# Publish layer
with open('my-layer.zip', 'rb') as f:
response = lambda_client.publish_layer_version(
LayerName='common-dependencies',
Content={'ZipFile': f.read()},
CompatibleRuntimes=['python3.9', 'python3.10', 'python3.11'],
CompatibleArchitectures=['x86_64', 'arm64']
)

# Attach to function
lambda_client.update_function_configuration(
FunctionName='my-function',
Layers=[
response['LayerVersionArn'],
'arn:aws:lambda:us-east-1:123456789:layer:another-layer:1'
]
)

Layer Strategy:

# Layer 1: Common utilities (logging, AWS SDK)
# Layer 2: Business logic
# Layer 3: Runtime extensions

import json
from common_utils import logger, metrics # From Layer 1
from domain_models import Order # From Layer 2

def lambda_handler(event, context):
logger.info("Processing", extra={'order_id': event['order_id']})
order = Order.from_dict(event)
metrics.record_count('orders_processed', 1)
return {'statusCode': 200}

🔍 Interviewer Notes: Testing code organization and deployment optimization.

❌ Common Mistakes:

  • Putting function-specific code in shared layers
  • Not versioning layers properly
  • Creating layers >250MB unzipped

Q6: How do you secure Lambda functions?​

Technical Answer: Lambda security involves IAM roles, VPC configuration, and resource policies.

IAM Role (Least Privilege):

import boto3

# Minimal policy for specific function
minimal_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "SpecificDynamoDBTable",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:PutItem"],
"Resource": "arn:aws:dynamodb:us-east-1:123456789:table/Orders"
},
{
"Sid": "SpecificS3Bucket",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::my-bucket/uploads/*"
},
{
"Sid": "CloudWatchLogs",
"Effect": "Allow",
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
"Resource": "arn:aws:logs:us-east-1:123456789:log-group:/aws/lambda/my-function:*"
}
]
}

VPC Configuration:

import boto3

lambda_client = boto3.client('lambda')

# Lambda in VPC for private resources
lambda_client.update_function_configuration(
FunctionName='my-function',
VpcConfig={
'SubnetIds': ['subnet-123', 'subnet-456'],
'SecurityGroupIds': ['sg-789']
}
)

Environment Variables Encryption:

import boto3
import os
import base64

kms = boto3.client('kms')

# Decrypt at runtime
def get_secret():
encrypted = base64.b64decode(os.environ['SECRET_ENCRYPTED'])
decrypted = kms.decrypt(CiphertextBlob=encrypted)
return decrypted['Plaintext'].decode()

def lambda_handler(event, context):
password = get_secret()
# Use password...

Resource-Based Policy:

# Allow only specific API Gateway
lambda_client.add_permission(
FunctionName='my-function',
StatementId='AllowAPIGateway',
Action='lambda:InvokeFunction',
Principal='apigateway.amazonaws.com',
SourceArn='arn:aws:execute-api:us-east-1:123456789:abc123/prod/POST/users'
)

🔍 Interviewer Notes: Testing security best practices and IAM knowledge.

❌ Common Mistakes:

  • Using * in IAM policies
  • Storing secrets in plain text
  • Not using VPC endpoints
  • Overly permissive resource policies

Q7: What are Lambda concurrency limits?​

Technical Answer:

  • Account limit: 1000 concurrent executions per region
  • Reserved concurrency: Guaranteed capacity for a function
  • Provisioned concurrency: Pre-warmed instances

Concurrency Management:

import boto3

lambda_client = boto3.client('lambda')

# Set reserved concurrency (max concurrent)
lambda_client.put_function_concurrency(
FunctionName='my-function',
ReservedConcurrentExecutions=100
)

# Set provisioned concurrency
lambda_client.put_provisioned_concurrency_config(
FunctionName='my-function',
Qualifier='prod',
ProvisionedConcurrentExecutions=50
)

Throttling Handling:

from botocore.exceptions import ClientError

def lambda_handler(event, context):
try:
response = lambda_client.invoke(
FunctionName='downstream-function',
Payload=json.dumps(event)
)
return response
except ClientError as e:
if e.response['Error']['Code'] == 'TooManyRequestsException':
return {'statusCode': 429, 'body': 'Overloaded'}
raise

🔍 Interviewer Notes: Testing scaling limits and backpressure handling.

❌ Common Mistakes:

  • Not setting reserved concurrency for critical functions
  • Ignoring account-level limits
  • Not handling TooManyRequestsException

Q8: How do you monitor Lambda functions?​

Technical Answer: Use CloudWatch Logs, CloudWatch Metrics, X-Ray, and Lambda Insights.

Structured Logging:

import json
import logging
import time

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
start = time.time()

# Structured log entry
logger.info(json.dumps({
'message': 'Processing started',
'request_id': context.aws_request_id,
'function_name': context.function_name,
'memory_limit': context.memory_limit_in_mb,
'event_type': event.get('type')
}))

try:
result = process_event(event)

logger.info(json.dumps({
'message': 'Processing completed',
'duration_ms': (time.time() - start) * 1000,
'status': 'success'
}))
return result

except Exception as e:
logger.error(json.dumps({
'message': 'Processing failed',
'error_type': type(e).__name__,
'duration_ms': (time.time() - start) * 1000
}))
raise

X-Ray Tracing:

from aws_xray_sdk.core import xray_recorder, patch_all

patch_all() # Trace AWS calls

@xray_recorder.capture('process_order')
def process_order(order_id):
# This subsegment appears in X-Ray
table.get_item(Key={'id': order_id})

def lambda_handler(event, context):
xray_recorder.current_subsegment().put_annotation('user_id', event['user_id'])

for order in event['orders']:
process_order(order['id'])

return {'statusCode': 200}

🔍 Interviewer Notes: Testing observability and debugging practices.

❌ Common Mistakes:

  • Using print() instead of structured logging
  • Not adding correlation IDs
  • Not using X-Ray for distributed tracing

2. Intermediate Topics​

Q9: How do you implement multi-region Lambda?​

Technical Answer: Multi-region Lambda requires cross-region replication, DynamoDB Global Tables, and Route 53 health checks.

Cross-Region Setup:

import boto3

regions = ['us-east-1', 'us-west-2', 'eu-west-1']

for region in regions:
lambda_client = boto3.client('lambda', region_name=region)

with open('function.zip', 'rb') as f:
lambda_client.create_function(
FunctionName='user-api',
Runtime='python3.11',
Handler='app.handler',
Code={'ZipFile': f.read()},
Role='arn:aws:iam::123456789:role/lambda-execution',
Environment={'Variables': {'REGION': region}}
)

DynamoDB Global Tables:

# DynamoDB Global Tables for multi-region data
dynamodb = boto3.client('dynamodb', region_name='us-east-1')

dynamodb.create_global_table(
GlobalTableName='users',
ReplicationGroup=[
{'RegionName': 'us-east-1'},
{'RegionName': 'us-west-2'},
{'RegionName': 'eu-west-1'}
]
)

# Lambda reads/writes to local endpoint
def lambda_handler(event, context):
region = os.environ['AWS_REGION']
dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table('users')
table.put_item(Item={'id': '123', 'name': 'John'})

🔍 Interviewer Notes: Testing disaster recovery and global architecture understanding.

❌ Common Mistakes:

  • Not considering replication lag
  • Missing conflict resolution
  • Not testing failover scenarios

Q10: How do you optimize Lambda for high throughput?​

Technical Answer: High-throughput Lambda requires batching, parallelization, and efficient resource use.

SQS Batch Processing:

def lambda_handler(event, context):
batch_size = len(event['Records'])
print(f"Processing {batch_size} messages")

failed_ids = []

for record in event['Records']:
try:
process_message(record['body'])
except Exception as e:
failed_ids.append({'itemIdentifier': record['messageId']})

# Only failed messages retried
return {'batchItemFailures': failed_ids}

Kinesis Parallel Processing:

import base64

def lambda_handler(event, context):
for record in event['Records']:
payload = base64.b64decode(record['kinesis']['data'])
data = json.loads(payload)
process_record(data)

return {'statusCode': 200}

# Event Source Mapping config:
# - Batch Size: Up to 10,000 records
# - Parallelization Factor: Up to 10
# - Bisect Batch on Error: Split failed batches

🔍 Interviewer Notes: Testing optimization strategies and scaling knowledge.

❌ Common Mistakes:

  • Processing one record at a time
  • Not using parallelization factor
  • Ignoring memory-CPU correlation

Q11: How do you implement Step Functions with Lambda?​

Technical Answer: Step Functions orchestrate multiple Lambda functions with error handling, parallel execution, and state management.

State Machine Definition:

{
"Comment": "Order Processing Workflow",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:validate-order",
"Next": "CheckInventory",
"Catch": [
{
"ErrorEquals": ["ValidationException"],
"Next": "ValidationFailed"
}
]
},
"CheckInventory": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:check-inventory",
"Next": "InventoryDecision"
},
"InventoryDecision": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.inventory_available",
"BooleanEquals": true,
"Next": "ProcessPayment"
},
{
"Variable": "$.inventory_available",
"BooleanEquals": false,
"Next": "NotifyOutOfStock"
}
]
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:process-payment",
"Next": "ParallelProcessing",
"Retry": [
{
"ErrorEquals": ["PaymentException"],
"IntervalSeconds": 2,
"MaxAttempts": 3,
"BackoffRate": 2
}
]
},
"ParallelProcessing": {
"Type": "Parallel",
"Branches": [
{
"StartAt": "SendConfirmation",
"States": { "SendConfirmation": { "Type": "Task", "End": true } }
},
{
"StartAt": "UpdateAnalytics",
"States": { "UpdateAnalytics": { "Type": "Task", "End": true } }
}
],
"Next": "OrderComplete"
},
"OrderComplete": { "Type": "Succeed" },
"OrderFailed": { "Type": "Fail" }
}
}

SDK Integration:

import boto3
import json

sfn = boto3.client('stepfunctions')

def lambda_handler(event, context):
response = sfn.start_execution(
stateMachineArn='arn:aws:states:...:stateMachine:order-processing',
name=f"order-{event['order_id']}",
input=json.dumps({'order': event})
)
return {'execution_arn': response['executionArn']}

def check_status(execution_arn):
response = sfn.describe_execution(executionArn=execution_arn)
return {'status': response['status'], 'output': response.get('output')}

🔍 Interviewer Notes: Testing workflow orchestration and error handling patterns.

❌ Common Mistakes:

  • Putting too much logic in one Lambda
  • Not handling timeouts
  • Not using parallel states

3. Advanced Topics​

Q12: How do you implement Lambda extensions?​

Technical Answer: Lambda extensions run alongside function invocations for monitoring and observability.

Extension API (External):

#!/usr/bin/env python3
# extension.py

import http.client
import json
import os

EXTENSION_API = os.environ['AWS_LAMBDA_RUNTIME_API']
EXTENSION_NAME = 'my-observability-extension'

def register_extension():
conn = http.client.HTTPConnection(EXTENSION_API)
conn.request('POST', '/2020-01-01/extension/register',
json.dumps({'events': ['INVOKE', 'SHUTDOWN']}),
{'Lambda-Extension-Name': EXTENSION_NAME})
return conn.getresponse().getheader('Lambda-Extension-Identifier')

def next_event(extension_id):
conn = http.client.HTTPConnection(EXTENSION_API)
conn.request('GET', '/2020-01-01/extension/event/next',
headers={'Lambda-Extension-Identifier': extension_id})
return json.loads(conn.getresponse().read())

def main():
extension_id = register_extension()
while True:
event = next_event(extension_id)
if event.get('eventType') == 'SHUTDOWN':
break

if __name__ == '__main__':
main()

🔍 Interviewer Notes: Testing advanced Lambda features and observability patterns.

❌ Common Mistakes:

  • Not handling shutdown events
  • Blocking function execution
  • Not respecting extension timeouts

Q13: How do you implement custom Lambda runtimes?​

Technical Answer: Custom runtimes allow Lambda to run any language by implementing the Runtime API.

Runtime Bootstrap:

#!/usr/bin/env python3
# bootstrap.py

import http.client
import json
import os
import sys

RUNTIME_API = os.environ['AWS_LAMBDA_RUNTIME_API']
HANDLER = os.environ['_HANDLER']

def next_invocation():
conn = http.client.HTTPConnection(RUNTIME_API)
conn.request('GET', '/2018-06-01/runtime/invocation/next')
response = conn.getresponse()
request_id = response.getheader('Lambda-Runtime-Aws-Request-Id')
return request_id, json.loads(response.read())

def send_response(request_id, result, is_error=False):
conn = http.client.HTTPConnection(RUNTIME_API)
endpoint = f'/2018-06-01/runtime/invocation/{request_id}/{"error" if is_error else "response"}'
conn.request('POST', endpoint, json.dumps(result))

def main():
module_name, handler_name = HANDLER.rsplit('.', 1)
module = __import__(module_name)
handler = getattr(module, handler_name)

while True:
try:
request_id, event = next_invocation()
context = {'aws_request_id': request_id}
result = handler(event, context)
send_response(request_id, result)
except Exception as e:
send_response(request_id, {'errorType': type(e).__name__, 'errorMessage': str(e)}, True)

if __name__ == '__main__':
main()

🔍 Interviewer Notes: Testing deep understanding of Lambda internals.

❌ Common Mistakes:

  • Not handling all Runtime API endpoints
  • Not implementing proper error reporting
  • Missing initialization error handling

Additional Core Questions​

Q14: What are the Lambda limits?​

Technical Answer:

LimitValue
Memory128 MB - 10,240 MB
Timeout900 seconds (15 min)
Package size (compressed)50 MB
Package size (uncompressed)250 MB
Environment variables4 KB
Concurrent executions1000 per region (default)
Layers5 per function
Payload size (sync)6 MB
Payload size (async)256 KB

🔍 Interviewer Notes: Testing knowledge of service limits.


Q15: How do you package and deploy Lambda functions?​

Technical Answer:

# Create deployment package
pip install -r requirements.txt -t package/
cp lambda_function.py package/
cd package && zip -r ../deployment.zip .

# Use AWS CLI
aws lambda update-function-code \
--function-name my-function \
--zip-file fileb://deployment.zip

# Or use SAM/CloudFormation

SAM Template:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.lambda_handler
Runtime: python3.11
Timeout: 30
MemorySize: 512
Environment:
Variables:
TABLE_NAME: !Ref MyTable
Events:
ApiEvent:
Type: Api
Properties:
Path: /users
Method: post

🔍 Interviewer Notes: Testing deployment practices and Infrastructure as Code.


Q16: How do you test Lambda functions locally?​

Technical Answer:

# lambda_function.py
def lambda_handler(event, context):
return {'statusCode': 200, 'body': 'Hello'}

# test_lambda.py
import unittest
from lambda_function import lambda_handler

class TestLambda(unittest.TestCase):
def test_handler(self):
event = {'name': 'Test'}
context = {'aws_request_id': '123'}
result = lambda_handler(event, context)
self.assertEqual(result['statusCode'], 200)

if __name__ == '__main__':
unittest.main()

Using SAM CLI:

# Invoke locally
sam local invoke MyFunction -e events/api-gateway.json

# Start API locally
sam local start-api

# Debug
sam local invoke MyFunction -d 5858

🔍 Interviewer Notes: Testing development workflow knowledge.


Q17: What is Lambda@Edge?​

Technical Answer: Lambda@Edge runs Lambda functions at CloudFront edge locations for request/response modification.

Use Cases:

  • A/B testing
  • Authentication/authorization
  • URL rewrites
  • Adding security headers
  • Image optimization

CloudFront Event Types:

  • viewer-request: User request arrives
  • origin-request: Before forwarding to origin
  • origin-response: Origin returns response
  • viewer-response: Before returning to user

🔍 Interviewer Notes: Testing CDN integration knowledge.

❌ Common Mistakes:

  • Using Lambda@Edge when regular Lambda + API Gateway suffice
  • Exceeding 5-second timeout for viewer events
  • Not understanding regional cache implications

Q18: How do you implement canary deployments for Lambda?​

Technical Answer: Use Lambda aliases and weighted routing.

import boto3

lambda_client = boto3.client('lambda')

# Publish version
version_response = lambda_client.publish_version(
FunctionName='my-function'
)
version = version_response['Version']

# Update alias with routing config
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion=version,
RoutingConfig={
'AdditionalVersionWeights': {
'1': 0.1 # 10% traffic to previous version
}
}
)

CodeDeploy for Linear Deployment:

Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: prod
DeploymentPreference:
Type: Linear10PercentEvery1Minute
Alarms:
- !Ref ErrorRateAlarm
Hooks:
PreTraffic: !Ref PreTrafficHookFunction
PostTraffic: !Ref PostTrafficHookFunction

🔍 Interviewer Notes: Testing deployment strategies and safe rollout practices.


Q19: How do you optimize Lambda memory configuration?​

Technical Answer: Memory and CPU are proportional. More memory = more CPU.

Power Tuning:

import json

def lambda_handler(event, context):
memory = int(context.memory_limit_in_mb)

# CPU-intensive tasks benefit from more memory
# I/O-bound tasks may not

start = time.time()

# Simulate work
result = heavy_computation()

duration = time.time() - start

# Calculate cost efficiency
# Cost = (memory/1024) * (duration/100ms) * rate

return {
'memory': memory,
'duration_ms': duration * 1000,
'cost_per_invocation': calculate_cost(memory, duration)
}

Optimization Tips:

  • Use Lambda Power Tuning tool to find sweet spot
  • 1792MB = 1 vCPU (linear scaling up to this point)
  • Above 1792MB, you get more than 1 vCPU (multithreading)

🔍 Interviewer Notes: Testing cost optimization understanding.


Q20: How do you handle large payloads in Lambda?​

Technical Answer: Use S3 for payloads >6MB (sync) or >256KB (async).

import boto3
import json

s3 = boto3.client('s3')

def lambda_handler(event, context):
# Event contains S3 reference
bucket = event['bucket']
key = event['key']

# Stream large file
response = s3.get_object(Bucket=bucket, Key=key)

# Process in chunks to minimize memory
for chunk in response['Body'].iter_chunks(chunk_size=8192):
process_chunk(chunk)

return {'statusCode': 200}

# Alternative: Use S3 Object Lambda for transformation

🔍 Interviewer Notes: Testing workarounds for service limits.


Q21: What is the Lambda execution context?​

Technical Answer: The execution context is the runtime environment that Lambda provides for your function. It includes the operating system, runtime, libraries, and any initialized code outside the handler.

Execution Context Lifecycle:

# Code outside handler runs ONCE per context initialization
import boto3

# These are initialized during cold start and reused
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
s3_client = boto3.client('s3')

# Global state persists across warm invocations
cache = {}
connection_pool = []

def lambda_handler(event, context):
# This code runs EVERY invocation
# Can reuse resources initialized above

# Access context properties
print(f"Function: {context.function_name}")
print(f"Memory: {context.memory_limit_in_mB}")
print(f"Time remaining: {context.get_remaining_time_in_millis()}")

return {'statusCode': 200}

Best Practice: Initialize resources outside the handler for reuse.

🔍 Interviewer Notes: Testing understanding of Lambda lifecycle optimization.

❌ Common Mistakes:

  • Creating connections inside the handler
  • Not understanding what persists across invocations
  • Storing per-request state in global variables

Q22: What are the Lambda invocation limits?​

Technical Answer: Lambda has several limits that affect function execution.

Invocation Limits:

LimitValueNotes
Invocation payload (sync)6 MBRequest/response
Invocation payload (async)256 KBEvent payload
Execution timeout15 minutesConfigurable
Memory128 MB - 10,240 MB1 MB increments
Environment variables4 KBTotal size
Layers5 per function250 MB unzipped each
Concurrency1000 per regionCan be increased

Handling Large Payloads:

def lambda_handler(event, context):
# For large payloads, use S3
if 's3_bucket' in event:
s3 = boto3.client('s3')
response = s3.get_object(
Bucket=event['s3_bucket'],
Key=event['s3_key']
)
data = json.loads(response['Body'].read())
else:
data = event['data']

# Process data
result = process_large_data(data)

# Return via S3 if result is large
if len(json.dumps(result)) > 6000000:
s3.put_object(
Bucket='results-bucket',
Key=f'result-{context.aws_request_id}.json',
Body=json.dumps(result)
)
return {'s3_location': f's3://results-bucket/result-{context.aws_request_id}.json'}

return result

🔍 Interviewer Notes: Testing knowledge of service limits and workarounds.

❌ Common Mistakes:

  • Not checking payload size before sending
  • Not using S3 for large payloads
  • Not handling limit exceeded errors

Q23: How do you use Lambda function URLs?​

Technical Answer: Lambda function URLs provide a built-in HTTPS endpoint without API Gateway.

Creating Function URL:

import boto3

lambda_client = boto3.client('lambda')

# Create function URL
response = lambda_client.create_function_url_config(
FunctionName='my-function',
Qualifier='$LATEST',
AuthType='NONE', # or 'AWS_IAM' for authenticated
Cors={
'AllowOrigins': ['https://example.com'],
'AllowMethods': ['GET', 'POST'],
'AllowHeaders': ['content-type', 'authorization'],
'MaxAge': 86400
}
)

function_url = response['FunctionUrl']

Handling CORS in Lambda:

def lambda_handler(event, context):
# Handle preflight
if event['requestContext']['http']['method'] == 'OPTIONS':
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
}
}

# Main request
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({'message': 'Hello'})
}

Comparison with API Gateway:

FeatureFunction URLAPI Gateway
ThrottlingNone (use concurrency)Built-in
AuthIAM or NoneIAM, Cognito, Lambda, etc.
CachingNoYes
WAFNoYes
Request validationNoYes
CostFreePer request

🔍 Interviewer Notes: Testing knowledge of simpler API alternatives.

❌ Common Mistakes:

  • Using Function URL when API Gateway features needed
  • Not handling CORS properly
  • Not implementing throttling

Q24: What are Lambda environment variables?​

Technical Answer: Environment variables provide configuration without code changes. Lambda supports encryption with KMS.

import os

def lambda_handler(event, context):
# Access environment variables
db_host = os.environ.get('DB_HOST')
db_port = os.environ.get('DB_PORT', '5432') # Default value
api_key = os.environ.get('API_KEY')

# For debugging (remove in production!)
print(f"Connecting to {db_host}:{db_port}")

return {'statusCode': 200}

Setting via AWS CLI:

aws lambda update-function-configuration \
--function-name my-function \
--environment "Variables={DB_HOST=prod.db.com,API_KEY=secret}"

🔍 Interviewer Notes: Testing configuration management knowledge.

❌ Common Mistakes:

  • Hardcoding config instead of env vars
  • Logging secrets (security risk)
  • Not using Parameter Store/Secrets Manager for sensitive data

Q25: How do you use Lambda Layers?​

Technical Answer: Lambda Layers are ZIP archives containing libraries, custom runtimes, or other dependencies.

# Layer contains shared libraries
# No need to include in deployment package
import numpy as np
import pandas as pd

def lambda_handler(event, context):
df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
return {'statusCode': 200, 'body': str(df.to_dict())}

Creating a Layer:

# Create layer structure
mkdir -p python/lib/python3.9/site-packages
pip install requests -t python/lib/python3.9/site-packages/

# Zip it
zip -r layer.zip python

# Publish layer
aws lambda publish-layer-version \
--layer-name requests-layer \
--description "Requests library" \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.9

Layer Limits:

  • 5 layers per function
  • 250 MB unzipped total
  • Can use AWS-provided layers (NumPy, SciPy, etc.)

🔍 Interviewer Notes: Testing code reuse and deployment optimization.

❌ Common Mistakes:

  • Including layers in deployment package (duplication)
  • Wrong Python version in layer path
  • Not updating layers when dependencies change

Q26: How do you handle Lambda timeouts?​

Technical Answer: Lambda has a 15-minute maximum timeout. Handle gracefully using context remaining time.

def lambda_handler(event, context):
import signal

# Set up timeout handler
def timeout_handler(signum, frame):
# Cleanup before timeout
save_checkpoint()
raise Exception("Function timeout")

# Check remaining time
if context.get_remaining_time_in_millis() < 5000:
return {'statusCode': 202, 'message': 'Partial processing, continue with next batch'}

process_data(event)
return {'statusCode': 200}

🔍 Interviewer Notes: Testing graceful degradation patterns.

❌ Common Mistakes:

  • Not checking remaining time
  • Not implementing partial processing
  • Not handling cleanup on timeout

Q27: What is Lambda Provisioned Concurrency?​

Technical Answer: Keeps execution environments initialized for immediate response, eliminating cold starts.

import boto3

lambda_client = boto3.client('lambda')

# Configure provisioned concurrency
lambda_client.put_provisioned_concurrency_config(
FunctionName='my-function',
Qualifier='1',
ProvisionedConcurrentExecutions=100
)

# Set up Application Auto Scaling
autoscaling = boto3.client('application-autoscaling')

autoscaling.register_scalable_target(
ServiceNamespace='lambda',
ResourceId='function:my-function:1',
ScalableDimension='lambda:function:ProvisionedConcurrency',
MinCapacity=10,
MaxCapacity=100
)

autoscaling.put_scaling_policy(
PolicyName='lambda-scaling',
ServiceNamespace='lambda',
ResourceId='function:my-function:1',
ScalableDimension='lambda:function:ProvisionedConcurrency',
PolicyType='TargetTrackingScaling',
TargetTrackingScalingPolicyConfiguration={
'TargetValue': 0.7, # 70% utilization
'PredefinedMetricSpecification': {
'PredefinedMetricType': 'LambdaProvisionedConcurrencyUtilization'
}
}
)

Cost Comparison:

  • Provisioned: $0.000004646 per GB-s (always on)
  • On-demand: $0.0000166667 per GB-s (when running)

🔍 Interviewer Notes: Testing latency optimization and cost tradeoffs.

❌ Common Mistakes:

  • Over-provisioning (high cost)
  • Not using autoscaling
  • Not considering scheduled scaling for predictable patterns

Q28: How do you use Lambda with API Gateway?​

Technical Answer: API Gateway triggers Lambda functions via HTTP requests with built-in throttling, caching, and security.

def lambda_handler(event, context):
"""
API Gateway v2 (HTTP API) event format
"""
print(f"Request path: {event['rawPath']}")
print(f"HTTP method: {event['requestContext']['http']['method']}")
print(f"Query params: {event.get('queryStringParameters', {})}")

# Parse body
body = json.loads(event.get('body', '{}'))

return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'message': 'Success',
'data': body
})
}

# API Gateway v1 (REST API) has slightly different format
# event['path'] instead of event['rawPath']
# event['httpMethod'] instead of event['requestContext']['http']['method']

API Gateway Types:

FeatureHTTP APIREST APIWebSocket API
LatencyLowHigherPersistent
CachingNoYesNo
Request validationBasicFullCustom
WAFNoYesNo
CostLowerHigherPer message

🔍 Interviewer Notes: Testing API integration knowledge.

❌ Common Mistakes:

  • Using REST API when HTTP API suffices (higher cost)
  • Wrong event format (v1 vs v2)
  • Not handling CORS preflight

Q29: How do you handle Lambda dead letter queues?​

Technical Answer: DLQs capture failed async invocations for later analysis and replay.

import boto3

lambda_client = boto3.client('lambda')

# Create SQS queue for DLQ
sqs = boto3.client('sqs')
dlq_queue = sqs.create_queue(QueueName='lambda-dlq')
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_queue['QueueUrl'],
AttributeNames=['QueueArn']
)['Attributes']['QueueArn']

# Configure function with DLQ
lambda_client.update_function_configuration(
FunctionName='my-function',
DeadLetterConfig={'TargetArn': dlq_arn}
)

# Process DLQ messages
import boto3

sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName='lambda-dlq')

for message in queue.receive_messages(MaxNumberOfMessages=10):
# Parse failed invocation
failed_event = json.loads(message.body)

print(f"Failed request: {failed_event['requestContext']['requestId']}")
print(f"Error: {failed_event['responsePayload']}")

# Decide: retry, alert, or discard
if is_retryable(failed_event):
retry_invocation(failed_event)
else:
send_alert(failed_event)

message.delete()

Retry Behavior:

  • Async: 2 retries (total 3 attempts) before DLQ
  • Sync: No retries, immediate failure
  • Event source mapping: Depends on configuration

🔍 Interviewer Notes: Testing error handling and reliability patterns.

❌ Common Mistakes:

  • Not setting up DLQs for async functions
  • Not monitoring DLQ depth
  • Not processing DLQ messages

Q30: What is Lambda event source mapping?​

Technical Answer: Event source mapping polls event sources and invokes Lambda synchronously.

import boto3

lambda_client = boto3.client('lambda')

# Create event source mapping for SQS
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:sqs:us-east-1:123456789:my-queue',
FunctionName='my-function',
BatchSize=10,
MaximumBatchingWindowInSeconds=5,
ParallelizationFactor=1,
DestinationConfig={
'OnSuccess': {
'Destination': 'arn:aws:sns:us-east-1:123456789:success-topic'
},
'OnFailure': {
'Destination': 'arn:aws:sqs:us-east-1:123456789:dlq'
}
}
)

# For DynamoDB Streams
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:dynamodb:us-east-1:123456789:table/my-table/stream/...',
FunctionName='my-function',
StartingPosition='LATEST',
BatchSize=100,
BisectBatchOnFunctionError=True,
MaximumRecordAgeInSeconds=3600,
RetryAttempts=3,
ParallelizationFactor=10 # Up to 10 concurrent batches per shard
)

Event Source Types:

  • SQS queue
  • SNS topic
  • DynamoDB Streams
  • Kinesis streams
  • MQ brokers (ActiveMQ, RabbitMQ)
  • Apache Kafka (MSK)

🔍 Interviewer Notes: Testing event-driven architecture knowledge.

❌ Common Mistakes:

  • Wrong StartingPosition (TRIM_HORIZON vs LATEST)
  • Not handling partial batch failures
  • Not setting up DLQs for stream processing

Q31: How do you implement Lambda blue-green deployments?​

Technical Answer: Blue-green deployment shifts traffic between two function versions with zero downtime.

import boto3

lambda_client = boto3.client('lambda')

# 1. Publish new version
version_response = lambda_client.publish_version(
FunctionName='my-function',
Description='v2 - new features'
)
new_version = version_response['Version']

# 2. Create/update alias with weighted routing
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion=new_version,
RoutingConfig={
'AdditionalVersionWeights': {
'1': 0.9, # 90% to old version
new_version: 0.1 # 10% to new version
}
}
)

# 3. Monitor CloudWatch metrics for errors
cloudwatch = boto3.client('cloudwatch')

metrics = cloudwatch.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName='Errors',
Dimensions=[
{'Name': 'FunctionName', 'Value': 'my-function'},
{'Name': 'Resource', 'Value': 'my-function:prod'}
],
StartTime=datetime.utcnow() - timedelta(hours=1),
EndTime=datetime.utcnow(),
Period=300,
Statistics=['Sum']
)

# 4. Gradually shift traffic if metrics look good
# Or rollback if errors detected

# 5. Full cutover when confident
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion=new_version,
RoutingConfig={'AdditionalVersionWeights': {}}
)

Deployment Strategies:

  • Canary: 10% → 50% → 100%
  • Linear: Gradual percentage increase
  • All-at-once: Immediate cutover (risky)

🔍 Interviewer Notes: Testing deployment strategy knowledge.

❌ Common Mistakes:

  • Not monitoring metrics during canary
  • No automatic rollback on error threshold
  • Forgetting to update both function code and dependencies

Q32: How do you debug Lambda functions locally?​

Technical Answer: Local debugging speeds up development before deploying to AWS.

# Using AWS SAM CLI
# template.yaml
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: app.lambda_handler
Runtime: python3.9
Events:
ApiEvent:
Type: Api
Properties:
Path: /hello
Method: get
# Local invoke with SAM
sam local invoke MyFunction -e events.json

# Local API Gateway simulation
sam local start-api

# Debug with VS Code
# .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: SAM Local",
"type": "python",
"request": "attach",
"port": 5890,
"host": "localhost"
}
]
}
# Using lambda-local (npm)
# lambda-local -l index.js -h handler -e event.json

# Using AWS Lambda Runtime Interface Emulator (RIE)
# docker run -p 9000:8080 my-lambda-image
# curl -XPOST http://localhost:9000/2015-03-31/functions/function/invocations \
# -d '{"key": "value"}'

# Using moto for mocking AWS services in tests
from moto import mock_aws

@mock_aws
def test_lambda_handler():
# Mock DynamoDB, S3, etc.
pass

🔍 Interviewer Notes: Testing development workflow knowledge.

❌ Common Mistakes:

  • Not testing with SAM before deploying
  • Different behavior between local and AWS
  • Not mocking AWS services in unit tests

Q33: How do you implement Lambda error handling?​

Technical Answer: Implement error handling with try-except blocks, custom error responses, and retry configuration.

import json
import logging
from botocore.exceptions import ClientError

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
try:
# Validate input
if 'user_id' not in event:
raise ValueError("Missing required field: user_id")

result = process_user(event['user_id'])
return {
'statusCode': 200,
'body': json.dumps({'success': True, 'data': result})
}

except ValueError as e:
logger.warning(f"Validation error: {str(e)}")
return {
'statusCode': 400,
'body': json.dumps({'error': 'Validation failed', 'message': str(e)})
}

except ClientError as e:
error_code = e.response['Error']['Code']
logger.error(f"AWS API error {error_code}: {str(e)}")
return {
'statusCode': 502,
'body': json.dumps({'error': 'Service unavailable', 'code': error_code})
}

except Exception as e:
logger.exception(f"Unexpected error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps({'error': 'Internal server error'})
}

def process_user(user_id):
# Business logic
return {'user_id': user_id, 'processed': True}

🔍 Interviewer Notes: Testing error handling maturity.

❌ Common Mistakes: Catching all exceptions silently; returning 200 for errors; no structured error responses; logging sensitive data in errors.


Q34: How do you use Lambda with CloudWatch Logs?​

Technical Answer: Lambda automatically logs to CloudWatch. Use structured logging for searchability and alarms.

import json
import logging

# Configure structured logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
# Structured log entry
log_data = {
'level': 'INFO',
'function': context.function_name,
'request_id': context.aws_request_id,
'message': 'Processing event',
'event_type': event.get('type'),
'user_id': event.get('user_id'),
'memory_mb': context.memory_limit_in_mb,
'remaining_ms': context.get_remaining_time_in_millis()
}
logger.info(json.dumps(log_data))

# Business logic
result = process(event)

# Log completion
logger.info(json.dumps({
'level': 'INFO',
'request_id': context.aws_request_id,
'message': 'Processing complete',
'duration_ms': result.get('duration'),
'records_processed': result.get('count')
}))

return result

# CloudWatch Logs Insights query examples:
# fields @timestamp, @message | filter @message like /ERROR/
# fields @timestamp, user_id | filter event_type = 'order_created'

🔍 Interviewer Notes: Testing observability practices.

❌ Common Mistakes: Plain text logs (not structured); logging sensitive data; no request_id correlation; excessive logging (cost, performance); using print() instead of logger.


Q35: How do you implement Lambda retries and DLQ?​

Technical Answer: Configure async invocation retries (2 retries by default) and Dead Letter Queues for failed events.

import boto3

lambda_client = boto3.client('lambda')

# Create DLQ (SQS queue)
sqs = boto3.client('sqs')
dlq_response = sqs.create_queue(QueueName='lambda-dlq')
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_response['QueueUrl'],
AttributeNames=['QueueArn']
)['Attributes']['QueueArn']

# Update function with DLQ
lambda_client.update_function_configuration(
FunctionName='my-async-function',
DeadLetterConfig={
'TargetArn': dlq_arn
}
)

# Configure async retry behavior
lambda_client.put_function_event_invoke_config(
FunctionName='my-async-function',
MaximumRetryAttempts=2, # 0-2, default 2
MaximumEventAgeInSeconds=3600, # 60-21600, default 21600 (6 hours)
DestinationConfig={
'OnSuccess': {
'Destination': 'arn:aws:sns:us-east-1:123456789:success-topic'
},
'OnFailure': {
'Destination': dlq_arn # Same as DeadLetterConfig or SNS/SQS/EventBridge
}
}
)

# Process from DLQ
import json

def process_dlq(event, context):
for record in event['Records']:
failed_event = json.loads(record['body'])

# Log for analysis
print(f"Failed event: {failed_event}")

# Optional: Retry with backoff
# Or alert on-call team
# Or save to S3 for later analysis

return {'processed': len(event['Records'])}

Retry Behavior:

  • Immediate retry
  • 1 minute delay
  • 2 minutes delay
  • Then to DLQ

🔍 Interviewer Notes: Testing reliability patterns.

❌ Common Mistakes: No DLQ configured; not monitoring DLQ; infinite retry loops; not handling idempotency on retry; DLQ without alarms.


Q36: How do you use Lambda with AWS X-Ray?​

Technical Answer: Enable X-Ray for distributed tracing to analyze performance and debug requests across services.

from aws_xray_sdk.core import xray_recorder, patch_all
from aws_xray_sdk.core import AWSXRayTracingContext
import boto3

# Patch boto3 for auto-tracing
patch_all()

@xray_recorder.capture('lambda_handler')
def lambda_handler(event, context):
# Add annotation for filtering
xray_recorder.put_annotation('user_id', event.get('user_id', 'unknown'))
xray_recorder.put_annotation('operation', 'process_order')

# Add metadata
xray_recorder.put_metadata('event_size', len(str(event)))

with xray_recorder.in_subsegment('validate_input'):
validate_event(event)

with xray_recorder.in_subsegment('fetch_data'):
data = fetch_from_dynamodb(event['id'])

with xray_recorder.in_subsegment('process_data'):
result = process(data)

return result

def fetch_from_dynamodb(id):
# Auto-traced by patch_all()
dynamodb = boto3.client('dynamodb')
return dynamodb.get_item(
TableName='my-table',
Key={'id': {'S': id}}
)

# Manual tracing for custom code
from aws_xray_sdk.core import xray_recorder

@xray_recorder.capture('heavy_computation')
def heavy_computation(data):
# This subsegment will appear in trace
return sum(x ** 2 for x in data)

Enable X-Ray:

  • Console: Configuration → Monitoring → Active tracing
  • API: TracingConfig={'Mode': 'Active'}

🔍 Interviewer Notes: Testing observability implementation.

❌ Common Mistakes: Not enabling active tracing; no custom subsegments for business logic; forgetting to patch boto3; not using annotations for filtering.


Q37: How do you use Lambda with Step Functions?​

Technical Answer: Lambda tasks in Step Functions for state machine orchestration of multi-step workflows.

import json

def validate_order(event, context):
"""Step 1: Validate order"""
order = event['order']

if not order.get('items'):
raise ValueError("Order has no items")

return {
'order_id': order['id'],
'is_valid': True,
'total': sum(item['price'] * item['quantity'] for item in order['items'])
}

def process_payment(event, context):
"""Step 2: Process payment"""
import boto3

payment = event['payment']

# Payment processing logic
if payment['amount'] <= 0:
raise ValueError("Invalid payment amount")

return {
'payment_id': f"pay-{event['order_id']}",
'status': 'completed',
'amount_charged': payment['amount']
}

def send_confirmation(event, context):
"""Step 3: Send email confirmation"""
import boto3

ses = boto3.client('ses')

ses.send_email(
Source='orders@example.com',
Destination={'ToAddresses': [event['customer_email']]},
Message={
'Subject': {'Data': f"Order {event['order_id']} Confirmed"},
'Body': {'Text': {'Data': f"Your order for ${event['total']} is confirmed."}}
}
)

return {'email_sent': True, 'order_id': event['order_id']}

Step Functions ASL:

{
"Comment": "Order Processing Workflow",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789:function:validate_order",
"Next": "ProcessPayment",
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "ValidationFailed" }]
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789:function:process_payment",
"Next": "SendConfirmation",
"Retry": [
{ "ErrorEquals": ["PaymentServiceException"], "MaxAttempts": 3 }
]
},
"SendConfirmation": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789:function:send_confirmation",
"End": true
},
"ValidationFailed": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789:function:notify_failure",
"End": true
}
}
}

🔍 Interviewer Notes: Testing workflow orchestration.

❌ Common Mistakes: Complex business logic in Step Functions (keep in Lambda); no error handling; not using retry/backoff; state too large (>256KB).


Q38: How do you implement Lambda with S3 events?​

Technical Answer: S3 event notifications trigger Lambda when objects are created, deleted, or restored.

import boto3
import json

def process_s3_event(event, context):
"""Process S3 create object events"""
s3 = boto3.client('s3')

for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
size = record['s3']['object']['size']
event_name = record['eventName']

print(f"Event: {event_name}, Bucket: {bucket}, Key: {key}")

if event_name.startswith('ObjectCreated'):
# Process new file
if key.endswith('.csv'):
process_csv(s3, bucket, key)
elif key.endswith('.json'):
process_json(s3, bucket, key)
elif key.endswith('.zip'):
process_archive(s3, bucket, key)

elif event_name.startswith('ObjectRemoved'):
# Handle deletion
cleanup_metadata(key)

def process_csv(s3, bucket, key):
"""Process CSV file from S3"""
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read().decode('utf-8')

# Parse CSV
lines = content.split('\n')
for line in lines[1:]: # Skip header
if line.strip():
process_record(line.split(','))

# Terraform/CloudFormation S3 notification configuration
# {
# "LambdaFunctionConfigurations": [{
# "LambdaFunctionArn": "arn:aws:lambda:...:process_s3_event",
# "Events": ["s3:ObjectCreated:*"],
# "Filter": {
# "KeyFilterRules": [{
# "Name": "prefix",
# "Value": "uploads/"
# }, {
# "Name": "suffix",
# "Value": ".csv"
# }]
# }
# }]
# }

S3 Event Types:

  • s3:ObjectCreated:* - Any create
  • s3:ObjectCreated:Put - Upload
  • s3:ObjectCreated:Copy - Copy
  • s3:ObjectRemoved:* - Delete

🔍 Interviewer Notes: Testing event-driven patterns.

❌ Common Mistakes: No S3 permission (s3:GetObject); processing large files in Lambda (timeout); recursive trigger loops; not using event filtering.


Q39: How do you use Lambda with DynamoDB Streams?​

Technical Answer: DynamoDB Streams capture item-level changes and trigger Lambda for reactive processing.

import boto3
import json

def process_dynamodb_stream(event, context):
"""Process DynamoDB stream records"""

for record in event['Records']:
event_name = record['eventName'] # INSERT, MODIFY, REMOVE
table_name = record['eventSourceARN'].split('/')[1]

if event_name == 'INSERT':
new_image = record['dynamodb']['NewImage']
item = {k: list(v.values())[0] for k, v in new_image.items()}

print(f"New item in {table_name}: {item}")

# Send welcome email for new users
if table_name == 'Users' and item.get('type') == 'new':
send_welcome_email(item['email'], item['name'])

elif event_name == 'MODIFY':
old_image = record['dynamodb'].get('OldImage', {})
new_image = record['dynamodb']['NewImage']

# Check specific field changes
old_status = old_image.get('status', {}).get('S')
new_status = new_image.get('status', {}).get('S')

if old_status != new_status and new_status == 'shipped':
order_id = new_image['order_id']['S']
send_shipment_notification(order_id)

elif event_name == 'REMOVE':
old_image = record['dynamodb']['OldImage']
item = {k: list(v.values())[0] for k, v in old_image.items()}

# Archive deleted item
archive_to_s3(item)

# Stream view types:
# - NEW_IMAGE: Only new item
# - OLD_IMAGE: Only old item
# - NEW_AND_OLD_IMAGES: Both
# - KEYS_ONLY: Only key attributes

Stream Configuration:

# Enable DynamoDB Stream
dynamodb = boto3.client('dynamodb')
dynamodb.update_table(
TableName='my-table',
StreamSpecification={
'StreamEnabled': True,
'StreamViewType': 'NEW_AND_OLD_IMAGES'
}
)

# Create Lambda event source mapping
lambda_client = boto3.client('lambda')
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:dynamodb:us-east-1:123456789:table/my-table/stream/2024-01-01T00:00:00.000',
FunctionName='process-stream',
StartingPosition='LATEST',
BatchSize=100,
ParallelizationFactor=10
)

🔍 Interviewer Notes: Testing stream processing patterns.

❌ Common Mistakes: Not handling batch failures (entire batch retries); no idempotency (same record may appear multiple times); wrong stream view type; not handling TTL deletes (REMOVE events).


Q40: How do you implement Lambda layers?​

Technical Answer: Lambda layers share code, libraries, and dependencies across functions without including in deployment package.

# Create layer directory structure
mkdir -p python/lib/python3.9/site-packages

# Install dependencies
pip install requests pymongo boto3 -t python/lib/python3.9/site-packages/

# Create layer zip
zip -r my-layer.zip python/

# Publish layer
aws lambda publish-layer-version \
--layer-name common-dependencies \
--description "Common Python libraries" \
--zip-file fileb://my-layer.zip \
--compatible-runtimes python3.9 python3.10

# Add layer to function
aws lambda update-function-configuration \
--function-name my-function \
--layers arn:aws:lambda:us-east-1:123456789:layer:common-dependencies:1
# Lambda handler using layer imports
import requests
import pymongo
from shared_utils import validate_input, format_response

# Layer imports available without bundling
def lambda_handler(event, context):
# validate_input from layer
validated = validate_input(event)

# requests from layer
response = requests.get('https://api.example.com/data')

return format_response(response.json())

Layer Limits:

  • 5 layers per function
  • Total size: 250MB unzipped
  • Can include custom runtime
  • Can include configuration files

Layer Best Practices:

  • Common libraries (boto3, requests)
  • Custom business logic shared across functions
  • Large dependencies (ML libraries)
  • Configuration or certificate files

🔍 Interviewer Notes: Testing code reuse strategies.

❌ Common Mistakes: Too many layers (complexity); not versioning layers; including unnecessary files; not testing layer with function runtime; circular dependencies between layers.


Q41: How do you implement Lambda with Secrets Manager?​

Technical Answer: Retrieve secrets from AWS Secrets Manager for secure credential management without hardcoding.

import boto3
import json
from botocore.exceptions import ClientError

# Cache secret to avoid repeated API calls
_secret_cache = {}

def get_secret(secret_name, region='us-east-1'):
"""Retrieve secret with caching"""

if secret_name in _secret_cache:
return _secret_cache[secret_name]

session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region
)

try:
get_secret_value_response = client.get_secret_value(SecretId=secret_name)

if 'SecretString' in get_secret_value_response:
secret = get_secret_value_response['SecretString']
_secret_cache[secret_name] = json.loads(secret)
else:
import base64
secret = base64.b64decode(get_secret_value_response['SecretBinary'])
_secret_cache[secret_name] = secret

return _secret_cache[secret_name]

except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == 'ResourceNotFoundException':
raise ValueError(f"Secret {secret_name} not found")
elif error_code == 'InvalidRequestException':
raise ValueError(f"Invalid request for secret {secret_name}")
raise

def lambda_handler(event, context):
# Get database credentials
db_secret = get_secret('prod/database/credentials')

username = db_secret['username']
password = db_secret['password']
host = db_secret['host']

# Connect to database
connection_string = f"postgresql://{username}:{password}@{host}/mydb"

# API key from Secrets Manager
api_key = get_secret('prod/api/external-service')['api_key']

return {'statusCode': 200, 'body': 'Processing complete'}

# Using Lambda extensions for caching (better performance)
# AWS Parameters and Secrets Lambda Extension
# Fetches secrets before handler invocation, caches locally

Secret Rotation:

# Lambda rotation function template
def lambda_handler(event, context):
import boto3

arn = event['SecretId']
token = event['ClientRequestToken']
step = event['Step']

service_client = boto3.client('secretsmanager')

if step == 'createSecret':
# Generate new password
new_password = generate_password()
service_client.put_secret_value(
SecretId=arn,
ClientRequestToken=token,
SecretString=json.dumps({'password': new_password}),
VersionStages=['AWSPENDING']
)

elif step == 'setSecret':
# Update database with new credentials
secret = service_client.get_secret_value(SecretId=arn, VersionStage='AWSPENDING')
update_database_password(secret)

elif step == 'testSecret':
# Verify new credentials work
secret = service_client.get_secret_value(SecretId=arn, VersionStage='AWSPENDING')
test_connection(secret)

elif step == 'finishSecret':
# Move version to AWSCURRENT
service_client.update_secret_version_stage(
SecretId=arn,
VersionStage='AWSCURRENT',
MoveToVersionId=token,
RemoveFromVersionId=event['AWSCURRENT']
)

🔍 Interviewer Notes: Testing security best practices.

❌ Common Mistakes: Hardcoding secrets; not caching (costly API calls); no error handling; retrieving secrets on every invocation instead of caching; logging secrets.


Q42: How do you implement Lambda canary deployments?​

Technical Answer: Canary deployments shift traffic gradually between versions to reduce risk.

import boto3

lambda_client = boto3.client('lambda')

# Create alias with routing config
def setup_canary(function_name, version):
"""Setup canary deployment with 10% traffic to new version"""

lambda_client.create_alias(
FunctionName=function_name,
Name='prod',
FunctionVersion=version,
RoutingConfig={
'AdditionalVersionWeights': {
version: 0.1 # 10% to new version
}
}
)

# Shift traffic gradually
def shift_traffic(function_name, alias_name, new_version, percentage):
"""Update canary percentage"""

lambda_client.update_alias(
FunctionName=function_name,
Name=alias_name,
RoutingConfig={
'AdditionalVersionWeights': {
new_version: percentage / 100
}
}
)

# Example progression: 10% → 25% → 50% → 100%
# shift_traffic('my-function', 'prod', '2', 10)
# shift_traffic('my-function', 'prod', '2', 25)
# shift_traffic('my-function', 'prod', '2', 50)
# shift_traffic('my-function', 'prod', '2', 100) # Full promotion

With CodeDeploy:

# appspec.yaml for CodeDeploy
version: 0.0
Resources:
- myLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Name: "my-function"
Alias: "prod"
CurrentVersion: "1"
TargetVersion: "2"
Hooks:
- BeforeAllowTraffic:
- Location: "arn:aws:lambda:...:pre-traffic-hook"
- AfterAllowTraffic:
- Location: "arn:aws:lambda:...:post-traffic-hook"

Canary Strategies:

StrategyTraffic SplitDuration
Canary10Percent30Minutes10% then 100%30 min
Canary10Percent5Minutes10% then 100%5 min
Linear10PercentEvery10Minutes10% increments10 min each
AllAtOnce100%Immediate

🔍 Interviewer Notes: Testing deployment safety.

❌ Common Mistakes: No CloudWatch alarms for rollback; canary without validation; shifting too fast; no automatic rollback triggers; not checking error rates.


Q43: How do you implement Lambda provisioned concurrency?​

Technical Answer: Provisioned concurrency keeps functions initialized to eliminate cold starts for latency-sensitive applications.

import boto3

lambda_client = boto3.client('lambda')

# Configure provisioned concurrency
def setup_provisioned_concurrency(function_name, qualifier, count):
"""Setup provisioned concurrency for alias or version"""

response = lambda_client.put_provisioned_concurrency_config(
FunctionName=function_name,
Qualifier=qualifier, # alias name or version number
ProvisionedConcurrentExecutions=count
)

return response

# Scale provisioned concurrency based on schedule
# Use Application Auto Scaling
application_autoscaling = boto3.client('application-autoscaling')

# Register scalable target
application_autoscaling.register_scalable_target(
ServiceNamespace='lambda',
ResourceId=f'function:{function_name}:prod',
ScalableDimension='lambda:function:ProvisionedConcurrency',
MinCapacity=10,
MaxCapacity=100
)

# Scheduled scaling - increase during business hours
application_autoscaling.put_scheduled_action(
ServiceNamespace='lambda',
ResourceId=f'function:{function_name}:prod',
ScalableDimension='lambda:function:ProvisionedConcurrency',
ScheduledActionName='scale-up-morning',
Schedule='cron(0 8 ? * MON-FRI *)',
ScalableTargetAction={
'MinCapacity': 50,
'MaxCapacity': 100
}
)

# Check provisioned concurrency status
response = lambda_client.get_provisioned_concurrency_config(
FunctionName=function_name,
Qualifier='prod'
)

print(f"Requested: {response['RequestedProvisionedConcurrentExecutions']}")
print(f"Available: {response['AvailableProvisionedConcurrentExecutions']}")
print(f"Allocated: {response['AllocatedProvisionedConcurrentExecutions']}")
print(f"Status: {response['Status']}") # IN_PROGRESS, READY, FAILED

Provisioned Concurrency Cost:

  • Billed per GB-second while warm
  • More expensive than on-demand
  • Use only for latency-critical functions

Auto Scaling Triggers:

  • Target utilization percentage
  • Scheduled scaling
  • Step scaling based on invocations

🔍 Interviewer Notes: Testing performance optimization.

❌ Common Mistakes: Provisioned concurrency for all functions (expensive); not using auto-scaling; not monitoring utilization; forgetting qualifier (alias/version); wrong capacity planning.


Q44: How do you use Lambda with EFS?​

Technical Answer: Mount EFS file systems to Lambda for persistent storage and large file processing.

import boto3
import os

# Lambda with EFS mounted at /mnt/data
def process_large_file(event, context):
mount_path = '/mnt/data'

# Read from EFS
file_path = os.path.join(mount_path, event['filename'])

with open(file_path, 'r') as f:
content = f.read()

# Process large file (can be GBs)
results = process_content(content)

# Write results back to EFS
output_path = os.path.join(mount_path, 'output', event['output_name'])
with open(output_path, 'w') as f:
f.write(json.dumps(results))

return {'statusCode': 200, 'output': output_path}

# Machine learning model serving
def ml_inference(event, context):
import tensorflow as tf

# Load model from EFS (too large for Lambda package)
model_path = '/mnt/data/models/my-model'
model = tf.keras.models.load_model(model_path)

# Perform inference
prediction = model.predict(event['input_data'])

return {'prediction': prediction.tolist()}

# Terraform configuration
# resource "aws_efs_mount_target" "lambda" {
# file_system_id = aws_efs_file_system.lambda_storage.id
# subnet_id = aws_subnet.lambda.id
# security_groups = [aws_security_group.efs.id]
# }
#
# resource "aws_lambda_function" "with_efs" {
# file_system_config {
# arn = aws_efs_access_point.lambda.arn
# local_mount_path = "/mnt/data"
# }
# vpc_config {
# subnet_ids = [aws_subnet.lambda.id]
# security_group_ids = [aws_security_group.lambda.id]
# }
# }

EFS + Lambda Use Cases:

  • Large file processing (>500MB)
  • ML model serving
  • Shared state between invocations
  • Data caching

Considerations:

  • Requires VPC configuration
  • EFS mount adds cold start time (~1-2 seconds)
  • Must handle concurrent writes carefully

🔍 Interviewer Notes: Testing storage integration.

❌ Common Mistakes: EFS in different AZ than Lambda (latency); not handling mount failures; concurrent write conflicts; forgetting VPC config; wrong security group rules.


Q45: How do you implement Lambda security best practices?​

Technical Answer: Secure Lambda with least privilege IAM, VPC isolation, encryption, and environment variable protection.

# IAM least privilege policy
lambda_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudWatchLogs",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:us-east-1:123456789:log-group:/aws/lambda/my-function:*"
},
{
"Sid": "SpecificDynamoDBTable",
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789:table/my-table"
},
{
"Sid": "SpecificS3Bucket",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::my-bucket/uploads/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": "private"
}
}
}
]
}

# VPC configuration for network isolation
lambda_client = boto3.client('lambda')
lambda_client.update_function_configuration(
FunctionName='my-function',
VpcConfig={
'SubnetIds': ['subnet-12345', 'subnet-67890'],
'SecurityGroupIds': ['sg-secure'],
'VpcId': 'vpc-12345'
}
)

# Environment variable encryption
lambda_client.update_function_configuration(
FunctionName='my-function',
Environment={
'Variables': {
'DATABASE_URL': 'encrypted-url',
'API_KEY': 'encrypted-key'
}
},
KMSKeyArn='arn:aws:kms:us-east-1:123456789:key/my-key'
)

# Security scanning in CI/CD
# Use tools like:
# - Checkov for IaC scanning
# - Bandit for Python security
# - Safety for dependency scanning

# Example: Scan for secrets in code
import re

def scan_for_secrets(code):
patterns = {
'aws_access_key': r'AKIA[0-9A-Z]{16}',
'secret_key': r'[0-9a-zA-Z/+]{40}',
'password_assignment': r'password\s*=\s*["\'][^"\']+["\']'
}

findings = []
for name, pattern in patterns.items():
if re.search(pattern, code):
findings.append(f"Potential {name} found")

return findings

Security Checklist:

  • IAM least privilege
  • VPC for network isolation
  • KMS encryption for env vars
  • No hardcoded secrets
  • Security scanning in CI/CD
  • X-Ray for request tracing

🔍 Interviewer Notes: Testing security awareness.

❌ Common Mistakes: Admin access in Lambda role; public VPC subnets; hardcoded credentials; no encryption; no security scanning; overly permissive security groups.


Q46: How do you optimize Lambda performance?​

Technical Answer: Optimize with memory tuning, connection reuse, code optimization, and runtime selection.

# Connection reuse - outside handler
import boto3
from botocore.config import Config

# Initialize once, reuse across invocations
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('my-table')
s3 = boto3.client('s3', config=Config(max_pool_connections=50))

def lambda_handler(event, context):
# Reuse connections - no initialization overhead
table.put_item(Item=event)
return {'statusCode': 200}

# Memory tuning
def get_optimal_memory(function_name):
"""Analyze CloudWatch logs to find optimal memory setting"""
import boto3

logs = boto3.client('logs')

# Query for billed duration vs memory
query = """
fields @timestamp, @message
| filter @message like /Billed Duration/
| parse @message /Billed Duration: * ms/ as duration
| parse @message /Memory Size: * MB/ as memory
| stats avg(duration) by memory
"""

# Lower memory = lower cost but potentially higher duration
# Higher memory = higher cost but faster execution
# Find sweet spot: cost per execution = (memory/1024) * (duration/100ms) * $0.0000166667

return optimal_memory

# Lazy loading for large dependencies
def get_heavy_resource():
"""Load heavy resource only when needed"""
if not hasattr(get_heavy_resource, '_cache'):
import heavy_ml_library
get_heavy_resource._cache = heavy_ml_library.load_model()
return get_heavy_resource._cache

def lambda_handler(event, context):
if event.get('needs_ml'):
model = get_heavy_resource()
return model.predict(event['data'])
return {'statusCode': 200}

# Use faster runtime
# Python 3.11 faster than 3.9
# Java with GraalVM native image (SnapStart)
# Rust for compute-intensive tasks

# Minimize deployment package
# - Remove unnecessary files
# - Use Lambda layers for dependencies
# - Compress assets

Performance Tuning:

OptimizationImpact
Connection reuseReduces latency 100-500ms
Memory increaseMay reduce duration more than cost increase
Runtime upgrade10-30% speed improvement
Lazy loadingReduces cold start
Provisioned concurrencyEliminates cold start

🔍 Interviewer Notes: Testing optimization skills.

❌ Common Mistakes: New connection per request; wrong memory size (not tested); loading all dependencies at startup; not using latest runtime; synchronous calls that could be async.


Q47: How do you implement Lambda with Kinesis?​

Technical Answer: Lambda processes records from Kinesis Data Streams for real-time data streaming.

import json
import base64

def process_kinesis_records(event, context):
"""Process Kinesis data stream records"""

failed_records = []

for record in event['Records']:
try:
# Decode Kinesis record
payload = base64.b64decode(record['kinesis']['data'])
data = json.loads(payload)

# Process based on event type
event_type = data.get('event_type')

if event_type == 'order_created':
process_order(data)
elif event_type == 'user_signup':
process_user_signup(data)
elif event_type == 'payment_processed':
process_payment(data)

# Log progress
print(f"Processed record: {record['kinesis']['sequenceNumber']}")

except Exception as e:
print(f"Failed to process record: {str(e)}")
failed_records.append({
'itemIdentifier': record['kinesis']['sequenceNumber']
})

# Return failed records for retry
return {'batchItemFailures': failed_records}

# Event source mapping configuration
import boto3

lambda_client = boto3.client('lambda')

# Create Kinesis trigger
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:kinesis:us-east-1:123456789:stream/my-stream',
FunctionName='process-kinesis',
StartingPosition='LATEST', # or TRIM_HORIZON
BatchSize=100,
MaximumBatchingWindowInSeconds=5,
ParallelizationFactor=10, # Multiple Lambda instances per shard
DestinationConfig={
'OnFailure': {
'Destination': 'arn:aws:sns:us-east-1:123456789:dlq-topic'
}
}
)

# Kinesis processing patterns
def aggregate_records(records):
"""Aggregate multiple records for batch processing"""
orders = []
users = []

for record in records:
data = json.loads(base64.b64decode(record['kinesis']['data']))

if data['type'] == 'order':
orders.append(data)
elif data['type'] == 'user':
users.append(data)

# Batch insert to DynamoDB
if orders:
batch_write_orders(orders)
if users:
batch_write_users(users)

Kinesis + Lambda Features:

  • Batch processing (up to 10,000 records or 6MB)
  • Parallelization factor (multiple Lambdas per shard)
  • Batching window (0-300 seconds)
  • Partial batch response (retry specific records)
  • On-failure destination (DLQ)

🔍 Interviewer Notes: Testing stream processing.

❌ Common Mistakes: Not handling partial batch failures; processing one record at a time (inefficient); no checkpoint tracking; wrong starting position; not handling provisioned throughput exceeded.



2. Intermediate Topics​

Q48: How do you implement Lambda CI/CD pipelines?​

Technical Answer: Lambda SnapStart is a feature for Java functions that reduces cold start times by initializing the function ahead of time and creating a snapshot.

How it works:

  1. Lambda initializes your function during publishing
  2. Takes a snapshot of the initialized execution environment
  3. On invocation, restores from snapshot instead of initializing from scratch

Benefits:

  • Up to 10x faster cold starts for Java
  • No code changes required
  • Works with Java 11 and Java 17

Limitations:

  • Only available for Java runtime
  • Snapshots are regional
  • Some operations may need re-initialization after restore
# Enable SnapStart when publishing version
import boto3

lambda_client = boto3.client('lambda')

# Publish version with SnapStart
response = lambda_client.publish_version(
FunctionName='my-java-function',
SnapStart={
'ApplyOn': 'PublishedVersions' # or 'None' to disable
}
)

🔍 Interviewer Notes: Testing knowledge of latest Lambda features and Java optimization.

❌ Common Mistakes:

  • Trying to use SnapStart with Python/Node.js
  • Not testing that connections work after restore
  • Not understanding that snapshots are regional

Q49: How do you use Lambda with EventBridge?​

Technical Answer: EventBridge is a serverless event bus that can trigger Lambda functions based on events from AWS services, SaaS applications, or custom events.

EventBridge Rule with Lambda Target:

import boto3

events = boto3.client('events')

# Create custom event bus
events.create_event_bus(
Name='my-application-events',
Description='Event bus for my application'
)

# Create rule
events.put_rule(
Name='order-created-rule',
EventBusName='my-application-events',
EventPattern=json.dumps({
'source': ['order-service'],
'detail-type': ['Order Created'],
'detail': {
'status': ['confirmed']
}
}),
State='ENABLED'
)

# Add Lambda as target
events.put_targets(
Rule='order-created-rule',
EventBusName='my-application-events',
Targets=[{
'Id': '1',
'Arn': 'arn:aws:lambda:us-east-1:123456789:function:process-order',
'RetryPolicy': {
'MaximumRetryAttempts': 3,
'MaximumEventAgeInSeconds': 3600
},
'DeadLetterConfig': {
'Arn': 'arn:aws:sqs:us-east-1:123456789:failed-events'
}
}]
)

Lambda Handler for EventBridge:

import json

def lambda_handler(event, context):
"""
EventBridge event structure:
{
"version": "0",
"id": "12345678-1234-1234-1234-123456789012",
"detail-type": "Order Created",
"source": "order-service",
"account": "123456789",
"time": "2024-01-01T00:00:00Z",
"region": "us-east-1",
"detail": {
"order_id": "12345",
"customer_id": "67890",
"amount": 99.99
}
}
"""

# Extract order details
order = event['detail']

# Process order
process_order(order)

return {'statusCode': 200}

Scheduling with EventBridge:

# Schedule Lambda to run every hour
events.put_rule(
Name='hourly-cleanup',
ScheduleExpression='rate(1 hour)', # or 'cron(0 12 * * ? *)'
State='ENABLED'
)

events.put_targets(
Rule='hourly-cleanup',
Targets=[{
'Id': '1',
Arn': 'arn:aws:lambda:...:function:cleanup-function'
}]
)

🔍 Interviewer Notes: Testing event-driven architecture and scheduling patterns.

❌ Common Mistakes:

  • Not handling duplicate events (EventBridge may deliver more than once)
  • Not using dead letter queues for failed events
  • Wrong EventPattern syntax

Q50: How do you use Lambda Container Images?​

Technical Answer: Lambda supports container images up to 10GB, allowing you to include large dependencies and custom runtimes.

Dockerfile for Lambda:

# Use AWS Lambda base image for Python
FROM public.ecr.aws/lambda/python:3.11

# Copy requirements and install
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy function code
COPY app.py .

# Set the handler
CMD ["app.lambda_handler"]

Building and Pushing:

# Build image
docker build -t my-lambda-function:latest .

# Authenticate with ECR
aws ecr get-login-password | docker login --username AWS --password-stdin 123456789.dkr.ecr.us-east-1.amazonaws.com

# Tag and push
docker tag my-lambda-function:latest 123456789.dkr.ecr.us-east-1.amazonaws.com/my-lambda-function:latest
docker push 123456789.dkr.ecr.us-east-1.amazonaws.com/my-lambda-function:latest

Creating Lambda from Container:

import boto3

lambda_client = boto3.client('lambda')

lambda_client.create_function(
FunctionName='container-function',
Code={
'ImageUri': '123456789.dkr.ecr.us-east-1.amazonaws.com/my-lambda-function:latest'
},
PackageType='Image',
Role='arn:aws:iam::123456789:role/lambda-execution-role',
Timeout=30,
MemorySize=512
)

Multi-Stage Build for Smaller Images:

# Build stage
FROM public.ecr.aws/lambda/python:3.11 AS builder

COPY requirements.txt .
RUN pip install --user -r requirements.txt

# Production stage
FROM public.ecr.aws/lambda/python:3.11

# Copy only the installed packages
COPY --from=builder /root/.local/lib/python3.11/site-packages /var/lang/lib/python3.11/site-packages

COPY app.py .
CMD ["app.lambda_handler"]

🔍 Interviewer Notes: Testing container knowledge and Lambda deployment options.

❌ Common Mistakes:

  • Using non-Lambda base images (missing Lambda Runtime API)
  • Not handling image size (affects cold starts)
  • Not using multi-stage builds

Q51: How do you implement blue-green deployments with Lambda?​

Technical Answer: Use weighted aliases to gradually shift traffic between versions.

import boto3

lambda_client = boto3.client('lambda')

# Publish new version
new_version = lambda_client.publish_version(
FunctionName='my-function'
)['Version']

# Update alias with 10% to new version
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion=new_version,
RoutingConfig={
'AdditionalVersionWeights': {
'1': 0.1 # 10% to version 1 (old)
}
}
)

# Monitor metrics, then shift more traffic
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion=new_version,
RoutingConfig={
'AdditionalVersionWeights': {
'1': 0.5 # 50% split
}
}
)

# Finally, 100% to new version
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion=new_version,
RoutingConfig={
'AdditionalVersionWeights': {}
}
)

Rollback:

# Rollback to previous version
lambda_client.update_alias(
FunctionName='my-function',
Name='prod',
FunctionVersion='1' # Previous stable version
)

🔍 Interviewer Notes: Testing deployment strategies and risk management.

❌ Common Mistakes:

  • Not monitoring metrics during canary
  • Not having automatic rollback criteria
  • Not testing alias routing locally

Q52: What is Lambda Insights and how do you use it?​

Technical Answer: Lambda Insights is a monitoring solution that collects system-level metrics from Lambda functions.

Enabling Lambda Insights:

# Add Lambda Insights layer
lambda_client.update_function_configuration(
FunctionName='my-function',
Layers=[
'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14'
]
)

Metrics Collected:

  • CPU utilization
  • Memory utilization
  • Network utilization
  • Cold start duration
  • Init duration

Viewing in CloudWatch:

import boto3

cloudwatch = boto3.client('cloudwatch')

# Get Lambda Insights metrics
response = cloudwatch.get_metric_statistics(
Namespace='LambdaInsights',
MetricName='memory_utilization',
Dimensions=[
{'Name': 'function_name', 'Value': 'my-function'}
],
StartTime=datetime.utcnow() - timedelta(hours=1),
EndTime=datetime.utcnow(),
Period=60,
Statistics=['Average', 'Maximum']
)

🔍 Interviewer Notes: Testing observability and monitoring practices.

❌ Common Mistakes:

  • Not enabling Lambda Insights in production
  • Not using metrics to right-size functions
  • Not correlating with application metrics

Q53: How do you handle partial failures in Lambda batch processing?​

Technical Answer: Use partial batch response to report which records failed.

SQS with Partial Batch Response:

def lambda_handler(event, context):
batch_item_failures = []

for record in event['Records']:
message_id = record['messageId']
try:
process_message(record['body'])
except RetryableException as e:
# Will be retried
batch_item_failures.append({'itemIdentifier': message_id})
except NonRetryableException as e:
# Send to DLQ, don't retry
send_to_dlq(record)
except Exception as e:
# Unknown error, retry
batch_item_failures.append({'itemIdentifier': message_id})

return {'batchItemFailures': batch_item_failures}

Kinesis with Bisect on Error:

# Event source mapping configuration
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:kinesis:...:stream/my-stream',
FunctionName='my-function',
BatchSize=100,
BisectBatchOnError=True, # Split batch on error
MaximumRetryAttempts=3,
MaximumRecordAgeInSeconds=3600,
ParallelizationFactor=10
)

🔍 Interviewer Notes: Testing error handling in batch processing.

❌ Common Mistakes:

  • Not implementing partial batch response
  • Not distinguishing retryable vs non-retryable errors
  • Not handling poison pill messages

Q54: How do you optimize Lambda for ML inference?​

Technical Answer: ML workloads require specific optimizations for Lambda.

Container Image with Model:

FROM public.ecr.aws/lambda/python:3.11

# Install ML libraries
RUN pip install torch torchvision numpy

# Download and cache model during build
COPY download_model.py .
RUN python download_model.py

COPY inference.py .

CMD ["inference.handler"]

Inference Handler:

import json
import torch

# Load model once during cold start
model = None

def load_model():
global model
if model is None:
model = torch.load('/opt/ml/model.pth')
model.eval()
return model

def handler(event, context):
# Model already loaded
model = load_model()

# Parse input
input_data = json.loads(event['body'])

# Inference
with torch.no_grad():
result = model(input_data)

return {
'statusCode': 200,
'body': json.dumps({'prediction': result.tolist()})
}

Provisioned Concurrency for ML:

# Keep ML functions warm
lambda_client.put_provisioned_concurrency_config(
FunctionName='ml-inference',
Qualifier='prod',
ProvisionedConcurrentExecutions=10
)

🔍 Interviewer Notes: Testing ML workload optimization.

❌ Common Mistakes:

  • Loading model inside handler (every invocation)
  • Not using provisioned concurrency for low latency
  • Not using appropriate memory size for CPU-bound inference

Q55: How do you implement Lambda function versioning and aliases?​

Technical Answer: Versions are immutable snapshots. Aliases are pointers to versions.

Versioning Best Practices:

import boto3

lambda_client = boto3.client('lambda')

def deploy_new_version(function_name):
"""Deploy with blue-green strategy"""

# 1. Update $LATEST
lambda_client.update_function_code(
FunctionName=function_name,
ZipFile=open('function.zip', 'rb').read()
)

# 2. Wait for update
waiter = lambda_client.get_waiter('function_updated')
waiter.wait(FunctionName=function_name)

# 3. Publish version
version_response = lambda_client.publish_version(
FunctionName=function_name,
Description='Release v1.2.3 - bug fixes'
)
new_version = version_response['Version']

# 4. Create/update alias with canary
lambda_client.update_alias(
FunctionName=function_name,
Name='prod',
FunctionVersion=new_version,
RoutingConfig={
'AdditionalVersionWeights': {
str(int(new_version) - 1): 0.1
}
}
)

return new_version

# List all versions
versions = lambda_client.list_versions_by_function(
FunctionName='my-function'
)['Versions']

# Delete old versions (keep last 10)
for v in versions[:-10]:
if v['Version'] != '$LATEST':
lambda_client.delete_function(
FunctionName='my-function',
Qualifier=v['Version']
)

🔍 Interviewer Notes: Testing deployment management and versioning strategy.

❌ Common Mistakes:

  • Not using aliases (clients point to versions directly)
  • Not cleaning up old versions (hitting limit)
  • Not using weighted routing for canary

Q56: How do you use Lambda with Amazon API Gateway?​

Technical Answer: API Gateway triggers Lambda synchronously for REST APIs.

API Gateway + Lambda Integration:

def lambda_handler(event, context):
"""
API Gateway event structure:
{
"resource": "/users/{id}",
"path": "/users/123",
"httpMethod": "GET",
"headers": {...},
"queryStringParameters": {"expand": "profile"},
"pathParameters": {"id": "123"},
"body": null,
"requestContext": {
"authorizer": {"claims": {"sub": "user-uuid"}}
}
}
"""

http_method = event['httpMethod']
path_params = event.get('pathParameters', {})
query_params = event.get('queryStringParameters', {}) or {}

if http_method == 'GET':
user_id = path_params.get('id')
user = get_user(user_id, query_params.get('expand'))
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(user)
}

elif http_method == 'POST':
body = json.loads(event['body'])
new_user = create_user(body)
return {
'statusCode': 201,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(new_user)
}

API Gateway Lambda Authorizer:

def authorizer(event, context):
"""
Custom authorizer for API Gateway
"""
token = event['authorizationToken']

try:
# Validate JWT
claims = validate_jwt(token)

return {
'principalId': claims['sub'],
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{
'Action': 'execute-api:Invoke',
'Effect': 'Allow',
'Resource': event['methodArn']
}]
},
'context': {
'userId': claims['sub'],
'role': claims['role']
}
}
except Exception:
return {
'principalId': 'unauthorized',
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{
'Action': 'execute-api:Invoke',
'Effect': 'Deny',
'Resource': event['methodArn']
}]
}
}

🔍 Interviewer Notes: Testing API integration and authentication patterns.

❌ Common Mistakes:

  • Not returning proper API Gateway response format
  • Not handling CORS in Lambda (should be in API Gateway)
  • Not using authorizer context

Q57: How do you implement Lambda security scanning?​

Technical Answer: Use Lambda Code Signing and vulnerability scanning.

Code Signing Configuration:

import boto3

signer = boto3.client('signer')
lambda_client = boto3.client('lambda')

# Create signing profile
signing_profile = signer.put_signing_profile(
profileName='lambda-signing',
signingMaterial={'certificateArn': 'arn:aws:acm:...'},
signatureValidityPeriod={'type': 'MONTHS', 'value': 12},
platformArn='arn:aws:signer::...:/aws/lambda-sha384-ecdsa'
)

# Enable code signing on function
lambda_client.put_function_code_signing_config(
FunctionName='my-function',
CodeSigningConfigArn='arn:aws:lambda:...:code-signing-config:...'
)

Lambda Layers for Security Scanning:

# Security scanning layer
def lambda_handler(event, context):
# Scan dependencies for vulnerabilities
import subprocess
result = subprocess.run(
['safety', 'check', '--json'],
capture_output=True,
text=True
)

if result.returncode != 0:
print(f"Vulnerabilities found: {result.stdout}")
# Notify security team

return {'statusCode': 200}

🔍 Interviewer Notes: Testing security practices and supply chain security.

❌ Common Mistakes:

  • Not enabling code signing
  • Not scanning dependencies
  • Not validating signing profiles

Q58: How do you implement structured logging in Lambda?​

Technical Answer: Use structured JSON logging for better CloudWatch Logs parsing and analysis. Python's logging module with JSON formatter enables searchable, filterable logs.

Code Example:

import json
import logging
import os
from datetime import datetime

# Configure structured logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
# Structured log entry
logger.info(json.dumps({
"timestamp": datetime.utcnow().isoformat(),
"request_id": context.aws_request_id,
"function_name": context.function_name,
"event_type": event.get('detail-type', 'unknown'),
"message": "Function invoked",
"environment": os.environ.get('STAGE', 'dev')
}))

try:
result = process_event(event)
logger.info(json.dumps({
"message": "Processing successful",
"result_id": result.get('id'),
"duration_ms": context.get_remaining_time_in_millis()
}))
return {"status": "success", "data": result}
except Exception as e:
logger.error(json.dumps({
"message": "Processing failed",
"error": str(e),
"error_type": type(e).__name__
}))
raise

def process_event(event):
return {"id": "123", "processed": True}

CloudWatch Logs Insights Query:

fields @timestamp, @message
| filter @message like /request_id/
| parse @message "[*] *" as level, msg
| stats count() by level

🔍 Interviewer Notes: Tests logging best practices and operational awareness.

❌ Common Mistakes:

  • Using print() instead of structured logging
  • Not including request IDs for tracing
  • Logging sensitive data (PII, credentials)

Q59: How do you monitor Lambda with CloudWatch Metrics?​

Technical Answer: Lambda automatically publishes metrics to CloudWatch. Key metrics include invocations, duration, errors, throttles, and concurrent executions. Use these for alerting and optimization.

Key Metrics Table:

MetricDescriptionThreshold Recommendation
InvocationsNumber of function callsN/A - volume indicator
DurationExecution time>80% of timeout
ErrorsFailed invocations>1% error rate
ThrottlesThrottled invocations>0 - investigate immediately
ConcurrentExecutionsConcurrent runs>80% of limit
IteratorAgeStream processing lag>500ms for Kinesis/DynamoDB

Setting Up Alarms:

import boto3

cloudwatch = boto3.client('cloudwatch')

def create_lambda_alarm(function_name):
cloudwatch.put_metric_alarm(
AlarmName=f'{function_name}-high-errors',
AlarmDescription='Lambda error rate > 5%',
MetricName='Errors',
Namespace='AWS/Lambda',
Statistic='Sum',
Period=300, # 5 minutes
EvaluationPeriods=1,
Threshold=5,
ComparisonOperator='GreaterThanThreshold',
Dimensions=[
{'Name': 'FunctionName', 'Value': function_name}
],
AlarmActions=['arn:aws:sns:us-east-1:123456789:alerts']
)

🔍 Interviewer Notes: Tests monitoring strategy and CloudWatch knowledge.

❌ Common Mistakes:

  • Not setting up alarms on errors/throttles
  • Monitoring average duration instead of p99
  • Not tracking concurrent executions

Q60: How do you use Lambda with CloudWatch Logs subscription filters?​

Technical Answer: CloudWatch Logs subscription filters enable real-time processing of log data by streaming to Lambda, Kinesis, or Firehose for analysis, alerting, or archiving.

Code Example:

import boto3
import json

logs = boto3.client('logs')

def create_subscription_filter(function_name, log_group):
logs.put_subscription_filter(
logGroupName=log_group,
filterName='ErrorAlertFilter',
filterPattern='ERROR' if False else '?ERROR ?error ?Exception',
destinationArn=f'arn:aws:lambda:us-east-1:123456789:function:{function_name}',
distribution='ByLogStream'
)

# Lambda function to process log events
def log_processor_handler(event, context):
import base64
import gzip
from datetime import datetime

# Decode and decompress CloudWatch Logs data
compressed_data = base64.b64decode(event['awslogs']['data'])
log_data = json.loads(gzip.decompress(compressed_data))

# Process log events
for log_event in log_data['logEvents']:
message = json.loads(log_event['message'])
if message.get('level') == 'ERROR':
# Send to alerting system
print(f"ALERT: {message}")

return {'status': 'processed'}

Subscription Filter Patterns:

PatternMatches
ERRORLog messages containing "ERROR"
?ERROR ?errorCase-insensitive error matching
[timestamp, *]JSON with timestamp field

🔍 Interviewer Notes: Tests real-time log processing and event-driven patterns.

❌ Common Mistakes:

  • Not handling compressed log data
  • Incorrect IAM permissions for destination
  • Filter pattern syntax errors

Q61: How do you implement exponential backoff in Lambda?​

Technical Answer: Exponential backoff with jitter reduces retry storms and throttling. AWS SDKs have built-in retry logic, but custom implementations need careful design for idempotency.

Code Example:

import time
import random
from botocore.exceptions import ClientError

def exponential_backoff(max_retries=5, base_delay=1):
"""Decorator for exponential backoff with jitter"""
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except ClientError as e:
if e.response['Error']['Code'] in ['Throttling', 'RequestLimitExceeded']:
if attempt == max_retries - 1:
raise
# Exponential backoff with jitter
delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
print(f"Retry {attempt + 1}/{max_retries} after {delay:.2f}s")
time.sleep(delay)
else:
raise
return None
return wrapper
return decorator

@exponential_backoff(max_retries=5)
def call_external_api(url, payload):
import requests
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
return response.json()

def lambda_handler(event, context):
result = call_external_api('https://api.example.com/data', event)
return {'status': 'success', 'data': result}

🔍 Interviewer Notes: Tests error handling and resilience patterns.

❌ Common Mistakes:

  • Not adding jitter (causes retry storms)
  • Infinite retry loops
  • Not making operations idempotent

Q62: How do you handle Lambda function idempotency?​

Technical Answer: Idempotency ensures multiple identical requests produce the same result without side effects. Use unique request IDs stored in DynamoDB with TTL for idempotency tracking.

Code Example:

import boto3
import uuid
from datetime import datetime, timedelta

dynamodb = boto3.resource('dynamodb')
idempotency_table = dynamodb.Table('LambdaIdempotency')

def idempotent_handler(event, context):
# Extract or generate idempotency key
request_id = event.get('request_id') or str(uuid.uuid4())

# Check if already processed
try:
response = idempotency_table.get_item(
Key={'request_id': request_id}
)
if 'Item' in response:
print(f"Request {request_id} already processed")
return response['Item']['result']
except Exception as e:
print(f"Idempotency check failed: {e}")

# Process the request
result = process_business_logic(event)

# Store result for idempotency
idempotency_table.put_item(
Item={
'request_id': request_id,
'result': result,
'expires_at': int((datetime.now() + timedelta(hours=24)).timestamp())
}
)

return result

def process_business_logic(event):
return {'processed': True, 'data': event}

Idempotency Strategies:

StrategyUse CaseProsCons
DynamoDB TTLAPI operationsFast, automatic cleanupCost, eventual consistency
S3 object lockLarge payloadsDurable, versionedSlower, more complex
In-memory cacheHigh-frequencyFastestLost on cold start

🔍 Interviewer Notes: Tests distributed systems thinking and API design.

❌ Common Mistakes:

  • Not considering idempotency key selection
  • Storing too much data in idempotency table
  • Not setting TTL on tracking records

Q63: How do you implement dead letter queues (DLQ) for Lambda?​

Technical Answer: DLQs capture failed async invocations for later analysis and reprocessing. Configure SQS or SNS as DLQ destinations for async and stream sources.

Code Example:

import boto3

lambda_client = boto3.client('lambda')
sqs = boto3.client('sqs')

def configure_dlq(function_name, queue_url):
# Get queue ARN
queue_attrs = sqs.get_queue_attributes(
QueueUrl=queue_url,
AttributeNames=['QueueArn']
)
queue_arn = queue_attrs['Attributes']['QueueArn']

# Configure DLQ for async invocations
lambda_client.put_function_event_invoke_config(
FunctionName=function_name,
DestinationConfig={
'OnFailure': {
'Destination': queue_arn
}
}
)
print(f"DLQ configured: {queue_arn}")

# Process failed events from DLQ
def dlq_processor_handler(event, context):
for record in event['Records']:
# Parse failed invocation
failed_payload = json.loads(record['body'])
original_event = json.loads(failed_payload.get('requestPayload', '{}'))

print(f"Processing failed event: {failed_payload}")

# Implement reprocessing logic or alerting
if should_retry(original_event):
retry_with_backoff(original_event)
else:
send_to_error_team(failed_payload)

return {'status': 'processed'}

def should_retry(event):
return event.get('retry_count', 0) < 3

def retry_with_backoff(event):
import boto3
lambda_client = boto3.client('lambda')
event['retry_count'] = event.get('retry_count', 0) + 1
lambda_client.invoke(
FunctionName='my-function',
InvocationType='Event',
Payload=json.dumps(event)
)

🔍 Interviewer Notes: Tests error handling architecture and async patterns.

❌ Common Mistakes:

  • Not processing DLQ messages (leads to data loss)
  • Configuring DLQ for sync invocations (not supported)
  • Not setting up alarms on DLQ depth

Q64: How do you handle Lambda partial failures in batch processing?​

Technical Answer: When processing batched records (SQS, Kinesis, DynamoDB Streams), partial failures must be handled by returning failed record IDs so Lambda can retry only those records.

Code Example:

def lambda_handler(event, context):
records = event.get('Records', [])
failed_record_ids = []

for record in records:
try:
process_record(record)
except Exception as e:
print(f"Failed to process record: {record['messageId']}, Error: {e}")
failed_record_ids.append(record['messageId'])

# For SQS: return batch item failures
if failed_record_ids:
return {
'batchItemFailures': [
{'itemIdentifier': record_id} for record_id in failed_record_ids
]
}

return {'status': 'success'}

def process_record(record):
import json
body = json.loads(record['body'])

# Simulate processing
if body.get('should_fail'):
raise Exception("Simulated failure")

print(f"Processed record: {body}")

# For Kinesis/DynamoDB Streams: use checkpointing
def kinesis_handler(event, context):
for record in event['Records']:
try:
process_kinesis_record(record)
except Exception as e:
# With Kinesis, failing stops processing
# Implement custom checkpointing or accept potential data loss
print(f"Failed to process shard: {record['kinesis']['sequenceNumber']}")
raise # Let Lambda retry the batch

Batch Failure Handling:

SourceFailure BehaviorSolution
SQSPartial batch failureReturn batchItemFailures
KinesisEntire batch retryEnsure idempotency, use smaller batches
DynamoDB StreamsEntire batch retryProcess in try-catch, checkpoint manually

🔍 Interviewer Notes: Tests understanding of stream processing and fault tolerance.

❌ Common Mistakes:

  • Not returning failed record IDs for SQS
  • Throwing exceptions that retry all records
  • Not making processing idempotent

Q65: How do you implement Lambda retry policies?​

Technical Answer: Lambda provides built-in retry logic: 2 retries for async invocations, configurable for stream sources. Understand retry behavior to design resilient systems.

Retry Behavior Table:

Invocation TypeDefault RetriesMax RetriesDLQ Support
Synchronous00No
Asynchronous22Yes
SQS3 (visibility timeout)ConfigurableYes
Kinesis/DynamoDBUntil success or timeoutConfigurableNo (use checkpointing)

Code Example:

import boto3

lambda_client = boto3.client('lambda')

def configure_retry_policy(function_name):
# Async invocation configuration
lambda_client.put_function_event_invoke_config(
FunctionName=function_name,
MaximumRetryAttempts=2, # 0-2 for async
MaximumEventAgeInSeconds=21600 # 6 hours max
)

def invoke_with_retry(function_name, payload):
try:
response = lambda_client.invoke(
FunctionName=function_name,
InvocationType='Event', # Async
Payload=json.dumps(payload)
)
print(f"Invoked async: {response['StatusCode']}")
except Exception as e:
print(f"Invocation failed: {e}")
# Client is responsible for retry logic for sync calls
raise

# Stream source retry configuration
def configure_stream_retry(event_source_uuid):
lambda_client.update_event_source_mapping(
UUID=event_source_uuid,
MaximumRetryAttempts=10000, # For streams
MaximumRecordAgeInSeconds=604800, # 7 days
BisectBatchOnFunctionError=True # Debug failing batches
)

🔍 Interviewer Notes: Tests understanding of Lambda retry mechanisms and when to implement custom retry.

❌ Common Mistakes:

  • Expecting retries on sync invocations
  • Not configuring DLQ for async functions
  • Not handling idempotency with retries

Q66: How do you test Lambda error handling locally?​

Technical Answer: Use Lambda runtime interface emulator (RIE) and testing frameworks to simulate failures, timeouts, and error conditions locally before deployment.

Code Example:

import pytest
import json
from unittest.mock import patch, Mock

# Lambda function to test
def lambda_handler(event, context):
if event.get('should_fail'):
raise Exception("Simulated failure")

if event.get('timeout_soon'):
import time
time.sleep(context.get_remaining_time_in_millis() / 1000 + 1)

return {'status': 'success'}

# Test class
class TestLambdaErrorHandling:
def test_success(self):
event = {'test': 'data'}
context = Mock()
context.get_remaining_time_in_millis = Mock(return_value=300000)

result = lambda_handler(event, context)
assert result['status'] == 'success'

def test_failure(self):
event = {'should_fail': True}
context = Mock()

with pytest.raises(Exception) as exc_info:
lambda_handler(event, context)
assert "Simulated failure" in str(exc_info.value)

def test_timeout_handling(self):
event = {'timeout_soon': True}
context = Mock()
context.get_remaining_time_in_millis = Mock(return_value=100) # 100ms left

# Function should handle low time remaining gracefully
result = lambda_handler(event, context)
# Assert timeout handling logic

@patch('boto3.client')
def test_external_service_failure(self, mock_boto):
# Mock external service failure
mock_client = Mock()
mock_client.invoke.side_effect = Exception("Service unavailable")
mock_boto.return_value = mock_client

# Test retry logic
event = {'action': 'call_external'}
# Implement and test retry with backoff

# Run with: python -m pytest test_lambda.py -v

Local Testing Tools:

ToolPurposeCommand
pytestUnit testspytest test_lambda.py
motoAWS service mockingpip install moto
aws-lambda-rieRuntime emulator./aws-lambda-rie my-function

🔍 Interviewer Notes: Tests testing strategy and local development practices.

❌ Common Mistakes:

  • Only testing happy path
  • Not mocking AWS services
  • Not testing timeout scenarios

Q67: How do you implement Lambda canary deployments?​

Technical Answer: Canary deployments gradually shift traffic to new Lambda versions using aliases with routing configurations. This enables safe production deployments with automatic rollback on errors.

Code Example:

import boto3

lambda_client = boto3.client('lambda')

def setup_canary_deployment(function_name, new_version):
# Create alias with weighted routing
lambda_client.create_alias(
FunctionName=function_name,
Name='prod',
FunctionVersion=new_version,
Description='Production alias with canary',
RoutingConfig={
'AdditionalVersionWeights': {
new_version: 0.1 # 10% traffic to new version
}
}
)
print(f"Canary deployment: 10% to version {new_version}")

def shift_traffic_gradually(function_name, new_version):
"""Shift traffic 10% -> 50% -> 100%"""
weights = [0.1, 0.3, 0.5, 0.75, 1.0]

for weight in weights:
lambda_client.update_alias(
FunctionName=function_name,
Name='prod',
RoutingConfig={
'AdditionalVersionWeights': {
new_version: weight
}
}
)
print(f"Traffic shifted: {weight*100}% to version {new_version}")

# Monitor error rates before continuing
if not check_error_rates(function_name):
print("Error rate too high, rolling back!")
rollback_deployment(function_name, new_version)
break

import time
time.sleep(300) # Wait 5 minutes between shifts

# Finalize: point alias to new version only
lambda_client.update_alias(
FunctionName=function_name,
Name='prod',
FunctionVersion=new_version,
RoutingConfig={'AdditionalVersionWeights': {}}
)

def check_error_rates(function_name):
import boto3
cloudwatch = boto3.client('cloudwatch')

# Get error metric for last 5 minutes
response = cloudwatch.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName='Errors',
Dimensions=[{'Name': 'FunctionName', 'Value': function_name}],
StartTime=datetime.utcnow() - timedelta(minutes=5),
EndTime=datetime.utcnow(),
Period=300,
Statistics=['Sum']
)

errors = response['Datapoints'][0]['Sum'] if response['Datapoints'] else 0
return errors < 5 # Arbitrary threshold

def rollback_deployment(function_name, current_version):
# Get previous version
versions = lambda_client.list_versions_by_function(FunctionName=function_name)
sorted_versions = sorted([int(v['Version']) for v in versions['Versions'] if v['Version'] != '$LATEST'])
previous_version = str(sorted_versions[-2]) # Second to last

lambda_client.update_alias(
FunctionName=function_name,
Name='prod',
FunctionVersion=previous_version
)
print(f"Rolled back to version {previous_version}")

🔍 Interviewer Notes: Tests deployment strategies and production safety.

❌ Common Mistakes:

  • Not monitoring during canary
  • Shifting traffic too quickly
  • Not implementing rollback logic

Q68: How do you use Lambda environment variables for configuration?​

Technical Answer: Environment variables provide runtime configuration without code changes. Use them for feature flags, API endpoints, and configuration, but never store secrets (use Secrets Manager instead).

Code Example:

import os
import json

def lambda_handler(event, context):
# Read environment variables
stage = os.environ.get('STAGE', 'dev')
api_endpoint = os.environ.get('API_ENDPOINT')
log_level = os.environ.get('LOG_LEVEL', 'INFO')

# Feature flags
enable_caching = os.environ.get('ENABLE_CACHE', 'false').lower() == 'true'
max_retries = int(os.environ.get('MAX_RETRIES', '3'))

print(f"Running in {stage} with log level {log_level}")

# Use configuration
if enable_caching:
print("Caching enabled")

# Don't store secrets in env vars!
# BAD: api_key = os.environ['API_KEY'] # Insecure
# GOOD: Use Secrets Manager instead

return {
'stage': stage,
'cache_enabled': enable_caching
}

# AWS CLI: Set environment variables
"""
aws lambda update-function-configuration \
--function-name my-function \
--environment Variables='{
"STAGE": "production",
"API_ENDPOINT": "https://api.example.com",
"LOG_LEVEL": "WARN",
"ENABLE_CACHE": "true",
"MAX_RETRIES": "5"
}'
"""

Environment Variable Best Practices:

PracticeDoDon't
SecretsUse Secrets ManagerStore in env vars
ConfigurationUse env varsHardcode values
StagesDifferent vars per stageSame vars everywhere
EncryptionEnable at restLeave plaintext

🔍 Interviewer Notes: Tests configuration management and security awareness.

❌ Common Mistakes:

  • Storing API keys/secrets in environment variables
  • Not encrypting environment variables at rest
  • Hardcoding configuration values

Q69: How do you implement Lambda function configuration management?​

Technical Answer: Manage Lambda configuration through IaC (CloudFormation, Terraform, SAM) for consistency, versioning, and environment-specific deployments.

SAM Template Example:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31

Parameters:
Stage:
Type: String
Default: dev
AllowedValues: [dev, staging, prod]

Conditions:
IsProduction: !Equals [!Ref Stage, prod]

Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub "my-function-${Stage}"
Runtime: python3.11
Handler: index.lambda_handler
CodeUri: ./src/
MemorySize: !If [IsProduction, 1024, 512]
Timeout: !If [IsProduction, 30, 10]
Environment:
Variables:
STAGE: !Ref Stage
LOG_LEVEL: !If [IsProduction, WARN, DEBUG]
API_ENDPOINT: !Ref ApiEndpoint
ReservedConcurrencyLimit: !If [IsProduction, 100, 10]
Policies:
- AWSLambdaBasicExecutionRole
- Version: "2012-10-17"
Statement:
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref MySecret

ApiEndpoint:
Type: String
Default: https://api.example.com

MySecret:
Type: AWS::SecretsManager::Secret
Properties:
SecretString: '{"api_key": "secret-value"}'

Configuration Management Tools:

ToolUse CaseProsCons
SAMSimple serverlessNative, simpleLimited to Lambda
CloudFormationAWS-nativeFree, integratedVerbose YAML
TerraformMulti-cloudProvider ecosystemExtra tooling
Serverless FrameworkMulti-cloudPlugin ecosystemAbstraction overhead

🔍 Interviewer Notes: Tests IaC knowledge and deployment practices.

❌ Common Mistakes:

  • Manual console changes (not in code)
  • Not versioning configuration
  • Environment-specific hardcoded values

Q70: How do you implement Lambda package and dependency management?​

Technical Answer: Package Lambda functions with dependencies using layers, container images, or deployment packages. Choose based on size, complexity, and runtime needs.

Code Example:

# Method 1: ZIP deployment package
mkdir package
pip install --target ./package requests boto3 pandas
cp lambda_function.py ./package/
cd package && zip -r ../deployment.zip .
aws lambda update-function-code --function-name my-function --zip-file fileb://deployment.zip

# Method 2: Lambda Layers (shared dependencies)
pip install --target ./python requests boto3
zip -r layer.zip python/
aws lambda publish-layer-version \
--layer-name my-dependencies \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.11

# Method 3: Container images (up to 10GB)
# Dockerfile
FROM public.ecr.aws/lambda/python:3.11
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY lambda_function.py .
CMD ["lambda_function.lambda_handler"]

docker build -t my-lambda:latest .
docker tag my-lambda:latest 123456789.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest
docker push 123456789.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest
aws lambda update-function-code \
--function-name my-function \
--image-uri 123456789.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest

Packaging Comparison:

MethodSize LimitUse CaseCold Start
ZIP50MB (direct), 250MB (S3)Small dependenciesStandard
Layers250MB each, 5 layersShared libsStandard
Container10GBLarge dependencies, MLSlightly slower

🔍 Interviewer Notes: Tests deployment and dependency management knowledge.

❌ Common Mistakes:

  • Including unnecessary dependencies
  • Not using layers for shared code
  • Exceeding size limits

Q71: How do you create and use Lambda Layers?​

Technical Answer: Lambda Layers are ZIP archives that contain libraries, dependencies, or custom runtimes. They promote code sharing across functions and reduce deployment package size.

Code Example:

# Create a layer for Python dependencies
mkdir -p python/lib/python3.11/site-packages
pip install --target python/lib/python3.11/site-packages requests boto3 pandas
zip -r my-layer.zip python/

# Publish the layer
aws lambda publish-layer-version \
--layer-name my-dependencies \
--zip-file fileb://my-layer.zip \
--compatible-runtimes python3.11 \
--description "Common dependencies for my functions"

# Use layer in function
aws lambda update-function-configuration \
--function-name my-function \
--layers arn:aws:lambda:us-east-1:123456789:layer:my-dependencies:1

Lambda Function Using Layer:

# No need to install requests/boto3 - they're in the layer
import requests
import boto3

def lambda_handler(event, context):
# Use layer libraries
response = requests.get('https://api.example.com/data')
return {'status': 'success', 'data': response.json()}

Layer Management:

AspectBest Practice
SizeKeep under 250MB uncompressed
VersioningAlways reference specific layer version
Shared codePut common utilities in layers
RuntimeMatch layer runtime to function

🔍 Interviewer Notes: Tests understanding of code reuse and deployment optimization.

❌ Common Mistakes:

  • Not pinning layer versions (breaks reproducibility)
  • Putting large dependencies in every function
  • Layer runtime mismatch with function

Q72: How do you manage multiple Lambda Layers?​

Technical Answer: You can attach up to 5 layers per function. Layer order matters - later layers override earlier ones for conflicting files.

Code Example:

# Publish multiple specialized layers
# Layer 1: Common utilities
mkdir -p utils-layer/python
echo "def helper(): return 'helper'" > utils-layer/python/utils.py
cd utils-layer && zip -r ../utils-layer.zip .

# Layer 2: Database connectors
mkdir -p db-layer/python
pip install --target db-layer/python pymongo psycopg2-binary
cd db-layer && zip -r ../db-layer.zip .

# Layer 3: ML libraries (large)
mkdir -p ml-layer/python
pip install --target ml-layer/python numpy pandas scikit-learn
cd ml-layer && zip -r ../ml-layer.zip .

# Attach layers in order (last layer wins for conflicts)
aws lambda update-function-configuration \
--function-name my-function \
--layers \
arn:aws:lambda:us-east-1:123456789:layer:utils:1 \
arn:aws:lambda:us-east-1:123456789:layer:db-connectors:3 \
arn:aws:lambda:us-east-1:123456789:layer:ml-libs:2

Function Using Multiple Layers:

# Available from layers
from utils import helper
import pymongo
import pandas as pd

def lambda_handler(event, context):
# Use utilities from layer
helper_result = helper()

# Use database from layer
client = pymongo.MongoClient('mongodb://...')

# Use ML libs from layer
df = pd.DataFrame(event.get('data', []))

return {'status': 'success'}

🔍 Interviewer Notes: Tests layer architecture and dependency management.

❌ Common Mistakes:

  • Exceeding 5 layer limit
  • Not understanding layer precedence
  • Putting everything in one giant layer

Q73: How do you use Lambda with RDS Proxy?​

Technical Answer: RDS Proxy pools database connections, reducing Lambda cold start overhead and preventing connection exhaustion. Use it for Lambda functions accessing RDS databases.

Code Example:

import boto3
import pymysql
from rds_proxy import RDSProxyConnection

# RDS Proxy endpoint in environment
proxy_endpoint = os.environ['RDS_PROXY_ENDPOINT']
db_name = os.environ['DB_NAME']
secret_arn = os.environ['SECRET_ARN']

# Initialize outside handler (reused across warm starts)
secret_client = boto3.client('secretsmanager')

def get_db_connection():
# Fetch credentials from Secrets Manager
secret = json.loads(
secret_client.get_secret_value(SecretId=secret_arn)['SecretString']
)

# Connect through RDS Proxy
return pymysql.connect(
host=proxy_endpoint,
user=secret['username'],
password=secret['password'],
database=db_name,
connect_timeout=5,
read_timeout=5
)

def lambda_handler(event, context):
connection = None
try:
connection = get_db_connection()

with connection.cursor() as cursor:
cursor.execute("SELECT * FROM users WHERE id = %s", (event['user_id'],))
result = cursor.fetchone()

return {'user': result}
except Exception as e:
print(f"Database error: {e}")
return {'error': str(e)}
finally:
if connection:
connection.close()

RDS Proxy Benefits:

Without ProxyWith Proxy
1000 Lambda = 1000 connectionsConnection pooling
Cold start = new connectionReuse pooled connections
Throttling riskManaged pool

🔍 Interviewer Notes: Tests database connection management and serverless patterns.

❌ Common Mistakes:

  • Not using RDS Proxy with Lambda + RDS
  • Creating new connections every invocation
  • Not handling connection timeouts

Q74: How do you implement Lambda with VPC networking?​

Technical Answer: Lambda in VPC requires ENIs (Elastic Network Interfaces) for network access. Use VPC endpoints to avoid NAT Gateway costs for AWS services, and be aware of cold start implications.

Code Example:

# Lambda in VPC can access:
# - Resources in same VPC (RDS, ElastiCache, etc.)
# - Internet via NAT Gateway
# - AWS services via VPC endpoints

import boto3
import pymysql

# This works in VPC with RDS in same VPC
def lambda_in_vpc(event, context):
# Access RDS in VPC
conn = pymysql.connect(
host=os.environ['RDS_ENDPOINT'],
user='admin',
password='password',
database='mydb'
)

# Access S3 via VPC endpoint (no NAT needed)
s3 = boto3.client('s3')
data = s3.get_object(Bucket='my-bucket', Key='data.json')

return {'status': 'success'}

# CloudFormation for VPC Lambda
"""
Resources:
VPCLambdaFunction:
Type: AWS::Lambda::Function
Properties:
VpcConfig:
SecurityGroupIds:
- !Ref LambdaSecurityGroup
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
Environment:
Variables:
RDS_ENDPOINT: !GetAtt RDSInstance.Endpoint.Address
"""

VPC Lambda Considerations:

AspectImpactMitigation
Cold start+10-30 secondsProvisioned concurrency
ENI limitsAccount limitsRequest limit increase
Internet accessRequires NAT GatewayUse VPC endpoints for AWS services
CostNAT Gateway costsVPC endpoints

🔍 Interviewer Notes: Tests VPC networking and Lambda integration knowledge.

❌ Common Mistakes:

  • Not configuring security groups correctly
  • Expecting internet access without NAT/VPC endpoints
  • Not considering ENI limits

Q75: How do you optimize Lambda for VPC cold starts?​

Technical Answer: VPC cold starts create ENIs which takes 10+ seconds. Mitigate with provisioned concurrency, keep-alive pings, or avoid VPC when possible (use VPC endpoints/Lambda Destinations).

Code Example:

# Enable provisioned concurrency for VPC functions
import boto3

lambda_client = boto3.client('lambda')

# Create alias with provisioned concurrency
response = lambda_client.publish_version(
FunctionName='my-vpc-function'
)
version = response['Version']

lambda_client.put_provisioned_concurrency_config(
FunctionName='my-vpc-function',
Qualifier=version,
ProvisionedConcurentExecutions=10 # Keep 10 warm
)

# Or use SQS to trigger keep-alive
def keep_alive_handler(event, context):
"""Scheduled via EventBridge to ping VPC functions"""
lambda_client.invoke(
FunctionName='my-vpc-function',
InvocationType='Event',
Payload=json.dumps({'keep_alive': True})
)

# Better yet: Avoid VPC if possible
# Use VPC endpoints for S3, DynamoDB, SQS, SNS
# Only use VPC for RDS, ElastiCache, or internal services

VPC Optimization Strategies:

StrategyCold StartCostComplexity
Provisioned ConcurrencyEliminatedHighLow
Keep-alive pingsReducedLowMedium
Avoid VPCBestLowLow
VPC endpointsBetterMediumMedium

🔍 Interviewer Notes: Tests VPC performance optimization knowledge.

❌ Common Mistakes:

  • Not using provisioned concurrency for latency-sensitive VPC functions
  • Putting Lambda in VPC unnecessarily
  • Not using VPC endpoints

Q76: How do you implement Lambda with DynamoDB?​

Technical Answer: Lambda integrates with DynamoDB via streams, Get/Put operations, or as event source. Use IAM roles for permissions and handle throttling/errors gracefully.

Code Example:

import boto3
from boto3.dynamodb.conditions import Key

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')

def lambda_get_user(event, context):
user_id = event['pathParameters']['id']

response = table.get_item(Key={'user_id': user_id})

if 'Item' not in response:
return {'statusCode': 404, 'body': 'User not found'}

return {'statusCode': 200, 'body': json.dumps(response['Item'])}

def lambda_write_user(event, context):
user_data = json.loads(event['body'])

table.put_item(Item={
'user_id': user_data['id'],
'name': user_data['name'],
'email': user_data['email'],
'created_at': datetime.now().isoformat()
})

return {'statusCode': 201, 'body': 'User created'}

# Process DynamoDB Streams
def dynamodb_stream_handler(event, context):
for record in event['Records']:
if record['eventName'] == 'INSERT':
new_image = record['dynamodb']['NewImage']
print(f"New user created: {new_image}")
elif record['eventName'] == 'MODIFY':
print(f"User updated: {record['dynamodb']['Keys']}")

DynamoDB Integration Patterns:

PatternUse CaseConsiderations
Direct APISimple CRUDHandle throttling
DynamoDB StreamsReact to changesProcess in order
Event Source MappingBatch processingError handling

🔍 Interviewer Notes: Tests DynamoDB integration and event-driven patterns.

❌ Common Mistakes:

  • Not handling ProvisionedThroughputExceeded
  • Not using batch operations
  • Not processing stream errors

Q77: How do you implement Lambda with S3 events?​

Technical Answer: S3 can invoke Lambda on object creation/deletion. Configure event notifications on S3 bucket to trigger Lambda with the object key in the event.

Code Example:

import boto3
import json

s3 = boto3.client('s3')

def lambda_handler(event, context):
# Process S3 event
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']

print(f"Processing s3://{bucket}/{key}")

# Get object
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read().decode('utf-8')

# Process content
result = process_file(content)

# Write result to another bucket
s3.put_object(
Bucket='processed-bucket',
Key=f"processed/{key}",
Body=json.dumps(result)
)

return {'status': 'success'}

def process_file(content):
return {'lines': len(content.split('\n')), 'size': len(content)}

# S3 event notification configuration (via AWS CLI)
"""
aws s3api put-bucket-notification-configuration \
--bucket my-source-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [
{
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789:function:my-function",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{"Name": "prefix", "Value": "uploads/"}
]
}
}
}
]
}'
"""

S3 Event Patterns:

Event TypeTriggerUse Case
s3:ObjectCreated:*New objectImage processing, data ingestion
s3:ObjectRemoved:*DeletionCleanup, audit
s3:ObjectRestore:*RestoreArchival processing

🔍 Interviewer Notes: Tests S3 integration and event-driven architecture.

❌ Common Mistakes:

  • Not handling large objects (use S3 Select)
  • Recursive triggers (Lambda writes to same bucket)
  • Not configuring S3 bucket permissions

Q78: How do you use Lambda with API Gateway?​

Technical Answer: API Gateway integrates with Lambda as a proxy or non-proxy integration. Use Lambda proxy integration for simple setups, non-proxy for fine-grained control.

Code Example:

import json

def lambda_handler(event, context):
# API Gateway Lambda proxy integration
http_method = event['httpMethod']
path = event['path']
body = json.loads(event.get('body', '{}'))
query_params = event.get('queryStringParameters', {})

if http_method == 'GET':
user_id = event['pathParameters']['id']
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'user_id': user_id, 'method': 'GET'})
}

elif http_method == 'POST':
return {
'statusCode': 201,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'message': 'Created', 'data': body})
}

return {'statusCode': 405, 'body': 'Method not allowed'}

# API Gateway configuration (SAM template)
"""
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
DefinitionBody:
swagger: "2.0"
paths:
/users/{id}:
get:
x-amazon-apigateway-integration:
uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyFunction.Arn}/invocations
httpMethod: POST
type: aws_proxy
"""

API Gateway Integration Types:

TypeProsCons
Lambda ProxySimple, full event accessLess control
Non-proxyFine-grained controlMore config

🔍 Interviewer Notes: Tests API Gateway integration and REST API patterns.

❌ Common Mistakes:

  • Not returning proper response format
  • Not handling CORS
  • Not validating input

Q79: How do you implement Lambda security best practices?​

Technical Answer: Follow least privilege IAM, encrypt environment variables, use Secrets Manager for credentials, enable CloudTrail logging, and scan dependencies for vulnerabilities.

Code Example:

import boto3
import os
from aws_secretsmanager_caching import SecretCache, SecretCacheConfig

# Use Secrets Manager instead of env vars for secrets
secrets_client = boto3.client('secretsmanager')
cache = SecretCache(SecretCacheConfig(), secrets_client)

def get_secret():
secret_arn = os.environ['SECRET_ARN']
secret_string = cache.get_secret_string(secret_arn)
return json.loads(secret_string)

def lambda_handler(event, context):
# Get credentials securely
secrets = get_secret()
api_key = secrets['api_key']

# Use IAM roles (not hardcoded credentials)
s3 = boto3.client('s3') # Uses execution role

# Encrypt sensitive data in transit
import ssl
import requests
response = requests.get('https://api.example.com',
headers={'X-Api-Key': api_key},
verify=True) # Always verify SSL

return {'status': 'success'}

# IAM Policy (least privilege)
"""
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Effect": "Allow",
"Action": ["secretsmanager:GetSecretValue"],
"Resource": "arn:aws:secretsmanager:*:*:secret:my-app/*"
}
]
}
"""

Security Checklist:

PracticeImplementation
Least privilegeMinimize IAM permissions
SecretsUse Secrets Manager
EncryptionKMS for env vars, TLS for transit
DependenciesScan with Lambda layers or CodePipeline
LoggingCloudTrail + CloudWatch

🔍 Interviewer Notes: Tests security mindset and AWS security best practices.

❌ Common Mistakes:

  • Using * in IAM policies
  • Storing secrets in environment variables
  • Not encrypting sensitive data

Q80: How do you use Lambda with SQS?​

Technical Answer: Lambda can poll SQS queues via event source mapping. Configure batch size, error handling, and DLQs for robust message processing.

Code Example:

import json
import boto3

def lambda_handler(event, context):
results = []

for record in event['Records']:
# SQS message
message_body = json.loads(record['body'])
message_id = record['messageId']

print(f"Processing message {message_id}: {message_body}")

try:
# Process message
result = process_message(message_body)
results.append({'message_id': message_id, 'status': 'success'})
except Exception as e:
print(f"Failed to process {message_id}: {e}")
# With SQS + Lambda, you can return batch item failures
raise # Let Lambda retry

return {'processed': len(results)}

def process_message(message):
# Your business logic here
return {'processed': True}

# Configure SQS event source mapping
"""
aws lambda create-event-source-mapping \
--function-name my-function \
--event-source-arn arn:aws:sqs:us-east-1:123456789:my-queue \
--batch-size 10 \
--maximum-batching-window-in-seconds 10 \
--enabled
"""

SQS Integration Configuration:

SettingValuePurpose
Batch size1-10Messages per invocation
Batching window0-300sWait for more messages
Error handlingDLQFailed message destination
Filter criteriaJSONFilter messages

🔍 Interviewer Notes: Tests message queue integration and async processing.

❌ Common Mistakes:

  • Not handling partial failures
  • Not configuring DLQ
  • Too large batch size (timeout risk)

Q81: How do you configure IAM roles for Lambda?​

Technical Answer: Lambda execution roles grant permissions to AWS services. Follow least privilege: only grant permissions actually needed by the function.

Code Example:

# IAM Role Trust Policy (who can assume the role)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}

# IAM Role Policy (what the role can do)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
}
]
}

# Attach role to Lambda
"""
aws lambda update-function-configuration \
--function-name my-function \
--role arn:aws:iam::123456789:role/my-lambda-role
"""

IAM Best Practices:

PracticeImplementation
Least privilegeOnly required actions + resources
Resource-level permissionsSpecific ARNs, not *
Separate rolesPer function or function group

🔍 Interviewer Notes: Tests IAM knowledge and security mindset.

❌ Common Mistakes:

  • Using * for actions or resources
  • Reusing same role for all functions
  • Not rotating access keys (if using IAM user)

Q82: How do you implement resource policies for Lambda?​

Technical Answer: Resource policies control who can invoke your Lambda function. Use them for cross-account access, EventBridge, or API Gateway permissions.

Code Example:

import boto3

lambda_client = boto3.client('lambda')

def add_cross_account_permission(function_name, principal_account):
lambda_client.add_permission(
FunctionName=function_name,
StatementId='AllowCrossAccountInvoke',
Action='lambda:InvokeFunction',
Principal=principal_account,
SourceArn='arn:aws:sqs:us-east-1:123456789:my-queue'
)

# Check existing permissions
response = lambda_client.get_policy(FunctionName='my-function')
print(json.dumps(json.loads(response['Policy']), indent=2))

🔍 Interviewer Notes: Tests cross-account access and resource policy understanding.

❌ Common Mistakes:

  • Not specifying SourceArn (security risk)
  • Forgetting to update policies when resources change

Q83: How do you implement Lambda with EventBridge?​

Technical Answer: EventBridge is a serverless event bus. Lambda subscribes to rules that match events and invoke the function with filtered events.

Code Example:

def lambda_handler(event, context):
detail_type = event.get('detail-type', '')
source = event.get('source', '')
detail = event.get('detail', {})

if detail_type == 'Order Placed':
return process_order(detail)

return {'status': 'ignored'}

def process_order(order):
print(f"Processing order: {order['order_id']}")
return {'status': 'processed'}

EventBridge Pattern Example:

{
"source": ["com.example.orders"],
"detail-type": ["Order Placed"]
}

🔍 Interviewer Notes: Tests event-driven architecture and EventBridge usage.

❌ Common Mistakes:

  • Not granting EventBridge permission to invoke Lambda
  • Incorrect event pattern syntax

Q84: How do you use Lambda with Step Functions?​

Technical Answer: Step Functions orchestrate Lambda functions in state machines. Use for complex workflows, retries, parallel execution, and human approval steps.

Code Example:

# Lambda function in the workflow
def validate_order(event, context):
order = event

if not order.get('items'):
return {'error': 'No items in order'}

order['validated'] = True
return order

# Step Functions state machine definition (ASL)
state_machine = {
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789:function:validate-order",
"Next": "ProcessPayment"
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789:function:process-payment",
"End": True
}
}
}

🔍 Interviewer Notes: Tests workflow orchestration and Step Functions knowledge.

❌ Common Mistakes:

  • Not handling Lambda errors in state machine
  • Missing End/Next in state definitions

Q85: How do you implement Lambda with X-Ray tracing?​

Technical Answer: X-Ray traces Lambda executions end-to-end. Enable active tracing to see downstream calls, latency, and errors in service map.

Code Example:

import boto3
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all

patch_all()

def lambda_handler(event, context):
s3 = boto3.client('s3')

with xray_recorder.in_subsegment('ProcessData') as subsegment:
data = process_data(event)
subsegment.put_annotation('item_count', len(data))

s3.put_object(Bucket='my-bucket', Key='data.json', Body=json.dumps(data))
return {'status': 'success'}

# Enable X-Ray on Lambda
"""
aws lambda update-function-configuration \
--function-name my-function \
--tracing-config Mode=Active
"""

🔍 Interviewer Notes: Tests observability and distributed tracing knowledge.

❌ Common Mistakes:

  • Not patching boto3 (no downstream traces)
  • Not enabling active tracing

Q86: How do you implement Lambda with Secrets Manager?​

Technical Answer: Secrets Manager stores and rotates credentials. Cache secrets locally (outside handler) to reduce API calls and improve performance.

Code Example:

import boto3
import json
import os
from aws_secretsmanager_caching import SecretCache, SecretCacheConfig

secrets_client = boto3.client('secretsmanager')
cache_config = SecretCacheConfig()
cache = SecretCache(cache_config, secrets_client)

def get_secret(secret_arn):
secret_string = cache.get_secret_string(secret_arn)
return json.loads(secret_string)

def lambda_handler(event, context):
db_secret_arn = os.environ['DB_SECRET_ARN']
db_creds = get_secret(db_secret_arn)

import pymysql
conn = pymysql.connect(
host=db_creds['host'],
user=db_creds['username'],
password=db_creds['password'],
database=db_creds['dbname']
)

return {'status': 'success'}

🔍 Interviewer Notes: Tests secrets management and caching best practices.

❌ Common Mistakes:

  • Not caching secrets (cold start overhead)
  • Storing secrets in environment variables

Q87: How do you implement Lambda with SNS?​

Technical Answer: SNS triggers Lambda via subscriptions. Use for fan-out patterns, notifications, and decoupled messaging.

Code Example:

def lambda_handler(event, context):
for record in event['Records']:
sns_message = json.loads(record['Sns']['Message'])
print(f"Message: {sns_message}")

message_attributes = record['Sns'].get('MessageAttributes', {})
if 'event_type' in message_attributes:
process_event(message_attributes['event_type']['Value'], sns_message)

return {'status': 'success'}

# Subscribe Lambda to SNS topic
"""
aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:123456789:my-topic \
--protocol lambda \
--notification-endpoint arn:aws:lambda:us-east-1:123456789:function:my-function
"""

🔍 Interviewer Notes: Tests pub/sub patterns and SNS integration.

❌ Common Mistakes:

  • Not granting SNS invoke permission
  • Not handling idempotency (SNS retries)

Q88: How do you implement Lambda with Kinesis?​

Technical Answer: Kinesis Data Streams invoke Lambda with records in batches. Configure batch size, parallelization, and error handling for stream processing.

Code Example:

def lambda_handler(event, context):
records_processed = 0

for record in event['Records']:
import base64
payload = json.loads(base64.b64decode(record['kinesis']['data']))
process_kinesis_record(payload)
records_processed += 1

return {'records_processed': records_processed}

def process_kinesis_record(payload):
print(f"Processing: {payload}")

# Configure event source mapping
"""
aws lambda create-event-source-mapping \
--function-name my-function \
--event-source-arn arn:aws:kinesis:us-east-1:123456789:stream/my-stream \
--starting-position LATEST \
--batch-size 100
"""

🔍 Interviewer Notes: Tests stream processing and Kinesis knowledge.

❌ Common Mistakes:

  • Not handling idempotency (Kinesis retries)
  • Too large batch size (timeout risk)

Q89: How do you implement Lambda with EFS?​

Technical Answer: EFS provides shared file system access to Lambda. Mount EFS to Lambda for large file processing, shared state, or model storage.

Code Example:

import os
import json

EFS_MOUNT = '/mnt/efs'

def lambda_handler(event, context):
input_file = os.path.join(EFS_MOUNT, 'input', 'data.json')

if os.path.exists(input_file):
with open(input_file, 'r') as f:
data = json.load(f)

return {'status': 'success'}

# Lambda VPC configuration with EFS mount
"""
aws lambda update-function-configuration \
--function-name my-function \
--file-system-configs FileSystemArn=arn:aws:elasticfilesystem:...:access-point/fsap-789,LocalMountPath=/mnt/efs
"""

🔍 Interviewer Notes: Tests EFS integration and file system usage.

❌ Common Mistakes:

  • Not configuring VPC for EFS access
  • Not handling missing mount point

Q90: How do you implement Lambda blue-green deployments?​

Technical Answer: Blue-green deployments use two parallel environments (blue=current, green=new). Route traffic gradually using weighted aliases or API Gateway stages.

Code Example:

import boto3

lambda_client = boto3.client('lambda')

def setup_blue_green(function_name, new_version):
# Create alias pointing to new version
lambda_client.create_alias(
FunctionName=function_name,
Name='green',
FunctionVersion=new_version
)

# Test green environment
test_result = run_smoke_tests(function_name, 'green')

if test_result['success']:
# Switch production alias to green
lambda_client.update_alias(
FunctionName=function_name,
Name='prod',
FunctionVersion=new_version
)

🔍 Interviewer Notes: Tests deployment strategies and production safety.

❌ Common Mistakes:

  • Not testing green environment
  • Not keeping blue for quick rollback

Q91: How do you implement Lambda with CloudFront?​

Technical Answer: CloudFront can invoke Lambda@Edge or CloudFront Functions for request/response manipulation at edge locations.

Code Example:

# Lambda@Edge for CloudFront
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']

# Add security headers
request['headers']['strict-transport-security'] = [
{'key': 'Strict-Transport-Security', 'value': 'max-age=31536000'}
]

return request

🔍 Interviewer Notes: Tests edge computing and CDN integration.

❌ Common Mistakes:

  • Not understanding Lambda@Edge restrictions
  • Timeouts at edge (max 5s for viewer events)

Q92: How do you implement Lambda with Cognito?​

Technical Answer: Cognito can trigger Lambda for authentication customization. Use for custom auth flows, challenges, and user validation.

Code Example:

def lambda_handler(event, context):
trigger_source = event['triggerSource']

if trigger_source == 'DefineAuthChallenge_Authentication':
if event['request']['session']:
last_challenge = event['request']['session'][-1]
if last_challenge['challengeResult']:
event['response']['issueTokens'] = True
event['response']['failAuthentication'] = False

return event

🔍 Interviewer Notes: Tests custom authentication and Cognito integration.

❌ Common Mistakes:

  • Not understanding Cognito trigger sources
  • Security flaws in custom challenges

Q93: How do you implement Lambda with IoT Core?​

Technical Answer: IoT Core rules can trigger Lambda to process device messages. Use for real-time device data processing, alerting, or device shadow updates.

Code Example:

def lambda_handler(event, context):
for record in event.get('Records', [event]):
payload = json.loads(record.get('payload', '{}'))
device_id = payload.get('deviceId')
temperature = payload.get('temperature')

if temperature and temperature > 80:
send_alert(device_id, temperature)

return {'status': 'success'}

def send_alert(device_id, temperature):
import boto3
iot_data = boto3.client('iot-data')
iot_data.publish(
topic=f"devices/{device_id}/alerts",
payload=json.dumps({'alert': 'HIGH_TEMP'})
)

🔍 Interviewer Notes: Tests IoT integration and real-time data processing.

❌ Common Mistakes:

  • Not granting IoT permission to invoke Lambda
  • Not handling malformed device payloads

Q94: How do you implement Lambda with S3 Batch Operations?​

Technical Answer: S3 Batch Operations can invoke Lambda to perform custom actions on large numbers of S3 objects.

Code Example:

def lambda_handler(event, context):
task = event['task']
s3_key = task['s3Key']

# Process S3 object
result = process_s3_object(s3_key)

return {
'invocationSchemaVersion': '2.0',
'results': [{
'taskId': task['taskId'],
'resultCode': 'Succeeded' if result['success'] else 'PermanentFailure'
}]
}

🔍 Interviewer Notes: Tests bulk operations and S3 Batch understanding.

❌ Common Mistakes:

  • Not returning correct response format
  • Not handling missing objects

Q95: How do you implement Lambda with Application Load Balancer?​

Technical Answer: ALB can invoke Lambda as a target. Use for HTTP-based workloads that need load balancing, health checks, and path-based routing.

Code Example:

def lambda_handler(event, context):
http_method = event['httpMethod']
path = event['path']

if path == '/health':
return {
'statusCode': 200,
'statusDescription': '200 OK',
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'status': 'healthy'})
}

return {'statusCode': 200, 'body': 'Success'}

🔍 Interviewer Notes: Tests load balancer integration and HTTP concepts.

❌ Common Mistakes:

  • Not returning correct ALB response format
  • Not granting ALB invoke permission

Q96: How do you implement Lambda with KMS encryption?​

Technical Answer: Lambda can use KMS to encrypt/decrypt data at rest or in transit. Use environment variable encryption or encrypt sensitive data before storing.

Code Example:

import boto3
import base64

kms = boto3.client('kms')

def encrypt_data(data, key_id):
response = kms.encrypt(KeyId=key_id, Plaintext=data.encode('utf-8'))
return base64.b64encode(response['CiphertextBlob']).decode('utf-8')

def lambda_handler(event, context):
key_id = os.environ['KMS_KEY_ID']
sensitive_data = event.get('sensitive_field', '')

if sensitive_data:
encrypted = encrypt_data(sensitive_data, key_id)
print(f"Encrypted: {encrypted}")

return {'status': 'success'}

🔍 Interviewer Notes: Tests encryption knowledge and KMS usage.

❌ Common Mistakes:

  • Not handling KMS decryption errors
  • Storing plaintext secrets

Q97: How do you implement Lambda with Amazon MQ?​

Technical Answer: Amazon MQ (ActiveMQ/RabbitMQ) can be used with Lambda via event source mapping (for ActiveMQ) or polling patterns.

Code Example:

def lambda_handler(event, context):
for record in event.get('Records', []):
message = json.loads(record['body'])
print(f"Received MQ message: {message}")
process_mq_message(message)

return {'status': 'success'}

🔍 Interviewer Notes: Tests message broker integration and hybrid architectures.

❌ Common Mistakes:

  • Not handling connection pooling
  • Not using Secrets Manager for MQ credentials

Q98: How do you implement Lambda with AppSync?​

Technical Answer: AppSync (GraphQL) can invoke Lambda as a data source. Use for custom resolvers, business logic, or integrating non-AWS data sources.

Code Example:

def lambda_handler(event, context):
field_name = event['info']['fieldName']
arguments = event.get('arguments', {})

if field_name == 'getUser':
return get_user(arguments.get('id'))
elif field_name == 'createOrder':
return create_order(arguments)

raise Exception(f"Unknown field: {field_name}")

def get_user(user_id):
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
response = table.get_item(Key={'user_id': user_id})
return response.get('Item', {})

🔍 Interviewer Notes: Tests GraphQL and AppSync integration.

❌ Common Mistakes:

  • Not returning correct format for AppSync
  • Not understanding resolver mapping templates

Q99: How do you implement Lambda with CodeDeploy?​

Technical Answer: CodeDeploy can manage Lambda deployments with validation tests, traffic shifting, and automatic rollback on failures.

Code Example:

def lambda_handler(event, context):
# This is the new version being deployed
version = event.get('version', 'unknown')

# Perform health checks
if not is_healthy():
raise Exception("Health check failed")

return {'status': 'validated', 'version': version}

def is_healthy():
try:
import boto3
s3 = boto3.client('s3')
s3.list_buckets()
return True
except:
return False

🔍 Interviewer Notes: Tests deployment automation and CodeDeploy integration.

❌ Common Mistakes:

  • Not implementing validation hooks
  • Not configuring automatic rollback

Q100: How do you monitor Lambda costs and optimize spending?​

Technical Answer: Lambda costs are based on number of requests × duration × memory. Use Lambda Power Tuning, trim dependencies, and optimize memory configuration for cost.

Code Example:

# Cost optimization strategies

# 1. Optimize memory (more memory = more CPU = faster = less duration)
# Use AWS Lambda Power Tuning to find optimal memory

# 2. Reduce package size (faster cold starts = less billed duration)

# 3. Use async where possible (cheaper, no waiting)
import boto3

def trigger_async_processing(event):
lambda_client = boto3.client('lambda')
lambda_client.invoke(
FunctionName='async-processor',
InvocationType='Event', # Async = cheaper
Payload=json.dumps(event)
)

# 4. Monitor costs with Cost Explorer API
def get_lambda_costs():
ce = boto3.client('ce')
response = ce.get_cost_and_usage(
TimePeriod={'Start': '2024-01-01', 'End': '2024-01-31'},
Granularity='MONTHLY',
Metrics=['BlendedCost'],
GroupBy=[{'Type': 'DIMENSION', 'Key': 'SERVICE'}]
)

Cost Optimization Checklist:

StrategyImpact
Power TuningFind optimal memory (20-40% savings)
Reduce invocationsUse caching, batching
Trim dependenciesSmaller packages = faster cold starts

🔍 Interviewer Notes: Tests cost optimization and operational awareness.

❌ Common Mistakes:

  • Not monitoring Lambda costs
  • Over-provisioning memory
  • Not using Power Tuning

Q101: How does AWS Lambda integrate with VPC networking?​

Technical Answer: Lambda functions can connect to VPC resources by configuring VPC access, which attaches an Elastic Network Interface (ENI) to the function's execution environment in your VPC subnet. This allows the function to access private VPC resources like RDS, ElastiCache, or EC2 instances while keeping traffic within the VPC.

Code/Config Example:

aws lambda update-function-configuration \
--function-name my-function \
--vpc-config SubnetIds=subnet-12345678,subnet-87654321,SecurityGroupIds=sg-12345678

🔍 Interviewer Notes: Tests understanding of Lambda VPC integration basics and ENI usage.

❌ Common Mistakes:

  • Believing Lambda functions can access VPC resources without VPC configuration
  • Forgetting that VPC-connected functions lose internet access by default (need NAT Gateway for public internet)
  • Not knowing ENIs are created in each subnet specified

Q102: What is an Elastic Network Interface (ENI) in the context of Lambda VPC access?​

Technical Answer: An ENI is a virtual network interface attached to a Lambda function's execution environment when VPC access is enabled, residing in the specified VPC subnets with private IP addresses. ENIs handle all network traffic between the function and VPC resources, and are managed by AWS (created/deleted as functions scale).

Code/Config Example:

# SAM template VPC config
Resources:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
VpcConfig:
SubnetIds:
- subnet-12345678
- subnet-87654321
SecurityGroupIds:
- sg-12345678

🔍 Interviewer Notes: Tests knowledge of ENI role in Lambda networking and AWS-managed lifecycle.

❌ Common Mistakes:

  • Thinking ENIs are static and persist after function deletion
  • Assuming ENIs are shared across multiple functions
  • Not realizing ENI creation adds to cold start latency

Q103: How does VPC configuration impact Lambda cold start times?​

Technical Answer: Configuring VPC access adds 10+ seconds to cold start times when ENIs need to be created, as AWS must provision and attach ENIs in your subnets before the execution environment starts. This ENI setup latency is eliminated for warm starts until the function scales or ENIs are recycled.

Code/Config Example:

# CloudWatch Logs Insights query to find cold starts
fields @timestamp, @message
| filter @message like /INIT_START/
| stats count() by bin(5m)

🔍 Interviewer Notes: Tests understanding of VPC cold start tradeoffs and ENI provisioning impact.

❌ Common Mistakes:

  • Claiming VPC configuration has no impact on cold starts
  • Not knowing ENI creation is the primary cause of VPC cold start latency
  • Assuming Provisioned Concurrency eliminates VPC cold start penalties (it reduces but ENI setup still occurs initially)

Q104: What are the requirements for Lambda to access private VPC resources?​

Technical Answer: Lambda requires at least one subnet in your VPC with available IP addresses, and a security group that allows outbound traffic to your target VPC resources (and inbound if needed). The subnets must have routes to the target resources, and if internet access is needed, a NAT Gateway in a public subnet with appropriate routing.

Code/Config Example:

# CloudFormation security group for Lambda
LambdaSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group for Lambda VPC access
VpcId: vpc-12345678
SecurityGroupEgress:
- IpProtocol: tcp
FromPort: 5432
ToPort: 5432
DestinationSecurityGroupId: sg-target-rds

🔍 Interviewer Notes: Tests knowledge of VPC networking prerequisites for Lambda access.

❌ Common Mistakes:

  • Forgetting that subnets need available IP addresses for ENIs
  • Using the same security group for Lambda and target resources without proper rules
  • Not configuring NAT Gateway when internet access is required for VPC-connected functions

Q105: Can a Lambda function in a VPC access the public internet?​

Technical Answer: By default, VPC-connected Lambda functions cannot access the public internet, as ENIs are assigned private IPs and subnets lack public internet routes. To enable internet access, deploy a NAT Gateway in a public subnet, update private subnet route tables to use the NAT Gateway as default route, and ensure security groups allow outbound traffic.

Code/Config Example:

# CloudFormation route table entry for NAT Gateway
PrivateRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: vpc-12345678

NATRoute:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateRouteTable
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref MyNATGateway

🔍 Interviewer Notes: Tests understanding of VPC routing and NAT Gateway requirements for internet access.

❌ Common Mistakes:

  • Assuming VPC-connected functions have internet access by default
  • Placing NAT Gateway in private subnet (must be public to access internet)
  • Forgetting to update subnet route tables to use the NAT Gateway

Q106: How are ENIs managed when Lambda functions scale?​

Technical Answer: AWS automatically creates ENIs in your specified subnets as Lambda scales out to handle increased concurrency, with one ENI per execution environment per subnet. ENIs are reused across invocations of warm execution environments, and are deleted when the function is scaled in or deleted, but may persist for a short time after deletion.

Code/Config Example:

aws ec2 describe-network-interfaces \
--filters "Name=subnet-id,Values=subnet-12345678" "Name=description,Values=*Lambda*" \
--query "NetworkInterfaces[*].{ID:NetworkInterfaceId,Status:Status,PrivateIp:PrivateIpAddress}"

🔍 Interviewer Notes: Tests knowledge of ENI lifecycle during Lambda scaling events.

❌ Common Mistakes:

  • Believing ENIs are created per invocation (they are per execution environment, reused for warm starts)
  • Not knowing ENIs are deleted when the function is removed
  • Assuming ENIs are evenly distributed across all specified subnets

Q107: What is a VPC endpoint and how can it be used with Lambda?​

Technical Answer: VPC endpoints enable private connections between your VPC and AWS services (like S3, DynamoDB) without traversing the public internet, using either Gateway or Interface endpoints. Lambda functions in a VPC can use Gateway endpoints for S3/DynamoDB (free, no ENI required) or Interface endpoints for other services (requires ENI in subnet, hourly cost).

Code/Config Example:

# CloudFormation Gateway endpoint for S3
S3Endpoint:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: vpc-12345678
VpcEndpoints:
- !Ref S3GatewayEndpoint

S3GatewayEndpoint:
Type: AWS::EC2::VPCEndPoint
Properties:
VpcId: vpc-12345678
ServiceName: com.amazonaws.us-east-1.s3
RouteTableIds:
- !Ref PrivateRouteTable

🔍 Interviewer Notes: Tests understanding of private AWS service access from VPC-connected Lambda functions.

❌ Common Mistakes:

  • Confusing Gateway and Interface endpoints (Gateway is free, for S3/DynamoDB; Interface is paid, for most other services)
  • Not knowing Gateway endpoints don't require ENIs
  • Assuming all AWS services can use Gateway endpoints

Q108: How does cold start impact different Lambda use cases?​

Technical Answer: Cold starts add latency (100ms to 10+ seconds) that is acceptable for async/background tasks but problematic for user-facing synchronous APIs requiring consistent low latency. VPC-connected functions, larger deployment packages, and languages with longer startup times (Java, .NET) experience worse cold start penalties.

Code/Config Example:

import os
import time

is_cold_start = True

def lambda_handler(event, context):
global is_cold_start
start_time = time.time()

if is_cold_start:
print(f"Cold start detected")
is_cold_start = False
else:
print(f"Warm start")

print(f"Execution time: {time.time() - start_time}ms")
return {"statusCode": 200}

🔍 Interviewer Notes: Tests ability to evaluate cold start tradeoffs for different workloads.

❌ Common Mistakes:

  • Claiming cold starts are never a problem for any use case
  • Not knowing VPC configuration increases cold start latency
  • Forgetting that Provisioned Concurrency can mitigate cold starts for critical workloads

Q109: What is the relationship between Lambda subnets and ENI availability?​

Technical Answer: Lambda requires subnets with sufficient available IP addresses to provision ENIs, as each execution environment in a subnet uses one ENI (and thus one private IP). If a subnet runs out of IP addresses, Lambda cannot scale further in that subnet, leading to throttling errors.

Code/Config Example:

aws ec2 describe-subnets \
--subnet-ids subnet-12345678 \
--query "Subnets[*].{SubnetId:SubnetId,AvailableIpAddressCount:AvailableIpAddressCount,CidrBlock:CidrBlock}"

🔍 Interviewer Notes: Tests understanding of IP address planning for Lambda VPC deployments.

❌ Common Mistakes:

  • Choosing subnets with small CIDR blocks (e.g., /28) that quickly run out of IPs
  • Not monitoring available IP counts in subnets used by Lambda
  • Assuming Lambda can use public subnets without issues (works but not best practice for private resources)

Q110: How can you reduce cold start latency for VPC-connected Lambda functions?​

Technical Answer: Use Provisioned Concurrency to keep execution environments initialized and ready to respond, avoid overly large deployment packages, use lighter runtimes (Python/Node.js over Java/.NET), and minimize the number of subnets (ENIs are created in all specified subnets per environment). For Java, enable SnapStart to reduce initialization time.

Code/Config Example:

# CloudFormation Provisioned Concurrency configuration
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 10

🔍 Interviewer Notes: Tests knowledge of cold start mitigation strategies for VPC-connected functions.

❌ Common Mistakes:

  • Only applying Provisioned Concurrency without right-sizing deployment packages
  • Not knowing SnapStart is only available for Java runtimes
  • Forgetting that Provisioned Concurrency incurs additional costs

Q111: What is Provisioned Concurrency in AWS Lambda?​

Technical Answer: Provisioned Concurrency keeps a specified number of Lambda execution environments initialized and ready to respond immediately, eliminating cold starts for those concurrent executions. It is ideal for latency-sensitive workloads and is billed separately from standard invocation costs.

Code/Config Example:

aws lambda put-provisioned-concurrency-config \
--function-name my-function \
--qualifier prod \
--provisioned-concurrent-executions 20

🔍 Interviewer Notes: Tests understanding of Provisioned Concurrency purpose and use cases.

❌ Common Mistakes:

  • Thinking Provisioned Concurrency eliminates all cold starts (only for provisioned instances)
  • Not knowing Provisioned Concurrency incurs additional costs
  • Confusing Provisioned Concurrency with Reserved Concurrency

Q112: How do you configure Provisioned Concurrency for a Lambda function alias?​

Technical Answer: Provisioned Concurrency is configured on a Lambda function version or alias, specifying the number of concurrent environments to keep initialized. You can update the configuration using the AWS CLI, console, CloudFormation, or SAM templates, and can set different values for different aliases.

Code/Config Example:

# SAM template Provisioned Concurrency on alias
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: prod
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 15

🔍 Interviewer Notes: Tests knowledge of Provisioned Concurrency configuration methods and alias targeting.

❌ Common Mistakes:

  • Trying to configure Provisioned Concurrency on $LATEST (not supported, must use version/alias)
  • Forgetting that each alias/version can have its own Provisioned Concurrency setting
  • Not knowing that Provisioned Concurrency applies to the entire function version, not individual invocations

Q113: What are the cost implications of using Provisioned Concurrency?​

Technical Answer: You are billed for the number of Provisioned Concurrency units (not actual invocations) from the time they are enabled until they are disabled, with a minimum billing duration of 1 minute. Costs are higher than standard invocations for idle capacity, so it should only be used for latency-critical workloads.

Code/Config Example:

# Conceptual cost calculation
# Provisioned cost = $0.0000041667/GB-second * Memory(GB) * ProvisionedCount * Seconds

🔍 Interviewer Notes: Tests awareness of Provisioned Concurrency pricing model and cost optimization.

❌ Common Mistakes:

  • Assuming you only pay when Provisioned Concurrency environments are invoked
  • Not knowing there is a 1-minute minimum billing duration
  • Over-provisioning Provisioned Concurrency for non-critical workloads

Q114: How does Provisioned Concurrency interact with function scaling?​

Technical Answer: Provisioned Concurrency provides a baseline of ready environments; if invocation traffic exceeds the provisioned count, Lambda scales out standard execution environments (which may cold start) to handle additional load. The provisioned environments are used first before scaling standard environments.

Code/Config Example:

# CloudWatch Logs Insights: Compare provisioned vs standard invocations
fields @timestamp, ProvisionedConcurrencyInvocations, UnreservedConcurrencyInvocations
| filter FunctionName = "my-function"
| stats sum(ProvisionedConcurrencyInvocations), sum(UnreservedConcurrencyInvocations) by bin(5m)

🔍 Interviewer Notes: Tests understanding of Provisioned Concurrency scaling behavior and limits.

❌ Common Mistakes:

  • Believing Provisioned Concurrency caps total function concurrency (it's a baseline, not a limit)
  • Not knowing standard scaling still occurs when traffic exceeds provisioned count
  • Assuming Provisioned Concurrency environments are never recycled (they are managed by AWS)

Q115: Can you use Provisioned Concurrency with VPC-connected Lambda functions?​

Technical Answer: Yes, Provisioned Concurrency works with VPC-connected functions, and initializes the ENIs in your specified subnets during the provisioning process to eliminate ENI-related cold starts. This makes it particularly useful for VPC functions that have high cold start latencies from ENI setup.

Code/Config Example:

# CloudFormation: VPC function with Provisioned Concurrency
VpcLambda:
Type: AWS::Serverless::Function
Properties:
VpcConfig:
SubnetIds: [subnet-12345678]
SecurityGroupIds: [sg-12345678]
AutoPublishAlias: prod
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 10

🔍 Interviewer Notes: Tests knowledge of Provisioned Concurrency compatibility with VPC configurations.

❌ Common Mistakes:

  • Thinking Provisioned Concurrency doesn't help VPC functions (it eliminates ENI cold start setup)
  • Not knowing ENIs are pre-created during Provisioned Concurrency initialization
  • Forgetting that VPC-connected functions still need proper routing for internet access

Q116: How do you monitor Provisioned Concurrency utilization?​

Technical Answer: Use CloudWatch metrics like ProvisionedConcurrencyUtilization (percentage of provisioned environments in use), ProvisionedConcurrencyInvocations (invocations using provisioned capacity), and UnreservedConcurrencyInvocations (invocations using standard scaling). Low utilization indicates over-provisioning.

Code/Config Example:

aws cloudwatch get-metric-statistics \
--namespace AWS/Lambda \
--metric-name ProvisionedConcurrencyUtilization \
--dimensions Name=FunctionName,Value=my-function Name=Resource,Value=my-function:prod \
--start-time 2026-05-01T00:00:00Z \
--end-time 2026-05-01T23:59:59Z \
--period 3600 \
--statistics Average

🔍 Interviewer Notes: Tests ability to monitor and optimize Provisioned Concurrency usage.

❌ Common Mistakes:

  • Not monitoring utilization and over-provisioning unnecessarily
  • Confusing ProvisionedConcurrencyInvocations with total invocations
  • Ignoring UnreservedConcurrencyInvocations which indicate traffic exceeding provisioned capacity

Q117: What is the difference between Provisioned Concurrency and Reserved Concurrency?​

Technical Answer: Reserved Concurrency sets a maximum concurrency limit for a function version/alias and reserves that capacity exclusively for the function, while Provisioned Concurrency keeps environments initialized to eliminate cold starts. Reserved Concurrency controls scaling limits, Provisioned Concurrency controls cold start latency.

Code/Config Example:

# CloudFormation: Reserved Concurrency (no cold start benefit)
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
ReservedConcurrencyLimit: 50

🔍 Interviewer Notes: Tests differentiation between concurrency reservation and provisioning.

❌ Common Mistakes:

  • Using the terms interchangeably
  • Not knowing Reserved Concurrency does not eliminate cold starts
  • Thinking Provisioned Concurrency sets a concurrency limit (it does not)

Q118: Can you enable auto-scaling for Provisioned Concurrency?​

Technical Answer: Yes, you can use Application Auto Scaling to adjust Provisioned Concurrency based on CloudWatch metrics like ProvisionedConcurrencyUtilization or request count. This allows dynamic adjustment of provisioned capacity to match workload demands and control costs.

Code/Config Example:

# Register Provisioned Concurrency as scalable target
aws application-autoscaling register-scalable-target \
--service-namespace lambda \
--resource-id function:my-function:prod \
--scalable-dimension lambda:function:ProvisionedConcurrency \
--min-capacity 10 \
--max-capacity 100

🔍 Interviewer Notes: Tests knowledge of dynamic Provisioned Concurrency scaling options.

❌ Common Mistakes:

  • Believing Provisioned Concurrency is static and cannot auto-scale
  • Not knowing Application Auto Scaling is used for dynamic adjustment
  • Setting min/max capacity too loosely leading to cost overruns

Q119: How does Provisioned Concurrency impact function deployment and updates?​

Technical Answer: When you publish a new function version, you must configure Provisioned Concurrency for the new version/alias separately; it does not automatically carry over from previous versions. Updating the alias to point to a new version with Provisioned Concurrency may cause brief cold starts during the transition if the new version's environments are not pre-initialized.

Code/Config Example:

# SAM template with deployment preference for Provisioned Concurrency
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: prod
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 20
DeploymentPreference:
Type: Linear10PercentEvery10Minutes

🔍 Interviewer Notes: Tests understanding of Provisioned Concurrency lifecycle during deployments.

❌ Common Mistakes:

  • Assuming Provisioned Concurrency applies to $LATEST or all versions automatically
  • Not configuring Provisioned Concurrency for new versions after deployment
  • Forgetting that alias updates may trigger cold starts if new version's capacity is not provisioned

Q120: What are the limits for Provisioned Concurrency?​

Technical Answer: The default maximum Provisioned Concurrency per region is 1000 across all functions, with a per-function maximum of 1000 (adjustable via AWS support). You cannot set Provisioned Concurrency below 1 or above your account/function limits, and it is not supported for $LATEST.

Code/Config Example:

# Check current account limits (conceptual)
aws service-quotas list-service-quotas --service-code lambda --query "Quotas[?QuotaName=='Provisioned Concurrency']"

🔍 Interviewer Notes: Tests awareness of Provisioned Concurrency quotas and limits.

❌ Common Mistakes:

  • Not knowing there is a per-region default limit of 1000
  • Trying to set Provisioned Concurrency on $LATEST (unsupported)
  • Exceeding account limits without requesting an increase

Q121: What is asynchronous invocation in AWS Lambda?​

Technical Answer: Async invocation is used for event sources that do not wait for a response (e.g., S3 events, SNS, EventBridge), where Lambda queues the event and returns a 202 status immediately. Failed invocations are retried twice automatically, then sent to a Dead Letter Queue (DLQ) or Lambda Destination if configured.

Code/Config Example:

aws lambda invoke \
--function-name my-function \
--invocation-type Event \
--payload '{"key": "value"}' \
response.json

🔍 Interviewer Notes: Tests understanding of async invocation basics and use cases.

❌ Common Mistakes:

  • Confusing sync and async invocation types
  • Not knowing async invocations are queued and return 202 immediately
  • Forgetting that async invocations have default retries

Q122: What are Lambda Destinations for async invocations?​

Technical Answer: Lambda Destinations allow you to send the results of async invocations (success or failure) to supported AWS services (SQS, SNS, EventBridge, Lambda) without writing custom code in the function. You can configure separate destinations for successful and failed invocations.

Code/Config Example:

aws lambda put-function-event-invoke-config \
--function-name my-function \
--maximum-retry-attempts 2 \
--destination-config '{"OnSuccess": {"Destination": "arn:aws:sqs:us-east-1:123456789012:success-queue"}, "OnFailure": {"Destination": "arn:aws:sns:us-east-1:123456789012:failure-topic"}}'

🔍 Interviewer Notes: Tests knowledge of Destinations purpose and configuration.

❌ Common Mistakes:

  • Confusing Destinations with DLQs (Destinations replace DLQs for async invocations)
  • Not knowing you can set different destinations for success/failure
  • Forgetting that Destinations are only for async invocations

Q123: How do you configure a Dead Letter Queue (DLQ) for async Lambda invocations?​

Technical Answer: For async invocations, you can configure an SQS queue or SNS topic as a DLQ to receive events that failed all retries (legacy approach, Destinations are preferred now). DLQs are configured via the function's event invoke config or in the console.

Code/Config Example:

# CloudFormation DLQ configuration
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
DeadLetterConfig:
TargetArn: arn:aws:sqs:us-east-1:123456789012:my-dlq

🔍 Interviewer Notes: Tests understanding of DLQ configuration and legacy vs modern approaches.

❌ Common Mistakes:

  • Using DLQs instead of Destinations for new workloads
  • Confusing DLQ with Destinations (DLQs only capture failures after all retries)
  • Not knowing DLQs are only for async invocations

Q124: What is the difference between on-failure Destinations and DLQs?​

Technical Answer: Destinations are the newer, recommended approach that supports more targets (SQS, SNS, EventBridge, Lambda) and captures both success and failure results, while DLQs are legacy, only support SQS/SNS, and only capture failure results after all retries are exhausted.

Code/Config Example:

# SAM template: Destination for success to EventBridge
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
EventInvokeConfig:
DestinationConfig:
OnSuccess:
Destination: arn:aws:events:us-east-1:123456789012:event-bus/default

🔍 Interviewer Notes: Tests differentiation between DLQ and Destinations.

❌ Common Mistakes:

  • Using DLQs for new implementations (Destinations are preferred)
  • Not knowing Destinations support success results
  • Assuming DLQs support more target types than Destinations

Q125: How does event source mapping work for stream-based sources (Kinesis, DynamoDB Streams)?​

Technical Answer: Event source mapping (ESM) is a Lambda resource that reads records from stream or queue sources (Kinesis, DynamoDB Streams, SQS) and invokes the function synchronously with batched records. ESM manages checkpointing (tracking processed records) automatically for streams.

Code/Config Example:

# CloudFormation ESM for Kinesis
KinesisEventSource:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !GetAtt MyLambdaFunction.Arn
EventSourceArn: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
StartingPosition: LATEST
BatchSize: 100

🔍 Interviewer Notes: Tests understanding of event source mapping for stream-based sources.

❌ Common Mistakes:

  • Confusing ESM with push-based event sources (S3, SNS use push, not ESM)
  • Not knowing ESM manages checkpointing for streams
  • Forgetting that ESM invokes functions synchronously with batches

Q126: How do you configure batch processing for SQS event source mapping?​

Technical Answer: For SQS event sources, configure batch size (max 10,000 records), batch window (max 300 seconds) to wait for records, and report batch item failures to handle partial batch failures. Failed batches are retried until the message retention period expires.

Code/Config Example:

# SAM template: SQS ESM with partial batch response
SqsEventSource:
Type: AWS::Serverless::EventSource
Properties:
FunctionName: !Ref MyLambdaFunction
Events:
- Type: SQS
Queue: !Ref MySqsQueue
BatchSize: 10
MaximumBatchingWindowInSeconds: 10
FunctionResponseTypes:
- ReportBatchItemFailures

🔍 Interviewer Notes: Tests knowledge of SQS batch processing and error handling.

❌ Common Mistakes:

  • Not enabling ReportBatchItemFailures leading to full batch retries on single failure
  • Setting batch size too high causing timeout issues
  • Forgetting that SQS messages are deleted only after successful processing

Q127: What is the difference between sync and async invocation error handling?​

Technical Answer: Sync invocations return errors directly to the caller, who must handle retries; async invocations retry automatically (2x by default), then send to DLQ/Destination. Poll-based sources (ESM) retry until the source retention period expires, with checkpointing to track progress.

Code/Config Example:

# Python: Return partial batch failure for SQS
def lambda_handler(event, context):
failed_ids = []
for record in event["Records"]:
try:
process_record(record)
except Exception:
failed_ids.append(record["messageId"])
return {"batchItemFailures": [{"itemIdentifier": id} for id in failed_ids]}

🔍 Interviewer Notes: Tests understanding of error handling across invocation types.

❌ Common Mistakes:

  • Implementing retries for async invocations in function code (AWS handles retries)
  • Not returning partial batch failures for SQS leading to redundant retries
  • Confusing error handling for sync vs async vs poll-based sources

Q128: How do you configure EventBridge as a destination for Lambda async invocations?​

Technical Answer: Configure EventBridge as an OnSuccess or OnFailure destination in the function's event invoke config, specifying the EventBridge bus ARN. The invocation result is sent as an event to the bus, which can then route to downstream targets.

Code/Config Example:

aws lambda put-function-event-invoke-config \
--function-name my-function \
--destination-config '{"OnSuccess": {"Destination": "arn:aws:events:us-east-1:123456789012:event-bus/default"}}'

🔍 Interviewer Notes: Tests knowledge of EventBridge integration with Lambda Destinations.

❌ Common Mistakes:

  • Not having IAM permissions for Lambda to write to EventBridge
  • Forgetting to create an EventBridge rule to process the destination events
  • Confusing EventBridge bus ARN format

Q129: What are the retry policies for asynchronous Lambda invocations?​

Technical Answer: Async invocations retry failed attempts twice by default (configurable up to 2), with exponential backoff between retries. If all retries fail, the event is sent to the configured DLQ or Destination. You can also set a maximum event age (default 6 hours, max 6 hours) before retries are stopped.

Code/Config Example:

# CloudFormation event invoke config with retry settings
FunctionEventInvokeConfig:
Type: AWS::Lambda::EventInvokeConfig
Properties:
FunctionName: my-function
Qualifier: prod
MaximumRetryAttempts: 2
MaximumEventAgeInSeconds: 21600
DestinationConfig:
OnFailure:
Destination: arn:aws:sns:us-east-1:123456789012:failure-topic

🔍 Interviewer Notes: Tests understanding of async retry policies and configuration.

❌ Common Mistakes:

  • Setting maximum retry attempts higher than 2 (not supported)
  • Not knowing maximum event age is 6 hours
  • Forgetting that retries are only for async invocations

Q130: How do you handle partial batch failures for DynamoDB Streams event source mapping?​

Technical Answer: For DynamoDB Streams ESM, enable ReportBatchItemFailures and return a list of failed sequence numbers in the function response. Lambda will retry only the failed records, not the entire batch, reducing redundant processing.

Code/Config Example:

# Python: DynamoDB Streams partial batch failure
def lambda_handler(event, context):
failed_seq_nums = []
for record in event["Records"]:
try:
process_record(record)
except Exception:
failed_seq_nums.append(record["dynamodb"]["SequenceNumber"])
return {"batchItemFailures": [{"itemIdentifier": seq} for seq in failed_seq_nums]}

🔍 Interviewer Notes: Tests knowledge of partial batch failure handling for stream sources.

❌ Common Mistakes:

  • Not enabling ReportBatchItemFailures for stream ESM
  • Returning message IDs instead of sequence numbers for DynamoDB Streams
  • Forgetting that partial failure response is required to avoid full batch retries

Q131: What is the difference between push and poll-based event sources for Lambda?​

Technical Answer: Push-based sources (S3, SNS, EventBridge) send events directly to Lambda, invoking the function immediately. Poll-based sources (Kinesis, DynamoDB Streams, SQS) require Event Source Mapping (ESM) to poll the source and invoke the function with batched records.

Code/Config Example:

# Push-based (S3) vs Poll-based (SQS) event config
Resources:
PushEvent:
Type: AWS::Serverless::Function
Properties:
Events:
S3Event:
Type: S3
Properties:
Bucket: my-bucket
Events: s3:ObjectCreated:*

PollEvent:
Type: AWS::Serverless::Function
Properties:
Events:
SqsEvent:
Type: SQS
Properties:
Queue: !Ref MySqsQueue

🔍 Interviewer Notes: Tests differentiation between push and poll event sources.

❌ Common Mistakes:

  • Using ESM for push-based sources (incorrect)
  • Forgetting that poll-based sources require ESM resource
  • Confusing which sources use push vs poll

Q132: How do you configure parallelization factor for Kinesis/DynamoDB Streams ESM?​

Technical Answer: Parallelization factor sets the number of concurrent Lambda invocations per shard (1-10, default 1), allowing higher throughput for high-volume streams. Each parallel invocation processes a different partition of the shard's records.

Code/Config Example:

# CloudFormation ESM with parallelization factor
KinesisESM:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
EventSourceArn: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
ParallelizationFactor: 5

🔍 Interviewer Notes: Tests knowledge of stream throughput scaling with parallelization factor.

❌ Common Mistakes:

  • Setting parallelization factor higher than 10 (unsupported)
  • Not knowing parallelization factor applies per shard
  • Forgetting that higher parallelization increases Lambda concurrency usage

Q133: What is the purpose of the StartingPosition parameter in stream ESM?​

Technical Answer: StartingPosition defines where Lambda starts reading records from the stream: TRIM_HORIZON (oldest available record), LATEST (new records only), or AT_TIMESTAMP (specific timestamp). This only applies when creating a new ESM, not for existing ones.

Code/Config Example:

# DynamoDB Streams ESM with AT_TIMESTAMP
DynamoDBESM:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
EventSourceArn: arn:aws:dynamodb:us-east-1:123456789012:table/my-table/stream/*
StartingPosition: AT_TIMESTAMP
StartingPositionTimestamp: 2026-05-01T00:00:00Z

🔍 Interviewer Notes: Tests understanding of stream reading start positions.

❌ Common Mistakes:

  • Changing StartingPosition on existing ESM (has no effect)
  • Using AT_TIMESTAMP without specifying StartingPositionTimestamp
  • Confusing TRIM_HORIZON with LATEST

Q134: How do you handle SQS message visibility timeout with Lambda ESM?​

Technical Answer: The SQS visibility timeout should be set to at least 6 times the Lambda function timeout to allow for retries. If the function times out, the message becomes visible again after the timeout, and Lambda retries processing.

Code/Config Example:

# CloudFormation SQS queue with visibility timeout
MySqsQueue:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeoutSeconds: 360 # 6x 60s Lambda timeout
MessageRetentionPeriod: 1209600

🔍 Interviewer Notes: Tests knowledge of SQS-Lambda integration timeout alignment.

❌ Common Mistakes:

  • Setting visibility timeout shorter than function timeout (causes concurrent processing)
  • Not knowing visibility timeout should be 6x function timeout
  • Forgetting that SQS retries are managed by the queue, not Lambda

Q135: What is the maximum batch size for different event sources?​

Technical Answer: SQS standard queues: 10,000 records; SQS FIFO: 10 records; Kinesis/DynamoDB Streams: 10,000 records; S3: 1 record (no batching). Batch size controls how many records are sent to the function in a single invocation.

Code/Config Example:

# SAM template with max batch sizes
Events:
SqsEvent:
Type: SQS
BatchSize: 10000 # Max for standard SQS
KinesisEvent:
Type: Kinesis
BatchSize: 10000 # Max for Kinesis

🔍 Interviewer Notes: Tests awareness of batch size limits per event source.

❌ Common Mistakes:

  • Setting batch size higher than maximum allowed for the source
  • Using batch size 10,000 for SQS FIFO (max 10)
  • Not knowing S3 does not support batching

Q136: How do you configure a batch window for event source mapping?​

Technical Answer: Batch window (0-300 seconds) sets the maximum time Lambda waits to gather records up to the batch size before invoking the function. This is useful for low-volume streams to avoid invoking with small batches, reducing costs.

Code/Config Example:

# CloudFormation ESM with batch window
SqsESM:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
EventSourceArn: !GetAtt MySqsQueue.Arn
BatchSize: 100
MaximumBatchingWindowInSeconds: 10

🔍 Interviewer Notes: Tests knowledge of batch window optimization for low-volume sources.

❌ Common Mistakes:

  • Setting batch window longer than 300 seconds (unsupported)
  • Not using batch window for low-throughput sources (wastes invocations)
  • Confusing batch window with function timeout

Q137: What is checkpointing in the context of stream event source mapping?​

Technical Answer: Checkpointing is the process of tracking which stream records have been successfully processed, managed automatically by ESM for Kinesis and DynamoDB Streams. Checkpoints are saved to the stream service, so processing resumes from the last checkpoint if the ESM is updated or recreated.

Code/Config Example:

# CloudWatch Logs Insights: Checkpoint lag
fields @timestamp, shardId, sequenceNumber
| filter @message like /Checkpoint/
| stats latest(sequenceNumber) by shardId

🔍 Interviewer Notes: Tests understanding of stream processing state management.

❌ Common Mistakes:

  • Thinking checkpointing is managed by the Lambda function (it's ESM)
  • Not knowing checkpointing uses stream service (not Lambda state)
  • Forgetting that checkpoint lag can indicate processing delays

Q138: How do you configure on-failure destinations for poll-based event source mapping?​

Technical Answer: For ESM (poll-based sources), you can configure on-failure destinations (SQS, SNS, EventBridge, Lambda) to send a record of failed batches after all retries are exhausted. This is configured in the ESM resource, not the function's event invoke config.

Code/Config Example:

# CloudFormation ESM with on-failure destination
KinesisESM:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !Ref MyLambdaFunction
EventSourceArn: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
DestinationConfig:
OnFailure:
Destination: arn:aws:sqs:us-east-1:123456789012:failed-records-queue

🔍 Interviewer Notes: Tests knowledge of ESM-specific failure handling.

❌ Common Mistakes:

  • Configuring ESM destinations in function event invoke config (incorrect)
  • Not knowing ESM supports on-failure destinations
  • Confusing ESM destinations with async invocation destinations

Q139: What are the limits for Event Source Mapping per region?​

Technical Answer: Default ESM limit is 1000 per region per account, with a maximum of 5 concurrent ESMs per stream shard (adjustable via AWS support). Each ESM can only map one source to one function.

Code/Config Example:

# List ESMs for a Kinesis stream
aws lambda list-event-source-mappings \
--event-source-arn arn:aws:kinesis:us-east-1:123456789012:stream/my-stream

🔍 Interviewer Notes: Tests awareness of ESM quotas and limits.

❌ Common Mistakes:

  • Not knowing default ESM limit is 1000 per region
  • Trying to map one ESM to multiple functions (unsupported)
  • Exceeding per-shard concurrent ESM limit

Q140: How do you handle failed SQS messages with Lambda ESM?​

Technical Answer: Failed SQS messages are retried until the queue's message retention period expires, with visibility timeout controlling retry frequency. Enable ReportBatchItemFailures to retry only failed messages, not the entire batch.

Code/Config Example:

# Python: Return failed SQS message IDs
def lambda_handler(event, context):
failed_ids = []
for record in event["Records"]:
try:
process_record(record)
except Exception:
failed_ids.append(record["messageId"])
return {"batchItemFailures": [{"itemIdentifier": id} for id in failed_ids]}

🔍 Interviewer Notes: Tests knowledge of SQS message failure handling with ESM.

❌ Common Mistakes:

  • Not enabling ReportBatchItemFailures for SQS ESM
  • Forgetting that SQS retries are managed by queue retention, not Lambda
  • Confusing SQS failure handling with stream failure handling

Q141: What is AWS SAM and how is it used with Lambda?​

Technical Answer: AWS SAM (Serverless Application Model) is an open-source framework for building serverless apps, using simplified YAML templates to define Lambda functions, event sources, and dependencies. SAM CLI provides commands to build, test, and deploy serverless stacks locally and to AWS.

Code/Config Example:

# Basic SAM template for Lambda
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Resources:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: index.handler
Runtime: python3.12
Events:
S3Event:
Type: S3
Properties:
Bucket: my-bucket
Events: s3:ObjectCreated:*

🔍 Interviewer Notes: Tests knowledge of SAM basics and use cases.

❌ Common Mistakes:

  • Confusing SAM with CloudFormation (SAM is a superset with transforms)
  • Not knowing SAM CLI is required for local testing
  • Forgetting that SAM templates are converted to CloudFormation before deployment

Q142: How do you define Lambda function event sources in CloudFormation?​

Technical Answer: In CloudFormation, Lambda event sources are defined either directly in the function's Properties (for push sources) or as separate AWS::Lambda::EventSourceMapping resources (for poll-based sources). SAM simplifies this with the Events property syntax.

Code/Config Example:

# CloudFormation Event Source Mapping
MyEventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
FunctionName: !GetAtt MyLambdaFunction.Arn
EventSourceArn: arn:aws:sqs:us-east-1:123456789012:my-queue
BatchSize: 10

🔍 Interviewer Notes: Tests understanding of CloudFormation event source configuration.

❌ Common Mistakes:

  • Defining poll-based sources in function Properties (incorrect, use ESM)
  • Not knowing push sources can be embedded in function Properties
  • Forgetting that CloudFormation requires explicit ESM resources (unlike SAM)

Q143: What is the difference between AWS::Lambda::Function and AWS::Serverless::Function?​

Technical Answer: AWS::Lambda::Function is the native CloudFormation resource for Lambda, requiring explicit IAM roles, event mappings, and permissions. AWS::Serverless::Function is a SAM resource that auto-generates IAM roles, event permissions, and ESM resources from simplified configuration.

Code/Config Example:

# Native CloudFormation vs SAM Serverless
Resources:
# Native CloudFormation
NativeLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt LambdaRole.Arn
Runtime: python3.12
Code:
S3Bucket: my-bucket
S3Key: function.zip

# SAM Serverless
SamLambda:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: python3.12
CodeUri: src/

🔍 Interviewer Notes: Tests differentiation between native and SAM Lambda resources.

❌ Common Mistakes:

  • Using AWS::Serverless::Function in native CloudFormation without SAM transform
  • Not knowing SAM auto-generates IAM roles
  • Forgetting that SAM requires the AWS::Serverless-2016-10-31 transform

Q144: How do you package and deploy Lambda functions using SAM CLI?​

Technical Answer: Use sam build to process dependencies and package code, sam package to upload artifacts to S3, and sam deploy to deploy the CloudFormation stack. For local testing, sam local invoke runs the function in a Docker container.

Code/Config Example:

# SAM CLI deployment workflow
sam build --use-container
sam deploy --guided

🔍 Interviewer Notes: Tests knowledge of SAM CLI workflow and commands.

❌ Common Mistakes:

  • Forgetting to run sam build before sam deploy
  • Not using --use-container for compiled runtimes (Java, .NET)
  • Forgetting that sam deploy requires S3 bucket for large packages

Q145: What are Lambda layers and how do you define them in IaC?​

Technical Answer: Layers are ZIP archives containing libraries, dependencies, or shared code that can be referenced by multiple Lambda functions. In SAM/CloudFormation, define layers as AWS::Serverless::LayerVersion or AWS::Lambda::LayerVersion, and reference them in function's Layers property.

Code/Config Example:

# SAM template with Lambda layer
SharedLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: shared-dependencies
ContentUri: layer/
CompatibleRuntimes:
- python3.12

MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Layers:
- !Ref SharedLayer

🔍 Interviewer Notes: Tests knowledge of Lambda layers and IaC configuration.

❌ Common Mistakes:

  • Not matching layer's CompatibleRuntimes with function's runtime
  • Forgetting that layer version ARNs are immutable (new version on update)
  • Including unnecessary files in layer package increasing size

Q146: How do you configure environment variables for Lambda in CloudFormation?​

Technical Answer: Environment variables are defined in the Function's Properties under Environment.Variables, as key-value pairs. For sensitive values, reference AWS Secrets Manager or SSM Parameter Store instead of hardcoding.

Code/Config Example:

# CloudFormation environment variables
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Environment:
Variables:
DB_HOST: mydb.example.com
REGION: us-east-1

🔍 Interviewer Notes: Tests knowledge of environment variable configuration in IaC.

❌ Common Mistakes:

  • Hardcoding secrets in environment variables (use Secrets Manager)
  • Not knowing environment variables are encrypted at rest by default
  • Forgetting that environment variables count towards deployment package size limit

Q147: What is the purpose of the AWS::Serverless::Api resource in SAM?​

Technical Answer: AWS::Serverless::Api defines an API Gateway REST API associated with Lambda functions, auto-generating routes, methods, and integrations from function event configurations. It simplifies API Gateway setup compared to native CloudFormation.

Code/Config Example:

# SAM template with API Gateway
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod

MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Events:
ApiEvent:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /hello
Method: get

🔍 Interviewer Notes: Tests knowledge of SAM API Gateway integration.

❌ Common Mistakes:

  • Confusing REST API with HTTP API (SAM supports both via Api event type)
  • Not knowing SAM auto-generates API Gateway resources
  • Forgetting to define StageName for the API

Q148: How do you perform blue-green deployments for Lambda using SAM?​

Technical Answer: SAM supports deployment preferences (Linear, Canary, AllAtOnce) for Lambda aliases, gradually shifting traffic to new function versions. Configure DeploymentPreference in the function's properties to enable automated blue-green deployments.

Code/Config Example:

# SAM deployment preference
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: prod
DeploymentPreference:
Type: Linear10PercentEvery10Minutes
Alarms:
- !Ref FunctionErrorAlarm

🔍 Interviewer Notes: Tests knowledge of Lambda deployment strategies with SAM.

❌ Common Mistakes:

  • Not configuring alarms for deployment rollback
  • Forgetting that DeploymentPreference requires AutoPublishAlias
  • Confusing Linear with Canary deployment types

Q149: What are the benefits of using IaC (SAM/CloudFormation) for Lambda?​

Technical Answer: IaC enables version-controlled, reproducible Lambda deployments, automated rollbacks, and consistent configuration across environments. It eliminates manual console changes and integrates with CI/CD pipelines for automated deployments.

Code/Config Example:

# CloudFormation stack policy (enforce IaC-only updates)
StackPolicy:
Statement:
- Effect: Deny
Principal: "*"
Action: Update:*
Resource: "*"
Condition:
StringNotEquals:
aws:CalledVia: [cloudformation.amazonaws.com]

🔍 Interviewer Notes: Tests understanding of IaC benefits for Lambda.

❌ Common Mistakes:

  • Making manual console changes that drift from IaC template
  • Not version-controlling IaC templates
  • Forgetting to integrate IaC with CI/CD pipelines

Q150: How do you reference existing resources in SAM/CloudFormation Lambda templates?​

Technical Answer: Use CloudFormation intrinsic functions like !Ref, !GetAtt, !Sub to reference existing resources (e.g., S3 buckets, SNS topics) in the same stack or imported from other stacks. For cross-stack references, export values from one stack and import into another.

Code/Config Example:

# Cross-stack reference
# Stack A: Export
Outputs:
MyS3BucketArn:
Value: !GetAtt MyBucket.Arn
Export:
Name: MyS3BucketArn

# Stack B: Import
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Environment:
Variables:
BUCKET_ARN: !ImportValue MyS3BucketArn

🔍 Interviewer Notes: Tests knowledge of resource referencing in IaC.

❌ Common Mistakes:

  • Hardcoding ARNs instead of using intrinsic functions
  • Not exporting values before importing across stacks
  • Forgetting that imported values are static (no live updates)

Q151: What are Lambda function versions?​

Technical Answer: A version is a snapshot of a function's code and configuration that is immutable once published. Versions are numbered ($LATEST is the editable draft, versions are 1, 2, 3...), and allow you to reference specific iterations of the function.

Code/Config Example:

# Publish new Lambda version
aws lambda publish-version \
--function-name my-function \
--description "v1.1: Added error handling"

🔍 Interviewer Notes: Tests understanding of Lambda version basics.

❌ Common Mistakes:

  • Thinking $LATEST is a published version (it's the editable draft)
  • Not knowing versions are immutable
  • Forgetting that versions can be referenced by ARN

Q152: What is a Lambda alias?​

Technical Answer: An alias is a pointer to a specific function version (or weighted split between versions) that can be updated to shift traffic between versions. Aliases are mutable, so you can change which version they point to without updating callers.

Code/Config Example:

# Create alias with weighted traffic
aws lambda create-alias \
--function-name my-function \
--name prod \
--function-version 2 \
--routing-config AdditionalVersionWeights={"1"=0.1}

🔍 Interviewer Notes: Tests knowledge of alias purpose and traffic shifting.

❌ Common Mistakes:

  • Confusing aliases with versions (aliases are pointers, versions are snapshots)
  • Not knowing aliases support weighted traffic splitting
  • Forgetting that aliases are mutable

Q153: How do you implement CI/CD for Lambda functions?​

Technical Answer: Use CI/CD pipelines (GitHub Actions, GitLab CI, CodePipeline) to automate build, test, package, and deploy Lambda functions using IaC (SAM/CloudFormation). Integrate with testing frameworks and deployment preferences for blue-green deployments.

Code/Config Example:

# GitHub Actions workflow for Lambda deployment
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aws-actions/setup-sam@v2
- run: sam build
- run: sam deploy --no-confirm-changeset

🔍 Interviewer Notes: Tests knowledge of Lambda CI/CD implementation.

❌ Common Mistakes:

  • Not automating deployments, relying on manual console updates
  • Forgetting to run tests before deployment
  • Not integrating with IaC for reproducible deployments

Q154: How do you roll back a Lambda function deployment?​

Technical Answer: For versioned functions with aliases, update the alias to point back to the previous stable version. For IaC deployments, use CloudFormation stack rollback or update the stack to the previous template version.

Code/Config Example:

# Roll back alias to previous version
aws lambda update-alias \
--function-name my-function \
--name prod \
--function-version 1

🔍 Interviewer Notes: Tests understanding of rollback strategies.

❌ Common Mistakes:

  • Redeploying old code instead of rolling back alias
  • Not knowing CloudFormation supports automatic rollback on failure
  • Forgetting to test rollback procedure before incidents

Q155: What are the best practices for Lambda versioning and aliases?​

Technical Answer: Always use aliases for production invocations (not version numbers directly), publish versions for each deployment, and use weighted aliases for gradual traffic shifting. Avoid using $LATEST in production.

Code/Config Example:

# SAM template with auto-published alias
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: prod
DeploymentPreference:
Type: Linear10PercentEvery10Minutes

🔍 Interviewer Notes: Tests knowledge of versioning/alias best practices.

❌ Common Mistakes:

  • Using version numbers in production callers (breaks on new versions)
  • Not using aliases for traffic shifting
  • Deploying to $LATEST directly in production

Q156: How do you configure CodePipeline for Lambda deployment?​

Technical Answer: Set up a pipeline with source (CodeCommit, GitHub), build (CodeBuild to run SAM build/package), and deploy (CloudFormation to deploy the stack) stages. Add test stages and manual approval for production deployments.

Code/Config Example:

# buildspec.yml for CodePipeline build stage
version: 0.2
phases:
build:
commands:
- sam build
- sam package --s3-bucket my-bucket --output-template-file packaged.yaml
artifacts:
files: packaged.yaml

🔍 Interviewer Notes: Tests knowledge of AWS CodePipeline for Lambda.

❌ Common Mistakes:

  • Not including build stage to package dependencies
  • Forgetting to output packaged template as artifact
  • Not adding manual approval for production

Q157: What is the difference between $LATEST and published versions?​

Technical Answer: $LATEST is the mutable, editable draft of the function that can be modified directly, while published versions are immutable snapshots of $LATEST at the time of publishing. $LATEST cannot be used with Provisioned Concurrency.

Code/Config Example:

# $LATEST (mutable, for dev)
aws lambda invoke --function-name my-function $LATEST output.json

# Version 2 (immutable, for prod)
aws lambda invoke --function-name my-function:2 output.json

🔍 Interviewer Notes: Tests differentiation between $LATEST and versions.

❌ Common Mistakes:

  • Using $LATEST for production invocations
  • Not knowing $LATEST cannot be used with Provisioned Concurrency
  • Trying to modify published versions (immutable)

Q158: How do you shift traffic between Lambda versions using aliases?​

Technical Answer: Update the alias's routing config to set weighted percentages between two versions (primary version and additional version weights). Traffic is routed randomly based on the weights until updated.

Code/Config Example:

# SAM weighted alias
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: prod
RoutingConfig:
AdditionalVersionWeights:
1: 0.2 # 20% traffic to version 1

🔍 Interviewer Notes: Tests knowledge of traffic shifting with aliases.

❌ Common Mistakes:

  • Setting total weight to more than 1.0 (100%)
  • Not knowing traffic shifting is random, not sticky
  • Forgetting to monitor error rates when shifting traffic

Q159: How do you automate Lambda function testing in CI/CD?​

Technical Answer: Run unit tests (mocking AWS services), integration tests (invoking deployed functions in a test environment), and use tools like SAM local to test locally. Fail the pipeline if tests do not pass.

Code/Config Example:

# GitLab CI test stage
test:
stage: test
script:
- pip install pytest pytest-mock
- pytest tests/ -v
only:
- main

🔍 Interviewer Notes: Tests understanding of automated testing for Lambda.

❌ Common Mistakes:

  • Not mocking AWS service calls in unit tests
  • Forgetting to run integration tests in a test environment
  • Allowing pipelines to deploy with failing tests

Q160: What are the limits for Lambda function versions and aliases?​

Technical Answer: Maximum 100 published versions per function (adjustable via support), unlimited aliases per function. Each alias can point to one or two versions (weighted), and versions are immutable.

Code/Config Example:

# List function versions
aws lambda list-versions-by-function \
--function-name my-function \
--max-items 100

🔍 Interviewer Notes: Tests awareness of version/alias limits.

❌ Common Mistakes:

  • Not knowing default max 100 versions per function
  • Trying to modify published versions (immutable)
  • Exceeding version limit without requesting increase

Q161: How do you deploy Lambda functions as container images?​

Technical Answer: Package the function code and dependencies into a Docker image, push it to Amazon ECR, then create/update the Lambda function with the ECR image URI. Supported base images are provided by AWS for all supported runtimes.

Code/Config Example:

# Dockerfile for Python Lambda container
FROM public.ecr.aws/lambda/python:3.12
COPY src/ ${LAMBDA_TASK_ROOT}/
RUN pip install -r requirements.txt
CMD ["index.handler"]

🔍 Interviewer Notes: Tests knowledge of Lambda container image deployment.

❌ Common Mistakes:

  • Using non-AWS base images (unsupported, must use AWS provided)
  • Not setting CMD to handler in Dockerfile
  • Forgetting to push image to ECR before creating function

Q162: What are the size limits for Lambda container images?​

Technical Answer: Container images for Lambda can be up to 10GB in size, compared to 250MB for ZIP deployment packages. This allows larger dependencies or ML models to be included in the image.

Code/Config Example:

# Check ECR image size
aws ecr describe-images \
--repository-name my-lambda-repo \
--query "imageDetails[*].{Size:imageSizeInBytes,Tag:imageTags[0]}"

🔍 Interviewer Notes: Tests awareness of container image size limits.

❌ Common Mistakes:

  • Thinking container image limit is same as ZIP (250MB)
  • Not optimizing large images leading to longer cold starts
  • Forgetting that larger images increase pull time

Q163: How do you configure ECR permissions for Lambda to pull container images?​

Technical Answer: The Lambda function's execution role must have ecr:GetDownloadUrlForLayer, ecr:BatchGetImage, and ecr:GetAuthorizationToken permissions to pull images from ECR. AWS managed policy AmazonEC2ContainerRegistryReadOnly covers these.

Code/Config Example:

# IAM role for ECR access
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly

🔍 Interviewer Notes: Tests knowledge of ECR-Lambda IAM permissions.

❌ Common Mistakes:

  • Not granting ECR pull permissions to execution role
  • Using wrong managed policy (e.g., AmazonECS_FullAccess)
  • Forgetting that cross-account ECR requires additional permissions

Q164: What is the difference between ZIP and container image deployments for Lambda?​

Technical Answer: ZIP packages are limited to 250MB (unzipped), deployed via S3 or console, and faster to deploy. Container images support up to 10GB, use Docker for packaging, and are better for large dependencies.

Code/Config Example:

# ZIP deployment
aws lambda update-function-code --function-name my-func --zip-file fileb://func.zip

# Container deployment
aws lambda update-function-code --function-name my-func --image-uri 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-func:v1

🔍 Interviewer Notes: Tests differentiation between ZIP and container deployments.

❌ Common Mistakes:

  • Using container images for small functions (ZIP is simpler)
  • Not knowing container images support larger sizes
  • Forgetting that container deployments require ECR

Q165: How do you use Lambda layers with container images?​

Technical Answer: Layers are not supported with container images; instead, include all dependencies directly in the container image. This is a key difference from ZIP deployments which support layers.

Code/Config Example:

# No layers: Install dependencies in image
FROM public.ecr.aws/lambda/python:3.12
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY src/ ${LAMBDA_TASK_ROOT}/
CMD ["index.handler"]

🔍 Interviewer Notes: Tests knowledge of layers with container images.

❌ Common Mistakes:

  • Trying to reference layers in container image functions
  • Not including all dependencies in the container image
  • Forgetting layers are only for ZIP deployments

Q166: How do you tag Lambda container images?​

Technical Answer: Tag images when building/pushing to ECR, using semantic versioning (v1.0.0) or commit hashes for traceability. The image URI with tag is used to create/update the Lambda function.

Code/Config Example:

# Build and push tagged image
docker build -t my-lambda-func:v1 .
docker tag my-lambda-func:v1 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-lambda-func:v1
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-lambda-func:v1

🔍 Interviewer Notes: Tests knowledge of container image tagging best practices.

❌ Common Mistakes:

  • Using latest tag only (no traceability)
  • Not tagging images with version/commit hash
  • Forgetting to tag before pushing to ECR

Q167: What are the cold start implications of large container images?​

Technical Answer: Larger container images increase cold start times, as Lambda must pull the image from ECR and extract it before initializing the execution environment. Optimize images by minimizing layers and removing unnecessary files.

Code/Config Example:

# Multi-stage Dockerfile to minimize size
FROM public.ecr.aws/lambda/python:3.12 as builder
COPY requirements.txt .
RUN pip install --target ${LAMBDA_TASK_ROOT} -r requirements.txt

FROM public.ecr.aws/lambda/python:3.12
COPY --from=builder ${LAMBDA_TASK_ROOT} ${LAMBDA_TASK_ROOT}
COPY src/ ${LAMBDA_TASK_ROOT}/
CMD ["index.handler"]

🔍 Interviewer Notes: Tests understanding of cold start impact of container images.

❌ Common Mistakes:

  • Not optimizing container image size
  • Using single-stage Dockerfile with build dependencies
  • Forgetting that large images increase cold start latency

Q168: How do you update a Lambda function to a new container image version?​

Technical Answer: Use the update-function-code CLI command with the new image URI, or update the IaC template with the new image tag and redeploy. Lambda will pull the new image on next invocation (or immediately with Provisioned Concurrency).

Code/Config Example:

# Update function to new image version
aws lambda update-function-code \
--function-name my-func \
--image-uri 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-func:v2

🔍 Interviewer Notes: Tests knowledge of container image function updates.

❌ Common Mistakes:

  • Not updating the image tag in IaC templates
  • Forgetting that updates require ECR pull permissions
  • Not testing new image before updating production

Q169: Can you use private ECR repositories for Lambda container images?​

Technical Answer: Yes, Lambda supports pulling images from private ECR repositories in the same account or cross-account (with proper permissions). Public ECR repos are also supported using the public ECR URI.

Code/Config Example:

# ECR cross-account access policy
LambdaImageRepo:
Type: AWS::ECR::Repository
Properties:
RepositoryPolicyText:
Statement:
- Effect: Allow
Principal:
AWS: arn:aws:iam::098765432109:root
Action:
- ecr:BatchGetImage
- ecr:GetDownloadUrlForLayer

🔍 Interviewer Notes: Tests knowledge of private/cross-account ECR usage.

❌ Common Mistakes:

  • Not configuring ECR repository policy for cross-account access
  • Forgetting that Lambda execution role needs permissions for cross-account ECR
  • Using private ECR URI without proper permissions

Q170: How do you scan Lambda container images for vulnerabilities?​

Technical Answer: Enable ECR image scanning (basic or enhanced) to scan images for vulnerabilities on push. Integrate scan results with CI/CD pipelines to fail builds if critical vulnerabilities are found.

Code/Config Example:

# ECR repo with scan on push
LambdaImageRepo:
Type: AWS::ECR::Repository
Properties:
RepositoryName: my-lambda-repo
ImageScanningConfiguration:
ScanOnPush: true

🔍 Interviewer Notes: Tests knowledge of container image security scanning.

❌ Common Mistakes:

  • Not enabling ECR image scanning
  • Forgetting to integrate scan results with CI/CD
  • Ignoring critical vulnerabilities in scan results

Q171: What IAM permissions does a Lambda function need to access Secrets Manager?​

Technical Answer: The execution role needs secretsmanager:GetSecretValue and secretsmanager:DescribeSecret permissions for the target secret ARN. Use resource-level permissions to restrict access to specific secrets.

Code/Config Example:

# IAM policy for Secrets Manager access
SecretsManagerPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: LambdaSecretsAccess
Roles: [!Ref LambdaExecutionRole]
PolicyDocument:
Statement:
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref MySecret.Arn

🔍 Interviewer Notes: Tests knowledge of IAM permissions for Secrets Manager.

❌ Common Mistakes:

  • Granting wildcard (*) access to all secrets
  • Not including secretsmanager:GetSecretValue permission
  • Forgetting to restrict permissions to specific secret ARNs

Q172: How do you retrieve secrets from AWS Secrets Manager in Lambda?​

Technical Answer: Use the AWS SDK (boto3 for Python, AWS SDK for Node.js) to call get_secret_value, cache the secret in global scope to avoid repeated calls across warm starts. Use environment variables to store the secret ARN.

Code/Config Example:

# Python: Retrieve and cache secret
import boto3, json, os
from botocore.exceptions import ClientError

secret_arn = os.environ["SECRET_ARN"]
client = boto3.client("secretsmanager")
cached_secret = None

def get_secret():
global cached_secret
if not cached_secret:
resp = client.get_secret_value(SecretId=secret_arn)
cached_secret = json.loads(resp["SecretString"])
return cached_secret

🔍 Interviewer Notes: Tests ability to integrate Secrets Manager with Lambda.

❌ Common Mistakes:

  • Not caching secrets leading to throttling/extra cost
  • Hardcoding secret ARN instead of using environment variable
  • Forgetting to handle ClientError exceptions

Q173: What is the difference between storing secrets in environment variables vs Secrets Manager?​

Technical Answer: Environment variables are encrypted at rest but visible in console/config, and have size limits (4KB total). Secrets Manager supports rotation, fine-grained IAM access, larger secrets, and audit logging via CloudTrail.

Code/Config Example:

# Environment var (small, static)
db_host = os.environ["DB_HOST"]

# Secrets Manager (large, rotatable)
secret = get_secret() # From Q172
db_host = secret["host"]

🔍 Interviewer Notes: Tests differentiation between environment variables and Secrets Manager.

❌ Common Mistakes:

  • Using environment variables for large secrets (exceeds 4KB limit)
  • Not enabling rotation for Secrets Manager secrets
  • Forgetting that environment variables are visible in console

Q174: How do you configure Lambda function IAM execution role?​

Technical Answer: The execution role grants Lambda permissions to AWS services (e.g., S3, DynamoDB, CloudWatch Logs). Attach AWS managed policies (e.g., AWSLambdaBasicExecutionRole) or create custom policies with least privilege.

Code/Config Example:

# CloudFormation execution role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

🔍 Interviewer Notes: Tests knowledge of Lambda execution role configuration.

❌ Common Mistakes:

  • Granting administrator access to execution role
  • Not including basic execution policy for CloudWatch Logs
  • Forgetting to configure trust policy for lambda.amazonaws.com

Q175: How do you use AWS Parameter Store for Lambda configuration?​

Technical Answer: Parameter Store (SSM) stores plain text or encrypted (KMS) key-value pairs, cheaper than Secrets Manager for simple config. Use GetParameter or GetParametersByPath SDK calls to retrieve values, cache in global scope.

Code/Config Example:

# Python: Retrieve SSM parameter
import boto3
ssm = boto3.client("ssm")

def get_parameter(param_name):
resp = ssm.get_parameter(Name=param_name, WithDecryption=True)
return resp["Parameter"]["Value"]

🔍 Interviewer Notes: Tests knowledge of Parameter Store integration with Lambda.

❌ Common Mistakes:

  • Using Parameter Store for secrets (Secrets Manager is better for credentials)
  • Not caching parameters leading to extra API calls
  • Forgetting to enable WithDecryption for encrypted parameters

Q176: What are Lambda resource policies?​

Technical Answer: Resource policies grant cross-account or cross-service access to invoke the Lambda function (e.g., API Gateway, S3). They are attached to the function, not the execution role.

Code/Config Example:

# Add resource policy for S3 to invoke Lambda
aws lambda add-permission \
--function-name my-function \
--statement-id s3-invoke \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::my-bucket

🔍 Interviewer Notes: Tests understanding of Lambda resource policies vs IAM roles.

❌ Common Mistakes:

  • Confusing resource policies with execution role policies
  • Not knowing resource policies are for invoker access, not function permissions
  • Forgetting to restrict source ARN for cross-account access

Q177: How do you encrypt Lambda environment variables with KMS?​

Technical Answer: By default, environment variables are encrypted with an AWS managed KMS key; you can use a customer managed KMS key (CMK) for more control. Configure KmsKeyArn in the function's environment properties.

Code/Config Example:

# CloudFormation with custom KMS key
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Environment:
Variables:
DB_HOST: mydb.example.com
KmsKeyArn: !GetAtt MyKmsKey.Arn

🔍 Interviewer Notes: Tests knowledge of environment variable encryption with KMS.

❌ Common Mistakes:

  • Not granting Lambda execution role KMS decrypt permissions
  • Using default AWS managed key when custom control is needed
  • Forgetting that KMS encryption adds slight invocation latency

Q178: What is the principle of least privilege for Lambda IAM roles?​

Technical Answer: Least privilege means granting only the permissions required for the function to perform its task, no more. Avoid wildcard actions () or resources (), and use specific actions and resource ARNs.

Code/Config Example:

# Least privilege S3 read policy
S3ReadPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::my-bucket/*

🔍 Interviewer Notes: Tests understanding of least privilege best practices.

❌ Common Mistakes:

  • Using wildcard (*) for actions or resources
  • Granting full S3 access (s3:*) when only GetObject is needed
  • Not regularly auditing IAM policies

Q179: How do you audit Lambda function security?​

Technical Answer: Use CloudTrail to log API calls, CloudWatch Logs for invocation logs, and AWS Config to track configuration changes. Enable GuardDuty for threat detection and run IAM Access Analyzer to identify unused permissions.

Code/Config Example:

# Get CloudTrail events for Lambda
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=UpdateFunctionConfiguration

🔍 Interviewer Notes: Tests knowledge of Lambda security auditing tools.

❌ Common Mistakes:

  • Not enabling CloudTrail logging for Lambda API calls
  • Forgetting to review IAM policies regularly
  • Not using AWS Config to track config changes

Q180: How do you handle KMS key rotation for Lambda encrypted resources?​

Technical Answer: AWS managed KMS keys rotate automatically annually; customer managed keys can be rotated annually, or manually rotate by creating a new key version. Lambda automatically uses the latest key version for encryption/decryption.

Code/Config Example:

# Enable auto-rotation for CMK
aws kms enable-key-rotation --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

🔍 Interviewer Notes: Tests knowledge of KMS key rotation for Lambda.

❌ Common Mistakes:

  • Not enabling auto-rotation for customer managed keys
  • Forgetting that AWS managed keys rotate automatically
  • Deleting old key versions (breaks decryption of old data)

Q181: How do you optimize Lambda function memory for performance?​

Technical Answer: Use AWS Lambda Power Tuning to find the optimal memory setting, as higher memory also increases CPU allocation. More memory can reduce execution time, lowering total cost even if memory cost per GB-second is higher.

Code/Config Example:

# Power Tuning input event
{
"lambdaARN": "arn:aws:lambda:us-east-1:123456789012:function:my-func",
"powerValues": [128, 256, 512, 1024],
"num": 10,
"payload": {"key": "value"}
}

🔍 Interviewer Notes: Tests knowledge of memory optimization and Power Tuning.

❌ Common Mistakes:

  • Always using 128MB (too low for CPU-intensive tasks)
  • Not using Power Tuning to find optimal memory
  • Forgetting that higher memory = more CPU

Q182: What is the impact of deployment package size on Lambda performance?​

Technical Answer: Larger deployment packages increase cold start times, as Lambda must download and extract the package before initializing. Keep packages small by removing unused dependencies, using layers for shared code, and minifying code.

Code/Config Example:

# Check deployment package size
aws lambda get-function --function-name my-func --query "Configuration.CodeSize"
zipinfo function.zip | tail -1 # Show total ZIP size

🔍 Interviewer Notes: Tests understanding of package size impact on performance.

❌ Common Mistakes:

  • Including unnecessary dependencies in deployment package
  • Not using layers to split large dependencies
  • Forgetting that package size affects cold start

Q183: How do you optimize database connection management in Lambda?​

Technical Answer: Use connection pooling libraries, cache connections in global scope to reuse across warm starts, and use RDS Proxy to manage connections for serverless databases to avoid throttling.

Code/Config Example:

# Python: Cache DB connection globally
import pymysql, os
connection = None

def get_connection():
global connection
if not connection:
connection = pymysql.connect(host=os.environ["DB_HOST"], user=...)
return connection

🔍 Interviewer Notes: Tests knowledge of database connection optimization.

❌ Common Mistakes:

  • Creating new connection per invocation (causes throttling)
  • Not caching connections in global scope
  • Forgetting to use RDS Proxy for high concurrency

Q184: What are the best practices for Lambda function timeout configuration?​

Technical Answer: Set timeout to the maximum expected execution time plus buffer (3-6 seconds for standard functions, longer for async tasks). Avoid setting too high (wastes concurrency) or too low (causes timeouts).

Code/Config Example:

# CloudFormation timeout
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Timeout: 10 # 10 seconds

🔍 Interviewer Notes: Tests knowledge of timeout best practices.

❌ Common Mistakes:

  • Setting timeout too low (frequent timeouts)
  • Setting timeout too high (wastes concurrency capacity)
  • Not adjusting timeout for async vs sync functions

Q185: How do you reduce Lambda invocation latency?​

Technical Answer: Use Provisioned Concurrency for latency-sensitive workloads, keep functions warm with ping invocations, minimize cold start factors (package size, VPC ENI), and use lighter runtimes (Python/Node.js over Java/.NET).

Code/Config Example:

# CloudWatch Events rule to keep function warm
WarmUpRule:
Type: AWS::Events::Rule
Properties:
ScheduleExpression: rate(5 minutes)
Targets:
- Arn: !GetAtt MyLambdaFunction.Arn
Id: WarmUp

🔍 Interviewer Notes: Tests knowledge of latency reduction strategies.

❌ Common Mistakes:

  • Relying on warm-up pings (not a substitute for Provisioned Concurrency)
  • Not considering runtime choice for latency
  • Forgetting that VPC increases cold start latency

Q186: How do you optimize Lambda for high concurrency workloads?​

Technical Answer: Increase account concurrency limits, use Provisioned Concurrency to pre-warm environments, optimize function code for fast execution, and use async invocation to decouple request submission from processing.

Code/Config Example:

# Request concurrency limit increase (via AWS Support)
# Service: Lambda, Limit: Concurrent Executions

🔍 Interviewer Notes: Tests knowledge of high concurrency optimization.

❌ Common Mistakes:

  • Not requesting concurrency limit increases for high workloads
  • Not using Provisioned Concurrency for predictable high traffic
  • Forgetting that unoptimized code increases concurrency usage

Q187: What is the impact of runtime choice on Lambda performance?​

Technical Answer: Compiled runtimes (Java, .NET) have longer cold starts but faster execution; interpreted runtimes (Python, Node.js) have shorter cold starts but slower execution for CPU-intensive tasks. Choose based on workload needs.

Code/Config Example:

# Conceptual runtime performance comparison
Python 3.12: Cold start ~100ms, Execution ~500ms (CPU task)
Java 21: Cold start ~3000ms, Execution ~300ms (CPU task)

🔍 Interviewer Notes: Tests understanding of runtime performance tradeoffs.

❌ Common Mistakes:

  • Using Java for latency-sensitive low-traffic workloads
  • Choosing Python for heavy CPU tasks (slower execution)
  • Not considering cold start vs execution time tradeoffs

Q188: How do you use Lambda Insights for performance monitoring?​

Technical Answer: Enable Lambda Insights extension to collect detailed performance metrics (memory, CPU, network) and logs, visible in CloudWatch. It helps identify bottlenecks like high memory usage or slow dependencies.

Code/Config Example:

# SAM template with Lambda Insights
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Layers:
- !Sub arn:aws:lambda:${AWS::Region}:580247275435:layer:LambdaInsightsExtension:14
Environment:
Variables:
CW_LAMBDA_LOG_GROUP_NAME: /aws/lambda-insights/my-func

🔍 Interviewer Notes: Tests knowledge of Lambda Insights for performance tuning.

❌ Common Mistakes:

  • Not enabling Lambda Insights for performance monitoring
  • Forgetting to add Insights layer to function
  • Not reviewing Insights metrics to identify bottlenecks

Q189: How do you optimize S3 operations in Lambda?​

Technical Answer: Reuse S3 clients across warm starts (global scope), use multipart transfers for large files, and use S3 VPC endpoints for VPC-connected functions to reduce latency and cost.

Code/Config Example:

# Python: Reuse S3 client
import boto3
s3_client = None

def get_s3_client():
global s3_client
if not s3_client:
s3_client = boto3.client("s3")
return s3_client

🔍 Interviewer Notes: Tests knowledge of S3 operation optimization in Lambda.

❌ Common Mistakes:

  • Creating new S3 client per invocation
  • Not using multipart transfers for large files
  • Forgetting S3 VPC endpoints for private access

Q190: What are the best practices for Lambda function logging performance?​

Technical Answer: Log only necessary information, use structured logging (JSON), avoid logging sensitive data, and use log levels (DEBUG/INFO/ERROR) to control verbosity in production.

Code/Config Example:

# Structured JSON logging
import json, logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
logger.info(json.dumps({"message": "Processing", "event_id": event["id"]}))

🔍 Interviewer Notes: Tests knowledge of logging best practices for performance.

❌ Common Mistakes:

  • Logging excessive data (increases cost and latency)
  • Not using structured JSON logging
  • Logging sensitive data (PII, credentials)

Q191: How is Lambda pricing calculated?​

Technical Answer: Lambda pricing is based on number of requests (first 1M free per month) and GB-second (memory * execution time). Data transfer, Provisioned Concurrency, and ESM have separate charges.

Code/Config Example:

# Conceptual cost calculation
# 1M invocations, 128MB, 500ms each
requests_cost = 0 # First 1M free monthly
compute_cost = (128/1024) * 0.5 * 0.0000166667 # $0.0000166667 per GB-second
total = requests_cost + (compute_cost * 1_000_000)

🔍 Interviewer Notes: Tests understanding of Lambda pricing model.

❌ Common Mistakes:

  • Not knowing first 1M requests are free monthly
  • Forgetting that cost is memory * duration, not just duration
  • Ignoring additional costs (Provisioned Concurrency, data transfer)

Q192: How do you reduce Lambda compute costs?​

Technical Answer: Right-size memory (use Power Tuning), reduce execution time by optimizing code, use async invocation for non-latency-sensitive tasks, and delete unused functions/versions.

Code/Config Example:

# Find unused functions (not modified since 2026-01-01)
aws lambda list-functions --query "Functions[?LastModified < '2026-01-01'].FunctionName"

🔍 Interviewer Notes: Tests knowledge of compute cost optimization.

❌ Common Mistakes:

  • Over-provisioning memory "just in case"
  • Not optimizing slow code increasing execution time
  • Forgetting to delete unused functions

Q193: What are the cost implications of Provisioned Concurrency?​

Technical Answer: You pay for Provisioned Concurrency (GB-second) from when it's enabled to disabled, even if not invoked, with 1-minute minimum billing. Only use for latency-critical workloads.

Code/Config Example:

# Conceptual Provisioned Concurrency cost
# 10 instances, 1024MB, 1 month
cost = 10 * (1024/1024) * 0.0000041667 * 3600 * 24 * 30

🔍 Interviewer Notes: Tests awareness of Provisioned Concurrency costs.

❌ Common Mistakes:

  • Enabling Provisioned Concurrency for non-critical workloads
  • Not knowing 1-minute minimum billing
  • Over-provisioning Provisioned Concurrency

Q194: How do you reduce Lambda request costs?​

Technical Answer: Use async invocation to batch events (SQS, Kinesis) reducing invocation count, filter events at source (S3, EventBridge) to avoid unnecessary invocations, and delete unused event source mappings.

Code/Config Example:

# EventBridge rule with filter (reduce invocations)
EventRule:
Type: AWS::Events::Rule
Properties:
EventPattern:
source: [aws.s3]
detail-type: [Object Created]
detail:
bucket:
name: [my-bucket]
object:
key: [prefix: logs/]

🔍 Interviewer Notes: Tests knowledge of request cost optimization.

❌ Common Mistakes:

  • Not filtering events at source (unnecessary invocations)
  • Using synchronous invocation for batchable workloads
  • Forgetting to delete unused ESMs

Q195: What are the cost implications of Lambda layers?​

Technical Answer: Layers themselves are free, but increase deployment package size (if not used) leading to longer cold starts. Reusing layers across functions reduces storage costs for duplicate dependencies.

Code/Config Example:

# List all layers
aws lambda list-layers --query "Layers[*].LatestMatchingVersion.LayerVersionArn"

🔍 Interviewer Notes: Tests understanding of layer cost impact.

❌ Common Mistakes:

  • Including unused layers increasing package size
  • Not reusing layers across functions (duplicate storage)
  • Forgetting layers are free but affect cold start

Q196: How do you reduce data transfer costs with Lambda?​

Technical Answer: Use VPC endpoints for S3/DynamoDB to avoid NAT Gateway costs, process data in the same region as sources, and compress large payloads to reduce transfer volume.

Code/Config Example:

# S3 VPC endpoint (free, reduces NAT costs)
S3Endpoint:
Type: AWS::EC2::VPCEndPoint
Properties:
ServiceName: com.amazonaws.us-east-1.s3
VpcId: !Ref MyVpc

🔍 Interviewer Notes: Tests knowledge of data transfer cost optimization.

❌ Common Mistakes:

  • Using NAT Gateway for S3/DynamoDB access (VPC endpoints are free)
  • Not processing data in same region (cross-region costs)
  • Forgetting to compress large payloads

Q197: What is the cost impact of Lambda function versions?​

Technical Answer: Each published version stores a copy of the function code, incurring S3 storage costs. Delete unused versions to reduce storage costs (use lifecycle policies).

Code/Config Example:

# Delete old Lambda versions (conceptual)
aws lambda list-versions-by-function --function-name my-func \
--query "Versions[?Version !=\$LATEST].Version" --output text | xargs -I {} aws lambda delete-function --function-name my-func --qualifier {}

🔍 Interviewer Notes: Tests awareness of version storage costs.

❌ Common Mistakes:

  • Not deleting unused function versions
  • Publishing versions unnecessarily
  • Forgetting versions incur S3 storage costs

Q198: How do you use Cost Explorer to monitor Lambda costs?​

Technical Answer: Filter Cost Explorer by service (Lambda), usage type (Request, GB-Second, Provisioned Concurrency), and tag to identify cost drivers. Set up cost alerts for unexpected spikes.

Code/Config Example:

// Cost Explorer filter
{
"filter": {
"service": { "terms": { "values": ["Lambda"] } },
"usage_type": { "terms": { "values": ["Request", "GB-Second"] } }
}
}

🔍 Interviewer Notes: Tests knowledge of Lambda cost monitoring.

❌ Common Mistakes:

  • Not tagging Lambda functions for cost allocation
  • Ignoring Cost Explorer reports
  • Not setting up cost alerts

Q199: What are the cost implications of VPC-connected Lambda functions?​

Technical Answer: VPC-connected functions may incur NAT Gateway costs (if internet access needed), and ENI setup time does not add direct cost but increases cold start latency. Use VPC endpoints to avoid NAT costs.

Code/Config Example:

# Check NAT Gateway costs in Cost Explorer
aws ce get-cost-and-usage --time-period Start=2026-05-01,End=2026-05-31 --granularity MONTHLY --filter '{"service": {"terms": {"values": ["Amazon VPC"]}}}'

🔍 Interviewer Notes: Tests understanding of VPC Lambda cost impact.

❌ Common Mistakes:

  • Not using VPC endpoints (incurs NAT Gateway costs)
  • Forgetting NAT Gateway has hourly + data processing costs
  • Not knowing VPC connection itself is free

Q200: How do you implement cost governance for Lambda?​

Technical Answer: Use AWS Budgets to set cost thresholds, IAM policies to restrict high-cost configurations (e.g., large memory, Provisioned Concurrency), and tag functions for cost allocation.

Code/Config Example:

# IAM policy to restrict max memory to 1024MB
RestrictMemoryPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Effect: Deny
Action: lambda:UpdateFunctionConfiguration
Condition:
NumericGreaterThan:
lambda:MaxMemory: [1024]

🔍 Interviewer Notes: Tests knowledge of Lambda cost governance.

❌ Common Mistakes:

  • Not setting up AWS Budgets alerts
  • Forgetting to tag functions for cost tracking
  • Not restricting high-cost configurations via IAM

Q201: How do you test Lambda functions locally?​

Technical Answer: Use SAM local invoke to run functions in Docker containers locally, mimicking Lambda runtime. Test with sample event JSON, and use SAM local start-api for API Gateway integration testing.

Code/Config Example:

# Local invoke with test event
sam local invoke MyLambdaFunction --event events/test.json

🔍 Interviewer Notes: Tests knowledge of local Lambda testing.

❌ Common Mistakes:

  • Not using Docker for local Lambda testing
  • Forgetting to mock AWS service calls (S3, DynamoDB)
  • Not testing with sample event payloads

Q202: What are the best practices for unit testing Lambda functions?​

Technical Answer: Mock AWS SDK calls (using moto for Python, aws-sdk-mock for Node.js), isolate handler logic from AWS interactions, and test success, error, and edge cases.

Code/Config Example:

# Python unit test with moto
import boto3
from moto import mock_s3
import lambda_function

@mock_s3
def test_lambda_handler():
s3 = boto3.client("s3", region_name="us-east-1")
s3.create_bucket(Bucket="test-bucket")
event = {"Records": [{"s3": {"bucket": {"name": "test-bucket"}}}]}
response = lambda_function.lambda_handler(event, None)
assert response["statusCode"] == 200

🔍 Interviewer Notes: Tests understanding of unit testing for Lambda.

❌ Common Mistakes:

  • Calling real AWS services in unit tests
  • Not mocking all AWS SDK interactions
  • Forgetting to test error cases

Q203: How do you write integration tests for Lambda?​

Technical Answer: Deploy functions to a test environment, invoke them with real event sources, and verify results (e.g., S3 object created, DynamoDB item written). Use IaC to deploy test stacks automatically.

Code/Config Example:

# Conceptual integration test
def test_integration():
client = boto3.client("lambda")
response = client.invoke(FunctionName="my-func", Payload=json.dumps(event))
s3.head_object(Bucket="test-bucket", Key="output.txt")

🔍 Interviewer Notes: Tests knowledge of integration testing for Lambda.

❌ Common Mistakes:

  • Not cleaning up test resources after tests
  • Forgetting to deploy to isolated test environment
  • Not verifying side effects (S3, DB writes)

Q204: What is the SAM local start-api command used for?​

Technical Answer: It starts a local API Gateway that routes requests to Lambda functions defined in the SAM template, allowing local testing of HTTP endpoints without deploying to AWS.

Code/Config Example:

sam local start-api --port 3000
# Test: curl http://localhost:3000/hello

🔍 Interviewer Notes: Tests knowledge of local API Gateway testing.

❌ Common Mistakes:

  • Not using SAM local start-api for API testing
  • Forgetting to define API events in SAM template
  • Not testing different HTTP methods/paths

Q205: How do you debug Lambda functions locally?​

Technical Answer: Use SAM local invoke with --debug-port to attach a debugger (VS Code, PyCharm), set breakpoints in code, and step through execution. For Node.js, use --debug-port 5858.

Code/Config Example:

# Debug Python Lambda locally
sam local invoke MyLambdaFunction --event events/test.json --debug-port 5890
# Attach VS Code debugger to port 5890

🔍 Interviewer Notes: Tests knowledge of local Lambda debugging.

❌ Common Mistakes:

  • Not generating debug symbols for compiled runtimes (Java, .NET)
  • Forgetting to open debug port in Docker
  • Not matching runtime debug port

Q206: What are Lambda function test events?​

Technical Answer: Test events are JSON payloads simulating real event sources (S3, API Gateway, SQS) used to invoke functions in console or locally. SAM uses event JSON files for local testing.

Code/Config Example:

// S3 test event
{
"Records": [
{
"eventSource": "aws:s3",
"s3": {
"bucket": { "name": "test-bucket" },
"object": { "key": "test.txt" }
}
}
]
}

🔍 Interviewer Notes: Tests understanding of test event structure.

❌ Common Mistakes:

  • Using incorrect event format for source
  • Not matching event schema for runtime
  • Forgetting to test with multiple event variations

Q207: How do you use pytest for Lambda testing?​

Technical Answer: Structure tests in tests/ directory, use pytest-mock for mocking, and run pytest to execute all tests. Use conftest.py for shared fixtures.

Code/Config Example:

# pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py

🔍 Interviewer Notes: Tests knowledge of pytest with Lambda.

❌ Common Mistakes:

  • Not organizing tests in dedicated directory
  • Forgetting to install pytest and mock libraries
  • Not using fixtures to reuse setup

Q208: What is the difference between local testing and deployed testing?​

Technical Answer: Local testing uses Docker to mimic Lambda runtime but lacks AWS service connectivity (needs mocking). Deployed testing uses real AWS services, IAM roles, and event sources, but requires deployment.

Code/Config Example:

# Local (mocked)
sam local invoke --event test.json

# Deployed (real services)
aws lambda invoke --function-name my-func --payload '{}' output.json

🔍 Interviewer Notes: Tests differentiation between local and deployed testing.

❌ Common Mistakes:

  • Assuming local tests validate real AWS integration
  • Not running deployed integration tests
  • Forgetting local tests can't test IAM permissions

Q209: How do you automate Lambda testing in CI/CD?​

Technical Answer: Add test stages to CI/CD pipelines to run unit tests (with mocks) and deploy to a test environment for integration tests. Fail the pipeline if tests fail.

Code/Config Example:

# GitHub Actions test stage
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install pytest moto boto3
- run: pytest tests/ -v

🔍 Interviewer Notes: Tests knowledge of automated testing in CI/CD.

❌ Common Mistakes:

  • Not failing pipeline on test failures
  • Forgetting to run integration tests in test environment
  • Not mocking AWS services in unit tests

Q210: What are common Lambda testing pitfalls?​

Technical Answer: Not testing error cases, relying only on local tests without deployed integration tests, and not testing with realistic event payloads. Also, not testing cold vs warm start behavior.

Code/Config Example:

# Conceptual cold start test
time aws lambda invoke --function-name my-func --payload '{}' out.json

🔍 Interviewer Notes: Tests awareness of testing pitfalls.

❌ Common Mistakes:

  • Only testing happy path
  • Not testing with production-like payloads
  • Forgetting to test cold start behavior

Q211: What are Lambda extensions?​

Technical Answer: Extensions are lightweight scripts or executables that run within the Lambda execution environment alongside your function, enabling integration with monitoring, security, and governance tools (e.g., New Relic, Datadog). They can run before, during, and after function invocation.

Code/Config Example:

# Add extension layer to function
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Layers:
- arn:aws:lambda:us-east-1:123456789012:layer:my-extension:1

🔍 Interviewer Notes: Tests knowledge of Lambda extensions purpose and usage.

❌ Common Mistakes:

  • Confusing extensions with layers (extensions run alongside function, layers are code dependencies)
  • Not knowing extensions have their own lifecycle
  • Forgetting that extensions increase cold start latency

Q212: How do you use the Lambda Telemetry API?​

Technical Answer: The Telemetry API allows extensions to receive function logs and metrics directly from the Lambda runtime, without routing through CloudWatch Logs. Extensions subscribe to telemetry streams during the extension init phase.

Code/Config Example:

// Extension telemetry subscription
{
"protocol": "HTTP",
"types": ["platform", "function"],
"buffering": { "maxBytes": 1024, "maxItems": 100, "timeoutMs": 100 }
}

🔍 Interviewer Notes: Tests understanding of Telemetry API for extensions.

❌ Common Mistakes:

  • Not knowing Telemetry API is for extensions, not functions
  • Forgetting to subscribe to telemetry streams in extension init
  • Using Telemetry API to send logs (it receives logs)

Q213: What is idempotency in Lambda functions?​

Technical Answer: Idempotency ensures that processing the same event multiple times produces the same result, avoiding duplicate side effects (e.g., double-charging a customer). Implement using unique event IDs and persistent storage (DynamoDB) to track processed events.

Code/Config Example:

# Python idempotency with DynamoDB
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("ProcessedEvents")

def lambda_handler(event, context):
event_id = event["id"]
try:
table.put_item(Item={"eventId": event_id}, ConditionExpression="attribute_not_exists(eventId)")
except:
return {"statusCode": 200, "body": "Duplicate event"}
# Process event

🔍 Interviewer Notes: Tests knowledge of idempotency patterns for Lambda.

❌ Common Mistakes:

  • Not implementing idempotency for async/retried events
  • Storing idempotency keys only in memory (lost on cold start)
  • Forgetting to set TTL on processed event records

Q214: How do you handle partial failures in batch processing?​

Technical Answer: For batch event sources (SQS, Kinesis, DynamoDB Streams), return a list of failed record IDs/sequence numbers using ReportBatchItemFailures. Lambda will retry only failed records, not the entire batch.

Code/Config Example:

# Python partial batch failure response
def lambda_handler(event, context):
failed_ids = []
for record in event["Records"]:
try:
process(record)
except:
failed_ids.append(record["messageId"])
return {"batchItemFailures": [{"itemIdentifier": id} for id in failed_ids]}

🔍 Interviewer Notes: Tests understanding of partial batch failure handling.

❌ Common Mistakes:

  • Not enabling ReportBatchItemFailures on ESM
  • Returning entire batch as failed on single error
  • Forgetting to match failure ID type to event source (messageId vs sequenceNumber)

Q215: What are Lambda Destinations retry policies?​

Technical Answer: Destinations for async invocations retry sending to the target if the initial delivery fails, up to 24 hours with exponential backoff. You can configure the maximum age of events for destination delivery.

Code/Config Example:

# Configure destination retry
aws lambda put-function-event-invoke-config \
--function-name my-func \
--destination-config '{"OnFailure": {"Destination": "arn:aws:sqs:us-east-1:123456789012:dlq"}}' \
--maximum-event-age-in-seconds 21600

🔍 Interviewer Notes: Tests knowledge of Destinations retry behavior.

❌ Common Mistakes:

  • Not knowing Destinations retry failed deliveries
  • Forgetting maximum event age applies to destination delivery
  • Confusing Destinations retry with function invocation retry

Q216: How do you use Lambda with Step Functions?​

Technical Answer: Step Functions can invoke Lambda functions as tasks in state machines, passing input/output between states. Configure the Lambda task with retry/catch policies for error handling, and use IAM roles for Step Functions to invoke Lambda.

Code/Config Example:

// Step Functions state machine
{
"StartAt": "ProcessData",
"States": {
"ProcessData": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:my-func",
"Next": "Success"
}
}
}

🔍 Interviewer Notes: Tests knowledge of Lambda integration with Step Functions.

❌ Common Mistakes:

  • Not granting Step Functions IAM permission to invoke Lambda
  • Forgetting to handle Lambda errors in Step Functions with Catch
  • Not passing state input to Lambda function correctly

Q217: What is the Lambda runtime interface emulator (RIE)?​

Technical Answer: RIE is a tool to test Lambda functions locally without Docker, mimicking the Lambda runtime API. It is included in container images, or can be downloaded for ZIP packages to test handler responses.

Code/Config Example:

# Test with RIE
curl -Lo riemulator https://github.com/aws/aws-lambda-rie/releases/latest/download/aws-lambda-rie
chmod +x riemulator
./riemulator --handler index.handler --runtime python3.12

🔍 Interviewer Notes: Tests knowledge of RIE for local testing.

❌ Common Mistakes:

  • Not using RIE for container image local testing
  • Forgetting RIE is included in AWS base container images
  • Confusing RIE with SAM local (SAM uses Docker, RIE is standalone)

Q218: How do you handle Lambda function recursion?​

Technical Answer: Avoid recursive Lambda invocations (function invokes itself) as it can cause infinite loops and unexpected costs. Use Step Functions or SQS to implement retry/loop logic instead.

Code/Config Example:

# BAD: Recursive invocation
def lambda_handler(event, context):
if event.get("retry"):
boto3.client("lambda").invoke(FunctionName="my-func", Payload=json.dumps(event))

🔍 Interviewer Notes: Tests awareness of recursive invocation risks.

❌ Common Mistakes:

  • Implementing recursive Lambda invocations
  • Not setting concurrency limits to prevent recursive loops
  • Forgetting recursive calls incur invocation costs per iteration

Q219: What are the best practices for Lambda error handling?​

Technical Answer: Use try/catch in function code, configure async retries and destinations, use ReportBatchItemFailures for batch sources, and implement idempotency for retried events. Log errors with context for debugging.

Code/Config Example:

# Python error handling best practices
import logging
logger = logging.getLogger()
logger.setLevel(logging.ERROR)

def lambda_handler(event, context):
try:
process(event)
except Exception as e:
logger.error(f"Processing failed: {str(e)}", exc_info=True)
raise # Let Lambda handle retry/destination

🔍 Interviewer Notes: Tests knowledge of comprehensive error handling.

❌ Common Mistakes:

  • Swallowing exceptions without logging
  • Not configuring async retries/destinations
  • Forgetting to return partial batch failures for batch sources

Q220: How do you monitor Lambda function health?​

Technical Answer: Use CloudWatch metrics (Invocations, Errors, Duration, Throttles), CloudWatch Logs for invocation logs, and set CloudWatch alarms for error rates or throttles. Use Lambda Insights for detailed performance metrics.

Code/Config Example:

# CloudWatch alarm for Lambda errors
ErrorAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
MetricName: Errors
Namespace: AWS/Lambda
Threshold: 10
ComparisonOperator: GreaterThanThreshold

🔍 Interviewer Notes: Tests knowledge of Lambda health monitoring.

❌ Common Mistakes:

  • Not setting CloudWatch alarms for critical metrics
  • Forgetting to monitor throttles and concurrency
  • Not using Lambda Insights for performance visibility

Q221: What is Lambda SnapStart for Java?​

Technical Answer: SnapStart is a Java-only feature that optimizes cold starts by taking a snapshot of the initialized execution environment (after static init) and restoring it for subsequent invocations, reducing cold start times by up to 10x.

Code/Config Example:

# Enable SnapStart in SAM
MyJavaFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: java21
SnapStart:
ApplyOn: PublishedVersions

🔍 Interviewer Notes: Tests knowledge of SnapStart purpose and eligibility.

❌ Common Mistakes:

  • Thinking SnapStart works for non-Java runtimes
  • Not knowing SnapStart only applies to published versions
  • Forgetting to enable SnapStart in function config

Q222: How do you enable SnapStart for a Java Lambda function?​

Technical Answer: Set the SnapStart.ApplyOn property to PublishedVersions (for versions) or None (disabled) in the function configuration. SnapStart only takes effect when publishing new versions, not on $LATEST.

Code/Config Example:

# Enable SnapStart via CLI
aws lambda update-function-configuration \
--function-name my-java-func \
--snap-start ApplyOn=PublishedVersions

🔍 Interviewer Notes: Tests knowledge of SnapStart configuration.

❌ Common Mistakes:

  • Enabling SnapStart on $LATEST (no effect)
  • Not publishing new version after enabling SnapStart
  • Forgetting SnapStart is Java-only

Q223: What are the benefits of SnapStart for Java Lambda?​

Technical Answer: Reduces cold start times from 3-6 seconds to 200-500ms by restoring pre-initialized snapshots instead of running full JVM init. This makes Java viable for latency-sensitive workloads.

Code/Config Example:

# CloudWatch Logs Insights: Cold start comparison
fields @timestamp, @duration
| filter @message like /INIT_START/
| stats avg(@duration) by bin(5m)

🔍 Interviewer Notes: Tests understanding of SnapStart performance benefits.

❌ Common Mistakes:

  • Not knowing SnapStart reduces Java cold starts by 10x
  • Forgetting that init includes static code blocks
  • Thinking SnapStart eliminates all cold starts (still restores snapshot)

Q224: What are the limitations of Lambda SnapStart?​

Technical Answer: Only supports Java 11+ runtimes, does not work with $LATEST, and may have compatibility issues with native code or hard-coded file paths. Snapshots include all state after static initialization.

Code/Config Example:

# Check SnapStart status
aws lambda get-function --function-name my-func --query "Configuration.SnapStart"

🔍 Interviewer Notes: Tests awareness of SnapStart limitations.

❌ Common Mistakes:

  • Using SnapStart with Python/Node.js (unsupported)
  • Not knowing SnapStart requires published versions
  • Forgetting that snapshot includes all static init state

Q225: How do you optimize Java Lambda memory settings?​

Technical Answer: Java requires more memory than interpreted runtimes (minimum 512MB recommended), as JVM heap and metaspace need sufficient memory. Use SnapStart to reduce cold start, and tune JVM flags.

Code/Config Example:

# Java memory tuning
MyJavaFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: java21
MemorySize: 1024
Environment:
Variables:
JAVA_TOOL_OPTIONS: "-XX:+UseContainerSupport -XX:MaxRAMPercentage=75"

🔍 Interviewer Notes: Tests knowledge of Java memory optimization.

❌ Common Mistakes:

  • Using 128MB for Java (too low, causes OOM)
  • Not tuning JVM flags for container environment
  • Forgetting Java needs more memory than Python/Node

Q226: What are best practices for Java Lambda dependency management?​

Technical Answer: Use Maven/Gradle to package dependencies into shaded JAR (Uber JAR), minimize dependency size, and use layers for shared large dependencies. Avoid including unnecessary libraries.

Code/Config Example:

<!-- Maven shade plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
</execution>
</executions>
</plugin>

🔍 Interviewer Notes: Tests knowledge of Java dependency packaging.

❌ Common Mistakes:

  • Not using shaded JAR (causes class conflicts)
  • Including unnecessary dependencies increasing package size
  • Forgetting to use layers for shared Java libs

Q227: How do you handle Java Lambda cold starts without SnapStart?​

Technical Answer: Use Provisioned Concurrency to keep JVM environments warm, minimize static initialization work, and use lighter frameworks (e.g., Micronaut, Quarkus) over Spring Boot.

Code/Config Example:

# Provisioned Concurrency for Java
MyJavaFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: java21
ProvisionedConcurrencyConfig:
ProvisionedConcurrentExecutions: 10

🔍 Interviewer Notes: Tests knowledge of Java cold start mitigation without SnapStart.

❌ Common Mistakes:

  • Using Spring Boot for Lambda (heavy, slow init)
  • Not using Provisioned Concurrency for Java latency-sensitive workloads
  • Forgetting to minimize static init code

Q228: What is the Java Lambda runtime interface client?​

Technical Answer: The runtime interface client is a library that implements the Lambda runtime API for Java, handling communication between the runtime and the function code. It is included in the AWS SDK for Java 2.x.

Code/Config Example:

// Java Lambda handler
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class MyHandler implements RequestHandler<Map<String,String>, String> {
@Override
public String handleRequest(Map<String,String> input, Context context) {
return "Hello " + input.get("name");
}
}

🔍 Interviewer Notes: Tests knowledge of Java runtime client basics.

❌ Common Mistakes:

  • Not including runtime client dependency in JAR
  • Forgetting to implement RequestHandler interface
  • Using old AWS SDK 1.x (not recommended)

Q229: How do you use custom runtimes with Lambda Java?​

Technical Answer: While Java has managed runtimes, you can use custom runtime to run specific Java versions or frameworks by implementing the Lambda Runtime API. Package the runtime and function code in a container image.

Code/Config Example:

# Custom Java runtime (container)
FROM public.ecr.aws/lambda/java:21 as runtime
COPY target/my-func.jar /var/task/
CMD ["com.example.MyHandler::handleRequest"]

🔍 Interviewer Notes: Tests knowledge of custom runtimes for Java.

❌ Common Mistakes:

  • Using custom runtime when managed Java runtime exists
  • Not implementing Runtime API correctly
  • Forgetting to package runtime in container image

Q230: How do you monitor Java Lambda performance?​

Technical Answer: Enable Lambda Insights for JVM metrics (heap usage, GC activity), log JVM stats via SLF4J, and use SnapStart metrics (RestoreDuration) to track cold start improvements.

Code/Config Example:

// Log JVM memory
Runtime runtime = Runtime.getRuntime();
context.getLogger().log("Free memory: " + runtime.freeMemory());

🔍 Interviewer Notes: Tests knowledge of Java Lambda monitoring.

❌ Common Mistakes:

  • Not enabling Lambda Insights for JVM metrics
  • Forgetting to log JVM stats for debugging
  • Not tracking SnapStart RestoreDuration metric

Additional Core Questions​

Q231: What is the Lambda runtime API and when would you use it?​

Technical Answer: The Runtime API lets you build custom runtimes for Lambda. Use it when you need a language not natively supported by AWS or when you need specific runtime behavior customization. The custom runtime handles communication with Lambda via HTTP requests.

Code Example:

# Custom runtime loop
import urllib.request
import json

def runtime_loop():
while True:
# Get event from Lambda
req = urllib.request.Request('http://sandbox.localdomain/2015-03-31/runtime/invocation/next')
with urllib.request.urlopen(req) as response:
event = json.loads(response.read())
context = parse_context(response.headers)

# Process event
result = handler(event, context)

# Send response
invocation_id = response.headers['Lambda-Runtime-Aws-Request-Id']
req = urllib.request.Request(f'http://sandbox.localdomain/2015-03-31/runtime/invocation/{invocation_id}/response')
req.add_header('Content-Type', 'application/json')
urllib.request.urlopen(req, json.dumps(result).encode())

if __name__ == '__main__':
runtime_loop()

🔍 Interviewer Notes: Testing understanding of extensibility and custom runtimes.

❌ Common Mistakes:

  • Building custom runtime when Lambda layer would suffice
  • Not handling errors and error responses properly
  • Missing request timeout handling

Q232: How do you implement Lambda layers for dependencies?​

Technical Answer: Lambda layers package dependencies separately from function code. Each layer is a ZIP file extracted to /opt, allowing code reuse across functions. Python libraries go in /opt/python, Node in /opt/nodejs.

Code Example:

# Create layer structure
mkdir -p layer/python
pip install -r requirements.txt -t layer/python/
zip -r layer.zip layer/

# Reference in function
# serverless.yml
functions:
myFunction:
handler: index.handler
layers:
- arn:aws:lambda:us-east-1:123456789:layer:my-dependencies:1
# Function can now import layer dependencies
import pandas as pd # In layer
import boto3 # In layer

def handler(event, context):
df = pd.DataFrame({'data': [1, 2, 3]})
return df.to_dict()

🔍 Interviewer Notes: Testing dependency management and deployment optimization.

❌ Common Mistakes:

  • Too many layers causing longer cold starts
  • Not testing layer compatibility across functions
  • Missing native libraries for the runtime

Q233: What is Lambda@Edge and how does it differ from regular Lambda?​

Technical Answer: Lambda@Edge runs Lambda functions at CloudFront edge locations, closer to users. It supports Viewer Request/Response and Origin Request/Response triggers. Limitations include smaller deployment packages (1MB), shorter timeouts (5s/30s), and limited runtime support.

Code Example:

// Lambda@Edge viewer request handler
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;

// Add custom header
headers["x-custom-header"] = [{ key: "X-Custom-Header", value: "Hello" }];

// Redirect based on path
if (request.uri.startsWith("/admin")) {
return callback(null, {
status: "302",
statusDescription: "Found",
headers: {
location: [{ key: "Location", value: "https://admin.example.com" }],
},
});
}

callback(null, request);
};

🔍 Interviewer Notes: Testing CDN integration and global compute knowledge.

❌ Common Mistakes:

  • Not considering reduced timeout limits
  • Missing region specification in deployment
  • Not testing viewer vs origin triggers

Q234: How do you handle Lambda event source mapping configuration?​

Technical Answer: Event source mappings connect Lambda to Kinesis, DynamoDB Streams, or SQS. Configuration includes batch size, parallelization factor, starting position, and retry attempts. Proper tuning prevents throttling and optimizes throughput.

Configuration:

# SQS event mapping with batch processing
aws lambda create-event-source-mapping \
--function-name my-function \
--batch-size 10 \
--maximum-batching-window-in-seconds 5 \
--function-response-types ReportBatchItemFailures \
--event-source-arn arn:aws:sqs:us-east-1:123456789:my-queue

# Kinesis with parallelization
aws lambda create-event-source-mapping \
--function-name kinesis-processor \
--event-source-arn arn:aws:kinesis:us-east-1:123456789:stream/my-stream \
--batch-size 500 \
--starting-position LATEST \
--maximum-record-age-in-seconds 604800 \
--bisect-batch-on-function-error \
--maximum-retry-attempts 2

🔍 Interviewer Notes: Testing stream processing and batch optimization.

❌ Common Mistakes:

  • Not setting ReportBatchItemFailures for partial failures
  • Too large batch size causing timeouts
  • Not handling iterator age for stream lag

Q235: What are Lambda reserved concurrency and provisioned concurrency?​

Technical Answer: Reserved concurrency guarantees a maximum concurrent executions limit for a function, protecting other functions. Provisioned concurrency keeps functions initialized and ready to respond immediately, eliminating cold starts.

Code Example:

# Set reserved concurrency (protect from throttling)
import boto3
lambda_client = boto3.client('lambda')
lambda_client.put_function_concurrency(
FunctionName='critical-function',
ReservedConcurrentExecutions=50
)

# Set provisioned concurrency (eliminate cold starts)
lambda_client.put-provisioned-concurrency-config(
FunctionName='api-handler',
Qualifier='prod',
ProvisionedConcurrentExecutions=100
)

# Auto-scaling provisioned concurrency
import boto3
autoscaling = boto3.client('application-autoscaling')

autoscaling.register-scalable-target(
ServiceNamespace='lambda',
ResourceId='function:critical-function:prod',
ScalableDimension='lambda:function:ProvisionedConcurrency',
MinCapacity=10,
MaxCapacity=500
)

🔍 Interviewer Notes: Testing performance optimization and cost management.

❌ Common Mistakes:

  • Setting reserved concurrency too high (wasting capacity)
  • Not combining reserved and provisioned appropriately
  • Forgetting to warm up provisioned instances

Q236: How do you implement idempotency in Lambda with DynamoDB?​

Technical Answer: Idempotency prevents duplicate processing by tracking processed events. Use conditional writes to DynamoDB with event IDs as keys. This ensures exactly-once processing even with retries.

Code Example:

import boto3
from datetime import datetime

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('processed-events')

def lambda_handler(event, context):
results = []

for record in event['Records']:
event_id = record['messageId']

try:
# Conditional write - only succeeds if event_id doesn't exist
table.put_item(
Item={
'event_id': event_id,
'processed_at': datetime.utcnow().isoformat(),
'result': 'success'
},
ConditionExpression='attribute_not_exists(event_id)'
)

# Process the actual business logic
result = process_business_logic(record)
results.append(result)

except dynamodb.meta.client.exceptions.ConditionalCheckFailedException:
# Already processed - skip
print(f"Event {event_id} already processed, skipping")
results.append({'status': 'duplicate', 'event_id': event_id})
except Exception as e:
# Process failed - allow retry
raise e

return {'results': results}

🔍 Interviewer Notes: Testing distributed systems reliability patterns.

❌ Common Mistakes:

  • Not using condition expressions (race conditions)
  • Not cleaning up idempotency records (storage growth)
  • Processing before idempotency check (double-processing on race)

Q237: How do you implement Canary deployments for Lambda?​

Technical Answer: Lambda aliases with weighted routing enable canary deployments. Traffic shifting sends a percentage of invocations to new versions. Linear or exponential traffic shifting can be automated.

Code Example:

# Publish new version
aws lambda publish-version --function-name my-function --description "v2.0"

# Create alias pointing to new version with 5% traffic
aws lambda create-alias \
--function-name my-function \
--name live \
--function-version 22 \
--routing-config '{"AdditionalVersionWeights":{"21":0.95}}'

# Gradually shift traffic using CodeDeploy
aws deploy create-deployment \
--application-name my-lambda-app \
--deployment-group-name my-deployment-group \
--revision revisionType=AppSpecContent,appSpecContent='{"version": 0.0,"Resources":[{"TargetService":{"Type":"AWS::Lambda::Function","Properties":{"Name":"my-function","Alias":"live"}}},{"Hooks":["BeforeAllowTraffic","AfterAllowTraffic"]}]}'

Serverless Framework Example:

# serverless.yml
functions:
api:
handler: handler.main
events:
- http: GET /

resources:
- Outputs:
ApiUrl:
Description: URL of the API endpoint
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/${self:provider.stage}"

🔍 Interviewer Notes: Testing deployment strategies and traffic shifting.

❌ Common Mistakes:

  • Not monitoring during deployment
  • Too aggressive traffic shifting
  • Missing rollback criteria

Q238: How do you debug Lambda with X-Ray and CloudWatch?​

Technical Answer: X-Ray provides distributed tracing showing latency and errors across services. CloudWatch Logs capture function logs with structured data. Together they identify performance bottlenecks and error sources.

Code Example:

import boto3
from aws_xray_sdk.core import xray_recorder, patch_all
import logging

patch_all()

logger = logging.getLogger()
logger.setLevel(logging.INFO)

@xray_recorder.capture('process_order')
def process_order(order_id):
return table.get_item(Key={'id': order_id})

def lambda_handler(event, context):
# Add annotations for filtering
xray_recorder.current_subsegment().put_annotation('user_id', event['user_id'])

# Structured logging
logger.info({
'message': 'Processing started',
'request_id': context.aws_request_id,
'event_type': event.get('type')
})

with xray_recorder.capture('external_call'):
result = external_service.call(event)

logger.info({
'message': 'Processing completed',
'result_count': len(result)
})

return result

🔍 Interviewer Notes: Testing observability and debugging skills.

❌ Common Mistakes:

  • Not sampling production traffic (cost)
  • Missing subsegments for external calls
  • Not using annotations/filters effectively

Q239: How do you implement error handling with DLQ for different sources?​

Technical Answer: Different event sources have different DLQ configurations. SQS/SNS use redrive policies, EventBridge uses retry policies, and Lambda destinations handle async invocation results. Dead letter queues capture failed events for later processing.

Configuration:

# SQS DLQ configuration
Resources:
MyQueue:
Type: AWS::SQS::Queue
Properties:
RedrivePolicy:
deadLetterTargetArn: !GetAtt MyDLQ.Arn
maxReceiveCount: 3

MyDLQ:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600 # 14 days

# Lambda async invocation destinations
MyFunction:
Type: AWS::Lambda::Function
Properties:
DestinationConfig:
OnFailure:
Destination: !GetAtt FailureDLQ.Arn
OnSuccess:
Destination: !GetAtt SuccessQueue.Arn
# Processing DLQ messages
def lambda_handler(event, context):
for record in event['Records']:
try:
message_body = json.loads(record['body'])
process_message(message_body)
except Exception as e:
print(f"Failed to process: {e}")
# Message goes back to DLQ after max retries
raise e

🔍 Interviewer Notes: Testing error handling and reliability patterns.

❌ Common Mistakes:

  • Not setting appropriate maxReceiveCount
  • Not monitoring DLQ sizes
  • Not designing DLQ processing workflows

Q240: How do you optimize Lambda memory and timeout settings?​

Technical Answer: Lambda performance scales with memory allocation (CPU increases proportionally). Test different memory settings to find optimal cost/performance ratio. Timeout prevents runaway executions but shouldn't be too conservative.

Optimization Script:

import boto3
import time
import json

def benchmark_function(function_name, payload, memory_options):
client = boto3.client('lambda')
results = {}

for memory in memory_options:
# Update function memory
client.update_function_configuration(
FunctionName=function_name,
MemorySize=memory
)

time.sleep(10) # Wait for deployment

# Run multiple tests
times = []
for _ in range(5):
start = time.time()
client.invoke(FunctionName=function_name, Payload=json.dumps(payload))
times.append(time.time() - start)

results[memory] = {
'avg_duration': sum(times) / len(times),
'cost_per_invocation': (memory / 1024) * (sum(times) / len(times)) * 0.0000166667
}

return results

🔍 Interviewer Notes: Testing performance tuning methodology.

❌ Common Mistakes:

  • Not testing real workloads
  • Too short timeouts causing premature failures
  • Not considering burst memory needs
ConceptKey Point
Cold StartInitialize outside handler, use provisioned concurrency
ConcurrencyAccount (1000 default), reserved, provisioned
SecurityIAM least privilege, VPC endpoints, encrypted env vars
ScalingAutomatic, but handle throttling
CostMemory × Duration = Cost, Power Tuning helps

Senior / Principal — AWS Lambda Real World Scenarios​

Q241: Lambda cold start — p99 latency spikes on infrequent invocations​

Level: Senior

Scenario: A Lambda function handles user authentication. Most invocations are warm (<100ms). But after 15 minutes of inactivity, the first request takes 8-12 seconds (cold start). Users complain about slow login.

Impact: Poor user experience. High p99 latency. Login abandonment.

Root Cause: Lambda freezes the execution environment after idle time. The next invocation must initialize the runtime, load dependencies, and run init code before handling the request.

Simple explanation: A restaurant chef goes home after the last customer. When a new customer arrives at 3 AM, the chef must come back, preheat the oven, and prep ingredients before cooking.

Technical Answer:

  1. Use Provisioned Concurrency to keep initialized environments ready (eliminates cold starts).
  2. Initialize heavy dependencies (SDK clients, DB connections) outside the handler (in global scope) so they run once per environment, not per invocation.
  3. Use lighter runtime (Python/Node.js) vs Java/.NET for faster cold starts.
  4. Keep deployment package small (minimize dependencies, use layers).
  5. Use Lambda SnapStart (Java) or provisioned concurrency for latency-sensitive paths.

Code/Syntax Justification:

# Global scope - runs once per environment (cold start only)
import boto3
from myapp.db import Database

db_client = Database() # initialized once, reused across invocations
s3_client = boto3.client('s3') # initialized once

def handler(event, context):
# Handler runs on every invocation - keep it light
return db_client.query(event['user_id'])

Workflow Diagram:

First request after idle (cold start): Warm request:
Init runtime + load deps + run handler Skip init, run handler only
| |
v v
8-12 seconds < 100ms
|
v
Fix: Provisioned Concurrency keeps env warm

🔍 Behind the Question: Cold start causes, provisioned concurrency, global scope init, runtime selection.

❌ The Red Flags: Initializing heavy clients inside handler; no provisioned concurrency for latency-sensitive paths; large deployment packages.


Q242: Lambda concurrency limit hit — throttling (429/ThrottlingException)​

Level: Senior

Scenario: A Lambda function processes SQS messages. During peak traffic, invocations spike. AWS account concurrency limit is 1000 (default). Lambda returns ThrottlingException. Messages back up in SQS. DLQ fills up.

Impact: Requests rejected. Messages delayed or lost to DLQ. Partial outage.

Root Cause: Concurrent executions hit the account-level or function-level concurrency limit. No reserved concurrency set for critical functions. No throttling handling.

Simple explanation: A kitchen has 1000 order slots. 1500 orders come in. 500 are rejected. The kitchen can't cook faster than its capacity.

Technical Answer:

  1. Set Reserved Concurrency for critical functions to guarantee capacity.
  2. Set Provisioned Concurrency for latency-sensitive functions.
  3. Handle ThrottlingException with retry + exponential backoff in the caller.
  4. Use SQS as a buffer between producer and Lambda (SQS smooths spikes).
  5. Request concurrency limit increase from AWS if needed.
  6. Monitor Throttles and ConcurrentExecutions CloudWatch metrics.

Code/Syntax Justification:

# Caller with retry on throttling
import boto3
from botocore.config import Config

config = Config(retries={'max_attempts': 3, 'mode': 'adaptive'})
lambda_client = boto3.client('lambda', config=config)

# Or: set reserved concurrency via CloudFormation/terraform
# ReservedConcurrentExecutions: 500

Workflow Diagram:

Traffic spike
|
v
Concurrent executions reach limit (1000)
|
v
Lambda returns ThrottlingException
|
v
Without retry: With retry + backoff:
Request failed Wait 1s, 2s, 4s... then retry
|
v
Success or DLQ after max retries

🔍 Behind the Question: Concurrency limits, reserved concurrency, throttling handling, SQS as buffer.

❌ The Red Flags: No reserved concurrency for critical functions; no retry on throttling; no SQS buffer; not monitoring throttles.


Q243: Lambda + VPC — ENI limits and cold start impact​

Level: Principal

Scenario: A Lambda function needs to access an RDS database in a VPC. It's configured with VPC settings (subnets, security groups). Each invocation creates an ENI (Elastic Network Interface). ENI creation adds 5-10 seconds to cold starts. The function scales poorly.

Impact: Slow cold starts. Poor scaling. ENI exhaustion in the subnet.

Root Cause: Lambda in a VPC requires an ENI per concurrent execution. ENI creation is slow and limited by subnet IP availability. VPC Lambda has higher cold start than non-VPC Lambda.

Simple explanation: To enter the office building (VPC), every employee needs a security badge (ENI). Making badges takes time. If badges run out, nobody can enter.

Technical Answer:

  1. Use VPC only when needed (RDS, ElastiCache, internal services).
  2. Use RDS Proxy or ElastiCache to reduce connection overhead instead of direct DB connections from Lambda.
  3. Use Provisioned Concurrency to pre-create ENIs (avoids per-invocation ENI creation).
  4. Consider API Gateway + Lambda (non-VPC) calling a VPC endpoint or private integration instead.
  5. Use subnet with enough IPs; monitor EnisInUse vs available IPs.

Code/Syntax Justification:

# Lambda in VPC - initialize RDS client outside handler
import os
import psycopg2

# Connection initialized once per environment
db_connection = None

def get_db():
global db_connection
if db_connection is None:
db_connection = psycopg2.connect(
host=os.environ['DB_HOST'],
dbname=os.environ['DB_NAME']
)
return db_connection

def handler(event, context):
conn = get_db()
...

Workflow Diagram:

Non-VPC Lambda: VPC Lambda:
Invoke -> ready in 100ms Invoke -> create ENI -> ready in 5-10s
| |
v v
Fast cold start Slow cold start (ENI creation)
| |
v v
Fix: Provisioned Concurrency pre-warms ENIs

🔍 Behind the Question: VPC Lambda, ENI creation, cold start impact, RDS Proxy, subnet IP limits.

❌ The Red Flags: VPC Lambda for latency-sensitive paths; no provisioned concurrency with VPC; direct DB connections without RDS Proxy; subnet IP exhaustion.


Q244: Lambda environment variables — secrets exposure​

Level: Senior

Scenario: A Lambda function stores database credentials as plain-text environment variables. Anyone with lambda:GetFunctionConfiguration can read them. The credentials are also visible in CloudWatch Logs if accidentally printed.

Impact: Credential exposure. Database breach. Compliance violation.

Root Cause: Secrets stored in plain-text env vars. No encryption at rest. Logging accidentally exposes env vars.

Simple explanation: Writing the safe combination on a sticky note attached to the safe. Anyone who sees the note can open the safe.

Technical Answer:

  1. Use AWS Secrets Manager or Parameter Store (SecureString) for secrets.
  2. Reference secrets via {{resolve:secretsmanager:SecretId:SecretString:key}} in Lambda env vars.
  3. Use IAM least privilege: Lambda execution role needs secretsmanager:GetSecretValue only for specific secrets.
  4. Never log environment variables. Sanitize logs.
  5. Encrypt env vars with KMS (SSE-KMS) at minimum if not using Secrets Manager.

Code/Syntax Justification:

# Lambda env var referencing Secrets Manager
# In CloudFormation/SAM:
# DB_PASSWORD:
# Type: String
# Value: {{resolve:secretsmanager:prod/db:SecretString:password}}

import boto3
import os

secrets = boto3.client('secretsmanager')

def get_db_password():
resp = secrets.get_secret_value(SecretId=os.environ['SECRET_ARN'])
return resp['SecretString']

Workflow Diagram:

Plain-text env var: Secrets Manager reference:
Anyone with GetFunctionConfig Lambda execution role gets secret at runtime
can read credentials |
| |
v v
Credential exposure Encrypted at rest, least-privilege access

🔍 Behind the Question: Secret storage, env var security, Secrets Manager, IAM least privilege, log sanitization.

❌ The Red Flags: Plain-text secrets in env vars; logging env vars; over-privileged execution role; no encryption.


Q245: Lambda deployment — alias-based blue/green deployment​

Level: Principal

Scenario: A Lambda function is updated directly on the $LATEST version. The new code has a bug. All invocations immediately fail. Rollback requires re-deploying old code. Downtime during rollback.

Impact: Immediate outage for all users. No gradual rollout. No way to test with production traffic safely.

Root Cause: No versioning or alias strategy. Code deployed directly to $LATEST which serves all traffic.

Simple explanation: Replacing the engine in a running car. If it breaks, the car stops immediately. No spare engine to swap back quickly.

Technical Answer:

  1. Publish Lambda versions (immutable snapshots) after each deployment.
  2. Use aliases (prod, staging) that point to specific versions.
  3. Configure API Gateway or event source to invoke the alias, not $LATEST.
  4. Use CodeDeploy with Lambda for canary/linear deployments (shift 10% traffic, monitor, then 100%).
  5. Rollback = point alias back to previous version (instant).

Code/Syntax Justification:

# SAM template with versions and aliases
MyFunction:
Type: AWS::Serverless::Function
AutoPublishAlias: live # creates version + alias automatically
DeploymentPreference:
Type: Canary10Percent5Minutes # canary deployment

Workflow Diagram:

Direct $LATEST deployment: Version + Alias deployment:
New code breaks -> all fail Publish version v2
| Point alias 'live' to v2 (10% traffic)
v Monitor errors
Downtime during rollback Errors? -> point alias back to v1 (instant rollback)
|
v
No errors? -> shift 100% to v2

🔍 Behind the Question: Lambda versions, aliases, blue/green, canary deployment, CodeDeploy, instant rollback.

❌ The Red Flags: Deploying to $LATEST directly; no versioning; no aliases; no canary; slow rollback.


Q246: Lambda dead letter queue (DLQ) for async invocations​

Level: Senior

Scenario: A Lambda function is invoked asynchronously (S3 event, EventBridge). The function fails after 3 retries. The event is lost. There's no record of what failed. No way to reprocess.

Impact: Lost events. Silent failures. No reprocessing mechanism.

Root Cause: No DLQ configured for asynchronous invocation. Failed events are discarded after max retries.

Simple explanation: A courier tries to deliver a package 3 times. No one is home. The courier throws the package away instead of returning it to the post office.

Technical Answer:

  1. Configure a DLQ (SQS queue or SNS topic) on the Lambda function for asynchronous invocations.
  2. Failed events (after max retries) are sent to the DLQ.
  3. Monitor DLQ depth; alert on messages.
  4. Reprocess DLQ messages by triggering Lambda from SQS or SNS.
  5. Distinguish between synchronous (API Gateway) and asynchronous (S3, EventBridge) invocation DLQ behavior.

Code/Syntax Justification:

# Lambda with DLQ (SQS)
# In CloudFormation:
# DeadLetterConfig:
# TargetArn: arn:aws:sqs:region:account:my-dlq-queue

import boto3

# Reprocess DLQ messages
sqs = boto3.client('sqs')
def reprocess_dlq():
msgs = sqs.receive_message(QueueUrl=dlq_url, MaxNumberOfMessages=10)
for msg in msgs.get('Messages', []):
lambda_client.invoke(FunctionName='my-function', Payload=msg['Body'])
sqs.delete_message(QueueUrl=dlq_url, ReceiptHandle=msg['ReceiptHandle'])

Workflow Diagram:

Async invocation fails after max retries
|
v
Without DLQ: With DLQ:
Event discarded Event sent to SQS DLQ
| |
v v
Silent failure DLQ depth increases
|
v
Alert -> reprocess from DLQ

🔍 Behind the Question: Async invocation DLQ, failed event handling, reprocessing, monitoring.

❌ The Red Flags: No DLQ for async invocations; not monitoring DLQ; not reprocessing DLQ messages; confusing sync vs async DLQ behavior.


Q247: Lambda function URL vs API Gateway — when to use each​

Level: Senior

Scenario: A team exposes a Lambda via API Gateway REST API. They only need a simple webhook endpoint. API Gateway costs $3.50 per million requests plus data transfer. Function URL costs $0.20 per million requests. They're overpaying 17x.

Impact: Unnecessary API costs. Over-engineered architecture.

Root Cause: Using API Gateway for simple use cases that Function URL handles. Not evaluating cost/feature trade-offs.

Simple explanation: Using a 5-star restaurant catering service to deliver a sandwich. Function URL is the food truck — cheaper, simpler, does the job.

Technical Answer:

  1. Use Lambda Function URL for simple webhooks, internal services, cost-sensitive endpoints (no auth, basic CORS, no request validation).
  2. Use API Gateway when you need: auth (Cognito/IAM), request validation, API keys, usage plans, throttling, WebSocket, private endpoints, detailed metrics/logging, stage management.
  3. Function URL supports IAM auth and CORS natively but lacks advanced API management features.
  4. Consider cost: Function URL ~$0.20/million vs API Gateway ~$3.50/million (17x difference).

Code/Syntax Justification:

# Lambda Function URL - simple webhook
def handler(event, context):
# event comes directly from Function URL invocation
body = json.loads(event.get('body', '{}'))
return {'statusCode': 200, 'body': json.dumps({'ok': True})}

# Function URL config:
# AuthType: AWS_IAM or NONE
# Cors: AllowOrigins, AllowMethods, AllowHeaders

Workflow Diagram:

Simple webhook: Complex API:
Function URL API Gateway
| |
v v
Low cost ($0.20/million) Higher cost ($3.50/million)
Basic CORS + IAM auth Auth, API keys, validation, throttling
No API management Full API management

🔍 Behind the Question: Function URL vs API Gateway, cost comparison, feature trade-offs, webhook patterns.

❌ The Red Flags: API Gateway for simple webhooks; not evaluating cost; using API Gateway features not needed; Function URL for complex API management needs.


Q248: Lambda provisioned concurrency — cost vs latency trade-off​

Level: Principal

Scenario: A team enables Provisioned Concurrency on all Lambda functions to eliminate cold starts. The monthly bill doubles. Most functions are infrequently invoked and don't need low latency.

Impact: Unnecessary cost. Over-provisioning. Budget overrun.

Root Cause: Provisioned concurrency is charged per hour per concurrent execution, regardless of invocation count. Applied indiscriminately to all functions.

Simple explanation: Keeping 10 chefs in the kitchen 24/7 even though only 2 customers visit per day. You pay for idle chefs.

Technical Answer:

  1. Use Provisioned Concurrency only for latency-sensitive, user-facing functions (API, auth, webhooks).
  2. Use standard Lambda (cold start acceptable) for background jobs, batch processing, infrequent tasks.
  3. Use Auto Scaling for provisioned concurrency (schedule-based scaling).
  4. Monitor ProvisionedConcurrencyInvocations vs ProvisionedConcurrentExecutions to right-size.
  5. Consider Lambda SnapStart for Java/Python functions where cold start matters but cost is a concern.

Code/Syntax Justification:

# Provisioned concurrency configuration (CloudFormation/SAM)
# ProvisionedConcurrencyConfiguration:
# ProvisionedConcurrentExecutions: 5

# Right-size based on metrics:
# Watch: ProvisionedConcurrentExecutions (should be > 0 but < provisioned)
# If always 0: over-provisioned -> reduce
# If always at limit: under-provisioned -> increase

Workflow Diagram:

All functions provisioned: Right-sized provisioning:
10 functions x 5 concurrent x 24h Auth function: 5 concurrent (user-facing)
| Batch function: 0 (cold start OK)
v |
High cost ($$$) Data processing: 0 (cold start OK)
| |
v v
Optimize: provision only latency-sensitive Balanced cost and latency
functions

🔍 Behind the Question: Provisioned concurrency cost model, right-sizing, latency vs cost trade-off, SnapStart.

❌ The Red Flags: Provisioned concurrency on all functions; not monitoring utilization; not distinguishing latency-sensitive vs background functions.


Senior / Principal — AWS Lambda Real World Scenarios (Continued)​

Q249: Lambda cold start — SnapStart for Java/Python​

Level: Senior

Scenario: A Java Lambda function has cold starts of 8-12 seconds. Users experience slow first response. The team considers switching languages but wants to keep Java.

Impact: High p99 latency. Poor user experience. Cold start penalty on every scale-up.

Root Cause: Java's slow JVM initialization and class loading on cold start. No snapshot restoration.

Simple explanation: You have to warm up the oven every time you want to cook. SnapStart bakes the cake once and keeps it warm.

Technical Answer:

  1. Enable Lambda SnapStart for Java functions — initializes once, creates a snapshot, restores from snapshot on scale-in.
  2. SnapStart restores memory and CPU state in sub-second time (vs seconds for cold init).
  3. Available for Java 11+ and Python 3.12+ (limited regions/runtime support).
  4. Not suitable for functions with mutable state or time-sensitive initialization at init time.
  5. Monitor PostRuntimeDuration and SnapStart metrics.

Code/Syntax Justification:

# Enable SnapStart (via CloudFormation/SAM)
# SnapStart:
# ApplyOn: PublishedVersions

# Or via AWS CLI:
# aws lambda update-function-configuration --function-name my-java-fn \
# --snap-start ApplyOn=PublishedVersions

Workflow Diagram:

Java cold start (no SnapStart): Java cold start (with SnapStart):
Init JVM + load classes Restore from snapshot
| |
v v
8-12 seconds < 1 second
| |
v v
High p99 latency Low p99 latency

🔍 Behind the Question: SnapStart, JVM initialization, cold start optimization, runtime support.

❌ The Red Flags: SnapStart on functions with mutable init state; not monitoring SnapStart metrics; using SnapStart where not supported.


Q250: Lambda + EventBridge — event-driven architecture​

Level: Senior

Scenario: A team uses Lambda with direct S3 bucket notifications. They want to decouple event producers from consumers and add retry/routing flexibility.

Impact: Tight coupling. Hard to add new consumers. No built-in retry/Dead Letter Queue for failed events.

Root Cause: Direct invoke coupling between event source and Lambda. No event bus abstraction.

Simple explanation: You call each person directly to tell them news. If they're busy, you lose the message. An event bus lets you post once and interested parties listen.

Technical Answer:

  1. Use Amazon EventBridge as an event bus between producers and Lambda consumers.
  2. Producers put events to EventBridge; consumers (Lambda) subscribe via event rules.
  3. Add EventBridge DLQ for failed events after max retries.
  4. Enable content-based filtering so consumers only get relevant events.
  5. Decouples producers from consumers — add new Lambda consumers without changing producers.

Code/Syntax Justification:

# Producer: put event to EventBridge
events.put_events(
Entries=[{
'Source': 'myapp.order',
'DetailType': 'OrderPlaced',
'Detail': json.dumps(order),
'EventBusName': 'default'
}]
)

# Consumer: Lambda triggered by EventBridge rule
def handler(event, context):
order = event['detail']
process_order(order)

Workflow Diagram:

Direct S3 -> Lambda: EventBridge bus:
S3 -> Lambda (tightly coupled) Producer -> EventBridge -> Lambda consumers
| |
v v
Hard to add consumers Add consumer without changing producer
| |
v v
No retry/DLQ for failed events EventBridge DLQ for failed events

🔍 Behind the Question: EventBridge, event-driven architecture, decoupling, content filtering, DLQ.

❌ The Red Flags: Direct S3/Lambda coupling for complex workflows; no event bus; no DLQ.


Q251: Lambda + Step Functions — orchestration vs chaining​

Level: Senior

Scenario: A team chains Lambda functions directly (A invokes B invokes C). If B fails, the whole chain breaks. No retry logic. No visibility into chain state.

Impact: Fragile workflows. No retry. No state visibility. Hard to debug.

Root Cause: Direct Lambda chaining without orchestration. No built-in retry/state management.

Simple explanation: You pass a baton directly runner to runner. If one drops it, the race ends. Step Functions is like a race official tracking each handoff.

Technical Answer:

  1. Use AWS Step Functions for workflow orchestration (state machine).
  2. Step Functions manages state, retries, error handling, and visualization.
  3. Lambda functions are tasks within the state machine.
  4. Built-in retry policies, catch blocks, and wait states.
  5. Visual workflow execution history for debugging.

Code/Syntax Justification:

// Step Functions state machine
{
"Comment": "Order processing workflow",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:validate-order",
"Next": "ProcessPayment",
"Retry": [{ "ErrorEquals": ["States.TaskFailed"], "MaxAttempts": 3 }]
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:function:process-payment",
"Next": "SendNotification",
"Catch": [{ "ErrorEquals": ["States.All"], "Next": "HandleFailure" }]
}
}
}

Workflow Diagram:

Lambda chaining: Step Functions:
A -> B -> C (direct) State machine:
| |
v v
B fails -> whole chain breaks B fails -> retry 3x -> catch -> HandleFailure
| |
v v
No visibility Full execution history + visualization

🔍 Behind the Question: Step Functions, orchestration vs chaining, retry/catch, state management, execution history.

❌ The Red Flags: Direct Lambda chaining for complex workflows; no retry logic; no visibility into state.


Q252: Lambda function URL vs API Gateway​

Level: Principal

Scenario: A team exposes a Lambda via API Gateway REST API ($3.50/million requests). They only need a simple webhook. Function URL costs $0.20/million. They're overpaying 17x.

Impact: Unnecessary API costs. Over-engineered for simple use case.

Root Cause: Using API Gateway for simple webhooks that Function URL handles.

Simple explanation: Using a 5-star restaurant to deliver a sandwich. Function URL is the food truck — cheaper, simpler.

Technical Answer:

  1. Use Lambda Function URL for simple webhooks, internal services, cost-sensitive endpoints.
  2. Use API Gateway when you need: auth (Cognito/IAM), request validation, API keys, usage plans, throttling, WebSocket, private endpoints.
  3. Function URL supports IAM auth and CORS natively but lacks advanced API management.
  4. Cost: Function URL ~$0.20/million vs API Gateway REST ~$3.50/million.

Code/Syntax Justification:

# Lambda Function URL handler
def handler(event, context):
body = json.loads(event.get('body', '{}'))
return {'statusCode': 200, 'body': json.dumps({'ok': True})}

# Function URL config: AuthType (AWS_IAM or NONE), CORS settings

Workflow Diagram:

API Gateway: Function URL:
$3.50/million requests $0.20/million requests
| |
v v
Full API management (auth, keys, Simple webhook
throttling, validation) (IAM auth, CORS natively)

🔍 Behind the Question: Function URL vs API Gateway, cost comparison, feature trade-offs.

❌ The Red Flags: API Gateway for simple webhooks; not evaluating cost; Function URL for complex API management needs.


Q253: Lambda environment variables — secrets management​

Level: Senior

Scenario: A team stores database credentials as plain-text environment variables in Lambda. Anyone with Lambda read access can see them. Credentials are also in CloudWatch logs if logged.

Impact: Credential exposure. Security violation. Compliance issue.

Root Cause: Secrets in plain-text env vars. No encryption at rest beyond default.

Simple explanation: Writing the safe combination on a sticky note on the safe. Anyone who sees it can open the safe.

Technical Answer:

  1. Use AWS Secrets Manager or Systems Manager Parameter Store (SecureString) for secrets.
  2. Reference secrets via {{resolve:secretsmanager:...}} in Lambda env vars.
  3. Use IAM least privilege — Lambda execution role only needs access to specific secrets.
  4. Never log environment variables. Sanitize logs.
  5. Use encryption (KMS) for env vars at minimum if not using Secrets Manager.

Code/Syntax Justification:

# Lambda env var referencing Secrets Manager (CloudFormation)
# DB_PASSWORD:
# Type: String
# Value: {{resolve:secretsmanager:prod/db:SecretString:password}}

import boto3
secrets = boto3.client('secretsmanager')
def get_password():
resp = secrets.get_secret_value(SecretId=os.environ['SECRET_ARN'])
return resp['SecretString']

Workflow Diagram:

Plain-text env var: Secrets Manager:
Anyone with Lambda read access Encrypted at rest, least-privilege access
can see credentials Lambda execution role gets secret at runtime

🔍 Behind the Question: Secrets management, env var security, IAM least privilege, KMS encryption.

❌ The Red Flags: Plain-text secrets in env vars; logging env vars; over-privileged execution role.


Q254(b): Lambda VPC — ENI and cold start​

Level: Senior

Scenario: A Lambda function needs to access an RDS database in a VPC. It's configured with VPC subnets and security groups. Each invocation creates an ENI. Cold starts increase (ENI creation time).

Impact: Slow cold starts. ENI limits. Scaling constrained by ENI availability.

Root Cause: Lambda in VPC requires ENI per concurrent execution. ENI creation adds latency. Subnet IP limits constrain scale.

Simple explanation: You need a badge to enter the building. Making badges takes time. If badges run out, nobody can enter.

Technical Answer:

  1. Use VPC only when needed (RDS, ElastiCache, internal services).
  2. Use RDS Proxy or ElastiCache to reduce connection overhead instead of direct DB connections.
  3. Use Provisioned Concurrency to pre-warm ENIs (avoids per-invocation ENI creation).
  4. Consider API Gateway + Lambda (non-VPC) calling via VPC endpoint or private integration.
  5. Monitor ENI limits and subnet IP availability.

Code/Syntax Justification:

# VPC config in Lambda (CloudFormation)
# VpcConfig:
# SubnetIds: [subnet-1, subnet-2]
# SecurityGroupIds: [sg-1]

Workflow Diagram:

Lambda in VPC: Lambda non-VPC:
Invoke -> create ENI -> ready Invoke -> ready (no ENI)
| |
v v
5-10s cold start <1s cold start
ENI limit constrains scale No ENI limit

🔍 Behind the Question: VPC Lambda, ENI creation, RDS Proxy, Provisioned Concurrency, subnet limits.

❌ The Red Flags: VPC Lambda for latency-sensitive paths; no Provisioned Concurrency; direct DB connections without RDS Proxy.


Q255: Lambda dead letter queue (DLQ) for async invocations​

Level: Senior

Scenario: A Lambda function is invoked asynchronously (S3 event, EventBridge). The function fails after retries. The event is lost. No record of what failed.

Impact: Lost events. Silent failures. No reprocessing mechanism.

Root Cause: No DLQ configured for asynchronous invocation. Failed events discarded after max retries.

Simple explanation: A courier tries to deliver 3 times. No one home. Courier throws package away. No way to retry later.

Technical Answer:

  1. Configure DLQ (SQS queue or SNS topic) for async invocation.
  2. Failed events sent to DLQ after max retries (default 2 attempts, max 6).
  3. Monitor DLQ depth; alert on messages.
  4. Reprocess DLQ messages via Lambda or manual replay.
  5. Distinguish sync (API Gateway) vs async (S3, EventBridge) DLQ behavior.

Code/Syntax Justification:

# Lambda DLQ config (CloudFormation)
# DeadLetterConfig:
# TargetArn: arn:aws:sqs:...:my-dlq-queue

# Reprocess DLQ
sqs = boto3.client('sqs')
msgs = sqs.receive_message(QueueUrl=dlq_url)
for msg in msgs['Messages']:
lambda_client.invoke(FunctionName='my-fn', Payload=msg['Body'])
sqs.delete_message(QueueUrl=dlq_url, ReceiptHandle=msg['ReceiptHandle'])

Workflow Diagram:

Async invocation fails after Async invocation fails after DLQ:
retries -> event discarded retries -> event sent to DLQ
| |
v v
Silent failure DLQ depth increases -> alert
| |
v v
Data loss Reprocess DLQ messages

🔍 Behind the Question: Async invocation DLQ, failed event handling, reprocessing, monitoring.

❌ The Red Flags: No DLQ for async invocations; not monitoring DLQ; not reprocessing DLQ messages.


Q256: Lambda concurrency limits — reserved vs provisioned​

Level: Senior

Scenario: A Lambda function hits account concurrency limit (1000 default). Other functions in the account can't scale. Throttling (429) errors.

Impact: Cross-function interference. Throttling. Service degradation.

Root Cause: No Reserved Concurrency set. All functions share the unreserved account concurrency pool.

Simple explanation: 1000 parking spots shared by all employees. One team takes all spots. Others can't park.

Technical Answer:

  1. Set Reserved Concurrency for critical functions (guarantees capacity).
  2. Set Provisioned Concurrency for latency-sensitive functions (pre-warms).
  3. Account concurrency limit can be increased via AWS support.
  4. Monitor Throttles and ConcurrentExecutions CloudWatch metrics.
  5. Use SQS as buffer between event source and Lambda to smooth spikes.

Code/Syntax Justification:

# Set reserved concurrency
lambda_client.put_function_concurrency(
FunctionName='my-fn',
ReservedConcurrentExecutions=100
)

Workflow Diagram:

No reserved concurrency: Reserved concurrency:
All functions share pool Function A: 100 reserved
| |
v v
Function B throttles Function A Function A always has 100 concurrent
| |
v v
Cross-function interference Isolation

🔍 Behind the Question: Reserved concurrency, provisioned concurrency, account limits, throttling.

❌ The Red Flags: No reserved concurrency for critical functions; not monitoring throttles; account limit not increased.


Q257: Lambda packaging — container image vs ZIP​

Level: Senior

Scenario: A team packages Lambda as ZIP with 250MB of dependencies. Deployment is slow. Cold start is high due to large package. They need ML libraries >250MB.

Impact: Slow deployments. High cold start. Package size limit hit (250MB ZIP, 10GB container).

Root Cause: ZIP deployment package limited to 250MB (uncompressed). Large ML/ML libraries exceed this.

Simple explanation: You try to fit a large suitcase in an overhead bin. It doesn't fit. You need checked baggage (container image).

Technical Answer:

  1. Use Lambda container image packaging for packages >250MB (up to 10GB).
  2. Use ZIP for smaller packages (<250MB) — faster cold start, simpler.
  3. Container images stored in ECR. ZIP stored directly in Lambda.
  4. Multi-stage Docker builds to minimize image size.
  5. Use Lambda layers for shared dependencies across functions.

Code/Syntax Justification:

# Container image Lambda (Dockerfile)
FROM public.ecr.aws/lambda/python:3.12
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY app.py .
CMD ["app.lambda_handler"]

# Deploy via ECR + Lambda create-function with PackageType=Image

Workflow Diagram:

ZIP package: Container image:
< 250MB Up to 10GB
| |
v v
Fast cold start Slower cold start (larger image)
Simple deploy ECR push + Lambda update

🔍 Behind the Question: Package type, container image vs ZIP, size limits, ECR, Lambda layers.

❌ The Red Flags: ZIP >250MB; container image for small functions (unnecessary complexity); no multi-stage builds.


Q258: Lambda layers — shared dependencies​

Level: Senior

Scenario: 50 Lambda functions each include the same 50MB of common dependencies (pandas, numpy, requests). Each deployment uploads 50MB. Storage and deployment time wasted.

Impact: Redundant storage. Slow deployments. Inconsistent dependency versions.

Root Cause: Dependencies packaged in each function individually. No sharing.

Simple explanation: 50 apartments each buy the same tool. They should share one tool shed.

Technical Answer:

  1. Use Lambda Layers for shared dependencies (runtime, libraries, custom runtimes).
  2. Layer contents extracted to /opt in the execution environment.
  3. Up to 5 layers per function. Layer size counts toward deployment package limit.
  4. Update layer once — all functions using it get the update.
  5. Use AWS-provided layers (Powertools, etc.) or custom layers.

Code/Syntax Justification:

# Lambda function using layers
lambda_client.create_function(
FunctionName='my-fn',
Layers=[
'arn:aws:lambda:...:layer:powertools-python:1',
'arn:aws:lambda:...:layer:pandas-numpy:3'
]
)

Workflow Diagram:

Each function bundles deps: Shared layers:
50 x 50MB = 2.5GB total 1 x 50MB layer shared
| |
v v
Slow deployments, inconsistency Fast deployments, consistency

🔍 Behind the Question: Lambda layers, shared dependencies, /opt path, layer limits, AWS Powertools.

❌ The Red Flags: Bundling shared deps in every function; >5 layers per function; no version consistency.


Q259: Lambda power tuning — memory vs CPU​

Level: Senior

Scenario: A Lambda function is CPU-bound (image processing). The team set 128MB memory (default). CPU is proportionally low. Processing takes 30 seconds. Cost is high due to duration.

Impact: Slow processing. High cost (duration-based). Poor throughput.

Root Cause: Lambda allocates CPU linearly with memory. 128MB = low CPU. More memory = more CPU = faster processing = lower total cost despite higher per-MB rate.

Simple explanation: You have a small engine. It's slow. Bigger engine = faster = less total fuel even if it burns more per minute.

Technical Answer:

  1. Lambda CPU is proportional to memory. More memory = more CPU.
  2. Use AWS Lambda Power Tuning tool to find optimal memory for cost/duration.
  3. For CPU-bound workloads, more memory often reduces total cost (faster = less duration).
  4. For I/O-bound workloads, less memory may suffice.
  5. Monitor Duration and Cost across memory configurations.

Code/Syntax Justification:

# Lambda memory config (CloudFormation)
# MemorySize: 1024 # MB, affects CPU proportionally

Workflow Diagram:

128MB memory: 1024MB memory:
Low CPU High CPU
| |
v v
30 seconds duration 5 seconds duration
| |
v v
High total cost (long duration) Lower total cost (short duration)

🔍 Behind the Question: Power tuning, memory-CPU relationship, cost optimization, duration-based billing.

❌ The Red Flags: Default 128MB for CPU-bound workloads; not power tuning; assuming less memory = lower cost.


Q260: Lambda function versioning and aliases​

Level: Principal

Scenario: A team deploys directly to $LATEST. A bad deploy breaks all invocations immediately. No way to roll back quickly. Can't test with production traffic safely.

Impact: Immediate outage. No gradual rollout. No safe deploy process.

Root Cause: No versioning or alias strategy. Code deployed directly to $LATEST which serves all traffic.

Simple explanation: Replacing the engine in a running car. If it breaks, the car stops immediately. No spare engine.

Technical Answer:

  1. Publish Lambda versions (immutable snapshots) after each deployment.
  2. Use aliases (prod, staging) pointing to specific versions.
  3. Configure API Gateway or event source to invoke alias, not $LATEST.
  4. Use CodeDeploy with Lambda for canary/linear deployments (shift 10%, monitor, then 100%).
  5. Rollback = point alias back to previous version (instant).

Code/Syntax Justification:

# SAM with AutoPublishAlias
MyFunction:
Type: AWS::Serverless::Function
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent5Minutes

Workflow Diagram:

$LATEST deploy: Version + Alias deploy:
New code breaks -> all fail Publish version v2
| |
v v
Outage Point alias 'live' to v2 (10% traffic)
| |
v v
Slow rollback Errors? -> point alias to v1 (instant rollback)

🔍 Behind the Question: Lambda versions, aliases, blue/green, canary, CodeDeploy, instant rollback.

❌ The Red Flags: Deploying to $LATEST directly; no versioning; no aliases; no canary deployment.


Q261: Lambda async invocation — retry and backoff​

Level: Senior

Scenario: A Lambda function invoked asynchronously fails. Lambda retries automatically (2 attempts by default). The function is not idempotent. Side effects occur twice (double charge, duplicate email).

Impact: Duplicate processing. Side effects. Data inconsistency.

Root Cause: Async invocation retries on failure. Function not idempotent. No idempotency key.

Simple explanation: You pay at a cashier. Receipt printer jams. You pay again. Cashier charges twice because they don't know you already paid.

Technical Answer:

  1. Make Lambda functions idempotent (same input = same result, no duplicate side effects).
  2. Use idempotency keys (DynamoDB/Redis) to detect and skip duplicate processing.
  3. Configure max retry attempts (1-2 for async).
  4. Use DLQ for events that exhaust retries.
  5. Understand async invocation retry behavior (2 attempts, then DLQ or discard).

Code/Syntax Justification:

# Idempotent Lambda handler
import redis
r = redis.Redis()

def handler(event, context):
idempotency_key = event.get('idempotency_key')
if r.get(f'processed:{idempotency_key}'):
return {'status': 'already_processed'}
result = do_work(event)
r.setex(f'processed:{idempotency_key}', 86400, '1')
return result

Workflow Diagram:

Non-idempotent async: Idempotent async:
Invoke -> process -> side effect Invoke -> check idempotency key
| |
v v
Fail -> retry -> side effect again Already processed? -> skip
| |
v v
Duplicate side effect Single side effect

🔍 Behind the Question: Async invocation retry, idempotency, idempotency keys, DLQ, side effects.

❌ The Red Flags: Non-idempotent async functions; no idempotency key; not understanding retry behavior.


Q262(b): Lambda response streaming​

Level: Senior

Scenario: A Lambda function generates a large PDF report (10MB). The client waits for the entire response before receiving anything. Timeout at 29 seconds (Lambda response limit). Client sees nothing until complete.

Impact: High latency. Timeout risk. Poor user experience.

Root Cause: Lambda response buffering — entire response must be ready before sending. No streaming.

Simple explanation: You wait for the whole meal to be cooked before tasting anything. Streaming brings appetizers first.

Technical Answer:

  1. Use Lambda response streaming (HTTP API / Function URL with streaming).
  2. Stream response chunks as they're generated.
  3. Reduces time-to-first-byte. Avoids 6MB response payload limit for buffered responses.
  4. Use for large responses, SSE, or progressive rendering.
  5. Client must handle streaming (fetch with ReadableStream).

Code/Syntax Justification:

# Response streaming (Python)
def handler(event, context):
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/pdf'},
'body': generate_pdf_stream(), # generator/stream
'isBase64Encoded': False
}

Workflow Diagram:

Buffered response: Streaming response:
Generate full 10MB PDF Stream chunks as generated
| |
v v
Send entire response Client receives chunks immediately
| |
v v
Client waits (timeout risk) Time-to-first-byte < 1s

🔍 Behind the Question: Response streaming, HTTP API, time-to-first-byte, payload limits.

❌ The Red Flags: Buffered responses for large payloads; no streaming; hitting 6MB response limit.


Q263: Lambda + S3 event notification — infinite loop​

Level: Principal

Scenario: A Lambda function is triggered by S3 s3:ObjectCreated:* events. The function writes output to the same S3 bucket. Each output write triggers another invocation. Infinite loop. Cost explosion.

Impact: Infinite invocation loop. Cost explosion. Bucket full of output objects.

Root Cause: Lambda writing to the same bucket that triggers it. No event filtering or prefix separation.

Simple explanation: You ring a bell every time you enter a room. Entering the room rings the bell. You enter again because of the bell. Infinite loop.

Technical Answer:

  1. Write output to a different S3 bucket or different prefix than the trigger.
  2. Use S3 event notification filters (prefix/suffix) to limit scope.
  3. Check object metadata/tags to skip already-processed objects.
  4. Use EventBridge with rules for more control.
  5. Monitor invocation count and cost alerts.

Code/Syntax Justification:

# Skip already-processed objects
def handler(event, context):
for record in event['Records']:
key = record['s3']['object']['key']
if key.startswith('processed/'):
return # Skip already processed
# Process and write to different prefix
output_key = f'processed/{key}'
s3.copy_object(Bucket=bucket, CopySource=f'{bucket}/{key}', Key=output_key)

Workflow Diagram:

Infinite loop: No loop (different prefix):
Upload -> trigger Lambda Upload to /uploads/ -> trigger Lambda
| |
v v
Lambda writes to same bucket Lambda writes to /processed/
| |
v v
New object -> trigger again No trigger (different prefix)
Infinite loop Finite processing

🔍 Behind the Question: S3 event notifications, infinite loops, prefix filtering, idempotency.

❌ The Red Flags: Writing to same bucket/prefix that triggers; no prefix filtering; no cost alerts.


Q264: Lambda + SQS batch — partial batch failure​

Level: Senior

Scenario: A Lambda function is triggered by SQS with a batch of 10 messages. The function processes 9 successfully but fails on message 10. Lambda returns the whole batch. All 10 messages become visible again. Messages 1-9 are reprocessed (duplicate work).

Impact: Duplicate processing. Increased invocations. Higher cost. Side effects from reprocessing.

Root Cause: Lambda SQS trigger treats batch as atomic. No partial failure reporting.

Simple explanation: You grade 10 exams. The last one is unreadable. You throw away all 10 and make students retake all of them.

Technical Answer:

  1. Use batchItemFailures in response to report only failed message IDs.
  2. Process messages individually within the handler; track successes/failures.
  3. SQS only re-queues failed messages. Successful messages not reprocessed.
  4. Make function idempotent (reprocessing safe).
  5. Reduce batch size if partial failures are frequent.

Code/Syntax Justification:

def handler(event, context):
batch_item_failures = []
for record in event['Records']:
try:
process_message(record['body'])
except Exception:
batch_item_failures.append({'itemIdentifier': record['messageId']})
return {'batchItemFailures': batch_item_failures}

Workflow Diagram:

No partial failure reporting: With batchItemFailures:
All 10 returned to queue Only message 10 returned
| |
v v
Messages 1-9 reprocessed Messages 1-9 not reprocessed
Duplicate work Message 10 retried

🔍 Behind the Question: SQS batch, partial failure, batchItemFailures, idempotency.

❌ The Red Flags: Returning entire batch on single failure; not using batchItemFailures; non-idempotent function.


Q265: Lambda cost optimization — duration, memory, requests​

Level: Principal

Scenario: A team's Lambda bill is high. They don't know which function or configuration drives cost. They haven't analyzed duration vs memory trade-offs.

Impact: High operational cost. No cost attribution. No optimization target.

Root Cause: No cost analysis. Duration-based billing not optimized. Memory over-provisioned.

Simple explanation: You pay for electricity but don't know which appliance uses most. You can't reduce the bill.

Technical Answer:

  1. Use AWS Cost Explorer to attribute Lambda costs by function.
  2. Analyze Duration × Memory allocation = cost. Over-provisioned memory = wasted cost.
  3. Use Lambda Power Tuning to find optimal memory for cost/duration balance.
  4. Reduce duration (faster execution = lower cost).
  5. Use Graviton2 (arm64) for up to 34% better price-performance.

Code/Syntax Justification:

# Cost = Duration (GB-seconds) × Memory (GB) × Price per GB-second
# 1024MB = 1GB. 1 second = 1 GB-second.
# Optimize: reduce duration OR reduce memory (if CPU allows)

Workflow Diagram:

High cost: Cost optimization:
Memory over-provisioned Right-size memory (Power Tuning)
| |
v v
Long duration Reduce duration (faster code)
| |
v v
High cost Lower cost

🔍 Behind the Question: Cost optimization, duration-based billing, memory-CPU trade-off, Graviton2, Cost Explorer.

❌ The Red Flags: Over-provisioned memory; no cost analysis; not using Graviton2; not power tuning.


Senior / Principal — AWS Lambda Real World Scenarios (Continued)​

Q266: Lambda execution role — least privilege​

Level: Senior

Scenario: A Lambda function's execution role has AdministratorAccess. The function only needs to read from one S3 bucket and write to one DynamoDB table. Over-privileged role is a security risk.

Impact: Security risk. If compromised, attacker has full AWS access. Compliance violation.

Root Cause: Using a broad managed policy instead of least-privilege custom policy.

Simple explanation: Giving an employee the master key to the entire building when they only need one room.

Technical Answer:

  1. Use IAM least privilege — only permissions the function actually needs.
  2. Create a custom IAM policy with specific resources (bucket ARN, table ARN).
  3. Use lambda:GetFunction only if needed; avoid * resource where possible.
  4. Review execution role permissions in code review.
  5. Use IAM Access Analyzer to find unused permissions.

Code/Syntax Justification:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Effect": "Allow",
"Action": ["dynamodb:PutItem"],
"Resource": "arn:aws:dynamodb:...:table/my-table"
}
]
}

Workflow Diagram:

Over-privileged role: Least-privilege role:
AdministratorAccess s3:GetObject on specific bucket
| |
v v
Compromise = full AWS access Compromise = limited to specific resources

🔍 Behind the Question: IAM least privilege, execution role, IAM Access Analyzer, resource-specific permissions.

❌ The Red Flags: AdministratorAccess on execution role; * resource; no permission review.


Q267: Lambda timeout configuration​

Level: Senior

Scenario: A Lambda function has default 3-second timeout. A long-running operation (API call to slow downstream) takes 10 seconds. The function times out. Partial work is lost.

Impact: Function failures. Partial work. Retries cause duplicate processing.

Root Cause: Timeout too short for the operation. No handling of partial completion on timeout.

Simple explanation: You give a chef 3 minutes to cook a 10-minute dish. The chef is stopped mid-way. Meal incomplete.

Technical Answer:

  1. Set timeout based on maximum expected execution time (max 15 minutes).
  2. For operations >15 minutes, use Step Functions or EC2/Fargate instead.
  3. Handle partial completion — check if work was done before timeout.
  4. Use async invocation with DLQ for long operations.
  5. Monitor Duration and Timeout CloudWatch metrics.

Code/Syntax Justification:

# Lambda timeout config (CloudFormation)
# Timeout: 900 # 15 minutes max

Workflow Diagram:

3-second timeout: 30-second timeout:
Operation takes 10 seconds Operation takes 10 seconds
| |
v v
Timeout at 3s -> partial work Completes within timeout
| |
v v
Retry -> duplicate work Successful completion

🔍 Behind the Question: Timeout configuration, max 15 minutes, partial completion handling, async vs sync.

❌ The Red Flags: Default 3-second timeout for long operations; no partial completion handling; using Lambda for >15 min workloads.


Q268: Lambda + RDS — connection management​

Level: Senior

Scenario: A Lambda function connects to RDS on each invocation. At high concurrency (1000 concurrent), 1000 database connections are created. RDS connection limit exhausted. Database errors.

Impact: Database connection exhaustion. Application errors. RDS overload.

Root Cause: Each Lambda invocation creates a new database connection. No connection pooling. RDS max connections exceeded.

Simple explanation: You hire a new driver for every delivery. 1000 deliveries = 1000 drivers. The parking lot is full.

Technical Answer:

  1. Use RDS Proxy to pool connections — Lambda connects to Proxy, Proxy manages DB connections.
  2. Reuse database connections across invocations (global scope connection object).
  3. Set appropriate max_connections on RDS.
  4. Use serverless v2 (Aurora) for automatic scaling.
  5. Monitor DatabaseConnections CloudWatch metric.

Code/Syntax Justification:

# Reuse DB connection across invocations
import psycopg2
connection = None

def get_connection():
global connection
if connection is None:
connection = psycopg2.connect(...)
return connection

Workflow Diagram:

New connection per invocation: RDS Proxy + connection reuse:
1000 concurrent = 1000 DB conns 1000 Lambda -> RDS Proxy -> pooled DB conns
| |
v v
RDS max connections exceeded Connection pool managed
Database errors Stable DB connections

🔍 Behind the Question: RDS Proxy, connection pooling, connection reuse, max_connections, Aurora Serverless v2.

❌ The Red Flags: New DB connection per invocation; no connection pooling; not using RDS Proxy for high concurrency.


Q269: Lambda function URL authentication​

Level: Senior

Scenario: A Lambda Function URL is set to AuthType: NONE. Anyone with the URL can invoke it. The function processes sensitive data. Unauthorized access.

Impact: Unauthorized access. Data exposure. Security violation.

Root Cause: Function URL has no authentication. Publicly accessible.

Simple explanation: Leaving the front door unlocked with a sign "come in." Anyone can enter.

Technical Answer:

  1. Use AuthType: AWS_IAM for Function URL — requires AWS signature v4 signing.
  2. Use API Gateway with Cognito/IAM auth for more complex auth needs.
  3. Validate caller identity in function code (if using NONE, implement custom auth).
  4. Use resource-based policy to restrict which accounts/principals can invoke.
  5. Combine with WAF for additional protection.

Code/Syntax Justification:

# Function URL with AWS_IAM auth (CloudFormation)
# AuthType: AWS_IAM
# Cors:
# AllowOrigins: ['https://myapp.com']

Workflow Diagram:

AuthType: NONE: AuthType: AWS_IAM:
Anyone with URL can invoke Only signed requests can invoke
| |
v v
Unauthorized access Authorized access only

🔍 Behind the Question: Function URL auth, AWS_IAM, resource-based policy, WAF.

❌ The Red Flags: AuthType NONE for sensitive functions; no resource-based policy; no WAF.


Q270: Lambda function URL CORS​

Level: Senior

Scenario: A browser-based frontend calls a Lambda Function URL. The browser blocks the request due to CORS (Cross-Origin Resource Sharing). The function URL doesn't return CORS headers.

Impact: Frontend can't call the function. CORS errors in browser console.

Root Cause: Function URL not configured with CORS allowed origins/headers/methods.

Simple explanation: You send a letter to another country. The recipient's country rejects it because it doesn't have the right postal markings.

Technical Answer:

  1. Configure CORS on Function URL (AllowedOrigins, AllowMethods, AllowHeaders).
  2. Handle OPTIONS preflight requests if needed.
  3. Return Access-Control-Allow-Origin header in response.
  4. Use API Gateway if complex CORS rules needed.
  5. Test CORS from browser dev tools.

Code/Syntax Justification:

# Function URL CORS config (CloudFormation)
# Cors:
# AllowOrigins: ['https://myapp.com']
# AllowMethods: ['GET', 'POST', 'OPTIONS']
# AllowHeaders: ['content-type']

Workflow Diagram:

No CORS: CORS configured:
Browser blocks request Browser allows request
| |
v v
CORS error in console Request succeeds

🔍 Behind the Question: CORS, Function URL CORS config, preflight, browser security.

❌ The Red Flags: No CORS config; AllowOrigins: * for sensitive functions; not handling OPTIONS.


Q271: Lambda event source mapping — Kinesis/DynamoDB Streams​

Level: Senior

Scenario: A Lambda function reads from Kinesis Data Stream. The stream has multiple shards. The function processes records slowly. Some shards lag behind. Data accumulates.

Impact: Stream lag. Data processing delayed. Potential data loss if retention exceeded.

Root Cause: Lambda concurrency not matching shard count. Batch size too small. Processing too slow per record.

Simple explanation: You have 5 checkout lanes but only 1 cashier. Lanes back up. Customers wait.

Technical Answer:

  1. Set batch size appropriately (1-10000 records per invocation).
  2. Set max batch age (max time to wait for full batch).
  3. Use bisectOnBatchError to split failed batches.
  4. Provisioned concurrency should match shard count for parallel processing.
  5. Monitor IteratorAge CloudWatch metric.

Code/Syntax Justification:

# Event source mapping config
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:kinesis:...:stream/my-stream',
FunctionName='my-fn',
BatchSize=100,
MaxBatchingWindowInSeconds=5,
BisectBatchOnFunctionError=True,
MaximumRecordAgeInSeconds=3600
)

Workflow Diagram:

Small batch size: Larger batch + bisect:
1 record per invocation 100 records per invocation
| |
v v
High invocation overhead Efficient processing
| |
v v
Stream lag Stream keeps up

🔍 Behind the Question: Event source mapping, Kinesis/DynamoDB Streams, batch size, bisectOnBatchError, iterator age.

❌ The RedFlags: Batch size 1 for high throughput; no bisectOnBatchError; not monitoring iterator age.


Q272: Lambda function resolution — ARM64 (Graviton2)​

Level: Senior

Scenario: A team runs Lambda on x86_64. They want to reduce cost. Graviton2 (ARM64) offers up to 34% better price-performance for many workloads.

Impact: Higher cost than necessary. Not taking advantage of cheaper architecture.

Root Cause: Using x86_64 by default without evaluating Graviton2 compatibility.

Simple explanation: You buy a gas-guzzling car when a hybrid does the same job for less fuel.

Technical Answer:

  1. Test function on arm64 (Graviton2) — most Python/Node.js/Java workloads work without changes.
  2. Compare cost and performance (x86 vs arm64).
  3. Some workloads (intel-specific instructions, certain compiled libs) may not work on arm64.
  4. Update architecture in function configuration.
  5. Monitor cost savings after migration.

Code/Syntax Justification:

# Lambda architecture config (CloudFormation)
# Architectures:
# - arm64 # Graviton2
# # or
# - x86_64

Workflow Diagram:

x86_64: arm64 (Graviton2):
Standard price Up to 34% better price-performance
| |
v v
Higher cost Lower cost for compatible workloads

🔍 Behind the Question: Graviton2, arm64 vs x86_64, price-performance, architecture migration.

❌ The Red Flags: Defaulting to x86_64 without evaluating arm64; not testing arm64 compatibility; not monitoring cost savings.


Q273: Lambda function URL vs API Gateway — choosing​

Level: Principal

Scenario: A team needs to expose a Lambda as a webhook. They're deciding between Function URL and API Gateway. They need to consider cost, features, and future requirements.

Impact: Wrong choice leads to over-engineering or migration later.

Root Cause: Not evaluating requirements against capabilities of each option.

Simple explanation: Choosing between a food truck and a full restaurant. Depends on what you need.

Technical Answer:

  1. Use Function URL for: simple webhooks, internal services, cost-sensitive, IAM auth sufficient, no API management needed.
  2. Use API Gateway for: custom domains, API keys, usage plans, throttling, request validation, WebSocket, Cognito auth, detailed analytics, stage management.
  3. Can migrate from Function URL to API Gateway later if needed.
  4. Cost: Function URL ~$0.20/million vs API Gateway ~$3.50/million (REST).

Code/Syntax Justification:

# Decision criteria table in code comments
# Use Function URL if:
# - Simple webhook
# - IAM auth sufficient
# - Cost-sensitive
# Use API Gateway if:
# - Custom domain needed
# - API keys / usage plans
# - Request validation
# - WebSocket

Workflow Diagram:

Function URL: API Gateway:
Simple webhook Full API management
IAM auth API keys, throttling, validation
$0.20/million $3.50/million
| |
v v
Choose for cost/simplicity Choose for features/management

🔍 Behind the Question: Function URL vs API Gateway decision, cost, features, migration path.

❌ The Red Flags: API Gateway for simple webhooks; Function URL for complex API needs; not evaluating cost.


Q274(b): Lambda Provisioned Concurrency vs auto-scaling​

Level: Principal

Scenario: A team enables Provisioned Concurrency on all Lambda functions. Cold starts eliminated but cost doubled. Most functions are infrequently used.

Impact: Unnecessary cost. Over-provisioning.

Root Cause: Provisioned Concurrency on functions that don't need low latency.

Simple explanation: Keeping 10 chefs in the kitchen 24/7 when only 2 customers visit per day.

Technical Answer:

  1. Use Provisioned Concurrency only for latency-sensitive, user-facing functions.
  2. Use standard (on-demand) scaling for background jobs, infrequent tasks.
  3. Use Auto Scaling for provisioned concurrency (schedule-based).
  4. Monitor ProvisionedConcurrentExecutions vs ProvisionedConcurrencyInvocations.
  5. Right-size: provisioned should be > 0 but < limit for latency-sensitive functions.

Code/Syntax Justification:

# Provisioned concurrency config
lambda_client.put_provisioned_concurrency_config(
FunctionName='my-fn',
Qualifier='live',
ProvisionedConcurrentExecutions=5
)

Workflow Diagram:

All functions provisioned: Right-sized:
10 functions x 5 concurrent x 24h Auth function: 5 (user-facing)
| |
v v
High cost ($$$) Batch function: 0 (cold start OK)
| |
v v
Optimize: provision only latency-sensitive Data processing: 0 (cold start OK)
functions Balanced cost and latency

🔍 Behind the Question: Provisioned concurrency cost model, right-sizing, latency vs cost trade-off.

❌ The Red Flags: Provisioned concurrency on all functions; not monitoring utilization; not distinguishing latency-sensitive vs background.


Q275: Lambda logging — CloudWatch Logs​

Level: Senior

Scenario: A Lambda function logs extensively. CloudWatch Logs ingestion cost is high. Log retention is infinite (never deleted). Cost grows unbounded.

Impact: High logging cost. Storage grows forever. No retention policy.

Root Cause: No log retention policy. Excessive logging. No log level filtering.

Simple explanation: You keep every piece of paper you ever receive. House fills with paper. You should recycle after 30 days.

Technical Answer:

  1. Set CloudWatch Logs retention (e.g., 30 days, 90 days, 1 year).
  2. Use structured logging (JSON) with appropriate levels.
  3. Don't log request/response bodies for every request.
  4. Use log insights for querying instead of loading all logs.
  5. Consider CloudWatch Logs Insights or S3 export for long-term storage.

Code/Syntax Justification:

# CloudWatch Logs retention (CLI)
aws logs put-retention-policy \
--log-group-name /aws/lambda/my-fn \
--retention-in-days 30

Workflow Diagram:

No retention: Retention policy:
Logs kept forever 30 days hot -> delete
| |
v v
Cost grows unbounded Bounded cost, compliant

🔍 Behind the Question: CloudWatch Logs retention, log ingestion cost, structured logging, log levels.

❌ The Red Flags: Infinite retention; excessive logging; no log level filtering; not monitoring log cost.


Q276: Lambda function URL vs API Gateway cost comparison​

Level: Principal

Scenario: A team processes 100 million API requests/month via API Gateway REST API. Cost = 100M × $3.50/million = $350/month just for API Gateway. Function URL would be $20/month.

Impact: $330/month unnecessary cost. $3,960/year wasted.

Root Cause: Using API Gateway for a use case that doesn't need its advanced features.

Simple explanation: Paying $350/month for a restaurant when a $20/month food truck serves the same food.

Technical Answer:

  1. Calculate current API Gateway cost: requests × $3.50/million (REST).
  2. Evaluate if advanced features (API keys, usage plans, custom domains, throttling) are needed.
  3. If not, migrate to Function URL ($0.20/million).
  4. Consider HTTP API ($1.00/million) as middle ground.
  5. Monitor API Gateway costs in Cost Explorer.

Code/Syntax Justification:

# Cost calculation
api_gateway_cost = 100_000_000 * 3.50 / 1_000_000 # $350/month
function_url_cost = 100_000_000 * 0.20 / 1_000_000 # $20/month
savings = api_gateway_cost - function_url_cost # $330/month

Workflow Diagram:

API Gateway REST: Function URL:
$3.50/million $0.20/million
| |
v v
$350/month for 100M requests $20/month for 100M requests
Full API management Simple invoke

🔍 Behind the Question: Cost comparison, API Gateway pricing tiers, Function URL pricing, HTTP API middle ground.

❌ The RedFlags: Not calculating API Gateway costs; using REST API for simple invoke; not considering HTTP API ($1.00/million).


Q277: Lambda function URL private access​

Level: Senior

Scenario: A Lambda Function URL needs to be accessible only from within a VPC (private). Function URLs are public by default. The team needs private access.

Impact: Function URL is publicly accessible. Security risk.

Root Cause: Function URLs don't support VPC-only access natively. They're public endpoints.

Simple explanation: You want a door only employees can use, but it's on the public street.

Technical Answer:

  1. Function URLs are public — use API Gateway private endpoint for VPC-only access.
  2. Or use Function URL with IAM auth + resource-based policy restricting to specific accounts/VPCE.
  3. Use API Gateway private endpoint + VPC endpoint for fully private access.
  4. Use security groups and network ACLs for additional restriction.
  5. Consider if the function truly needs to be internet-accessible at all.

Code/Syntax Justification:

# API Gateway private endpoint (CloudFormation)
# EndpointConfiguration:
# Type: PRIVATE
# VpcEndpointIds: [vpce-12345678]

Workflow Diagram:

Function URL (public): API Gateway private endpoint:
Publicly accessible VPC-only access
| |
v v
Security risk Private VPC access

🔍 Behind the Question: Function URL public access, API Gateway private endpoint, VPC endpoint, network security.

❌ The Red Flags: Function URL with AuthType NONE for internal services; not using API Gateway private endpoint for VPC-only; no network restrictions.


Q278: Lambda + DynamoDB — throttling and provisioned capacity​

Level: Senior

Scenario: A Lambda function writes to DynamoDB with provisioned capacity (10 WCUs). During traffic spikes, writes are throttled. Lambda retries. DynamoDB throttling errors propagate.

Impact: DynamoDB throttling. Lambda retries. Increased cost. Slow writes.

Root Cause: DynamoDB provisioned capacity too low for write traffic. No auto-scaling or on-demand mode.

Simple explanation: A highway has 2 lanes. 1000 cars try to enter. Traffic jam. Cars wait.

Technical Answer:

  1. Use DynamoDB on-demand mode for unpredictable traffic (pay per request).
  2. Use auto-scaling for provisioned capacity (scale WCUs based on utilization).
  3. Use batch writes (BatchWriteItem, up to 25 items) to reduce request count.
  4. Implement exponential backoff and retry for throttling errors.
  5. Monitor ConsumedWriteCapacityUnits and ThrottledRequests metrics.

Code/Syntax Justification:

# DynamoDB batch write
dynamodb.batch_write_item(
RequestItems={
'my-table': [
{'PutRequest': {'Item': item1}},
{'PutRequest': {'Item': item2}}
]
}
)

Workflow Diagram:

Provisioned capacity too low: On-demand or auto-scaling:
10 WCUs Scale WCUs based on utilization
| |
v v
Throttled at 10 WCUs Scales up during traffic spike
| |
v v
Lambda retries No throttling

🔍 Behind the Question: DynamoDB provisioned vs on-demand, auto-scaling, batch writes, exponential backoff, throttling.

❌ The RedFlags: Provisioned capacity too low; no auto-scaling; no exponential backoff; single-item writes instead of batch.


Q279: Lambda function URL vs API Gateway — feature matrix​

Level: Principal

Scenario: A team is deciding between Function URL and API Gateway for a new public API. They need to evaluate features: auth, caching, request validation, usage plans, WebSocket, custom domains.

Impact: Wrong choice limits functionality or overpays.

Root Cause: Not evaluating feature requirements against platform capabilities.

Simple explanation: Comparing a bicycle to a car. Depends on how far you need to go and how many passengers.

Technical Answer:

  1. Feature matrix:
    • Function URL: IAM auth, CORS, basic invoke, $0.20/million, no custom domain, no usage plans, no caching.
    • API Gateway HTTP API: IAM/Cognito/JWT auth, CORS, basic invoke, $1.00/million, custom domains, some throttling.
    • API Gateway REST API: Full auth (Cognito, IAM, Lambda authorizer), request validation, usage plans, API keys, caching, WebSocket, custom domains, $3.50/million.
  2. Choose based on required features and budget.
  3. Can start with Function URL and migrate to API Gateway if needs grow.

Code/Syntax Justification:

# Decision matrix (pseudo-code)
if need_custom_domain or need_api_keys or need_usage_plans or need_websocket:
use API_GATEWAY
elif need_simple_invoke and cost_sensitive:
use FUNCTION_URL
elif need_jwt_auth_or_custom_domain:
use API_GATEWAY_HTTP

Workflow Diagram:

Feature requirements: Platform choice:
Custom domain + API keys API Gateway REST
JWT auth API Gateway HTTP
IAM auth only, cost-sensitive Function URL

🔍 Behind the Question: Feature matrix, API Gateway types (REST/HTTP), Function URL, pricing tiers, migration path.

❌ The Red Flags: Not evaluating features before choosing; Function URL for complex API needs; API Gateway for simple webhooks.


Q280: Lambda function URL invocation — SDK vs HTTP​

Level: Senior

Scenario: A team invokes a Lambda Function URL from another Lambda using lambda_client.invoke() (AWS SDK) instead of direct HTTP. They pay for API calls and have higher latency.

Impact: Unnecessary API cost. Higher latency. More complex.

Root Cause: Using AWS SDK invoke when direct HTTP to Function URL would work.

Simple explanation: You call a friend through an operator instead of calling directly. Extra cost and delay.

Technical Answer:

  1. Use direct HTTP(S) to Function URL endpoint — no AWS SDK needed, no signature needed if AuthType NONE.
  2. Use AWS SigV4 signing if AuthType AWS_IAM.
  3. Direct HTTP is cheaper (no API call cost) and lower latency.
  4. Use lambda_client.invoke() only for asynchronous invocation or when you need AWS SDK features.

Code/Syntax Justification:

# Direct HTTP to Function URL (no SDK needed)
import requests
resp = requests.get('https://<url>.lambda-url.us-east-1.on.aws/')

Workflow Diagram:

SDK invoke: Direct HTTP:
lambda_client.invoke() requests.get(function_url)
| |
v v
API call cost + latency Direct HTTP, lower cost
| |
v v
Higher cost Lower cost, faster

🔍 Behind the Question: Function URL invocation, SDK vs HTTP, SigV4 signing, latency, cost.

❌ The Red Flags: Using SDK invoke for synchronous Function URL calls; not using direct HTTP; unnecessary API costs.


Q281: Lambda response size limit​

Level: Senior

Scenario: A Lambda function returns a 10MB JSON response. The client gets a malformed response error. Lambda response payload limit is 6MB (buffered) or 20MB (streaming).

Impact: Response truncated. Client errors. Data loss.

Root Cause: Response exceeds Lambda payload limit. No streaming or chunking.

Simple explanation: You try to send a 10MB file through a 6MB email attachment. It gets rejected.

Technical Answer:

  1. Lambda buffered response limit: 6MB (request + response).
  2. Lambda streaming response limit: 20MB.
  3. For responses >6MB, use response streaming or return an S3 presigned URL.
  4. For requests >6MB (invocation), use S3 for large payloads.
  5. Compress responses (gzip) to reduce size.

Code/Syntax Justification:

# Return S3 presigned URL for large response
s3_url = s3.generate_presigned_url('get_object', Params={'Bucket': 'b', 'Key': 'large.json'})
return {'statusCode': 200, 'body': json.dumps({'url': s3_url})}

Workflow Diagram:

Buffered response (>6MB): Streaming or S3 URL:
Response truncated Stream chunks (20MB limit)
| |
v v
Client error Client receives full response
| |
v v
Use S3 presigned URL for >20MB Or use streaming

🔍 Behind the Question: Response payload limits (6MB buffered, 20MB streaming), S3 presigned URL, compression.

❌ The Red Flags: Returning >6MB buffered response; not using streaming/S3 for large responses; not compressing.


Q282: Lambda + API Gateway — mapping templates​

Level: Senior

Scenario: A team uses API Gateway REST API with mapping templates to transform request/response between client and Lambda. The templates are complex (VTL) and hard to maintain.

Impact: Complex maintenance. VTL is hard to debug. Transformation logic in API Gateway not in code.

Simple explanation: You translate a letter through a middleman who uses a secret code. Hard to verify the translation is correct.

Technical Answer:

  1. Use Lambda function to handle request/response transformation instead of VTL mapping templates.
  2. API Gateway passes request directly to Lambda (Lambda proxy integration).
  3. Lambda handles parsing, validation, transformation in code (Python/Node.js) — easier to test and debug.
  4. Use API Gateway only for routing, auth, throttling — not transformation.
  5. VTL is legacy; Lambda proxy is preferred.

Code/Syntax Justification:

# Lambda proxy integration - receives full request event
def handler(event, context):
# event has request details directly
body = json.loads(event.get('body', '{}'))
# Transform in Python (easy to test)
result = transform(body)
return {'statusCode': 200, 'body': json.dumps(result)}

Workflow Diagram:

VTL mapping templates: Lambda proxy integration:
API Gateway transforms via VTL API Gateway -> Lambda (direct)
| |
v v
Hard to debug, VTL Transform in Python (testable)
| |
v v
Complex maintenance Simple, code-based transformation

🔍 Behind the Question: API Gateway mapping templates vs Lambda proxy, VTL, request/response transformation.

❌ The Red Flags: Complex VTL mapping templates; not using Lambda proxy; transformation logic in API Gateway.


Q283: Lambda function URL rate limiting​

Level: Senior

Scenario: A Lambda Function URL is publicly accessible (AuthType NONE). A malicious actor sends 10,000 requests/second. The function scales and processes all. High cost. Potential abuse.

Impact: Uncontrolled scaling. High cost. Abuse vulnerability.

Root Cause: Function URL has no built-in rate limiting. No WAF. No throttling at the edge.

Simple explanation: You leave a tip jar on the street. Anyone can take as much as they want. No limit.

Technical Answer:

  1. Use AWS WAF with Function URL for rate limiting, IP allowlisting, bot control.
  2. Use API Gateway (with usage plans and throttling) instead of Function URL if rate limiting needed.
  3. Implement rate limiting in function code (token bucket, Redis counter).
  4. Set reserved concurrency to limit max concurrent executions.
  5. Monitor invocation count and set budget alerts.

Code/Syntax Justification:

# Rate limiting in function code (Redis counter)
import redis
r = redis.Redis()

def handler(event, context):
client_ip = event.get('requestContext', {}).get('identity', {}).get('sourceIp')
key = f'rate:{client_ip}'
count = r.incr(key)
r.expire(key, 60)
if count > 100:
return {'statusCode': 429, 'body': 'Rate limited'}

Workflow Diagram:

No rate limiting: With rate limiting:
Unlimited invocations WAF/API Gateway rate limit
| |
v v
High cost, abuse 100 req/min per IP
| |
v v
Function scales uncontrollably Requests beyond limit rejected

🔍 Behind the Question: Rate limiting, WAF, API Gateway usage plans, function code rate limiting, reserved concurrency.

❌ The Red Flags: AuthType NONE with no rate limiting; no WAF; not monitoring invocation count; no cost alerts.


Q284: Lambda function URL vs API Gateway — migration​

Level: Principal

Scenario: A team started with Function URL for a simple webhook. Now they need API keys, usage plans, and custom domains. They need to migrate to API Gateway.

Impact: Migration effort. Potential downtime. Client updates needed.

Root Cause: Started with Function URL without anticipating advanced API management needs.

Simple explanation: You built a food truck. Now you need a full restaurant with seating, reservations, and table service. Time to upgrade.

Technical Answer:

  1. Create API Gateway REST or HTTP API.
  2. Create Lambda integration pointing to same function.
  3. Update client calls to new API Gateway URL.
  4. Set up custom domain, API keys, usage plans.
  5. Keep Function URL as fallback during migration. Route 53 can shift traffic.
  6. Monitor error rates during migration.

Code/Syntax Justification:

# API Gateway + Lambda integration
apigateway.create_integration(
restApiId='api-id',
resourceId='resource-id',
type='AWS_PROXY',
integrationHttpMethod='POST',
uri='arn:aws:apigateway:...:lambda:path/2015-03-31/functions/arn:aws:lambda:...:function:my-fn/invocations'
)

Workflow Diagram:

Function URL -> API Gateway migration:
Function URL (simple) API Gateway (advanced)
| |
v v
Add custom domain, API keys New API Gateway URL
| |
v v
Route 53 traffic shift Client updates to new URL
| |
v v
Migration complete Full API management

🔍 Behind the Question: Migration path, Route 53 traffic shift, API Gateway integration, backward compatibility.

❌ The Red Flags: Not planning for migration; Function URL for needs that will grow; no client URL update plan.


Q285: Lambda + CloudWatch Logs Insights​

Level: Senior

Scenario: A team wants to analyze Lambda logs for errors over the past 24 hours. They don't know CloudWatch Logs Insights query syntax. They download logs and grep locally.

Impact: Slow analysis. Can't query at scale. Manual effort.

Root Cause: Not using CloudWatch Logs Insights for log analysis.

Simple explanation: You read every page of a book to find one sentence. You should use the index (CloudWatch Logs Insights).

Technical Answer:

  1. Use CloudWatch Logs Insights query language to query Lambda logs.
  2. Query by error level, request ID, duration, or custom fields.
  3. Create saved queries and dashboards for common analysis.
  4. Use fields @timestamp, @message etc. to filter and aggregate.
  5. Set up alerts on Insights query results (CloudWatch Alarms on metrics from Insights).

Code/Syntax Justification:

# CloudWatch Logs Insights query
fields @timestamp, @requestId, @duration, @status
| filter @status >= 400
| sort @timestamp desc
| limit 100

Workflow Diagram:

Download + grep locally: CloudWatch Logs Insights:
Download logs Query directly in CloudWatch
| |
v v
grep locally (slow) Query at scale (fast)
| |
v v
Manual analysis Dashboard + alert

🔍 Behind the Question: CloudWatch Logs Insights, log query language, log analysis, dashboards.

❌ The Red Flags: Downloading logs to grep locally; not using Logs Insights; no saved queries/dashboards.


Q286: Lambda function URL vs API Gateway — decision framework​

Level: Principal

Scenario: A team needs to choose between Function URL, API Gateway HTTP API, and API Gateway REST API for a new public API serving mobile and web clients. Requirements: JWT auth, custom domain, rate limiting, usage plans, <$500/month budget at 50M requests.

Impact: Wrong choice = over budget or missing features.

Root Cause: No decision framework. Evaluating options ad-hoc.

Simple explanation: Buying a car without knowing if you need a sedan, truck, or motorcycle.

Technical Answer:

  1. Calculate cost at 50M requests:
    • Function URL: 50M × $0.20 = $10/month (but no JWT auth, custom domains, usage plans)
    • API Gateway HTTP: 50M × $1.00 = $50/month (JWT auth, custom domains, some throttling)
    • API Gateway REST: 50M × $3.50 = $175/month (full features including usage plans, API keys)
  2. All within $500/month budget.
  3. Choose based on features needed:
    • Need usage plans + API keys → REST API ($175)
    • Need JWT auth + custom domain → HTTP API ($50)
    • Simple webhook, IAM auth → Function URL ($10)
  4. Document decision criteria and revisit as requirements change.

Code/Syntax Justification:

# Cost calculation at 50M requests
function_url = 50_000_000 * 0.20 / 1_000_000 # $10
http_api = 50_000_000 * 1.00 / 1_000_000 # $50
rest_api = 50_000_000 * 3.50 / 1_000_000 # $175

Workflow Diagram:

Requirements: JWT + custom domain + rate limiting:
Function URL ($10) HTTP API ($50) REST API ($175)
✗ no JWT auth ✓ JWT auth ✓ JWT auth
✗ no custom domain ✓ custom domain ✓ custom domain
✗ no usage plans ✗ no usage plans ✓ usage plans
| |
v v
Eliminated Selected: HTTP API ($50) or REST API ($175)

🔍 Behind the Question: Decision framework, cost calculation, feature requirements, budget constraints.

❌ The Red Flags: Not calculating costs; not documenting decision criteria; choosing based on familiarity not requirements.


Senior / Principal — AWS Lambda Real World Scenarios (Continued)​

Q287: Lambda + API Gateway — mapping request context​

Level: Senior

Scenario: A team needs to pass the calling user's identity (from API Gateway JWT authorizer) to the Lambda function. They don't know how to access it. They parse the raw event incorrectly.

Impact: Can't identify the caller. Can't enforce per-user logic. Security gap.

Root Cause: Not understanding API Gateway event structure — authorizer context is in requestContext.authorizer.

Simple explanation: You receive a package with a label. You throw away the label without reading it. You don't know who sent it.

Technical Answer:

  1. API Gateway passes authorizer context in event['requestContext']['authorizer'] (for JWT/Cognito) or event['requestContext']['identity'] (for IAM).
  2. Extract claims (Cognito JWT) or principalId (custom authorizer) from the event.
  3. Pass the identity to downstream logic for auditing and per-user enforcement.
  4. Don't trust client-sent headers — use API Gateway-authorized identity only.
  5. Log the identity with every log entry for traceability.

Code/Syntax Justification:

def handler(event, context):
authorizer = event.get('requestContext', {}).get('authorizer', {})
claims = authorizer.get('claims', {})
user_id = claims.get('sub') # Cognito user sub
# Use user_id for auditing and per-user logic

Workflow Diagram:

API Gateway JWT authorizer: Lambda event structure:
Client -> API Gateway -> Lambda event.requestContext.authorizer.claims.sub
| |
v v
JWT validated by API Gateway Extract user_id from claims
| |
v v
Lambda receives identity Use user_id in logs and logic

🔍 Behind the Question: API Gateway authorizer context, requestContext structure, identity extraction, JWT claims.

❌ The Red Flags: Parsing client-sent headers instead of authorizer context; not extracting identity; not logging identity.


Q288: Lambda cold start — provisioned concurrency vs snapstart​

Level: Senior

Scenario: A team compares Provisioned Concurrency vs SnapStart for cold start reduction. They don't understand when to use each. They enable both and pay double.

Impact: Unnecessary cost. Confusion about which solves what.

Root Cause: Not understanding the difference — Provisioned Concurrency keeps instances warm (pay per hour), SnapStart restores from snapshot (pay per invocation, sub-second restore).

Simple explanation: Provisioned Concurrency keeps the oven preheated all day. SnapStart bakes the cake once and reheats it instantly when needed.

Technical Answer:

  1. Provisioned Concurrency: keeps initialized environments ready (pay per hour per concurrent execution). Best for latency-sensitive, predictable traffic.
  2. SnapStart: initializes once per published version, restores from snapshot on scale-in (pay per invocation, sub-second). Best for Java/Python with predictable init.
  3. Can use both, but usually one suffices. SnapStart is cheaper for sporadic traffic; Provisioned Concurrency for steady low-latency needs.
  4. Monitor cold start duration with and without each to measure benefit.
  5. SnapStart not supported for all runtimes/regions.

Code/Syntax Justification:

# Provisioned Concurrency (pay per hour)
lambda_client.put_provisioned_concurrency_config(
FunctionName='my-fn', Qualifier='live',
ProvisionedConcurrentExecutions=5
)

# SnapStart (pay per invocation, restore from snapshot)
# CloudFormation: SnapStart: { ApplyOn: PublishedVersions }

Workflow Diagram:

Provisioned Concurrency: SnapStart:
Env always warm Init once, snapshot saved
| |
v v
Pay per hour (even if idle) Pay per invocation (restore)
| |
v v
Best for steady low-latency Best for sporadic traffic, Java/Python

🔍 Behind the Question: Provisioned Concurrency vs SnapStart, cold start strategies, cost comparison, runtime support.

❌ The Red Flags: Enabling both unnecessarily; using Provisioned Concurrency for sporadic traffic; using SnapStart where not supported.


Q289: Lambda function URL + API Gateway coexistence​

Level: Principal

Scenario: A team has both a Function URL and API Gateway pointing to the same Lambda. Clients use both URLs. Costs double. Configuration drifts. Hard to maintain.

Impact: Double cost. Configuration inconsistency. Maintenance burden.

Root Cause: Two entry points for the same function. No clear primary entry point.

Simple explanation: You have two front doors to the same house. You maintain both locks. Guests use both. Confusing.

Technical Answer:

  1. Choose one primary entry point (Function URL for simple, API Gateway for advanced).
  2. Disable or restrict the other (remove public access, add auth).
  3. Route all clients to the primary entry point.
  4. Use Route 53 or alias to point to the primary if needed.
  5. Monitor both for unexpected usage/cost.

Code/Syntax Justification:

# Remove public access from Function URL (keep for internal only)
lambda_client.update_function_url_config(
FunctionName='my-fn',
Qualifier='live',
AuthType='AWS_IAM' # Require auth, not NONE
)

Workflow Diagram:

Two entry points: One primary entry point:
Function URL + API Gateway API Gateway (primary) -> Lambda
| |
v v
Double cost, drift Single entry point, single config
| |
v v
Consolidate to one Monitor only one entry point

🔍 Behind the Question: Entry point consolidation, cost duplication, configuration drift, Route 53 traffic management.

❌ The Red Flags: Two public entry points for same function; no consolidation plan; monitoring both separately.


Q290: Lambda event filtering — SQS/Kinesis batch​

Level: Senior

Scenario: A Lambda function is triggered by SQS. It processes all messages but only cares about order_type: premium. Non-premium orders waste invocations and cost.

Impact: Unnecessary invocations. Higher cost. Wasted compute.

Root Cause: No event filtering at the event source mapping level. Lambda receives all messages and filters in code.

Simple explanation: You receive all mail and sort it yourself. You should have the mail sorter only deliver premium mail.

Technical Answer:

  1. Use Event Source Mapping filtering (SQS, Kinesis, DynamoDB Streams) to filter before invoking Lambda.
  2. Define filter criteria on event attributes — Lambda only invokes when filter matches.
  3. Reduces invocations and cost for irrelevant events.
  4. Filter pattern uses JSON matching on event attributes.
  5. Combine with batch size for efficiency.

Code/Syntax Justification:

# Event source mapping filter (CLI)
lambda_client.update_event_source_mapping(
UUID='esm-12345',
FilterCriteria={
'Filters': [{
'Pattern': '{"detail": {"order_type": ["premium"]}}'
}]
}
)

Workflow Diagram:

No filtering: Event filtering:
All messages -> Lambda Filter -> only premium -> Lambda
| |
v v
Process all (waste on non-premium) Process only premium
| |
v v
Higher cost Lower cost, fewer invocations

🔍 Behind the Question: Event source mapping filtering, SQS/Kinesis/DynamoDB Streams, filter patterns, invocation reduction.

❌ The Red Flags: Filtering in Lambda code instead of event source mapping; not using filter patterns; processing all events unnecessarily.


Q291: Lambda + CloudWatch Alarms — error rate​

Level: Senior

Scenario: A Lambda function has errors but no alarm. The team discovers issues from user complaints. No proactive alerting.

Impact: Issues undetected until users report. High MTTDR.

Root Cause: No CloudWatch Alarms on Lambda error metrics.

Simple explanation: You don't have a smoke alarm. You discover the fire when you smell smoke.

Technical Answer:

  1. Create CloudWatch Alarms on Lambda Errors metric (error rate > threshold).
  2. Alarm on Duration (slow invocations), Throttles (concurrency limits), IteratorAge (stream lag).
  3. Use SNS to notify on-call (PagerDuty, Slack, email).
  4. Set evaluation periods (e.g., 3 out of 5 periods) to avoid flapping.
  5. Create dashboards showing error rate, duration, throttles, invocations.

Code/Syntax Justification:

cloudwatch.put_metric_alarm(
AlarmName='HighLambdaErrors',
MetricName='Errors',
Namespace='AWS/Lambda',
Dimensions=[{'Name': 'FunctionName', 'Value': 'my-fn'}],
Statistic='Sum',
Period=60,
Threshold=5,
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=3,
AlarmActions=['arn:aws:sns:...:my-topic']
)

Workflow Diagram:

No alarm: CloudWatch Alarm:
Errors occur -> undetected Errors > threshold -> alarm -> SNS -> on-call
| |
v v
Users report issue Paged proactively
| |
v v
High MTTDR Low MTTDR

🔍 Behind the Question: CloudWatch Alarms, Lambda metrics (Errors, Duration, Throttles), SNS notification, MTTDR.

❌ The Red Flags: No alarms on Lambda errors; not monitoring throttles/duration; no on-call notification.


Q292: Lambda function URL + WAF​

Level: Senior

Scenario: A Lambda Function URL (AuthType NONE) is publicly accessible. It's targeted by bots and scrapers. The team wants to block malicious IPs and rate-limit.

Impact: Bot abuse. Scraping. High cost from unwanted invocations.

Root Cause: Function URL has no built-in WAF or rate limiting when AuthType NONE.

Simple explanation: Your shop is open to the street. Shoplifters take everything. No security guard.

Technical Answer:

  1. Use AWS WAF with Function URL for rate limiting, IP allow/block lists, bot control.
  2. Associate WAF web ACL with the Function URL.
  3. Create rules: rate limit (requests per 5 min), block known bad IPs, allow specific countries.
  4. Alternatively, use API Gateway (with WAF integration) instead of Function URL if WAF needed.
  5. Monitor WAF metrics (blocked requests, allowed requests).

Code/Syntax Justification:

# WAF web ACL associated with Function URL (CLI)
aws wafv2 associate-web-acl \
--web-acl-arn arn:aws:wafv2:...:webacl/my-acl \
--resource-arn arn:aws:lambda:...:url:my-fn-url

Workflow Diagram:

No WAF: WAF + Function URL:
All requests reach function WAF filters before function
| |
v v
Bots scrape, high cost Bad IPs blocked, rate limited
| |
v v
High cost, abuse Protected function

🔍 Behind the Question: AWS WAF, Function URL protection, rate limiting, IP allow/block lists, bot control.

❌ The Red Flags: Function URL with AuthType NONE and no WAF; no rate limiting; not monitoring blocked requests.


Q293: Lambda + EventBridge — event bus vs direct invoke​

Level: Senior

Scenario: A team invokes Lambda directly from multiple services (direct invoke). They want to decouple and add replay capability.

Impact: Tight coupling. No replay. No event history.

Root Cause: Direct invoke couples invoker to Lambda. No event buffer or replay.

Simple explanation: You call each person directly. If they miss the call, the message is lost. An event bus records all messages for replay.

Technical Answer:

  1. Use EventBridge event bus as an intermediary between services and Lambda.
  2. Services put events to EventBridge; Lambda subscribes via event rules.
  3. EventBridge replays failed events (replay from archive).
  4. Decouples invoker from Lambda — add new consumers without changing producers.
  5. Use EventBridge archives for event history and replay.

Code/Syntax Justification:

# Put event to EventBridge
events.put_events(
Entries=[{
'Source': 'myapp.order',
'DetailType': 'OrderPlaced',
'Detail': json.dumps(order),
'EventBusName': 'my-event-bus'
}]
)

Workflow Diagram:

Direct invoke: EventBridge bus:
Service A -> Lambda Service A -> EventBridge -> Lambda
| |
v v
Tight coupling, no replay Decoupled, replay capable

🔍 Behind the Question: EventBridge, event bus, decoupling, replay, archives.

❌ The Red Flags: Direct invoke for event-driven workflows; no event bus; no replay capability.


Q294: Lambda function URL — custom domain​

Level: Senior

Scenario: A team wants a custom domain (api.myapp.com) for their Lambda Function URL. Function URLs have auto-generated URLs (lambda-url.on.aws). They need a branded URL.

Impact: No custom domain. Unprofessional URL. Can't use existing SSL cert.

Root Cause: Function URLs don't support custom domains natively. Need API Gateway for custom domain.

Simple explanation: You want your store at shop.myapp.com but only have store-123.square.site. You need a domain front.

Technical Answer:

  1. Use API Gateway (REST or HTTP) with custom domain name for branded URLs.
  2. API Gateway integrates with Lambda (Lambda proxy).
  3. Use Route 53 or ACM for custom domain SSL certificate.
  4. Function URL can remain as internal/backup entry point.
  5. Map custom domain in API Gateway -> Lambda integration.

Code/Syntax Justification:

# API Gateway custom domain (CLI)
apigateway.create_domain_name(
domainName='api.myapp.com',
domainNameConfigurations=[{
'CertificateArn': 'arn:aws:acm:...:certificate/...',
'EndpointType': 'REGIONAL'
}]
)

Workflow Diagram:

Function URL (auto-generated): API Gateway + custom domain:
https://abc.lambda-url.on.aws https://api.myapp.com
| |
v v
Unbranded, hard to remember Branded, professional

🔍 Behind the Question: Custom domain, API Gateway domain names, ACM certificates, Route 53, Function URL limitations.

❌ The Red Flags: Expecting custom domain on Function URL; not using API Gateway for branded URLs; no SSL certificate management.


Q295: Lambda + S3 event — prefix/suffix filtering​

Level: Senior

Scenario: A Lambda function is triggered by S3 s3:ObjectCreated:* on a bucket. It processes ALL uploads including logs, temp files, and thumbnails. It only should process images in /uploads/.

Impact: Unnecessary invocations. Processing wrong files. Higher cost.

Root Cause: No S3 event notification filtering (prefix/suffix). Lambda receives all bucket events.

Simple explanation: You get notified for every file dropped in a room. You only want notifications for images in the uploads folder.

Technical Answer:

  1. Configure S3 event notification with Prefix (uploads/) and Suffix (.jpg, .png).
  2. Lambda only invokes for matching objects.
  3. Reduces invocations and cost for irrelevant events.
  4. Can configure multiple event notifications with different filters on the same bucket.
  5. Test filter patterns with sample object keys.

Code/Syntax Justification:

# S3 event notification filter (CLI)
aws s3api put-bucket-notification-configuration \
--bucket my-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [{
"Id": "image-upload",
"LambdaFunctionArn": "arn:aws:lambda:...:function:my-fn",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{"Name": "prefix", "Value": "uploads/"},
{"Name": "suffix", "Value": ".jpg"}
]
}
}
}]
}'

Workflow Diagram:

No filtering: S3 event filtering:
All uploads -> Lambda Only uploads/*.jpg -> Lambda
| |
v v
Process logs, temps, images Process only images
| |
v v
Higher cost, wrong processing Lower cost, correct processing

🔍 Behind the Question: S3 event notification filtering, prefix/suffix, invocation reduction, cost optimization.

❌ The Red Flags: No prefix/suffix filtering; processing all bucket events; not testing filter patterns.


Q296: Lambda function URL — invocation types (RequestResponse vs Event)​

Level: Senior

Scenario: A team invokes a Lambda Function URL synchronously (RequestResponse) for a long-running report generation (30 seconds). The client times out. They should use asynchronous invocation (Event).

Impact: Client timeouts. Failed invocations. Poor UX.

Root Cause: Using synchronous invocation for long-running operations. Client can't wait.

Simple explanation: You order a custom cake. You wait at the counter for 30 minutes. You should order and come back later.

Technical Answer:

  1. Use RequestResponse (synchronous) for quick operations (<15 seconds, immediate response needed).
  2. Use Event (asynchronous) for long-running operations (reports, image processing, emails).
  3. Async: Lambda returns 202 Accepted immediately, processes in background.
  4. Use DLQ for async failures. Use Step Functions for orchestration.
  5. Client polls or uses webhook for async result.

Code/Syntax Justification:

# Async invocation (Event)
lambda_client.invoke(
FunctionName='my-fn',
InvocationType='Event', # async
Payload=json.dumps(payload)
)

# Synchronous invocation (RequestResponse)
lambda_client.invoke(
FunctionName='my-fn',
InvocationType='RequestResponse', # sync (default)
Payload=json.dumps(payload)
)

Workflow Diagram:

Synchronous (RequestResponse): Asynchronous (Event):
Client waits for response Client gets 202 Accepted immediately
| |
v v
Timeout at 30s Lambda processes in background
| |
v v
Failed invocation Client polls or gets webhook later

🔍 Behind the Question: Invocation types (RequestResponse vs Event), async vs sync, DLQ, client polling.

❌ The Red Flags: Synchronous invocation for long operations; client timeouts; no async pattern for background work.


Senior / Principal — AWS Lambda Real World Scenarios (Continued)​

Q297: Lambda function URL — query string and headers​

Level: Senior

Scenario: A team invokes a Lambda Function URL with query string parameters and custom headers. The Lambda function doesn't receive them. They can't access event['queryStringParameters'] or event['headers'].

Impact: Can't read request parameters. Function doesn't behave as expected.

Root Cause: Not understanding the Function URL event structure — query string and headers are in specific event fields.

Simple explanation: You receive a letter with notes in the margin. You only read the main body. You miss the instructions in the margin.

Technical Answer:

  1. Function URL invocations pass request data in event['queryStringParameters'], event['headers'], event['path'], event['httpMethod'], event['body'].
  2. Query string parameters: event['queryStringParameters']['paramName'].
  3. Headers: event['headers']['header-name'] (case-insensitive).
  4. Body is base64-encoded if isBase64Encoded is true (binary payloads).
  5. Parse event['body'] as JSON for JSON payloads.

Code/Syntax Justification:

def handler(event, context):
query_params = event.get('queryStringParameters') or {}
user_id = query_params.get('user_id')
headers = event.get('headers') or {}
content_type = headers.get('content-type') or headers.get('Content-Type')
body = json.loads(event.get('body', '{}'))

Workflow Diagram:

Function URL invocation:
Client -> https://url?user_id=123 -> Lambda event:
event.queryStringParameters.user_id = '123'
event.httpMethod = 'GET'
event.path = '/'
| |
v v
Extract from event fields Use in function logic

🔍 Behind the Question: Function URL event structure, query string parameters, headers, body parsing, isBase64Encoded.

❌ The Red Flags: Not knowing where query params/headers live in the event; not handling isBase64Encoded; not parsing body as JSON.


Q298: Lambda + API Gateway — Lambda authorizer​

Level: Senior

Scenario: A team uses API Gateway with a custom Lambda authorizer for authentication. The authorizer returns an IAM policy. They don't understand how to scope the policy to specific resources.

Impact: Over-broad authorization. Users can access resources they shouldn't.

Root Cause: Lambda authorizer policy doesn't restrict resource ARN. All resources allowed or denied.

Simple explanation: You give a security guard a key that opens every door. You should give keys only to specific doors.

Technical Answer:

  1. Lambda authorizer returns an IAM policy with Resource ARN specific to the method ARN (event['methodArn']).
  2. Construct resource ARN from methodArn — replace the final part with the specific resource or use * for the method.
  3. Return Allow or Deny with specific resource scope.
  4. Cache the policy (ttlSeconds) to reduce authorizer invocations.
  5. Validate the token (JWT, API key, custom) before issuing the policy.

Code/Syntax Justification:

def handler(event, context):
method_arn = event['methodArn']
# Construct resource ARN from methodArn
parts = method_arn.split(':')
api_gateway_arn = ':'.join(parts[:5]) + ':*'
resource = f'{api_gateway_arn}/{parts[6]}' # specific method/resource

policy = {
'principalId': 'user123',
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{
'Action': 'execute-api:Invoke',
'Effect': 'Allow',
'Resource': resource
}]
}
}

Workflow Diagram:

Lambda authorizer:
Client -> API Gateway -> Lambda authorizer -> validate token
| |
v v
Return IAM policy with resource ARN API Gateway enforces policy
| |
v v
Allow/deny specific resource Access granted/denied

🔍 Behind the Question: Lambda authorizer, IAM policy, resource ARN scoping, methodArn, policy cache.

❌ The Red Flags: Policy with * resource (all resources); not validating token; no policy cache TTL.


Q299: Lambda + DynamoDB Streams — event source mapping​

Level: Senior

Scenario: A Lambda function is triggered by DynamoDB Streams. It processes each record (insert/modify/delete). The function processes records slowly. Stream lag increases. Records accumulate.

Impact: Stream lag. Data processing delayed. Potential data loss if retention (24 hours) exceeded.

Root Cause: Lambda concurrency too low for stream volume. Batch size too small. Processing too slow per record.

Simple explanation: You have 5 conveyor belts (shards) but only 1 worker. Belts back up. Items pile up.

Technical Answer:

  1. Set batch size appropriately (1-1000 records per invocation for DynamoDB Streams).
  2. Set max batch age (max time to wait for full batch).
  3. Use bisectOnBatchError to split failed batches.
  4. Provisioned concurrency should match shard count for parallel processing (one Lambda invocation per shard).
  5. Monitor IteratorAge CloudWatch metric.

Code/Syntax Justification:

# DynamoDB Streams event source mapping
lambda_client.create_event_source_mapping(
EventSourceArn='arn:aws:dynamodb:...:table/my-table/stream/2026-01-15T...',
FunctionName='my-fn',
BatchSize=100,
MaxBatchingWindowInSeconds=5,
BisectBatchOnFunctionError=True,
MaximumRecordAgeInSeconds=3600,
StartingPosition='LATEST'
)

Workflow Diagram:

DynamoDB Streams:
Table write -> Stream record -> Lambda event source mapping
| |
v v
Batch of records -> Lambda processes IteratorAge increases if slow
| |
v v
Slow processing -> stream lag Fast processing -> stream keeps up

🔍 Behind the Question: DynamoDB Streams, event source mapping, batch size, bisectOnBatchError, iterator age, shard concurrency.

❌ The RedFlags: Batch size 1 for high throughput; no bisectOnBatchError; not monitoring iterator age; provisioned concurrency too low.


Q300: Lambda + EventBridge — replay failed events​

Level: Senior

Scenario: An EventBridge event bus failed to deliver events to Lambda for 2 hours (Lambda was down). Events are lost. The team wants to replay them.

Impact: Lost events. Data not processed. Business impact.

Root Cause: No EventBridge archive configured. No replay capability.

Simple explanation: You miss phone calls while out of the office. No voicemail. You don't know who called.

Technical Answer:

  1. Enable EventBridge archive on the event bus — stores events for replay.
  2. Create an archive with retention period (e.g., 30 days).
  3. Replay events from archive to Lambda after recovery.
  4. Use replay to reprocess failed events from a specific time window.
  5. Monitor archive status and storage cost.

Code/Syntax Justification:

# Create EventBridge archive
events.create_archive(
ArchiveName='my-archive',
EventSourceArn='arn:aws:events:...:event-bus/default',
RetentionDays=30
)

# Replay events
events.start_replay(
ReplayName='replay-2026-01-15',
EventSourceArn='arn:aws:events:...:event-bus/default',
EventStartTime=datetime(2026, 1, 15, 10, 0),
EventEndTime=datetime(2026, 1, 15, 12, 0),
Destination='arn:aws:lambda:...:function:my-fn'
)

Workflow Diagram:

No archive: EventBridge archive:
Events lost when Lambda down Events stored in archive
| |
v v
Data lost permanently Replay from archive after recovery
| |
v v
Permanent data loss Recovered events

🔍 Behind the Question: EventBridge archive, replay, event retention, failed event recovery.

❌ The RedFlags: No archive configured; not replaying failed events; not monitoring archive storage cost.


Q301: Lambda function URL — binary payload support​

Level: Senior

Scenario: A client sends a binary file (image, PDF) to a Lambda Function URL. The function receives corrupted data. The body is base64-encoded but the function doesn't decode it.

Impact: Corrupted file. Function errors. Data loss.

Root Cause: Function URL base64-encodes binary payloads. Function doesn't decode isBase64Encoded body.

Simple explanation: You receive a letter in a secret code. You read it as plain text. It's gibberish.

Technical Answer:

  1. Check event['isBase64Encoded'] — if true, decode event['body'] from base64.
  2. For binary responses, set isBase64Encoded: true in response and base64-encode the body.
  3. Use Content-Type header to indicate binary type.
  4. Function URL supports binary media types (configure in API Gateway or handle in code).
  5. Test with binary payloads (images, PDFs, binary protobuf).

Code/Syntax Justification:

import base64

def handler(event, context):
if event.get('isBase64Encoded'):
body = base64.b64decode(event['body'])
else:
body = event['body'].encode()
# Process binary body
result = process_binary(body)
return {
'statusCode': 200,
'isBase64Encoded': True,
'body': base64.b64encode(result).decode(),
'headers': {'Content-Type': 'application/pdf'}
}

Workflow Diagram:

Binary payload:
Client -> binary file -> Function URL
event.isBase64Encoded = true
event.body = base64(encoded)
| |
v v
Decode base64 -> process binary Encode response as base64
| |
v v
Correct processing Client receives binary

🔍 Behind the Question: Function URL binary payload, isBase64Encoded, base64 encode/decode, Content-Type.

❌ The Red Flags: Not checking isBase64Encoded; not decoding binary body; not encoding binary response.


Q302: Lambda + CloudWatch Logs — log groups and retention​

Level: Senior

Scenario: A team has 100 Lambda functions. Each creates a CloudWatch Logs group (/aws/lambda/function-name). Log retention is infinite. Storage cost grows unbounded.

Impact: High logging cost. Storage grows forever. No retention enforcement.

Root Cause: No log retention policy on Lambda log groups. Logs kept indefinitely.

Simple explanation: You keep every receipt you've ever gotten. Your wallet is full. You should throw away old ones.

Technical Answer:

  1. Set CloudWatch Logs retention on each Lambda log group (e.g., 30, 90, 365 days).
  2. Use AWS Resource Groups or Tag Editor to apply retention across all Lambda log groups.
  3. Use CloudFormation/ Terraform to set retention at deployment time.
  4. Monitor log storage cost in CloudWatch Logs or Cost Explorer.
  5. Consider S3 export for long-term archival (cheaper than CloudWatch Logs).

Code/Syntax Justification:

# Set retention on Lambda log group
logs = boto3.client('logs')
logs.put_retention_policy(
logGroupName='/aws/lambda/my-fn',
retentionInDays=30
)

Workflow Diagram:

No retention: Retention policy:
Logs kept forever /aws/lambda/my-fn -> 30 days -> delete
| |
v v
Storage cost grows unbounded Bounded cost, predictable

🔍 Behind the Question: CloudWatch Logs retention, log groups, log storage cost, log group naming convention.

❌ The RedFlags: Infinite log retention; no retention policy; not monitoring log storage cost.


Q303: Lambda function URL — custom domain vs API Gateway​

Level: Principal

Scenario: A team needs a custom domain (api.myapp.com) for their Lambda. Function URLs don't support custom domains. They need to decide between API Gateway custom domain or keeping Function URL with auto-generated URL.

Impact: Wrong choice affects branding, SSL, client configuration.

Root Cause: Function URLs don't support custom domains. Need API Gateway for branded URLs.

Simple explanation: You want your store at shop.myapp.com but only have store-123.square.site. You need API Gateway as the domain front.

Technical Answer:

  1. Use API Gateway (REST or HTTP) with custom domain name for branded URLs.
  2. API Gateway integrates with Lambda (Lambda proxy integration).
  3. Use ACM for SSL certificate on custom domain.
  4. Use Route 53 for DNS (alias record to API Gateway).
  5. Function URL can remain as internal/backup entry point with IAM auth.

Code/Syntax Justification:

# API Gateway custom domain + Lambda integration (CLI)
apigateway.create_domain_name(
domainName='api.myapp.com',
domainNameConfigurations=[{
'CertificateArn': 'arn:aws:acm:...:certificate/...',
'EndpointType': 'REGIONAL'
}]
)
# Base path mapping: domain/stage -> Lambda
apigateway.create_base_path_mapping(
domainName='api.myapp.com',
basePath='api',
restApiId='api-id',
stage='prod'
)

Workflow Diagram:

Function URL (auto-generated): API Gateway + custom domain:
https://abc.lambda-url.on.aws https://api.myapp.com
| |
v v
Unbranded, hard to remember Branded, professional, SSL

🔍 Behind the Question: Custom domain, API Gateway domain names, ACM certificates, Route 53, Function URL limitations.

❌ The RedFlags: Expecting custom domain on Function URL; not using API Gateway for branded URLs; no SSL certificate management.


Q304: Lambda + S3 event — multiple buckets​

Level: Senior

Scenario: A team has one Lambda function processing uploads from 3 different S3 buckets. They create 3 separate Lambda functions (one per bucket). Code is duplicated. Hard to maintain.

Impact: Code duplication. Maintenance burden. Inconsistent behavior.

Root Cause: One Lambda function per S3 bucket instead of one function handling multiple buckets.

Simple explanation: You have 3 mailboxes. You hire 3 people to check them. You should have 1 person check all 3.

Technical Answer:

  1. Configure one Lambda function as event source for multiple S3 buckets.
  2. Use event['Records'][0]['s3']['bucket']['name'] to identify the source bucket.
  3. Route logic based on bucket name or object key prefix.
  4. Update event source mapping for each bucket to point to the same Lambda function.
  5. Reduces code duplication and maintenance.

Code/Syntax Justification:

def handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
if bucket == 'bucket-a':
process_bucket_a(key)
elif bucket == 'bucket-b':
process_bucket_b(key)

Workflow Diagram:

3 Lambda functions (one per bucket): 1 Lambda function (multiple buckets):
Bucket A -> Lambda A Bucket A -> Lambda
Bucket B -> Lambda B ---> Bucket B -> Lambda
Bucket C -> Lambda C Bucket C -> Lambda
| |
v v
3 codebases, maintenance burden 1 codebase, route by bucket name

🔍 Behind the Question: S3 event source mapping, multiple buckets, event source mapping, code reuse.

❌ The RedFlags: One Lambda per S3 bucket; code duplication; not routing by bucket name in code.


Q305: Lambda function URL — invocation latency​

Level: Senior

Scenario: A team measures Lambda Function URL invocation latency. It's higher than expected (200-500ms for simple functions). They don't understand the components.

Impact: High latency. Poor UX. Can't meet SLAs.

Root Cause: Function URL latency includes DNS resolution, TLS handshake, AWS backend routing, Lambda cold/warm start, function execution. Not just function execution time.

Simple explanation: You measure how long it takes to get a pizza. It includes driving to the store, ordering, cooking, and driving back. Not just cooking time.

Technical Answer:

  1. Lambda function URL latency components: DNS + TLS + AWS backend + cold/warm start + execution.
  2. Cold start adds 100ms-10s depending on runtime and size.
  3. Use Provisioned Concurrency to eliminate cold start.
  4. Use Graviton2 (arm64) for faster execution.
  5. Monitor Duration (function execution) vs total latency (client-measured).
  6. Use Edge-optimized API Gateway or CloudFront for global edge locations if latency matters.

Code/Syntax Justification:

# Measure Lambda Duration (from CloudWatch)
# Duration metric = function execution time only
# Client-measured latency = DNS + TLS + network + Duration + response transfer

Workflow Diagram:

Client-measured latency:
DNS -> TLS -> AWS backend -> cold/warm start -> Duration -> response
| |
v v
Included in client latency Measured by CloudWatch Duration metric

🔍 Behind the Question: Function URL latency components, cold start, DNS/TLS, Duration metric, Provisioned Concurrency.

❌ The RedFlags: Comparing client latency to CloudWatch Duration; not accounting for cold start; not using Provisioned Concurrency for latency-sensitive functions.


Q306: Lambda + EventBridge — input transformer​

Level: Senior

Scenario: An EventBridge event has a complex structure. The Lambda function only needs 3 fields. The team passes the entire event to Lambda. The function parses what it needs.

Impact: Larger payloads. More parsing in Lambda. Coupling to event structure.

Simple explanation: You receive a whole newspaper when you only want the weather. You should clip just the weather section.

Technical Answer:

  1. Use EventBridge input transformer to map only needed fields to the Lambda input.
  2. Define InputPathsMap and InputTemplate in the event rule target.
  3. Lambda receives only the transformed input, not the full event.
  4. Reduces payload size and coupling to event structure.
  5. Event source mapping (SQS, Kinesis) doesn't support input transformer — use EventBridge rules instead.

Code/Syntax Justification:

# EventBridge rule with input transformer
events.put_rule(
Name='order-rule',
EventPattern='{"detail": {"order_type": ["premium"]}}'
)
events.put_targets(
Rule='order-rule',
Targets=[{
'Id': 'lambda-target',
'Arn': 'arn:aws:lambda:...:function:my-fn',
'InputTransformer': {
'InputPathsMap': {'order_id': '$.detail.order_id', 'amount': '$.detail.amount'},
'InputTemplate': '{"order_id": <order_id>, "amount": <amount>}'
}
}]
)

Workflow Diagram:

Full event: Input transformer:
EventBridge -> full event -> Lambda EventBridge -> transformed input -> Lambda
| |
v v
Lambda parses full event Lambda receives only needed fields
| |
v v
Coupled to event structure Decoupled from event structure

🔍 Behind the Question: EventBridge input transformer, input paths map, input template, payload reduction, decoupling.

❌ The RedFlags: Passing full event when only needed fields; not using input transformer; Lambda coupled to event structure.


Senior / Principal — AWS Lambda Real World Scenarios (Continued)​

Q307: Lambda + API Gateway — mapping templates vs Lambda proxy​

Level: Senior

Scenario: A team uses API Gateway REST API with VTL mapping templates to transform requests before Lambda. The templates are complex and hard to debug. They want to simplify.

Impact: Complex maintenance. VTL hard to debug. Transformation logic not in code.

Root Cause: Using API Gateway mapping templates instead of Lambda proxy integration.

Simple explanation: You translate a letter through a middleman who uses a secret code. You should translate it yourself in a language you know.

Technical Answer:

  1. Use Lambda proxy integration — API Gateway passes the full request event to Lambda.
  2. Handle parsing, validation, transformation in Lambda code (Python/Node.js) — easier to test and debug.
  3. API Gateway handles routing, auth, throttling — not transformation.
  4. VTL mapping templates are legacy; Lambda proxy is the modern approach.
  5. Response: Lambda returns full HTTP response (statusCode, headers, body) — API Gateway passes through.

Code/Syntax Justification:

# Lambda proxy integration - receives full request event
def handler(event, context):
body = json.loads(event.get('body', '{}'))
headers = event.get('headers', {})
result = process(body, headers)
return {'statusCode': 200, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps(result)}

Workflow Diagram:

VTL mapping templates: Lambda proxy integration:
API Gateway transforms via VTL API Gateway -> Lambda (direct, full event)
| |
v v
Hard to debug, VTL Transform in Python (testable, versioned)
| |
v v
Complex maintenance Simple, code-based transformation

🔍 Behind the Question: API Gateway mapping templates vs Lambda proxy, VTL, request/response transformation, Lambda proxy integration.

❌ The RedFlags: Complex VTL mapping templates; not using Lambda proxy; transformation logic in API Gateway not code.


Q308: Lambda + Step Functions — service integration vs Lambda invoke​

Level: Senior

Scenario: A Step Functions state machine invokes Lambda functions directly for each task. Some tasks could be AWS service integrations (S3 put, DynamoDB put, SQS send) without Lambda. They use Lambda for everything.

Impact: Unnecessary Lambda invocations. Higher cost. More code to maintain.

Root Cause: Not using Step Functions service integrations for simple AWS service calls.

Simple explanation: You hire a person to move a file from one folder to another. You should just move it yourself — no person needed.

Technical Answer:

  1. Use Step Functions service integrations for: S3 (PutObject, GetObject), DynamoDB (PutItem, GetItem, UpdateItem), SQS (SendMessage), SNS (Publish), Batch (SubmitJob), ECS (RunTask).
  2. Service integrations run natively — no Lambda code, no Lambda cost.
  3. Use Lambda only for custom logic (transformations, decisions, calls to non-AWS services).
  4. Reduces cost (no Lambda invocation for simple operations) and complexity.
  5. Service integrations support .waitForTaskToken pattern for callback patterns.

Code/Syntax Justification:

// Step Functions - S3 PutObject service integration (no Lambda)
{
"StartAt": "PutObject",
"States": {
"PutObject": {
"Type": "Task",
"Resource": "arn:aws:states:::s3:putObject",
"Parameters": {
"Bucket.$": "$.bucket",
"Key.$": "$.key",
"Body.$": "$.body"
},
"End": true
}
}
}

Workflow Diagram:

Lambda for everything: Service integrations:
Lambda -> S3 PutObject Step Functions -> S3 PutObject (direct)
| |
v v
Lambda cost + code No Lambda cost, native AWS integration
| |
v v
More to maintain Less code, lower cost

🔍 Behind the Question: Step Functions service integrations, S3/DynamoDB/SQS/SNS direct integration, Lambda vs service integration, cost optimization.

❌ The RedFlags: Using Lambda for simple AWS service calls; not using service integrations; more Lambda cost than necessary.


Q309: Lambda function URL — query string size limit​

Level: Senior

Scenario: A team sends a large query string to a Lambda Function URL. The request fails. Function URL has query string size limits.

Impact: Request fails. Data not processed. Client errors.

Root Cause: Function URL has limits on query string size (part of the 6MB request payload limit for buffered, but query string specifically constrained).

Simple explanation: You try to write a long address on a small envelope. It doesn't fit. You need a bigger envelope (body) or streaming.

Technical Answer:

  1. Function URL request payload limit: 6MB (buffered) — includes query string, headers, body.
  2. For large data, use request body (POST/PUT) instead of query string.
  3. Query string is suitable for small parameters (IDs, filters, pagination).
  4. Use POST with JSON body for large or complex input.
  5. Consider API Gateway if larger request limits needed (API Gateway REST: 10MB).

Code/Syntax Justification:

# Bad: large data in query string
GET /process?data=VERY_LONG_BASE64_STRING...

# Good: data in body
POST /process
Content-Type: application/json
{"data": "VERY_LONG_BASE64_STRING", "options": {...}}

Workflow Diagram:

Query string for large data: Request body for large data:
GET /process?data=huge... POST /process {data: huge}
| |
v v
Fails (too long) Succeeds

🔍 Behind the Question: Function URL request payload limit, query string vs body, size limits, API Gateway comparison.

❌ The RedFlags: Large data in query string; hitting 6MB request limit; not using POST body for large data.


Q310: Lambda + CloudWatch — custom metrics​

Level: Senior

Scenario: A team wants to track custom business metrics (orders per minute, conversion rate) from Lambda. They don't know how to emit custom CloudWatch metrics.

Impact: No visibility into business metrics. Can't alert on business issues.

Root Cause: Not using CloudWatch PutMetricData from Lambda.

Simple explanation: You want to track sales but only measure server CPU. You're measuring the wrong thing.

Technical Answer:

  1. Use CloudWatch PutMetricData from Lambda to emit custom metrics (orders, conversion rate, revenue, error types).
  2. Use metric dimensions (service, environment, error_type) for filtering.
  3. Be careful with PutMetricData cost — batch metrics, don't put one call per invocation.
  4. Use CloudWatch Embedded Metric Format (EMF) for structured logging with metrics — more efficient than PutMetricData API calls.
  5. Create alarms on custom metrics for business issues.

Code/Syntax Justification:

# Embedded Metric Format (EMF) - more efficient than PutMetricData API
import json
print(json.dumps({
"_aws": {
"Timestamp": datetime.utcnow().timestamp() * 1000,
"CloudWatchMetrics": [{"Namespace": "MyApp", "Dimensions": [["service"]], "Metrics": [{"Name": "Orders", "Unit": "Count"}]}],
"service": "orders"
},
"Orders": 1,
"ConversionRate": 0.05
}))

Workflow Diagram:

PutMetricData API: Embedded Metric Format (EMF):
API call per metric Log JSON with embedded metrics
| |
v v
Higher API cost Lower cost, structured logging

🔍 Behind the Question: CloudWatch custom metrics, PutMetricData, EMF, metric dimensions, business metrics vs infrastructure metrics.

❌ The RedFlags: PutMetricData per invocation (high cost); not using EMF; no business metrics; only infrastructure metrics.


Q311: Lambda function URL — HTTP methods​

Level: Senior

Scenario: A team creates a Lambda Function URL. It only supports GET and POST by default. They need to support PUT, DELETE, PATCH for a REST API.

Impact: Can't support all HTTP methods. API incomplete.

Root Cause: Function URL supports all HTTP methods but the team may not realize they need to handle them in code.

Simple explanation: You have a door that opens both ways, but you only use it to enter. You can exit too — you just need to push instead of pull.

Technical Answer:

  1. Function URL supports all HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS).
  2. The event['httpMethod'] field tells the function which method was used.
  3. Route logic in Lambda based on httpMethod + event['path'].
  4. Handle OPTIONS preflight for CORS if using browser clients.
  5. API Gateway provides more method-based routing out of the box; Function URL requires code-based routing.

Code/Syntax Justification:

def handler(event, context):
method = event.get('httpMethod')
path = event.get('path')
if method == 'GET' and path == '/users':
return list_users()
elif method == 'POST' and path == '/users':
return create_user(event)
elif method == 'PUT' and path.startswith('/users/'):
return update_user(path, event)
elif method == 'DELETE' and path.startswith('/users/'):
return delete_user(path)
return {'statusCode': 405, 'body': 'Method not allowed'}

Workflow Diagram:

Function URL HTTP methods:
Client -> GET /users -> Lambda
event.httpMethod = 'GET', event.path = '/users'
| |
v v
Route by method + path Return appropriate response

🔍 Behind the Question: Function URL HTTP methods, httpMethod field, method-based routing, OPTIONS preflight, CORS.

❌ The RedFlags: Not handling all needed HTTP methods; not routing by httpMethod; not handling OPTIONS for CORS.


Q312: Lambda + EventBridge — cross-account events​

Level: Principal

Scenario: Team A (Account A) produces events. Team B (Account B) consumes them via Lambda. Cross-account event delivery doesn't work.

Impact: Cross-account event delivery fails. Team B can't process Team A's events.

Root Cause: EventBridge event bus doesn't have permissions for Account B. No cross-account event bus configuration.

Simple explanation: You send a letter to another company. Their mailroom rejects it because they don't accept mail from outside.

Technical Answer:

  1. Use EventBridge cross-account event bus — Account A puts events to its bus, Account B's event bus has a rule to receive from Account A's bus.
  2. Configure PutPermission on Account A's event bus allowing Account B.
  3. Account B creates an event bus rule with EventPattern matching Account A's events.
  4. Account B's Lambda subscribes to its own event bus rule.
  5. Use events:PutEvents cross-account permissions in IAM.

Code/Syntax Justification:

# Account A: put permission for Account B
events.put_permission(
EventBusName='default',
Action='events:PutEvents',
Principal='B_ACCOUNT_ID',
StatementId='allow-B'
)

# Account B: rule to receive from Account A
events.put_rule(
Name='receive-from-A',
EventPattern='{"source": ["myapp.order"], "detail-type": ["OrderPlaced"]}'
)

Workflow Diagram:

Cross-account events:
Account A (put events) -> EventBridge -> Account B (receive -> Lambda)
| |
v v
Permission needed (PutPermission) Rule matches events from A
| |
v v
Events delivered cross-account Lambda processes events

🔍 Behind the Question: EventBridge cross-account, PutPermission, event bus rules, cross-account event delivery.

❌ The RedFlags: No cross-account permission; not configuring event bus rules; assuming same-account only.


Q313: Lambda function URL — request/response size limits​

Level: Senior

Scenario: A team sends a 5MB request to a Lambda Function URL. It fails. They don't know the size limits.

Impact: Request fails. Data not processed.

Root Cause: Function URL request/response payload limits (6MB buffered request+response, 20MB streaming response).

Simple explanation: You try to send a 5MB file through a 6MB envelope. It barely fits but with headers it exceeds the limit.

Technical Answer:

  1. Function URL request limit: 6MB (request body + headers + query string, buffered).
  2. Function URL response limit: 6MB buffered, 20MB streaming.
  3. For requests >6MB, use S3 for large payloads or API Gateway (10MB request limit).
  4. For responses >6MB, use response streaming (20MB) or S3 presigned URL.
  5. Compress request/response (gzip) to reduce size.

Code/Syntax Justification:

# Check request size
if len(event.get('body', '')) > 5 * 1024 * 1024:
return {'statusCode': 413, 'body': 'Request too large'}

Workflow Diagram:

Request size limits:
6MB buffered (request + response) 20MB streaming (response only)
| |
v v
Use S3 for >6MB requests Use streaming for >6MB responses

🔍 Behind the Question: Function URL payload limits (6MB buffered, 20MB streaming), request/response size, S3 for large payloads, compression.

❌ The RedFlags: Not knowing size limits; sending >6MB requests without S3; not using streaming for large responses.


Q314: Lambda + API Gateway — usage plans and API keys​

Level: Senior

Scenario: A team wants to rate-limit API customers and charge them based on usage. API Gateway doesn't have built-in usage plans for Function URL.

Impact: No usage metering. No rate limiting per customer. Can't monetize API.

Root Cause: Function URL doesn't support usage plans or API keys. API Gateway does.

Simple explanation: You want to charge customers per API call. Function URL doesn't have a cash register. API Gateway does.

Technical Answer:

  1. Use API Gateway (REST or HTTP) with usage plans and API keys for metering and rate limiting.
  2. Usage plans: set rate (requests per second) and burst quota per API key.
  3. API keys: customers include x-api-key header; API Gateway tracks usage per key.
  4. Function URL: no usage plans — implement rate limiting in function code (Redis counter) or use WAF.
  5. Choose API Gateway if monetization/usage metering needed; Function URL if simple invoke.

Code/Syntax Justification:

# API Gateway usage plan (CLI)
apigateway.create_usage_plan(
name='my-plan',
apiStages=[{'apiId': 'api-id', 'stage': 'prod'}],
quota={'limit': 10000, 'period': 'MONTH'},
throttle={'rateLimit': 100, 'burstLimit': 200}
)

Workflow Diagram:

Function URL: API Gateway with usage plan:
No usage plans Usage plan -> rate limit + quota per API key
| |
v v
No metering Per-customer metering and billing

🔍 Behind the Question: API Gateway usage plans, API keys, rate limiting, Function URL limitations, monetization.

❌ The RedFlags: Expecting usage plans on Function URL; not using API Gateway for metered APIs; no rate limiting at all.


Q315: Lambda function URL — regional vs edge-optimized​

Level: Senior

Scenario: A team deploys a Lambda Function URL in us-east-1. Users in Europe experience high latency (200ms+). They want to reduce latency for global users.

Impact: High latency for distant users. Poor global UX.

Root Cause: Function URLs are regional — deployed in one AWS region. Users far from that region have higher latency.

Simple explanation: You open a shop in New York. Customers in London wait for shipping. You should open shops in London too (or use a CDN).

Technical Answer:

  1. Function URLs are regional — deployed in one region.
  2. For global users, use Amazon CloudFront in front of Function URL (edge locations) or API Gateway (edge-optimized endpoint).
  3. CloudFront caches responses at edge locations, reducing latency for repeat requests.
  4. Use API Gateway edge-optimized endpoint (CloudFront-managed) for global API access.
  5. Consider deploying the function in multiple regions for write-heavy global workloads.

Code/Syntax Justification:

# CloudFront distribution pointing to Function URL origin
cloudfront.create_distribution(
DistributionConfig={
'Origins': [{
'Id': 'function-url-origin',
'DomainName': 'abc.lambda-url.us-east-1.on.aws',
'CustomOriginConfig': {'OriginProtocolPolicy': 'https-only'}
}],
'DefaultCacheBehavior': {
'TargetOriginId': 'function-url-origin',
'ViewerProtocolPolicy': 'https-only'
}
}
)

Workflow Diagram:

Regional Function URL: CloudFront edge:
User in Europe -> us-east-1 (200ms) User in Europe -> edge location (20ms)
| |
v v
High latency Low latency (cached at edge)

🔍 Behind the Question: Function URL regional limitation, CloudFront edge locations, API Gateway edge-optimized, multi-region deployment, latency.

❌ The RedFlags: Expecting global low latency from single-region Function URL; not using CloudFront for global users; not deploying multi-region for writes.


Q316: Lambda — summary decision framework​

Level: Principal

Scenario: A team needs to choose the right AWS compute service for a new workload: Lambda, ECS, EKS, EC2, or Fargate. They don't know the decision criteria.

Impact: Wrong compute choice. Over-provisioning or under-provisioning. Higher cost or poor performance.

Root Cause: No decision framework. Choosing based on familiarity not requirements.

Simple explanation: Buying a vehicle without knowing if you need a bicycle, car, truck, or semi-truck.

Technical Answer:

  1. Decision framework:
    • Lambda: event-driven, short-lived (<15 min), variable traffic, no server management, pay per invocation.
    • Fargate: containerized, longer-running, predictable traffic, no server management, pay per vCPU/memory.
    • ECS/EKS: containerized, complex orchestration, need control over infrastructure, long-running.
    • EC2: full control, legacy apps, specific OS/license needs, long-running, predictable.
  2. Key decision factors: execution duration, traffic pattern, container vs serverless, operational overhead, cost model, compliance.
  3. Can combine: Lambda for event handling, ECS/EKS for long-running services, EC2 for specialized workloads.
  4. Document decision criteria and revisit as requirements change.

Code/Syntax Justification:

# Decision matrix (pseudo-code)
if execution_time < 15_min and event_driven:
use LAMBDA
elif containerized and no_server_mgmt:
use FARGATE
elif containerized and need_control:
use ECS or EKS
elif need_full_control or legacy:
use EC2

Workflow Diagram:

Decision framework:
Event-driven, <15 min -> Lambda
Containerized, no server mgmt -> Fargate
Containerized, need control -> ECS/EKS
Full control, legacy -> EC2
| |
v v
Choose based on requirements, not familiarity

🔍 Behind the Question: Compute service decision, Lambda vs Fargate vs ECS/EKS vs EC2, execution duration, event-driven, operational overhead.

❌ The RedFlags: Choosing based on familiarity not requirements; Lambda for long-running (>15 min) workloads; EC2 for simple event-driven workloads.