All practice questions

972 questions

Question 381Question

You are troubleshooting a high-volume Azure App Service application. You need to write an optimized Kusto Query Language (KQL) query in Application Insights to analyze dependencies associated with slow requests. Specifically, you want to identify the 95th95\text{th} percentile duration of dependency calls that occurred during requests that took longer than 3 seconds3\text{ seconds} (3000 ms3000\text{ ms}) within the last 24 hours24\text{ hours}.

Which KQL query should you use to retrieve this data with the best query performance?

Show answer & explanation

Answer: let timeLimit = ago(24h);
let slowRequests = requests
| where timestamp > timeLimit and duration > 3000
| project operation_Id;
dependencies
| where timestamp > timeLimit
| join kind=inner slowRequests on operation_Id
| summarize p95 = percentile(duration, 95) by name
| order by p95 desc

Answer

The correct query is the one that filters both the requests and dependencies tables by the 24-hour time range before joining them.
The correct query applies the time range filter to both the requests and dependencies tables before executing the join. In KQL, when joining two telemetry tables, it is critical to filter both datasets by time range. If one table is left unfiltered, the query optimizer cannot prune partitions effectively, resulting in a scan of all historical logs. Filtering first reduces the volume of data that needs to be loaded into memory and joined, ensuring optimal performance on large datasets.

Step-by-Step Solution

1
Define a time limit variable using the ago() function to represent the last 24 hours.
A reusable timeLimit variable representing the past 24 hours.
Creating a variable ensures consistency in the time filters applied to both telemetry tables.
2
Query the requests table, applying the time filter and filtering for duration > 3000 ms, then project only the operation_Id column.
A lightweight dataset of operation IDs for requests that exceeded the threshold in the last 24 hours.
Projecting only the required key (operation_Id) reduces memory overhead during the join operation.
3
Query the dependencies table, applying the time filter first, and perform an inner join with the filtered requests dataset on operation_Id.
A combined dataset containing dependency call records that occurred within the target 24-hour window and are linked to the slow requests.
Applying the time filter on both tables before the join prevents the query engine from scanning unnecessary partitions, maximizing performance.
4
Summarize the 95th percentile of the dependency duration grouped by the dependency name, and order the results descending.
An ordered list of dependency names and their 95th percentile latency during the slow requests.
This identifies which external resources or operations are contributing most to the application's slow response times.

Key Concept

To maintain high query performance on Application Insights telemetry, KQL queries must filter all joined tables by time-range before executing the join operation.
Question 382Question

A developer is investigating a performance bottleneck in an Azure Function App. They want to retrieve all dependency calls from the last 6 hours that took longer than the 90th percentile of all dependency durations during that same period. Complete the Kusto Query Language (KQL) query to retrieve these slow dependency calls by filling in the blanks.

Fill in the blanks below

kql
let threshold = toscalar(
dependencies
| where timestamp > ago(6h)
| summarize
(duration, 90)
);
dependencies
| where timestamp > ago(6h)
| where duration >

Show answer & explanation

Answer

Use 'percentile' or 'percentiles' in the first blank to compute the 90th percentile baseline, and use 'threshold' in the second blank to filter dependency durations against the computed scalar variable.
The query calculates the 90th percentile of dependency call durations over the last 6 hours using the `percentile` function. By using `toscalar()`, this single value is stored in the `threshold` variable. The main query then references `threshold` to filter for dependency records whose duration exceeds the computed value.

Step-by-Step Solution

1
Define the aggregation function to find the 90th percentile of dependency call durations.
The function `percentile(duration, 90)` is specified.
This determines the 90th percentile boundary value of the duration across all dependency records within the specified time range.
2
Assign the scalar value to a variable named threshold.
The `let threshold = toscalar(...)` expression assigns the scalar result.
Using `toscalar()` converts the single-value tabular result into a scalar type so it can be evaluated in subsequent filter comparisons.
3
Filter the primary dependencies table using the threshold variable.
The final filter statement evaluates `where duration > threshold`.
This isolates the dependency calls that took longer than the 90th percentile threshold limit.

Key Concept

Calculating percentiles and using scalar variables in Kusto Query Language (KQL) queries for telemetry analysis.
Estimated Time:1m 30s
Question 383Question

You are designing a secure, event-driven solution in Azure. You have an Event Grid custom topic and a Webhook endpoint. You must route events from the custom topic to the Webhook endpoint.

To ensure reliability and security, you must meet the following requirements:
- If event delivery to the Webhook fails, events must be dead-lettered to an Azure Storage blob container.
- Event Grid must write the dead-letter events to the container using a system-assigned managed identity.
- The subscription must be successfully validated.

Which four actions should you perform in sequence to configure the solution? To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.

Drag items to arrange them in the correct order

Show answer & explanation

Answer

First, enable a system-assigned managed identity on the Event Grid custom topic. Second, assign the Storage Blob Data Contributor role to the custom topic's managed identity on the destination storage account. Third, configure the Webhook endpoint to parse the incoming JSON array and return the validationCode from the subscription validation request. Finally, create the Event Grid subscription, specifying the Webhook endpoint, the storage container for dead-lettering, and configuring the subscription to use the custom topic's identity for dead-letter delivery.
To set up the scenario securely and reliably, you must follow a dependency chain. First, you enable a system-assigned managed identity on the Event Grid custom topic so that the security principal exists in Microsoft Entra. Second, you assign the Storage Blob Data Contributor role to that newly created identity on the storage account, ensuring the permission is active. Third, you configure the Webhook endpoint application to handle the subscription validation handshake. Finally, you create the Event Grid subscription, which triggers both the synchronous Webhook handshake and the dead-letter write validation using the configured managed identity.

Step-by-Step Solution

1
Enable a system-assigned managed identity on the Event Grid custom topic.
A Microsoft Entra security principal is generated for the custom topic resource.
You must establish the identity principal before you can assign RBAC permissions to it.
2
Assign the Storage Blob Data Contributor role to the custom topic's managed identity on the storage account.
The identity principal is granted write permissions on the storage account blob service.
During the creation of the event subscription, Azure Event Grid performs a write validation check against the dead-letter destination. If the role is not already assigned, subscription creation will fail.
3
Configure the Webhook endpoint to parse the incoming JSON array and return the validationCode from the subscription validation request.
The Webhook application is ready to respond to Event Grid's validation handshake.
When the event subscription is created, Event Grid sends a synchronous HTTP POST validation request. If the endpoint does not return the code, the subscription fails to create.
4
Create the Event Grid subscription, specifying the Webhook endpoint, the storage container for dead-lettering, and configuring the subscription to use the custom topic's identity for dead-letter delivery.
The event subscription is created, the validation handshake completes successfully, and dead-lettering is secured.
This registers the subscription in Azure and initiates the synchronous validation and dead-letter permissions validation checks.

Key Concept

Azure Event Grid custom topic subscription lifecycle, including managed identities for dead-lettering and endpoint validation handshakes.
Estimated Time:3m 0s
Question 384Question

You are monitoring a high-volume Azure App Service web application using Azure Application Insights. You need to write an optimized Kusto Query Language (KQL) query to count the number of slow external HTTP dependency calls.

The query must meet the following requirements:
1. Dynamically calculate the 90th percentile duration of all HTTP dependencies over the last 24 hours and use this as a threshold.
2. Filter the `dependencies` table to include only HTTP calls whose duration exceeds this threshold.
3. Join the filtered dependencies with the `requests` table to associate them with their parent operations.
4. Group the results by the operation name (from the `requests` table) and the dependency target (from the `dependencies` table) to display the total count of slow dependency calls.
5. Apply time-range filters as early as possible to minimize the volume of data scanned and prevent query performance issues.

Complete the KQL query below by filling in the blanks with the correct KQL functions, table fields, or join operators.

Fill in the blanks below

let start = ago(24h);
let threshold =
(
dependencies
| where timestamp >= start
| where type == "Http"
| summarize percentile(duration, 90)
);
dependencies
| where
>= start
| where type == "Http" and duration > threshold
| join kind=
(
requests
| where
>= start
) on operation_Id
| summarize SlowCount = count() by RequestName = name, Target = target
Show answer & explanation

Answer

The query must evaluate the subquery as a scalar value using toscalar, filter both tables early using timestamp, and perform an inner (or innerunique) join to group by fields from both tables.
The correct query uses toscalar to dynamically retrieve a single numeric threshold for comparison, restricts the data scan on both tables using the timestamp column for optimization, and uses an inner join to correlate and preserve columns from both tables so they can be grouped by request name and dependency target.

Step-by-Step Solution

1
Wrap the threshold subquery with the correct KQL function.
Using the toscalar function converts the single-column, single-row table output of the subquery into a scalar value.
In KQL, comparing a scalar field like duration to a subquery's result using scalar operators (like >) requires the subquery to be explicitly evaluated as a scalar value.
2
Identify the performance-critical filtering field for the tables.
Using the timestamp column to restrict query execution to the last 24 hours.
Applying time-range filters using the timestamp field on both tables before joining prevents full-table scans of the historical telemetry store, which is critical for query efficiency and avoiding timeouts on high-volume workspaces.
3
Select the correct join operator that preserves the required schema.
Using the inner (or innerunique) join kind.
Since the final projection requires columns from both tables (name from requests and target from dependencies), a semi-join cannot be used. An inner join preserves and correlates the columns from both tables based on the operation_Id.

Key Concept

Writing optimized KQL queries that combine scalar subqueries, early time-range filtering, and appropriate schema-preserving joins to troubleshoot App Insights telemetry.
Question 385Question

An organization is implementing a multi-tenant event-driven architecture using an Azure Event Grid Event Domain named `marketing-domain`. Each tenant is assigned a unique topic within the domain (for example, `marketing-domain/topics/tenant-alpha`) to isolate their marketing campaign events. You must grant a service principal representing `tenant-alpha` the minimum permissions required to create and manage their own event subscriptions within their topic, while strictly preventing them from managing or viewing subscriptions for other tenants' topics. Which configuration should you implement?

Show answer & explanation

Answer: Assign the service principal the Event Grid Subscription Contributor role at the scope: `/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/domains/marketing-domain/topics/tenant-alpha`

Answer

Assign the service principal the Event Grid Subscription Contributor role at the specific topic scope within the Event Domain.
The correct configuration is to assign the Event Grid Subscription Contributor role at the scope of the specific Event Domain topic. Azure Event Domains support granular RBAC scopes down to the individual topic level. This ensures that the tenant's service principal can only manage event subscriptions for their assigned topic, preventing access to other tenants' topics and satisfying the principle of least privilege.

Step-by-Step Solution

1
Identify the target Event Grid resource structure and tenant boundary.
Each tenant uses a specific topic within the Event Domain (`marketing-domain/topics/tenant-alpha`).
Understanding the topic's resource path is required to apply role-based access control (RBAC) at the narrowest scope.
2
Determine the minimum built-in Azure RBAC role needed to manage subscriptions.
The Event Grid Subscription Contributor role is identified.
This role allows creating and managing event subscriptions without granting broader administrative control over the topic or domain.
3
Assign the role at the correct scope to enforce tenant isolation.
Assign the Event Grid Subscription Contributor role at the specific topic scope path.
Granting permissions at the `/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/domains/marketing-domain/topics/tenant-alpha` scope prevents the service principal from viewing or interacting with other topics in the Event Domain.

Key Concept

Fine-grained role-based access control (RBAC) for Event Domain topics to isolate tenant subscriptions.
Question 386Question

An organization requires developer portal authentication for an Azure API Management (APIM) instance using Microsoft Entra ID. To implement this, you must configure the trust relationship between Microsoft Entra ID and the APIM developer portal. What is the correct sequence of steps to configure this identity provider and make it available to portal users?

Drag items to arrange them in the correct order

Show answer & explanation

Answer

The correct sequence starts with registering the app in Microsoft Entra ID, adding the provider to API Management, retrieving the redirect URL, configuring the redirect URL in Microsoft Entra ID, and finally publishing the developer portal.
The correct sequence follows the logical dependency flow: first, create the identity credentials by registering the application in Microsoft Entra ID. Second, input these credentials into the API Management identity provider configuration, which generates the instance-specific redirect URL. Third, retrieve this redirect URL from API Management. Fourth, configure the application registration in Microsoft Entra ID with the retrieved redirect URL to authorize authentication responses. Lastly, publish the developer portal so that the changes are compiled and the login option becomes active for users.

Step-by-Step Solution

1
Register the application in Microsoft Entra ID.
The Application ID and a client secret are generated.
Establishing the app registration creates the security principal and credentials that APIM will use to authenticate with Entra ID.
2
Add the Microsoft Entra ID identity provider in APIM.
The identity provider is configured, and a redirect URL is generated in the APIM portal.
This links the APIM developer portal to the Entra ID tenant using the credentials registered in the first step.
3
Retrieve the generated redirect URL from the APIM portal.
The redirect URL is copied to the clipboard.
The redirect URL is dynamic and instance-specific, meaning it must be captured from APIM to register it with Entra ID.
4
Add the redirect URL to the Entra ID app registration.
The app registration is updated to allow redirects to the APIM developer portal sign-in endpoint.
For security reasons, Entra ID will only send authentication tokens to pre-authorized redirect URIs.
5
Publish the APIM developer portal.
The portal is compiled and refreshed for visitors.
Any changes to identity providers, designs, or APIs are not visible to users in the developer portal until the portal is explicitly published.

Key Concept

Configuring Microsoft Entra ID authentication for the Azure API Management Developer Portal
Question 387Question

You are configuring an Azure API Management (APIM) instance to route requests to a backend microservice deployed on an Azure Virtual Machine. The backend microservice uses a self-signed SSL/TLS certificate for secure communication. When testing the API in APIM, you receive a HTTP 500 Bad Gateway error because the APIM instance cannot validate the trust chain of the self-signed certificate. You need to configure APIM to successfully communicate with the backend service. Which of the following actions should you perform to resolve this issue?

Show answer & explanation

Answer: Create a custom Backend resource in the API Management instance for the backend service, and disable backend certificate chain validation (for example, by setting the skipCertificateChainValidation parameter to true).

Answer

Create a custom Backend resource in the API Management instance for the backend service, and disable backend certificate chain validation (for example, by setting the skipCertificateChainValidation parameter to true).
Creating a custom Backend resource in the API Management instance and setting its skipCertificateChainValidation property to true allows API Management to establish a secure TLS connection with the backend even if it uses a self-signed certificate, bypassing the default trust chain validation.

Step-by-Step Solution

1
Identify the cause of the HTTP 500 Bad Gateway error.
Recognize that API Management fails to establish a TLS connection to the backend because the backend's self-signed certificate cannot be validated against a trusted root Certificate Authority (CA).
By default, API Management validates the entire certificate chain of backend services to ensure secure communication.
2
Select the appropriate API Management mechanism to handle self-signed certificates.
Determine that creating a custom Backend entity allows configuring specific TLS settings for that backend destination.
Standard API routing settings do not allow fine-grained certificate validation overrides; a custom Backend resource must be defined.
3
Configure the custom Backend resource to bypass certificate chain validation.
Disable certificate chain validation on the custom Backend resource (e.g., setting the skipCertificateChainValidation property to true).
This configuration tells API Management to accept the self-signed certificate presented by the backend service for TLS handshakes.

Key Concept

Bypassing certificate validation for custom backends in Azure API Management
Estimated Time:2m 0s
Question 388Question

An organization is monitoring an API gateway using Azure Application Insights. You need to write an optimized Kusto Query Language (KQL) query that calculates the success rate (percentage of successful requests) of HTTP requests received in the last 24 hours.

Which two of the following KQL queries will achieve this requirement efficiently?

Select all that apply

Show answer & explanation

Answer: requests
| where timestamp > ago(24h)
| summarize SuccessRate = countif(success == true) * 100.0 / count(); requests
| where timestamp > ago(24h)
| summarize SuccessCount = countif(success), TotalCount = count()
| project SuccessRate = (todouble(SuccessCount) * 100.0) / TotalCount

Answer

The correct queries filter by timestamp in the first stage of the query pipeline using the 'where timestamp > ago(24h)' clause, and then use either direct division or the project operator to calculate the percentage of successful requests.
The correct queries prioritize performance by placing the time-range filter 'where timestamp > ago(24h)' as the very first operator after the 'requests' table. They then successfully calculate the ratio of successful requests to total requests. The query with direct division computes the percentage in a single summarize block, while the query using the project operator divides the step into distinct summarize and project stages, both of which are valid and highly performant.

Step-by-Step Solution

1
Apply a time-range filter directly to the requests table.
Limits the scope of scanned telemetry data to only the last 24 hours, optimizing performance.
Omitting or delaying the time filter forces Azure Monitor to scan the entire data retention window.
2
Aggregate the total count and the count of successful requests.
Calculates the successful request count (using countif(success)) and overall request count.
Allows calculation of the percentage metric.
3
Compute the final success percentage.
Produces the success rate as a percentage of total requests.
Fulfills the business requirement of calculating the success rate.

Key Concept

Optimizing KQL queries in Azure Application Insights by placing time-range filters early in the query pipeline.
Question 389Question

An organization runs a C# (.NET) microservice to ingest IoT telemetry. The service utilizes the `Azure.Messaging.EventHubs.Processor` library and deploys multiple instances of `EventProcessorClient` that share a common Azure Blob Storage container as a checkpoint store. During peak loads, you observe partition thrashing where consumer instances continuously claim and release partition ownership from each other, resulting in excessive duplicate processing. Upon reviewing the client configuration, you find the following setup:

csharp
var options = new EventProcessorClientOptions
{
LoadBalancingUpdateInterval = TimeSpan.FromSeconds(15),
PartitionOwnershipExpirationInterval = TimeSpan.FromSeconds(10)
};

Which of the following actions should you perform to resolve the partition thrashing?

Show answer & explanation

Answer: Increase the PartitionOwnershipExpirationInterval to a value that is significantly greater than the LoadBalancingUpdateInterval, such as 45 seconds.

Answer

Increase the PartitionOwnershipExpirationInterval to a value that is significantly greater than the LoadBalancingUpdateInterval, such as 45 seconds.
Increasing the PartitionOwnershipExpirationInterval to a value greater than the LoadBalancingUpdateInterval ensures that an instance has sufficient opportunity to renew its ownership claim before another instance considers the partition orphaned. This stabilizes partition distribution across scale-out instances and resolves the thrashing behavior.

Step-by-Step Solution

1
Analyze the client configuration and identify the relationship between the load balancing and expiration intervals.
The LoadBalancingUpdateInterval is set to 1515 seconds, while the PartitionOwnershipExpirationInterval is set to 1010 seconds.
This shows that the partition ownership claim expires before the client has a chance to execute its next periodic check to renew it.
2
Determine the impact of the interval mismatch on scale-out instances.
When Instance 1 claims a partition, it is expected to hold it for 1010 seconds. However, Instance 1 only attempts to renew ownership every 1515 seconds. Between second 1010 and second 1515, the partition appears unowned (expired) to other instances.
This allows Instance 2 or other instances to claim the partition during their own load-balancing passes, causing constant reassignment (thrashing).
3
Select the correct SDK configuration change to stabilize partition assignment.
Increase the PartitionOwnershipExpirationInterval to a value greater than the LoadBalancingUpdateInterval (e.g., 4545 seconds).
This ensures that even if a load balancing pass is slightly delayed, the partition lease remains valid, giving the owning instance sufficient time to renew it.

Key Concept

Partition ownership and load balancing configuration in EventProcessorClient
Estimated Time:2m 0s
Question 390Question

You are developing a solution in Azure API Management (APIM). The API must allow cross-origin requests from a web client hosted at `https://portal.contoso.com`. You configure JSON Web Token (JWT) validation and response caching. During testing, the web client fails to access the API, throwing a CORS error in the browser console. The APIM gateway logs show that preflight `OPTIONS` requests are failing with an HTTP `401 Unauthorized` status code. You review the following policy configuration:

xml
<policies>
<inbound>
<base />
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
<openid-config url="https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration" />
<required-claims>
<claim name="aud">
<value>api://portal-backend</value>
</claim>
</required-claims>
</validate-jwt>
<cors allow-credentials="true">
<allowed-origins>
<origin>https://portal.contoso.com</origin>
</allowed-origins>
<allowed-methods>
<value>GET</value>
<value>POST</value>
</allowed-methods>
</cors>
<cache-lookup vary-by-developer="false" vary-by-developer-groups="false" downstream-caching-type="none">
<vary-by-query-parameter>id</vary-by-query-parameter>
</cache-lookup>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<cache-store duration="60" />
</outbound>
<on-error>
<base />
</on-error>
</policies>

Which change should you apply to the policy configuration to resolve the CORS error?

Show answer & explanation

Answer: Move the CORS policy so that it is defined before the JWT validation policy within the inbound element.

Answer

Move the CORS policy so that it is defined before the JWT validation policy within the inbound element.
Moving the CORS policy to precede the JWT validation policy is the correct solution. Because Azure API Management processes inbound policies sequentially, placing JWT validation first forces the incoming preflight OPTIONS requests to be evaluated for a JWT. Since preflight requests do not carry the Authorization header, this leads to a 401 Unauthorized response before the CORS headers are returned. Moving CORS to the top of the inbound section enables the gateway to handle the OPTIONS request and return the required headers immediately.

Step-by-Step Solution

1
Analyze the failed preflight requests
CORS preflight OPTIONS requests do not carry the Authorization header and fail with HTTP 401 Unauthorized.
Before making cross-origin requests, modern web browsers send a preflight OPTIONS request. Because it lacks credentials, it fails if forced to go through validation first.
2
Examine the policy order of execution in the inbound section
The validate-jwt policy is configured before the cors policy.
Azure API Management processes policies sequentially from top to bottom within the inbound section.
3
Determine the necessary rearrangement
The cors policy must execute before validate-jwt so it can intercept and handle the OPTIONS preflight request.
By placing CORS first, APIM returns the required Access-Control-Allow-* headers directly to the browser for OPTIONS requests before JWT validation occurs.

Key Concept

API Management policy execution order and CORS preflight handling
Question 391Question

An enterprise is migrating its legacy payment processing API to Azure API Management (APIM). To support blue-green deployments, the API gateway must route incoming requests dynamically based on a custom HTTP header named `X-Routing-Environment`. If the header value is `canary`, the gateway must route the request to a backend service registered with the ID `canary-endpoint`. Otherwise, the request should continue to the default backend.

Complete the following XML policy snippet to implement the dynamic routing logic. Fill in the blanks with the correct context variable and policy element name.

Fill in the blanks below

Complete the XML policy configuration below to dynamically route requests based on the header value:

xml
<policies>
<inbound>
<base />
<choose>
<when condition="@(
.Request.Headers.GetValueOrDefault("X-Routing-Environment") == "canary")">
<
backend-id="canary-endpoint" />
</when>
</choose>
</inbound>
</policies>
Show answer & explanation

Answer

The first blank must be filled with `context` and the second blank must be filled with `set-backend-service`.
The correct configuration uses the read-only C# context variable `context` to access the HTTP headers of the incoming request, and uses the `set-backend-service` policy to override the default backend with the registered backend service ID.

Step-by-Step Solution

1
Identify the C# context variable used within APIM policy expressions.
The `context` variable provides access to request headers and other contextual data.
The policy expression needs to read the incoming request header collection via `context.Request.Headers`.
2
Identify the policy element that redirects a request to a registered backend ID.
The `<set-backend-service>` policy element allows routing requests to a backend specified by its ID.
The requirement specifies routing the request to a backend service registered with the ID `canary-endpoint`, which is configured using `<set-backend-service backend-id="canary-endpoint" />`.

Key Concept

Dynamic backend routing using context variables and set-backend-service policies in Azure API Management.
Question 392Question

You are configuring caching policies in Azure API Management (APIM) for a weather forecast API to reduce backend load. The API has the following requirements:
- Cache successful backend responses for 300 seconds.
- Vary the cached responses based on the HTTP header named 'Accept-Language' and the query parameter named 'city'.
- Prevent caching of responses that contain sensitive data, which is indicated by a custom backend response header 'X-Cache-Private: true'.

Which two of the following policy configurations must you implement to meet these requirements?

Select all that apply

Show answer & explanation

Answer: Add the following policy inside the <inbound> section:
<cache-lookup vary-by-developer="false" vary-by-developer-groups="false" downstream-caching-type="none">
<vary-by-header>Accept-Language</vary-by-header>
<vary-by-query-parameter>city</vary-by-query-parameter>
</cache-lookup>; Add the following policy inside the <outbound> section:
<cache-store duration="300" condition="@(context.Response.Headers.GetValueOrDefault('X-Cache-Private', '') != 'true')" />

Answer

Configure the cache-lookup policy within the inbound section to vary by the Accept-Language header and the city query parameter, and configure the cache-store policy within the outbound section with a duration of 300 seconds and a condition checking that the X-Cache-Private header is not true.
To implement caching in Azure API Management (APIM), you must split the configuration between the inbound and outbound pipelines. The cache lookup must happen in the inbound pipeline to intercept requests and serve cached data when available. This cache lookup is configured using the <cache-lookup> policy, varying by the requested headers and parameters. The actual storing of the response must happen in the outbound pipeline via the <cache-store> policy, using a condition that dynamically inspects the backend response headers to prevent caching sensitive data.

Step-by-Step Solution

1
Place the <cache-lookup> policy in the <inbound> policy section.
This enables checking the API Management cache before sending the request to the backend service.
Looking up cached responses must happen during inbound processing to avoid forwarding the request to the backend if a cache hit occurs.
2
Configure the vary-by criteria in <cache-lookup>.
Add <vary-by-header>Accept-Language</vary-by-header> and <vary-by-query-parameter>city</vary-by-query-parameter> children to <cache-lookup>.
This ensures that API Management caches distinct responses for different language preferences and city requests.
3
Place the <cache-store> policy in the <outbound> policy section.
This enables caching backend responses as they return through the outbound pipeline.
Storing response content in the cache requires access to the response headers and body, which are only available in the outbound processing pipeline.
4
Configure the duration and conditional caching on <cache-store>.
Set duration to 300 and use a policy expression condition checking that the X-Cache-Private header value is not 'true'.
This guarantees that responses are stored for the requested 300 seconds and prevents sensitive data from being cached based on the backend response headers.

Key Concept

Azure API Management caching policy configuration requires cache lookup to occur in the inbound section and cache storage to occur in the outbound section.
Question 393Question

You are developing a C# (.NET) management utility to perform maintenance on an Azure Event Hubs ingestion pipeline. The pipeline uses the `EventProcessorClient` along with an Azure Blob Storage container to store checkpoints and partition ownership leases. To force a partition to be reprocessed from the beginning of the stream, your utility must delete the corresponding checkpoint blob. When the utility attempts to delete the blob, a `RequestFailedException` is thrown with HTTP status code 412412 (Precondition Failed) because an active processor instance holds an active lease on the blob. How should you resolve this issue in your C# code to successfully delete the checkpoint blob?

Show answer & explanation

Answer: Instantiate a `BlobLeaseClient` for the target blob, call the `BreakAsync` method to release the active lease, and then delete the blob.

Answer

Instantiate a BlobLeaseClient for the target blob, call the BreakAsync method to release the active lease, and then delete the blob.
Breaking the lease on the blob removes the concurrency lock held by the EventProcessorClient. This allows the maintenance utility to delete the checkpoint blob and reset the partition processing offset.

Step-by-Step Solution

1
Identify the target checkpoint blob representing the partition ownership inside the Azure Blob Storage container.
The URI and path to the specific blob representing the partition's checkpoint are determined.
The EventProcessorClient creates a specific blob for each partition to store partition leases and offset metadata.
2
Initialize a BlobLeaseClient referencing the targeted checkpoint blob using the Azure Storage SDK.
A client instance capable of executing lease operations on the blob is created.
Standard BlobClient operations fail on leased blobs unless a lease ID is provided or the lease is broken.
3
Execute the BreakAsync method on the BlobLeaseClient instance.
The lease state changes from leased to broken, which unlocks the blob.
Breaking the lease allows modifications and deletion of the blob without needing the original lease ID.
4
Delete the checkpoint blob using BlobClient.DeleteAsync.
The blob is deleted successfully, forcing the event processor to reprocess the partition from the start.
Deleting the checkpoint blob removes the progress offset marker, prompting the EventProcessorClient to default to the configured starting position.

Key Concept

Azure Event Hubs checkpointing lease management using Azure Blob Storage SDK

Alternative Method

If the utility has access to the active EventProcessorClient lease metadata, it can pass the active lease ID inside the BlobRequestConditions of BlobClient.DeleteAsync instead of breaking the lease.
Estimated Time:2m 30s
Question 394Question

You manage a vehicle telematics API named VeloTrack that is hosted on an Azure App Service Web App. The web app currently runs on a Standard (S1) App Service plan with a default instance count of 1. You need to configure metric-based autoscale settings to handle CPU spikes and prevent autoscale flapping. Which two configurations should you select to meet these requirements? (Choose two.)

Select all that apply

Show answer & explanation

Answer: A scale-out rule that increases the instance count by 1 when the CPU Percentage is greater than 80%.; A scale-in rule that decreases the instance count by 1 when the CPU Percentage is less than 35%.

Answer

To configure autoscale rules that handle CPU spikes and prevent flapping, you must define a scale-out rule to add an instance when CPU Percentage is greater than 80%, and a scale-in rule to remove an instance only when CPU Percentage falls below 35%.
The correct configurations are the rules that scale out at 80% CPU and scale in at 35% CPU. With a single instance at 80% CPU, scaling out to two instances halves the load to 40% CPU per instance. Setting the scale-in threshold to 35% ensures that the new load level (40%) does not trigger an immediate scale-in. Additionally, the Standard (S1) plan supports autoscale.

Step-by-Step Solution

1
Analyze the scale-out scenario and workload redistribution.
When 1 instance is running at 80% CPU, scaling out to 2 instances distributes the load, dropping CPU usage per instance to 40%.
Understanding the post-scale-out metric value is necessary to set a safe scale-in threshold.
2
Evaluate the scale-in threshold to prevent flapping.
Select a scale-in threshold less than 40% (such as 35%) so that the scale-in is not immediately triggered after scaling out.
A threshold like 60% is higher than the post-scale-out CPU of 40%, causing the system to scale back in immediately and loop continuously.
3
Verify plan tier compatibility.
Keep the app on the Standard (S1) plan because the Shared (D1) plan does not support autoscale capabilities.
Only Standard, Premium, and Isolated App Service plans support scale-out autoscale rules.

Key Concept

Autoscale flapping occurs when a scale-in threshold is set too close to the scale-out threshold, causing the post-scale metric to immediately trigger the opposite scaling action.
Question 395Question

You are developing a C# console application that processes telemetry alerts from wind turbines using an Azure Service Bus queue. The application uses the `Azure.Messaging.ServiceBus` SDK.

You write the following code:

csharp
using System;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;

// ... connection details omitted for brevity ...

var client = new ServiceBusClient(connectionString);
var options = new ServiceBusProcessorOptions
{
ReceiveMode = ServiceBusReceiveMode.PeekLock,
AutoCompleteMessages = false
};

ServiceBusProcessor processor = client.CreateProcessor(queueName, options);

processor.ProcessMessageAsync += async args =>
{
try
{
await ProcessAlertAsync(args.Message);
// Line X
}
catch (Exception)
{
// Line Y
}
};

You must ensure that:
1. Messages are not lost if the application crashes during processing.
2. Messages that fail due to transient errors are returned to the queue to be retried.
3. Successfully processed messages are removed from the queue immediately.

Which two code segments should you use to replace Line X and Line Y? (Select two.)

Select all that apply

Show answer & explanation

Answer: At Line X: `await args.CompleteMessageAsync(args.Message);`; At Line Y: `await args.AbandonMessageAsync(args.Message);`

Answer

To replace Line X and Line Y, you must call the asynchronous settlement methods `CompleteMessageAsync` and `AbandonMessageAsync` on the event arguments (`args`) object.
In PeekLock receive mode with manual settlement (`AutoCompleteMessages = false`), the processor does not automatically delete or release messages. Successful processing requires calling `CompleteMessageAsync` on the event arguments object to remove the message. Handling transient errors requires calling `AbandonMessageAsync` on the event arguments to return the message to the queue for future retry.

Step-by-Step Solution

1
Determine the required receive and autocomplete configuration.
PeekLock mode is used, and AutoCompleteMessages is disabled, indicating manual settlement is required to prevent message loss on crashes.
By default or when AutoCompleteMessages is false, the developer is responsible for manually completing or abandoning the message.
2
Select the correct API call to settle successfully processed messages.
Call `await args.CompleteMessageAsync(args.Message);` at Line X.
Completing the message removes it from the queue and marks processing as successful.
3
Select the correct API call to handle transient processing errors.
Call `await args.AbandonMessageAsync(args.Message);` at Line Y.
Abandoning the message releases the lock, allowing the message to return to the queue for retry up to the maximum delivery count.

Key Concept

Manual message settlement in PeekLock mode using the Azure.Messaging.ServiceBus SDK
Question 396Question

You are developing a C# desktop application that needs to authenticate users against Microsoft Entra ID using the Microsoft Identity Platform.

Which two components from the Microsoft.Identity.Client namespace must you use to configure and represent the client application?

Select two.

Select all that apply

Show answer & explanation

Answer: PublicClientApplicationBuilder; IPublicClientApplication

Answer

The application must use PublicClientApplicationBuilder to configure the application and IPublicClientApplication to represent the instantiated client application.
For a desktop application, which cannot securely store client secrets, you must use a public client flow. In MSAL.NET, public client applications are configured using the PublicClientApplicationBuilder and represented by the IPublicClientApplication interface.

Step-by-Step Solution

1
Determine the application type based on the deployment scenario.
Since a desktop application runs on a user's device and cannot keep client secrets secure, it is classified as a public client application.
Microsoft Identity Platform distinguishes between public clients (desktop/mobile) and confidential clients (web apps/daemons).
2
Select the correct builder class to instantiate the application.
Use the PublicClientApplicationBuilder class from the Microsoft.Identity.Client namespace to build the application configuration.
The builder pattern is used in MSAL.NET to construct the client application instance with required settings like Client ID and Tenant ID.
3
Identify the correct interface type representing the instantiated client.
The builder's Build() method returns an object implementing the IPublicClientApplication interface.
IPublicClientApplication provides the methods needed to acquire tokens for public clients, such as AcquireTokenInteractive.

Key Concept

Identifying MSAL client types and initializing MSAL.NET public client applications.
Question 397Question

A developer needs to configure a local development environment for a lightweight Go application using the Azure Functions Core Tools custom handler feature and test the function locally. Which sequence of steps should the developer perform?

Drag items to arrange them in the correct order

Show answer & explanation

Answer

The correct sequence is: Run 'func init --worker-runtime custom' in the command line, run 'func new --template "HTTP trigger" --name GoHandler' to add a new function trigger, compile the Go application source code into an executable file named 'handler', modify the 'host.json' file to set the 'defaultExecutablePath' property under the 'customHandler.description' section to 'handler', and finally run 'func start' to launch the Azure Functions host locally.
The correct sequence flows from establishing the local directory layout (init), creating the function trigger metadata (new), generating the executable from Go code (compile), mapping the host to this executable (host.json configuration), and executing the Functions runtime host (start).

Step-by-Step Solution

1
Initialize the project using 'func init --worker-runtime custom'.
Creates the project folder structure containing host.json and local.settings.json configured for a custom worker.
You must establish the Azure Functions project structure before you can add functions or configure handlers.
2
Create the function trigger using 'func new'.
Creates a function directory with a function.json defining the triggers and bindings.
A custom handler still relies on standard function.json metadata to determine which events should trigger the custom process.
3
Compile the Go source code.
Produces a standalone executable binary file (e.g., 'handler').
Go is a compiled language; the custom handler requires a compiled binary to receive requests forwarded by the host.
4
Configure the 'defaultExecutablePath' in host.json.
Points host.json to the compiled Go binary.
The Functions host reads host.json at startup to know the filename and location of the custom handler process to start.
5
Run 'func start'.
Launches the runtime and handler locally to accept requests.
Running the host requires all config and binaries to be in place, allowing you to test the HTTP execution locally.

Key Concept

Azure Functions Custom Handlers configuration and local development lifecycle
Question 398Question

An organization exposes an internal human resources API through Azure API Management (APIM). The API must meet the following security requirements:
1. Restrict access to clients originating from the IP subnet 192.168.100.0/24192.168.100.0/24.
2. Validate a JSON Web Token (JWT) issued by Microsoft Entra ID before routing the request to the backend service.

A developer defines the following APIM policy:

xml
<policies>
<inbound>
<base />
</inbound>
<backend>
<base />
</backend>
<outbound>
<ip-filter action="allow">
<address-subnet>192.168.100.0/24</address-subnet>
</ip-filter>
<jwt-validate header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
<openid-config url="https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration" />
</jwt-validate>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>

Which of the following describes the behavior of this policy configuration?

Show answer & explanation

Answer: The backend service will receive and process unauthorized and unfiltered requests because the IP filtering and JWT validation policies are defined in the outbound section, which executes after the backend service responds.

Answer

The backend service will receive and process unauthorized and unfiltered requests because the IP filtering and JWT validation policies are defined in the outbound section, which executes after the backend service responds.
The correct answer is correct because Azure API Management policy sections are executed in a strict chronological sequence: inbound, backend, outbound, and on-error. Inbound policies execute before the request is routed to the backend service, while outbound policies execute after the backend service has processed the request and returned a response to the gateway. Placing the IP filtering and JWT validation policies in the outbound section means that these validation checks are bypassed before the backend is invoked, exposing the backend service to unauthorized calls.

Step-by-Step Solution

1
Analyze the sections of the APIM policy XML structure.
The XML document defines the `<ip-filter>` and `<jwt-validate>` policies inside the `<outbound>` section, leaving the `<inbound>` section with only the `<base />` policy.
Determining the locations of key policy configurations is the first step in assessing their execution timing.
2
Evaluate the execution sequence of API Management policy pipelines.
APIM executes policies in a strict sequential order: inbound (before backend call) -> backend (during backend call routing/execution) -> outbound (after backend call, before client response).
Understanding the pipeline lifecycle determines when validation checks occur relative to the backend invocation.
3
Determine the impact of placing the security policies in the outbound section.
Since the `<inbound>` section has no filtering or validation, all incoming client requests are immediately forwarded to the backend service. The `<ip-filter>` and `<jwt-validate>` checks are only executed after the backend has fully processed the request, leaving the backend exposed to unauthorized invocations.
Identifying the mismatch between the desired security posture and actual execution order reveals the correct behavior.

Key Concept

Azure API Management policy execution order and section placement rules
Question 399Question

You are developing a web application using ASP.NET Core 8.0 that will run on Azure App Service. The application is configured to send telemetry to an Azure Application Insights instance. You need to implement the Application Insights Snapshot Debugger to capture call stacks when unhandled exceptions occur, and ensure that developers can download and analyze these snapshots from the Azure portal.

Which of the following actions should you perform? (Select TWO.)

Select all that apply

Show answer & explanation

Answer: Assign the developers to the Application Insights Snapshot Debugger role at the Application Insights resource scope.; Install the Microsoft.ApplicationInsights.SnapshotCollector NuGet package and register the collector in the application startup code.

Answer

To configure the Snapshot Debugger and enable developers to access it, you must install the Microsoft.ApplicationInsights.SnapshotCollector NuGet package and register the collector service in your startup code. Additionally, you must assign the developers to the Application Insights Snapshot Debugger role at the Application Insights resource scope.
To implement the Snapshot Debugger, the application code must include the Microsoft.ApplicationInsights.SnapshotCollector NuGet package and register the snapshot collector in startup. Additionally, to view the snapshots, users must be granted the Application Insights Snapshot Debugger role, as general contributor or reader roles do not have permission to view sensitive memory dumps.

Step-by-Step Solution

1
Add code-level telemetry capture for exception snapshots.
Installed the Microsoft.ApplicationInsights.SnapshotCollector NuGet package and registered it in the dependency injection container using builder.Services.AddSnapshotCollector().
This allows the application to capture local memory dumps and call stacks when an unhandled exception is thrown.
2
Ensure the hosting environment supports the Diagnostic Snapshot Collector.
Configured the App Service plan to a tier of Basic or higher (such as Standard or Premium).
Snapshot Debugger has a minimum requirement of the Basic (B1) App Service plan tier to run.
3
Configure role-based access control (RBAC) for the developers.
Assigned the Application Insights Snapshot Debugger role to the developer accounts.
Snapshots can contain sensitive data from application memory. Standard monitoring roles like Reader or Monitoring Contributor do not grant permissions to download or view these snapshots.

Key Concept

Configuring Application Insights Snapshot Debugger using code-based setup and RBAC roles.
Question 400Question

A company implements a data ingestion system using C# and the Azure.Storage.Blobs SDK (v12). A background service must overwrite the content of an existing block blob. To prevent concurrent write conflicts, an active lease has already been acquired on the target blob. The active lease ID is stored in a string variable named `activeLeaseId`.

You need to write the code that uploads the new content to the block blob, ensuring that the operation fails if the lease ID does not match. Which code segment should you use to perform the upload?

Show answer & explanation

Answer: var options = new BlobUploadOptions
{
Conditions = new BlobRequestConditions { LeaseId = activeLeaseId }
};
await blobClient.UploadAsync(contentStream, options);

Answer

Use BlobUploadOptions with the Conditions property set to a new instance of BlobRequestConditions with LeaseId set to activeLeaseId.
The correct answer correctly instantiates a BlobUploadOptions object, sets its Conditions property to a new instance of BlobRequestConditions, and assigns the lease ID to the LeaseId property. In Azure.Storage.Blobs v12, this is the standard and correct way to enforce lease constraints on a blob upload operation.

Step-by-Step Solution

1
Identify the modern Azure.Storage.Blobs SDK (v12) request conditions wrapper.
The BlobRequestConditions class is used to specify conditional access constraints such as lease IDs for blob operations.
This class replaces older access condition models from legacy SDKs.
2
Associate the request conditions with the upload operation.
The BlobUploadOptions class contains a Conditions property of type BlobRequestConditions.
This links the lease constraints to the specific upload request.
3
Set the lease ID condition to target the active lease.
Set the LeaseId property of the BlobRequestConditions instance to activeLeaseId.
This ensures the Azure Storage service validates that the client holds the active lease before completing the write operation.

Key Concept

Applying lease conditions to Azure Blob Storage write operations using the Azure.Storage.Blobs SDK (v12)
Estimated Time:1m 30s
PreviousPage 20 / 49Next
All practice questions — Microsoft Azure Developer (AZ-204) | Examkin