Troubleshooting and Optimization

271 questions

Question 141Question

A developer is troubleshooting an AWS Lambda function that processes large CSV data exports uploaded to an Amazon S3 bucket. The function is currently configured with 256 MB256\text{ MB} of memory and a timeout of 10 seconds10\text{ seconds}. During initial testing with small files, the function executes successfully. However, when processing larger files, the function consistently fails, and Amazon CloudWatch Logs show a `Task timed out after 10.00 seconds` error. Which action should the developer take to resolve this execution timeout issue?

Show answer & explanation

Answer: Increase the Lambda function's timeout configuration to allow more execution time, and allocate more memory to proportionally scale the CPU performance.

Answer

Increase the Lambda function's timeout configuration to allow more execution time, and allocate more memory to proportionally scale the CPU performance.
The correct action is to increase the Lambda function's timeout setting and allocate additional memory. Increasing the timeout directly extends the allowed run time of the function. Additionally, since AWS Lambda allocates CPU power proportionally to the configured memory size, increasing the memory allocation will speed up CPU-bound tasks like file parsing, preventing the function from timing out.

Step-by-Step Solution

1
Analyze the error message from CloudWatch Logs.
The log message `Task timed out after 10.00 seconds` indicates the function is hitting its configured execution time limit before completing the CSV processing.
Identifying the root cause as a timeout configuration limit is necessary before selecting the correct remediation strategy.
2
Evaluate the resource demands of the processing logic.
Processing larger files requires both more time and more compute power. In AWS Lambda, CPU performance scales proportionally with the allocated memory.
Understanding that increasing memory provides more CPU resources helps optimize processing speed for CPU-bound tasks like parsing CSV files.
3
Adjust the Lambda configuration settings.
Increasing the timeout limit beyond 10 seconds10\text{ seconds} and increasing the memory configuration beyond 256 MB256\text{ MB} allows the function to complete successfully.
This dual adjustment ensures the execution environment has both the raw computing power and the time limit necessary to handle larger payloads.

Key Concept

AWS Lambda resource allocation and execution limits
Estimated Time:1m 30s
Question 142Question

A developer is configuring an AWS CodePipeline with an AWS CodeDeploy stage to deploy a containerized application to an Amazon ECS service using a blue/green deployment strategy. The deployment fails. The developer observes two issues:
1. The CodeDeploy deployment fails immediately with an error indicating an invalid AppSpec file configuration, where the developer specified `BeforeInstall` and `AfterInstall` lifecycle hooks.
2. The ECS tasks fail to start because they cannot download the application configuration file from an Amazon S3 bucket, despite the developer having attached the S3 read permissions to the ECS Task Execution Role.

Which two actions should the developer take to resolve these deployment issues? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Replace the `BeforeInstall` and `AfterInstall` lifecycle hooks in the AppSpec file with `BeforeAllowTraffic` and `AfterAllowTraffic` hooks.; Move the S3 read permission policy from the ECS Task Execution Role to the ECS Task Role.

Answer

Replace the `BeforeInstall` and `AfterInstall` hooks with `BeforeAllowTraffic` and `AfterAllowTraffic`, and move the S3 read permission policy from the ECS Task Execution Role to the ECS Task Role.
The correct options modify the AppSpec hooks to use ECS-supported lifecycle hooks (`BeforeAllowTraffic` and `AfterAllowTraffic`) and assign S3 read permissions to the ECS Task Role, which is the role that containerized applications use to access AWS resources.

Step-by-Step Solution

1
Analyze the AppSpec lifecycle hook failure.
Identify that `BeforeInstall` and `AfterInstall` hooks are specific to EC2/On-Premises CodeDeploy deployments.
ECS deployments use specific hooks like `BeforeAllowTraffic` and `AfterAllowTraffic` for running lifecycle validation Lambda functions.
2
Analyze the Amazon S3 access failure from within the ECS tasks.
Determine that the application running inside the container needs permissions to access S3.
Permissions for containerized applications must be attached to the ECS Task Role, whereas the ECS Task Execution Role is for container agent operations like pulling images from ECR.
3
Select the correct combination of fixes.
The option to use ECS-supported hooks and the option to use the correct Task Role for S3 access are selected.
These steps address the invalid AppSpec structure and the permission mismatch.

Key Concept

Understanding ECS Task Roles vs Task Execution Roles, and ECS-specific CodeDeploy AppSpec lifecycle hooks.
Question 143Question

An application deployed on Amazon EC2 instances streams its log files to an Amazon CloudWatch Logs log group named `/aws/ec2/app-logs` using the Unified CloudWatch Agent. The application logs are structured as JSON objects, with the following format:

{
"timestamp": "2026-07-14T10:00:00Z",
"status": "FAIL",
"errorCode": 401,
"latency_ms": 150
}

A developer needs to configure a CloudWatch metric filter to track the number of failed login attempts where the `status` is `"FAIL"` and the `errorCode` is `401`. Additionally, the developer needs to run a CloudWatch Logs Insights query to find the 90th percentile of `latency_ms` for these specific failed login events, grouped into 15-minute intervals over the last 24 hours.

Which two options should the developer use to accomplish these tasks? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: A CloudWatch metric filter with the pattern `{ .status = "FAIL" && .errorCode = 401 }` to track the occurrences of failed logins; A CloudWatch Logs Insights query:

fields @timestamp, latency_ms
| filter status = "FAIL" and errorCode = 401
| stats pct(latency_ms, 90) by bin(15m)

Answer

The correct configurations are the metric filter with the pattern `{ .status = "FAIL" && .errorCode = 401 }` and the CloudWatch Logs Insights query that uses the `pct(latency_ms, 90)` function grouped `by bin(15m)`.
The correct metric filter configuration uses the correct JSON filter syntax `{ .status = "FAIL" && .errorCode = 401 }` to inspect JSON log properties. The correct CloudWatch Logs Insights query filters for the failed status and error code, then uses the `pct()` function to find the 90th percentile of latency grouped in 15-minute intervals using `by bin(15m)`.

Step-by-Step Solution

1
Analyze the JSON log format to identify the property names: status, errorCode, and latency_ms.
Identified the target JSON paths as .status,.status, .errorCode, and $.latency_ms.
Metric filters for JSON logs require referencing properties using the $. notation.
2
Construct the CloudWatch Logs metric filter pattern to match failed logins.
Created the pattern `{ .status = "FAIL" && .errorCode = 401 }`.
JSON metric filters must be enclosed in curly braces and use comparison/logical operators to evaluate JSON properties.
3
Construct the CloudWatch Logs Insights query to calculate the 90th percentile of latency grouped by 15-minute intervals.
Created the query `fields @timestamp, latency_ms | filter status = "FAIL" and errorCode = 401 | stats pct(latency_ms, 90) by bin(15m)`.
CloudWatch Logs Insights queries use the pct() or percentiles() function to calculate percentiles and by bin() for grouping time intervals.

Key Concept

CloudWatch Logs Metric Filter syntax for structured JSON logs and CloudWatch Logs Insights query syntax for calculating percentiles.
Estimated Time:2m 0s
Question 144Question

A developer is updating an existing AWS CloudFormation stack. The update fails due to a configuration error in a new resource, and the stack rolls back to its last known stable state, transitioning to the `UPDATE_ROLLBACK_COMPLETE` status. The developer corrects the error in the template.

Which action should the developer take to successfully deploy the corrected template changes?

Show answer & explanation

Answer: Apply the corrected template to the existing stack by running a new update operation.

Answer

Apply the corrected template to the existing stack by running a new update operation.
Applying the corrected template directly to the existing stack is the correct path forward because when an update fails and rolls back, the stack is in the UPDATE_ROLLBACK_COMPLETE state. This state is stable and allows direct update operations to be executed.

Step-by-Step Solution

1
Analyze the stack status and find that it is in the UPDATE_ROLLBACK_COMPLETE state.
The stack is confirmed to be in a stable, active state after a failed update, rather than a failed initial creation.
Determining the stack state is crucial because UPDATE_ROLLBACK_COMPLETE stacks can be updated directly, whereas ROLLBACK_COMPLETE stacks from initial creation must be deleted.
2
Resolve the configuration error in the template or parameters locally.
A valid, corrected template is ready for deployment.
The deployment failed due to a configuration error, so the root cause must be corrected before initiating another update.
3
Initiate a new stack update operation using the corrected template.
The update is executed against the existing stack, applying only the necessary resource changes.
Running a stack update directly on the existing stack avoids the downtime and overhead of recreation.

Key Concept

Handling failed CloudFormation stack updates and understanding the UPDATE_ROLLBACK_COMPLETE state.
Estimated Time:1m 0s
Question 145Question

A developer is troubleshooting an AWS Lambda function that processes transaction data from an Amazon Kinesis Data Stream. The Lambda function is configured with a timeout of 1010 seconds. The developer notices that the Kinesis stream's `GetRecords.IteratorAgeMilliseconds` metric is steadily increasing, and the same transaction records are appearing multiple times in the application logs. The Lambda function's CloudWatch logs indicate that some invocations are terminated after running for 1010 seconds. Which configuration change should the developer make to resolve this issue?

Show answer & explanation

Answer: Increase the timeout of the Lambda function and decrease the BatchSize in the Kinesis event source mapping.

Answer

Increase the timeout of the Lambda function and decrease the BatchSize in the Kinesis event source mapping.
Increasing the Lambda function's timeout configuration allows the function more time to process the batch of records before being terminated. Decreasing the BatchSize reduces the number of records Lambda retrieves in a single invocation, decreasing the total processing time per invocation. Together, these actions ensure that the Lambda function can successfully process each batch within the timeout limit, preventing execution terminations, retries of the same batch, duplicate processing, and a rising IteratorAgeMilliseconds metric.

Step-by-Step Solution

1
Analyze the symptoms from CloudWatch Metrics and logs.
The increasing `IteratorAgeMilliseconds` shows the consumer is falling behind the stream. Invocations terminating at 1010 seconds indicate execution timeouts, which cause the Lambda service to retry the same batch, leading to duplicate processing.
Identifying that the Lambda function is timing out while processing a full batch explains why records are processed repeatedly without advancing the stream pointer.
2
Adjust the Lambda configuration to ensure batches complete within the timeout limits.
Increasing the timeout parameter gives the function more execution headroom. Decreasing the batch size (e.g., from 100100 to 5050 records) reduces the processing time required for each individual invocation.
By resolving the timeout, executions complete successfully, allowing the Lambda service to commit the shard checkpoint and decrease the iterator age.

Key Concept

Lambda integration with Kinesis Data Streams and execution timeout handling
Estimated Time:1m 30s
Question 146Question

A developer is building a worker application running on Amazon ECS with Fargate. The application polls an Amazon SQS queue for messages, downloads the referenced files from Amazon S3, and writes processing metadata to an Amazon DynamoDB table. The ECS task role has the AWSXRayDaemonWriteAccess IAM policy attached, and the X-Ray daemon runs as a sidecar container in the task definition. Although trace segments for S3 and DynamoDB calls are generated, they appear as separate, disconnected traces in the AWS X-Ray console, and the relationship between the SQS message producer and the worker application's processing activities is not correlated. Which two actions must the developer take to resolve this issue and achieve end-to-end distributed tracing?

Select all that apply

Show answer & explanation

Answer: Extract the AWS X-Ray trace header from the SQS message system attributes in the worker application, and use the SDK to create a segment context using that header as the parent.; Instrument the AWS SDK clients for S3 and DynamoDB within the worker application code using the AWS X-Ray SDK.

Answer

To resolve the disconnected tracing issue, the developer must extract the AWS X-Ray trace header from the SQS message system attributes to propagate the parent tracing context, and instrument the S3 and DynamoDB SDK clients using the AWS X-Ray SDK to capture downstream requests.
The correct actions involve manually extracting the parent trace context from the SQS message system attributes to bridge the tracing gap across the queue, and instrumenting the AWS SDK clients (S3 and DynamoDB) using the AWS X-Ray SDK to record outgoing service calls.

Step-by-Step Solution

1
Extract the trace header from SQS messages.
The application retrieves the parent trace ID from the message metadata.
This establishes trace context propagation from the producer to the consumer.
2
Initialize the X-Ray SDK segment using the extracted trace header.
The worker application starts a segment nested under the producer's trace.
This links the SQS message production and the message consumption into a single distributed trace.
3
Instrument the AWS SDK clients for S3 and DynamoDB.
Calls to S3 and DynamoDB are captured as subsegments.
This allows X-Ray to record downstream service calls and link them back to the active tracing segment.

Key Concept

Distributed tracing correlation across asynchronous boundaries (SQS) and downstream SDK client instrumentation with AWS X-Ray.
Question 147Question

A developer has enabled active tracing on an AWS Lambda function. The function calls an external web service using a standard HTTP client library. In the AWS X-Ray console, the trace map displays the Lambda function execution segment, but the downstream HTTP calls to the external web service are missing from the trace. What should the developer do to include the downstream HTTP calls in the X-Ray trace map?

Show answer & explanation

Answer: Instrument the HTTP client library inside the application code using the AWS X-Ray SDK.

Answer

Instrument the HTTP client library inside the application code using the AWS X-Ray SDK.
To trace downstream HTTP calls, the developer must instrument the HTTP client library using the AWS X-Ray SDK. This instrumentation dynamically injects the X-Ray tracing header into outbound requests, allowing downstream services to participate in the trace.

Step-by-Step Solution

1
Identify why the downstream trace segment is missing.
Downstream HTTP client is not patched or instrumented, so the required tracing header (X-Amzn-Trace-Id) is not propagated.
AWS X-Ray active tracing on Lambda only covers Lambda itself; downstream calls require code instrumentation.
2
Apply the appropriate instrumentation method in the application code.
Use the AWS X-Ray SDK's HTTP instrumentation wrappers to wrap the HTTP client library.
This automatically injects the tracing header into outgoing HTTP requests and creates subsegments for the calls.

Key Concept

AWS X-Ray Downstream Context Propagation and HTTP Client Instrumentation
Estimated Time:45s
Question 148Question

A developer is troubleshooting an AWS Lambda function that occasionally terminates abruptly. To measure the frequency of these occurrences, the developer wants to create an Amazon CloudWatch metric that increments every time a function execution times out. The Lambda log group contains standard timeout log entries, such as:

`2026-07-14T12:00:00.000Z 88888888-4444-4444-4444-121212121212 Task timed out after 10.03 seconds`

Which log metric filter pattern must the developer configure on the log group to accurately capture only these timeout events?

Show answer & explanation

Answer: "Task timed out"

Answer

"Task timed out"
The correct answer is the option specifying the exact phrase in double quotes. In Amazon CloudWatch Logs, filter patterns for unstructured plain text logs can match an exact phrase by enclosing the phrase in double quotes. Since the standard Lambda timeout message contains the phrase "Task timed out", this pattern will match the line and increment the metric.

Step-by-Step Solution

1
Identify the format of the target log entry.
The log message is unstructured plain text containing the phrase "Task timed out".
Choosing the correct filter pattern syntax depends on whether the log is structured (JSON), space-delimited, or plain text.
2
Determine the appropriate CloudWatch Logs filter pattern syntax for plain text phrase matching.
A plain text search pattern uses double quotes around the exact phrase to match, resulting in "Task timed out".
Enclosing the phrase in double quotes performs an exact substring match on unstructured logs.

Key Concept

CloudWatch Metric Filter syntax for unstructured text logs
Estimated Time:45s
Question 149Question

A web application hosted on a private domain attempts to submit a `PUT` request to a backend API exposed via Amazon API Gateway using a Lambda Proxy integration. The web browser blocks the request and outputs a console error indicating that the CORS preflight request failed because the 'Access-Control-Allow-Origin' header is missing. Which steps should the developer perform to resolve this issue? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Define an OPTIONS method for the API Gateway resource that returns the required 'Access-Control-Allow-Origin' header.; Modify the Lambda function response object to include the 'Access-Control-Allow-Origin' header in its `headers` dictionary.

Answer

Define an OPTIONS method for the API Gateway resource that returns the required 'Access-Control-Allow-Origin' header, and modify the Lambda function response object to include the 'Access-Control-Allow-Origin' header in its headers dictionary.
To fix a CORS error in API Gateway when using Lambda Proxy integration, two separate adjustments are needed. First, the preflight OPTIONS request must be enabled on the API Gateway resource to respond with the 'Access-Control-Allow-Origin' header. Second, the backend Lambda function must return the 'Access-Control-Allow-Origin' header in its response JSON, because API Gateway does not inject headers into proxy responses.

Step-by-Step Solution

1
Analyze the error message and integration type.
Identified a CORS failure on an API Gateway endpoint using Lambda Proxy integration.
Since Lambda Proxy integration is used, the backend Lambda response must explicitly return the CORS headers along with the API Gateway resource preflight handling.
2
Configure the preflight OPTIONS request in API Gateway.
Created an OPTIONS method on the API Gateway resource returning the 'Access-Control-Allow-Origin' header.
This allows the browser's preflight check to succeed before initiating the actual PUT request.
3
Modify the Lambda function response.
Updated the returned JSON payload to include 'Access-Control-Allow-Origin' inside the headers block.
In proxy integrations, API Gateway does not modify the response headers, so the backend function must return them.

Key Concept

Handling CORS in API Gateway with Lambda Proxy Integration
Estimated Time:1m 30s
Question 150Question

A developer is implementing real-time processing of application logs generated by a payment service. The application writes JSON-formatted logs to an Amazon CloudWatch Logs log group. The developer sets up a CloudWatch Logs subscription filter to stream logs where the transaction status is "failed" and the error code is 504 to an AWS Lambda function for alerting.

During load testing, the developer observes that several alerts are missed, and the Lambda function's CloudWatch logs show multiple "Task timed out after 3.00 seconds" errors. The database connection initialization is currently located inside the Lambda handler function.

Which of the following represents the correct subscription filter pattern to extract these failed transactions, along with the appropriate troubleshooting step to resolve the Lambda timeout errors?

Show answer & explanation

Answer: Filter pattern: `{ .status = "failed" && .errorCode = 504 }`
Resolution: Increase the Lambda function's execution timeout and move the database connection initialization outside the handler function to leverage execution context reuse.

Answer

Filter pattern: `{ .status = "failed" && .errorCode = 504 }` and Resolution: Increase the Lambda function's execution timeout and move the database connection initialization outside the handler function to leverage execution context reuse.
The subscription filter pattern for JSON logs requires curly braces `{}` and prefixing JSON keys with `.` to properly parse and match values (e.g., `{ .status = "failed" && $.errorCode = 504 }`). To address the Lambda timeouts, moving the database connection initialization outside the handler function enables connection reuse across multiple invocations (execution context reuse). This avoids the heavy overhead of creating a new database connection on every function invocation, which is a major contributor to latency and timeouts.

Step-by-Step Solution

1
Analyze the log format and identify the correct CloudWatch Subscription Filter pattern syntax.
Since the logs are JSON-formatted, the filter pattern must use curly braces `{}` and reference fields using the `.` prefix (e.g., `{ .status = "failed" && $.errorCode = 504 }`).
Bracket-based syntax `[...]` is used for space-delimited text logs, whereas CloudWatch Logs requires JSON property paths for structured logs.
2
Examine the Lambda execution logs showing timeouts and identify the source of latency.
Initializing database connections inside the handler function leads to high connection establishment latency on every invocation.
During load spikes, establishing a new connection on every invocation leads to container resource exhaustion and execution timeouts.
3
Determine the correct mitigation to resolve the Lambda function's timeouts.
Move the database connection initialization code outside the handler to utilize execution context reuse, and increase the timeout.
Declaring the database client globally allows AWS Lambda to reuse the active connection pool across sequential warm invocations, dramatically reducing invocation latency.

Key Concept

CloudWatch Logs JSON Metric and Subscription Filter syntax combined with Lambda execution context reuse optimization.
Estimated Time:2m 0s
Question 151Question

A developer needs to monitor a serverless application's log group in Amazon CloudWatch Logs for database connection errors. The application logs errors in the format: `[ERROR] DatabaseConnectionError: Connection timed out`. The developer wants to count these errors and send notifications when they occur. Which TWO actions should the developer take to achieve this?

Select all that apply

Show answer & explanation

Answer: Create an Amazon CloudWatch Logs metric filter on the log group using the filter pattern "DatabaseConnectionError".; Create an Amazon CloudWatch alarm based on the custom metric published by the metric filter to trigger notifications when the threshold is exceeded.

Answer

Create an Amazon CloudWatch Logs metric filter on the log group using the filter pattern "DatabaseConnectionError" and create an Amazon CloudWatch alarm based on the custom metric to trigger notifications when the threshold is exceeded.
The correct approach involves creating a CloudWatch Logs metric filter to search for the specific pattern 'DatabaseConnectionError' in incoming log events. This filter increments a custom CloudWatch metric. Then, a CloudWatch alarm must be configured on that custom metric to trigger an alarm state and notify the team (e.g., via SNS) when the occurrence threshold is crossed.

Step-by-Step Solution

1
Analyze the log structure to identify the term to monitor.
The target term "DatabaseConnectionError" is identified within the log pattern.
The filter pattern needs to match this specific string in the log stream.
2
Configure the metric filter with the pattern.
A metric filter is created on the log group that increments a custom metric name whenever "DatabaseConnectionError" appears.
Metric filters translate log data into numeric metrics.
3
Create a CloudWatch alarm.
An alarm is configured to monitor the custom metric and send notifications (e.g., via Amazon SNS) when the error rate exceeds the defined limit.
Alarms are required to detect threshold breaches and initiate notification actions.

Key Concept

Configuring CloudWatch Logs metric filters and alarms to detect and alert on specific patterns in application logs.
Question 152Question

A developer is troubleshooting a Node.js application running on a local development workstation. The application uses the AWS SDK for JavaScript v3 to write data to an Amazon DynamoDB table. The developer's local environment contains multiple AWS CLI profiles configured in ~/.aws/credentials.

The developer sets the environment variable AWS_PROFILE=dev-profile in the terminal and runs the application. However, the application fails to write to the development database and instead attempts to write to the production database, resulting in access denied errors. Further investigation reveals that the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are currently set in the active terminal session and correspond to production credentials.

Which two actions will resolve this issue by ensuring the application uses the dev-profile credentials? (Choose two.)

Select all that apply

Show answer & explanation

Answer: Run the command to unset the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables in the active terminal session.; Modify the application code to initialize the DynamoDB client using the fromIni credential provider from the @aws-sdk/credential-providers package, explicitly specifying the dev-profile profile.

Answer

To resolve this issue, the developer should unset the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables in the active terminal session, or modify the application code to initialize the client using the fromIni credential provider targeting the dev-profile profile.
The default credential provider chain resolves environment variables first. Therefore, unsetting the active production environment variables forces the SDK to evaluate the next step in the chain, resolving the profile specified in the AWS_PROFILE environment variable. Alternatively, explicitly configuring the client in the code using the fromIni provider overrides the default chain sequence entirely, forcing the SDK to retrieve credentials from the specified local profile.

Step-by-Step Solution

1
Analyze the client-side credential resolution order of the AWS SDK default credential provider chain.
Confirm that environment variables (like AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) have the highest precedence, overriding profile-based settings.
This explains why the SDK ignores the AWS_PROFILE environment variable as long as the production keys are active in the terminal.
2
Determine the environment-level remediation step.
Unsetting the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY variables allows the chain to evaluate the next provider, which retrieves profile settings.
Unsetting environment variables forces the SDK to fall back to the shared credential file using the profile specified in AWS_PROFILE.
3
Determine the application code-level remediation step.
Using the fromIni provider explicitly loads the credentials from the dev-profile in the shared credentials file.
This bypasses the default chain precedence rules entirely, ensuring the application executes under the correct credentials regardless of terminal state.

Key Concept

AWS SDK credential resolution precedence and configuration overrides
Question 153Question

A developer attempts to deploy a new infrastructure stack using an AWS CloudFormation template. The initial stack creation fails during the creation of an Amazon DynamoDB table, and the stack status changes to ROLLBACK_COMPLETE. The developer corrects the table configuration in the template and wants to deploy the corrected template.

Which of the following actions can the developer take to deploy the updated template successfully? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Delete the current stack, and then create a new stack using the corrected template.; Deploy the corrected template as a new stack under a different stack name.

Answer

Deleting the failed stack and creating a new one, or deploying the template as a new stack with a different name.
To resolve a failed initial stack creation that has rolled back to the ROLLBACK_COMPLETE state, the developer must either delete the failed stack and create a new one using the corrected template, or deploy the template as a new stack with a different name. This is because a stack in the ROLLBACK_COMPLETE state from a failed initial creation cannot be updated directly.

Step-by-Step Solution

1
Identify the current state of the stack and how it was reached.
The stack is in the ROLLBACK_COMPLETE state due to a failure during its initial creation.
The rollback state determines what actions are allowed on the stack.
2
Determine if update operations are supported in the current state.
AWS CloudFormation does not allow update operations on stacks that have failed initial creation and rolled back to ROLLBACK_COMPLETE.
Understanding limitations of ROLLBACK_COMPLETE helps eliminate invalid update actions.
3
Select valid methods to deploy the corrected template.
The developer must either delete the failed stack and recreate it, or deploy the corrected template as a new stack with a different name.
These are the only allowed paths to deploy the resource definitions successfully.

Key Concept

Troubleshooting CloudFormation ROLLBACK_COMPLETE state on initial stack creation
Estimated Time:1m 0s
Question 154Question

A developer is setting up a new AWS CodeBuild project to build and package a containerized application. The developer creates an IAM role named CodeBuildDeploymentRole and attaches the AWSCodeBuildDeveloperAccess managed policy. When the developer initiates a build run, the build fails immediately during the setup phase with the error message: "CodeBuild is not authorized to perform: sts:AssumeRole on the specified credentials role". Which action should the developer take to resolve this failure?

Show answer & explanation

Answer: Modify the trust relationship of the CodeBuildDeploymentRole to allow the codebuild.amazonaws.com service principal to perform the sts:AssumeRole action.

Answer

Modify the trust relationship of the CodeBuildDeploymentRole to allow the codebuild.amazonaws.com service principal to perform the sts:AssumeRole action.
The correct answer is to modify the trust relationship of the role to allow the codebuild.amazonaws.com service principal to perform the sts:AssumeRole action. For any AWS service to assume an IAM role, the role's trust policy must explicitly permit the service's principal to perform the sts:AssumeRole API call.

Step-by-Step Solution

1
Analyze the error message showing that AWS CodeBuild is unauthorized to perform sts:AssumeRole on the specified IAM role.
Identify that the issue is due to a misconfigured IAM Trust Policy on the target role, preventing CodeBuild from assuming it.
Before a build execution begins, the CodeBuild service must assume the project's service role to acquire temporary security credentials.
2
Update the trust policy document of the CodeBuildDeploymentRole via the IAM Console or CLI.
Add codebuild.amazonaws.com as a trusted entity allowed to call sts:AssumeRole.
This establishes the trust relationship required for the AWS CodeBuild service principal to assume this specific role.

Key Concept

IAM Service Roles and Trust Relationships
Estimated Time:2m 0s
Question 155Question

A client receives a 500 Internal Server Error when attempting to call an Amazon API Gateway resource secured by a custom Lambda Authorizer. The Lambda Authorizer execution completes successfully with no errors in its Amazon CloudWatch logs. Which of the following is the most likely cause of this behavior?

Show answer & explanation

Answer: The custom Lambda Authorizer returned a response JSON payload that does not conform to the expected format containing principalId and policyDocument.

Answer

The custom Lambda Authorizer returned a response JSON payload that does not conform to the expected format containing principalId and policyDocument.
The correct response points out that a malformed JSON payload returned by the custom Lambda Authorizer (such as omitting principalId or policyDocument) causes API Gateway to fail validation, leading to a 500 Internal Server Error even if the Lambda code itself runs successfully without throwing errors.

Step-by-Step Solution

1
Analyze the HTTP status code and logs.
The client receives a 500 Internal Server Error, but the Lambda Authorizer execution completes successfully with no runtime errors in CloudWatch.
This indicates that the authorizer function executed successfully without throwing an exception, but API Gateway failed to process the output returned by the function.
2
Verify the required output format for Lambda Authorizers.
Lambda Authorizers must return a structured JSON response containing the principalId, policyDocument (with Statement, Action, Effect, Resource), and optionally context.
API Gateway requires this specific structure to validate permissions. If any of these fields are missing or incorrectly formatted, API Gateway cannot evaluate the policy and defaults to a 500 Internal Server Error.

Key Concept

API Gateway Lambda Authorizer response validation
Question 156Question

A developer is troubleshooting a client-side real estate web application hosted on `https://listings.example.com` that sends `POST` requests to an Amazon API Gateway REST API. The API is integrated with an AWS Lambda function using a Lambda Proxy integration. Users report that search submissions fail, and the browser console displays a CORS policy error indicating that the 'Access-Control-Allow-Origin' header is missing. Which two actions must the developer take to resolve this issue? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Configure the backend Lambda function to return the 'Access-Control-Allow-Origin' header in its JSON response headers.; Deploy the API Gateway REST API to a stage after enabling CORS on the resource in the console.

Answer

The developer must configure the backend Lambda function to return the 'Access-Control-Allow-Origin' header in its JSON response, and deploy the API Gateway REST API to a stage after enabling CORS on the resource.
The correct options are configuring the backend Lambda function to return the 'Access-Control-Allow-Origin' header in its response, and deploying the API Gateway REST API to a stage. When using Lambda Proxy integration, the backend Lambda function is responsible for returning the appropriate CORS headers in its response because API Gateway passes the response from Lambda directly without modification. Additionally, enabling CORS in the API Gateway console configures the preflight OPTIONS method, but the API must be deployed to the target stage for those settings to become active.

Step-by-Step Solution

1
Add the required CORS headers to the Lambda function response.
The Lambda function returns a payload containing headers: { 'Access-Control-Allow-Origin': 'https://listings.example.com' }.
Since the API uses Lambda Proxy integration, API Gateway does not automatically inject CORS headers into responses from the integration; the backend function must return them.
2
Enable CORS on the REST API resource and deploy the API.
The mock integration for the preflight OPTIONS method is created and deployed to the active stage.
Before browsers send a non-simple request (like POST with JSON payload), they perform a preflight OPTIONS request. API Gateway must have CORS enabled (to handle OPTIONS) and the API must be deployed to the stage to serve these requests.

Key Concept

Handling CORS in Amazon API Gateway REST APIs using Lambda Proxy Integration requires both configuring the API Gateway OPTIONS method (via Enable CORS) and returning the CORS headers directly from the backend Lambda function response.
Question 157Question

A developer is troubleshooting a failed AWS CodeDeploy deployment. The deployment was configured to update a containerized application running on an Amazon ECS service using a blue/green deployment strategy. The deployment failed during the validation phase with an error indicating that invalid lifecycle hooks were specified in the deployment specification file. Which of the following lifecycle hooks are unsupported for an Amazon ECS deployment and must be removed from the appspec.yaml file to resolve the issue? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: ApplicationStop; ApplicationStart

Answer

The unsupported lifecycle hooks for an Amazon ECS deployment are ApplicationStop and ApplicationStart.
For an Amazon ECS deployment, CodeDeploy supports a specific, limited set of lifecycle hooks: BeforeInstall, AfterInstall, AfterAllowTestTraffic, BeforeAllowTraffic, and AfterAllowTraffic. The ApplicationStop and ApplicationStart hooks are only used in EC2/On-Premises deployments to manage on-instance application states and will fail validation if included in an ECS AppSpec template.

Step-by-Step Solution

1
Determine the target compute platform for the CodeDeploy deployment.
The target platform is Amazon ECS.
CodeDeploy lifecycle hooks differ significantly depending on whether the deployment is for EC2/On-Premises, AWS Lambda, or Amazon ECS.
2
Review the list of valid lifecycle hooks for Amazon ECS in CodeDeploy.
The valid hooks for ECS are BeforeInstall, AfterInstall, AfterAllowTestTraffic, BeforeAllowTraffic, and AfterAllowTraffic.
This establishes which hooks CodeDeploy expects when parsing the ECS AppSpec file.
3
Identify the unsupported hooks from the choices.
ApplicationStop and ApplicationStart are invalid for ECS, as they are part of the EC2/On-Premises deployment lifecycle.
Adding EC2-specific hooks to an ECS AppSpec file triggers validation errors during the deployment phase.

Key Concept

AWS CodeDeploy AppSpec lifecycle hooks differ based on the target compute platform (EC2 vs. ECS vs. Lambda). Using hooks designed for EC2 (such as ApplicationStop and ApplicationStart) in an ECS deployment leads to validation failures.
Question 158Question

A developer is troubleshooting an application that streams JSON logs to an Amazon CloudWatch Logs log group. A representative log event in the log group is structured as follows:

{
"timestamp": "2026-07-14T12:00:00Z",
"level": "ERROR",
"error": {
"code": "DB_CONNECTION_FAILED",
"message": "Failed to connect to the database instance."
}
}

The developer created a CloudWatch metric filter with the pattern `{ $.error = "DB_CONNECTION_FAILED" }` to monitor database connection failures. However, the associated metric is not being populated, even though matching error logs are visible in the log group. What is the reason for this behavior?

Show answer & explanation

Answer: The filter pattern references the parent error object rather than the nested code property. It should be updated to { $.error.code = "DB_CONNECTION_FAILED" }.

Answer

The filter pattern references the parent error object rather than the nested code property. It should be updated to { $.error.code = "DB_CONNECTION_FAILED" }.
The correct answer explains that CloudWatch Logs requires a fully qualified JSON path to target a leaf node. The developer's pattern references the parent object 'error' (which evaluates to a nested map/dictionary) instead of the string property 'code'. By correcting the path to $.error.code, CloudWatch is able to successfully perform the equality comparison with the string 'DB_CONNECTION_FAILED'.

Step-by-Step Solution

1
Analyze the structured JSON log format to identify the path to the target error code.
The target string "DB_CONNECTION_FAILED" is located at the path $.error.code.
Correctly identifying the JSON hierarchy is required because CloudWatch Logs metric filters require complete JSON paths to match values.
2
Evaluate the developer's filter pattern { $.error = "DB_CONNECTION_FAILED" } against the JSON log hierarchy.
The selector $.error evaluates to the object { "code": "DB_CONNECTION_FAILED", "message": "Failed to connect to the database instance." }, which is not equal to the string "DB_CONNECTION_FAILED".
Understanding why the match fails requires evaluating the selector path's return type against the target value.
3
Select the option that fixes the path referencing issue using valid CloudWatch Logs metric filter syntax.
Updating the filter pattern to { $.error.code = "DB_CONNECTION_FAILED" } correctly compares the leaf node's string value.
This establishes a direct match on the string field, resolving the zero match issue.

Key Concept

CloudWatch Logs JSON Metric Filter Path Syntax
Question 159Question

A CORS preflight block error is displayed in the browser console when a client-side application hosted on https://webapp.example.com sends a request to an Amazon API Gateway REST API. The API is configured with a custom Lambda Authorizer. Investigation reveals that the error occurs only when the authorizer rejects requests containing expired JSON Web Tokens (JWTs), which prevents the browser from reading the actual 401 Unauthorized status code. How should the developer resolve this issue?

Show answer & explanation

Answer: Configure Gateway Responses in API Gateway for the Unauthorized and Access Denied response types to return the required Access-Control-Allow-Origin header.

Answer

Configure Gateway Responses in API Gateway for the Unauthorized and Access Denied response types to return the required Access-Control-Allow-Origin header.
Configuring Gateway Responses in API Gateway for the Unauthorized and Access Denied response types ensures that when a request fails authentication at the custom authorizer level, the response returned by API Gateway contains the necessary Access-Control-Allow-Origin headers. This allows the browser to process the 401 or 403 HTTP status code instead of blocking the response due to CORS policy violations.

Step-by-Step Solution

1
Analyze where the failure occurs in the API Gateway execution flow.
Since the token is expired, the custom Lambda Authorizer denies the request before API Gateway invokes the backend integration.
Understanding the request flow is essential to determine whether the error originates from the backend integration or API Gateway itself.
2
Determine the source of the generated HTTP error response.
API Gateway returns a gateway-generated response (such as 401 Unauthorized or 403 Forbidden).
When an authorizer rejects a request, API Gateway short-circuits the flow and handles the response directly.
3
Identify why the browser reports a CORS error on the authentication failure.
By default, Gateway Responses generated by API Gateway do not contain CORS headers (Access-Control-Allow-Origin).
A browser will reject any cross-origin response that lacks valid Access-Control-Allow-Origin headers, even if the backend integration is configured for CORS.
4
Configure the Gateway Responses in the API Gateway console or CloudFormation template.
The Access-Control-Allow-Origin header is added to the Unauthorized and Access Denied Gateway Responses, allowing the browser to read the actual HTTP response code.
This exposes the real status code (401/403) to the frontend client, allowing correct authentication error handling.

Key Concept

API Gateway Gateway Responses are used to customize responses and inject CORS headers for requests that fail before reaching the backend integration.
Question 160Question

A developer is configuring a CloudWatch Metric Filter to count the occurrences of HTTP 5xx errors from a web application's JSON-formatted log group. The JSON log events have the structure: `{"statusCode": 500, "message": "Internal Server Error"}`. The metric filter must count all events where `statusCode` is greater than or equal to 500. Which of the following configurations are required to correctly achieve this? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Define the metric filter pattern as `{ $.statusCode >= 500 }` to match the JSON key-value pair.; Set the metric value in the filter configuration to 1 to increment the metric count by 1 for each matching log event.

Answer

Define the metric filter pattern as `{ $.statusCode >= 500 }` and set the metric value in the filter configuration to 1.
The correct options are the ones stating to define the metric filter pattern as `{ .statusCode >= 500 }` and to set the metric value in the filter configuration to 1. CloudWatch Logs supports filtering JSON log messages using curly braces `{}` and the `.property` notation to inspect properties of the JSON object. Specifying a metric value of 1 instructs CloudWatch to increment the metric by 1 for each matching log event.

Step-by-Step Solution

1
Select the correct pattern syntax for JSON logs.
The JSON pattern syntax requires curly braces `{}` and the JSON path operator `.` to target the `statusCode` field (e.g., `{ .statusCode >= 500 }`).
CloudWatch Logs parses JSON events dynamically, but requires the correct query structure to extract fields.
2
Configure the metric increment value.
A metric value of 1 is specified to increment the custom metric count per occurrence.
This registers each matched error event as a single count for monitoring purposes.

Key Concept

CloudWatch Logs Metric Filters syntax and configuration for JSON-formatted log events.
Estimated Time:1m 0s
PreviousPage 8 / 14Next
Troubleshooting and Optimization Practice Questions — AWS Certified Developer - Associate — Page 8 | Examkin