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).