How do you handle errors and retries in serverless functions?
Answer
Error handling strategy depends on invocation type: (1) Synchronous (API Gateway) — return appropriate HTTP status codes; use try-catch and return structured error responses: { statusCode: 400, body: JSON.stringify({ error: 'Invalid input' }) }; (2) Asynchronous (S3, SNS) — Lambda retries twice with delay; configure DLQ for failed events; write idempotent handlers to handle retries safely; (3) SQS-triggered — return without throwing to acknowledge; throw to return message to queue for retry; configure SQS Dead Letter Queue with maxReceiveCount; use batch item failures to partially succeed: return { batchItemFailures: [{ itemIdentifier: msg.messageId }] } to retry only failed items; (4) Retry with exponential backoff — for SDK calls to external services, use AWS SDK's built-in retry logic or implement custom backoff; (5) Circuit breaker — implement circuit breaker pattern to stop calling failing external services. Key principle: all asynchronous handlers must be idempotent — safe to process the same event multiple times without side effects (duplicate charges, duplicate records).
Previous
What is provisioned concurrency in AWS Lambda?
Next
What is the event source mapping in AWS Lambda?
More Serverless Architecture Questions
View all →- Intermediate How do you reduce cold start latency in serverless functions?
- Intermediate What is AWS Step Functions and when would you use it?
- Intermediate How do you handle state in serverless applications?
- Intermediate What is the Serverless Framework and how does it work?
- Intermediate How do you implement authentication in a serverless API?