오류 처리와 재시도
복원력 있는 서버리스 애플리케이션을 위해 견고한 오류 처리, 배달 못한 편지 대기열, 재시도 메커니즘을 구현합니다.
오류 처리와 재시도은(는) CoddyKit의 무료 Serverless Backend with AWS Lambda & API Gateway 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Serverless Backend with AWS Lambda & API Gateway 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Serverless Backend with AWS Lambda & API Gateway 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Build Resilient Serverless Apps
In serverless architectures, things can go wrong. Network issues, service outages, or bugs in your code can all lead to failures.
Building resilient applications means they can recover gracefully from these issues, minimizing impact on users and preventing data loss. Error handling and retries are key to this.
Lambda Invocation Types
How Lambda handles errors and retries depends on how your function is invoked. There are two main types:
- Synchronous: The caller waits for a response (e.g., API Gateway, ALB).
- Asynchronous: The caller doesn't wait; Lambda queues the event (e.g., S3, SNS, SQS, EventBridge).
Each type has different retry behaviors by default.
Synchronous Invocation Retries
When a Lambda function is invoked synchronously and returns an error (or times out), Lambda does NOT automatically retry the function.
It's up to the service or client that invoked Lambda (e.g., API Gateway, your mobile app) to implement its own retry logic. Lambda simply passes the error back to the caller.
Asynchronous Invocation Retries
For asynchronous invocations, Lambda has built-in retry mechanisms. If your function fails due to an unhandled error or times out, Lambda will automatically retry the invocation twice.
This means a total of three attempts (initial + two retries) are made, with an exponential backoff between retries. This helps overcome transient issues.
Handling Errors in Code
Beyond Lambda's automatic retries, you should always implement error handling *within* your function code. This allows you to:
- Gracefully manage expected errors (e.g., missing input).
- Log specific details for debugging.
- Return custom error messages to callers.
In Python, the try-except block is your best friend for this.
Python Error Handling Example
This Python Lambda function uses try-except to handle potential KeyError if an expected key is missing, or ZeroDivisionError if a value is zero. Try running it with different inputs!
import json
def lambda_handler(event, context):
try:
# Expecting 'value' key in the event
num = event['value']
result = 100 / num
return {
'statusCode': 200,
'body': json.dumps(f'Result: {result}')
}
except KeyError:
print("Error: 'value' key missing in event.")
return {
'statusCode': 400,
'body': json.dumps('Input Error: Missing \'value\' in event.')
}
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
return {
'statusCode': 400,
'body': json.dumps('Input Error: Cannot divide by zero.')
}
except Exception as e:
print(f"An unexpected error occurred: {e}")
return {
'statusCode': 500,
'body': json.dumps(f'Server Error: {str(e)}')
}
# Example of how to run locally for testing
if __name__ == "__main__":
# Test case 1: Missing key
print("\n--- Test Case 1 (Missing Key) ---")
print(lambda_handler({}, None))
# Test case 2: Zero division
print("\n--- Test Case 2 (Zero Division) ---")
print(lambda_handler({'value': 0}, None))
# Test case 3: Success
print("\n--- Test Case 3 (Success) ---")
print(lambda_handler({'value': 25}, None))
# Test case 4: Non-numeric value (unhandled, falls to generic exception)
print("\n--- Test Case 4 (Type Error) ---")
print(lambda_handler({'value': 'abc'}, None))Dead-Letter Queues (DLQs)
What happens if an asynchronous Lambda invocation fails even after all retries? This is where Dead-Letter Queues (DLQs) come in!
A DLQ is an Amazon SQS queue or SNS topic where Lambda sends events it couldn't process successfully after all retry attempts. It's a crucial mechanism for:
- Preventing data loss.
- Debugging persistent issues.
- Manual reprocessing of failed events.
Configuring a DLQ
To set up a DLQ for your Lambda function:
- Create an SQS queue or SNS topic: This will be your DLQ.
- Grant Permissions: Ensure your Lambda function has permission to publish messages to the chosen SQS queue or SNS topic.
- Configure Lambda: In your Lambda function's configuration (under 'Asynchronous invocation'), specify the ARN of your SQS queue or SNS topic as the DLQ.
This ensures failed events have a safe landing spot.
DLQ Behavior in Action
It's important to understand *when* an event is sent to a DLQ:
- Only for asynchronous invocations.
- After all automatic retry attempts (initial + two retries) have failed.
- If the event's maximum age is exceeded, or the maximum retry attempts are exhausted.
The original event payload, along with some metadata, is sent to the DLQ.
DLQ Understanding
Let's check your understanding of Dead-Letter Queues!
Recap: Error Handling & Retries
You've learned how to make your serverless applications more robust!
- Synchronous vs. Asynchronous: Different invocation types have different default retry behaviors.
- In-code Error Handling: Use
try-exceptto catch and manage errors within your Lambda code. - Dead-Letter Queues (DLQs): A critical mechanism for capturing and inspecting events that fail after all automatic retries, preventing data loss for async invocations.
These practices are essential for building reliable serverless systems!
자주 묻는 질문
“오류 처리와 재시도” 강의는 무료인가요?
네 — “오류 처리와 재시도” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Serverless Backend with AWS Lambda & API Gateway 강의 전체를 잠금 해제할 수 있습니다. Serverless Backend with AWS Lambda & API Gateway 강의에는 총 4개의 강의가 포함되어 있습니다.
“오류 처리와 재시도”에서 뭘 배우나요?
복원력 있는 서버리스 애플리케이션을 위해 견고한 오류 처리, 배달 못한 편지 대기열, 재시도 메커니즘을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Serverless Backend with AWS Lambda & API Gateway을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Serverless Backend with AWS Lambda & API Gateway을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Serverless Backend with AWS Lambda & API Gateway은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“오류 처리와 재시도” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Serverless Backend with AWS Lambda & API Gateway 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Serverless Backend with AWS Lambda & API Gateway 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.