This chapter covers Application Insights, Microsoft's application performance management (APM) service for monitoring live applications. Application Insights is a critical topic for the AZ-204 exam, appearing in approximately 10-15% of questions, especially in the Monitor objective. You will learn how to instrument applications, collect telemetry, query data using Log Analytics, and set up alerts and dashboards. Mastering Application Insights is essential for diagnosing issues, understanding user behavior, and ensuring application reliability in production.
Jump to a section
Application Insights works like a flight data recorder (black box) in an aircraft. The recorder continuously captures thousands of parameters: altitude, speed, engine temperature, control positions, and cockpit audio. When an incident occurs, investigators don't guess—they replay the exact sequence of events. Similarly, Application Insights instruments your application to collect telemetry: requests, dependencies, exceptions, traces, and custom events. It stores this data in a time-series database with automatic sampling and aggregation. When a user reports a slow page or an error, you can query the exact request chain, see which SQL query caused the slowdown, and view the exception stack trace. Just as the recorder has limited storage and overwrites old data, Application Insights uses sampling to manage cost and retention. The correlation ID in Application Insights is like the flight number—it ties every event to a specific user operation across services. Without instrumentation, debugging a production issue is like investigating a crash without the black box: you have only logs and guesses.
What is Application Insights?
Application Insights is an extensible Application Performance Management (APM) service for developers and DevOps professionals. It automatically detects performance anomalies, includes powerful analytics tools, and integrates with Visual Studio and Azure DevOps. It helps you continuously improve performance and usability.
How It Works Internally
Application Insights instruments your application by collecting telemetry data: requests, dependencies, exceptions, traces, page views, and custom events. The instrumentation can be done via: - Auto-instrumentation: For Azure App Services, VMs, and on-premises via Application Insights Agent (formerly Status Monitor). No code changes required. - SDK: For .NET, Java, Node.js, Python, JavaScript, and others. Provides full control over telemetry. - OpenTelemetry: A vendor-neutral standard that can export to Application Insights.
Key Components and Defaults
#### Instrumentation Key (iKey) - A GUID that identifies your Application Insights resource. - Required for sending telemetry. - Can be stored in configuration files or environment variables.
#### Telemetry Types - Request: Incoming HTTP requests. Default: collected automatically for ASP.NET, ASP.NET Core, and Java. - Dependency: Outbound calls to SQL, HTTP, Azure services. Default: collected for ADO.NET, HTTP clients, Azure SDK. - Exception: Caught and uncaught exceptions. Default: collected automatically. - Trace: Log statements (e.g., using ILogger). Requires SDK configuration. - Custom Event: Business events (e.g., "OrderPlaced"). Requires manual tracking. - Page View: Client-side page loads (JavaScript SDK). - Metric: Numeric values (e.g., queue length). - Availability: Web tests that ping your endpoints.
#### Sampling - Adaptive Sampling: Automatically adjusts telemetry volume to stay under a configured maximum rate (default: 5 events per second for ASP.NET). - Fixed-rate Sampling: You set a percentage (e.g., 10%). - Ingestion Sampling: At the backend, if your data rate exceeds the pricing tier.
#### Retention - Default: 90 days for logs and metrics. - Continuous export: To Azure Storage for longer retention (up to 90 days per export). - Log Analytics workspace: Can retain up to 2 years with appropriate pricing tier.
Configuration and Verification Commands
#### Setting up Application Insights in an ASP.NET Core app
// In Program.cs
builder.Services.AddApplicationInsightsTelemetry();#### Configuring the Instrumentation Key
// appsettings.json
{
"ApplicationInsights": {
"InstrumentationKey": "your-ikey"
}
}#### Verifying telemetry is flowing - Use the Application Insights blade in Azure portal. - Navigate to "Live Metrics" to see real-time data. - Query using Log Analytics:
requests | where timestamp > ago(1h) | countInteraction with Related Technologies
Azure Monitor: Application Insights is part of Azure Monitor. It sends data to Log Analytics workspaces.
Log Analytics: Advanced query language (Kusto Query Language, KQL) for analyzing telemetry.
Azure Alerts: Set up metric or log alerts based on Application Insights data.
Azure Workbooks: Create rich visual reports combining data from multiple sources.
Azure Dashboards: Pin Application Insights charts for monitoring.
Azure DevOps: Integrate with deployment pipelines to detect regressions.
Smart Detection
Application Insights automatically analyzes telemetry and alerts you about:
Failed request rate anomalies
Performance anomalies
Resource utilization issues
Degradation in dependency calls
Distributed Tracing
For microservices, Application Insights correlates telemetry using: - Operation ID: Links all events for a single user request across services. - Parent ID: Establishes the hierarchy of calls. - W3C Trace-Context: Standard format for distributed tracing.
Pricing Tiers
Pay-as-you-go: per GB ingested, with a free grant of 5 GB/month.
Enterprise: per node, includes unlimited data retention.
Log Analytics workspace: separate pricing for workspace-based Application Insights.
Key Timers and Defaults
Sampling rate default: 5 events/second for adaptive sampling.
Retention: 90 days.
Data export interval: Continuous export batches every few minutes.
Live Metrics latency: < 5 seconds.
Availability test frequency: Every 5 minutes (default).
Code Example: Custom Event Tracking
using Microsoft.ApplicationInsights;
TelemetryClient telemetry = new TelemetryClient();
telemetry.Context.InstrumentationKey = "your-ikey";
telemetry.TrackEvent("OrderPlaced", new Dictionary<string, string> { {"OrderId", "123"} });Query Example: Top Slowest Requests
requests
| where timestamp > ago(24h)
| summarize avg(duration) by name
| order by avg_duration desc
| take 10Create Application Insights Resource
In the Azure portal, click 'Create a resource', search for 'Application Insights', and fill in the required fields: Subscription, Resource Group, Name, Region, and Workspace (workspace-based or classic). Choose workspace-based to enable Log Analytics integration. Click Review + Create, then Create. This creates a resource that will receive telemetry. The resource generates an Instrumentation Key (iKey) and a Connection String, both used to configure the SDK.
Instrument Your Application
Add the Application Insights SDK to your application. For .NET Core, add the `Microsoft.ApplicationInsights.AspNetCore` NuGet package and call `AddApplicationInsightsTelemetry()` in `ConfigureServices`. For Java, add the `applicationinsights-core` dependency and configure via `ApplicationInsights.xml`. For Node.js, use the `applicationinsights` npm package. For JavaScript, add the SDK snippet to your HTML pages. Each SDK automatically collects requests, dependencies, and exceptions.
Configure Telemetry Collection
Customize what telemetry is collected. You can enable/disable auto-collection, adjust sampling (adaptive or fixed-rate), and add custom telemetry. For example, to disable dependency collection: `builder.Services.AddApplicationInsightsTelemetry(options => options.EnableDependencyTrackingTelemetryModule = false);`. You can also set the Instrumentation Key in configuration files or environment variables.
Deploy and Verify Telemetry
Deploy your application to Azure (App Service, VM, etc.) or on-premises. Verify telemetry is flowing by navigating to the Application Insights blade in the portal. Use 'Live Metrics' to see real-time data. Alternatively, query the Log Analytics workspace: `requests | where timestamp > ago(1h) | count`. If no data appears, check the Instrumentation Key, ensure the SDK is initialized, and verify network connectivity to the ingestion endpoint.
Analyze and Set Up Alerts
Use the portal to explore telemetry: view the Application Map to see dependencies, use Performance blade to find slow requests, and use Failures blade to see exceptions. Create alerts based on metrics (e.g., failed requests > 5%) or log queries. For example, a metric alert on 'Failed requests' triggers when the count exceeds a threshold. You can also create Availability tests (URL ping tests) to monitor uptime.
Continuous Monitoring and Optimization
Regularly review smart detection alerts that automatically identify anomalies. Use Usage analysis to understand user behavior. Create Workbooks for custom dashboards. Export data to Azure Storage for long-term retention or to Power BI for deeper analysis. Optimize costs by adjusting sampling rates or using ingestion sampling. Update instrumentation as your application evolves.
Enterprise Scenario 1: E-commerce Platform Performance Monitoring
A large e-commerce company uses Application Insights to monitor their ASP.NET Core microservices. They instrument each service with the SDK and use distributed tracing to correlate requests across services. The operations team has set up metric alerts for high response times (> 2 seconds) and failure rates (> 1%). They use the Application Map to visualize dependencies and identify bottlenecks, such as a slow SQL database. They also track custom events like 'CheckoutStarted' and 'PaymentFailed' to monitor business KPIs. In production, they handle 10,000 requests per second and use adaptive sampling to keep costs manageable. A common issue is misconfigured sampling causing missing data for low-volume endpoints. They solved this by using fixed-rate sampling for critical endpoints.
Enterprise Scenario 2: SaaS Application User Analytics
A SaaS provider uses Application Insights to understand user behavior and diagnose issues. They instrument the frontend with the JavaScript SDK to collect page views and custom events. They use the Usage analysis features to build funnels and retention reports. They also use availability tests to monitor uptime across multiple regions. A challenge they faced was high data ingestion costs due to verbose trace logging. They implemented fixed-rate sampling at 10% for traces and used the Log Analytics workspace to retain data for 90 days. They also set up continuous export to Azure Blob Storage for compliance. A common misconfiguration is forgetting to set the Instrumentation Key in production, resulting in no telemetry. They use Azure Key Vault to securely store the key.
Enterprise Scenario 3: IoT Backend Monitoring
An IoT company monitors their Azure Functions backend using Application Insights. They use the built-in integration with Azure Functions – simply enabling Application Insights in the Function App settings. They collect telemetry for each function invocation, including bindings and dependencies. They use custom metrics to track device telemetry ingestion rates and error counts. They set up alerts for function failures and cold start delays. A common issue is 'sampling not applied to custom events' – they had to explicitly set sampling for custom telemetry. They also use Log Analytics queries to correlate device errors with backend exceptions. They export data to Power BI for executive dashboards.
What AZ-204 Tests on Application Insights
AZ-204 objective 4.1 focuses on monitoring application performance with Application Insights. The exam expects you to:
Choose the appropriate instrumentation method (SDK vs auto-instrumentation)
Configure telemetry collection (sampling, custom events, metrics)
Query telemetry using Log Analytics (KQL)
Set up alerts and dashboards
Analyze performance and diagnose issues using the portal
Common Wrong Answers and Why Candidates Choose Them
'Use Azure Monitor instead of Application Insights for APM' – While Application Insights is part of Azure Monitor, the exam specifically tests Application Insights for application-level monitoring. Azure Monitor is broader (infrastructure, platform). Candidates confuse the two.
'Enable adaptive sampling to reduce cost without losing any data' – Adaptive sampling reduces volume but does lose some data; it's a statistical sample. Candidates think sampling preserves all data.
'Use the Instrumentation Key in the connection string' – The connection string includes the Instrumentation Key but also the ingestion endpoint. Candidates might think they are interchangeable; but the connection string is the modern recommended approach.
'Set retention to 365 days for free' – Retention is 90 days by default; longer retention requires a Log Analytics workspace with additional cost. Candidates overestimate free retention.
Specific Numbers and Terms Appearing on the Exam
Default sampling rate: 5 events/second
Default retention: 90 days
Live Metrics latency: < 5 seconds
Availability test default interval: 5 minutes
KQL operators: where, summarize, join, project, take
Telemetry types: requests, dependencies, exceptions, traces, custom events, metrics
Edge Cases and Exceptions
Sampling and custom events: Custom events are NOT sampled by default; you must enable sampling for them.
Distributed tracing requires W3C Trace-Context; older format (Request-Id) is deprecated.
Workspace-based vs Classic: The exam may ask about the difference – workspace-based integrates with Log Analytics and allows longer retention.
Application Insights for containers: Use the SDK; auto-instrumentation is limited.
How to Eliminate Wrong Answers
Identify the core requirement: is it about cost control? Look for sampling. Is it about diagnosing a slow SQL query? Look for dependency tracking. Is it about correlating across services? Look for distributed tracing. For alerts, metric alerts are simpler; log alerts are more powerful but more expensive. Always check if the question mentions 'real-time' – that points to Live Metrics. If 'long-term storage' is needed, think continuous export or Log Analytics workspace.
Application Insights is an APM service for monitoring live applications; part of Azure Monitor.
Instrumentation can be done via SDK, auto-instrumentation, or OpenTelemetry.
Default telemetry retention is 90 days; use Log Analytics workspace for longer retention.
Adaptive sampling defaults to 5 events/second; custom events are not sampled by default.
Live Metrics provides real-time telemetry with <5 seconds latency.
Distributed tracing uses W3C Trace-Context to correlate requests across services.
Availability tests (URL ping) can be set to run every 5 minutes by default.
Smart Detection automatically alerts on anomalies in failures, performance, and dependencies.
Use Kusto Query Language (KQL) for analyzing telemetry in Log Analytics.
Connection String is the modern way to configure the SDK, replacing Instrumentation Key.
These come up on the exam all the time. Here's how to tell them apart.
Application Insights (Workspace-based)
Telemetry stored in a Log Analytics workspace
Can retain data up to 2 years
Supports cross-resource queries using Log Analytics
Integration with Azure Sentinel and other Log Analytics features
Requires a Log Analytics workspace (may incur additional cost)
Application Insights (Classic)
Telemetry stored in an Application Insights-specific storage
Retention limited to 90 days
Queries limited to the Application Insights resource
No direct integration with Log Analytics (use Continuous Export)
Simpler to set up; no dependency on Log Analytics workspace
Mistake
Application Insights is only for .NET applications
Correct
Application Insights supports multiple platforms: .NET, Java, Node.js, Python, JavaScript, and others. It also supports auto-instrumentation for Azure App Services and VMs regardless of language.
Mistake
Enabling adaptive sampling means no telemetry is lost
Correct
Adaptive sampling reduces telemetry volume by discarding some data. It is a statistical sample, so some events are not recorded. For critical transactions, use fixed-rate sampling or mark specific events as 'sampling preserved'.
Mistake
Application Insights can store telemetry indefinitely at no extra cost
Correct
Default retention is 90 days. For longer retention, you must use continuous export to Azure Storage or a Log Analytics workspace with a longer retention tier, which incurs additional costs.
Mistake
Live Metrics in Application Insights shows all telemetry with no sampling
Correct
Live Metrics shows a sample of telemetry for real-time monitoring. It is not a complete record. For full analysis, use Log Analytics queries.
Mistake
The Instrumentation Key is the only way to configure the SDK
Correct
The Connection String is the modern recommended approach. It includes the Instrumentation Key plus the ingestion endpoint. Microsoft recommends using the Connection String over the Instrumentation Key.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
In the Azure portal, navigate to your App Service, then under Settings, select 'Application Insights'. Click 'Enable' and select an existing or create a new Application Insights resource. This enables auto-instrumentation without code changes. The App Service will restart to apply the instrumentation. For more control, add the SDK manually.
Azure Monitor is a comprehensive monitoring service for Azure resources, including infrastructure (VMs, containers) and platform (Azure SQL, Storage). Application Insights is a subset of Azure Monitor focused on application performance monitoring (APM). Application Insights collects telemetry from your application code, while Azure Monitor collects metrics and logs from Azure services. Both are accessible via the Azure Monitor portal.
You can reduce costs by: 1) Enabling sampling (adaptive or fixed-rate) to reduce data volume. 2) Setting daily caps to limit ingestion. 3) Adjusting retention to 90 days or less. 4) Using continuous export to cheaper storage for long-term retention. 5) Filtering out unnecessary telemetry (e.g., disabling dependency tracking for non-critical dependencies). Monitor costs in the 'Usage and estimated costs' blade.
If you use workspace-based Application Insights, your data is stored in a Log Analytics workspace. You can query it using Kusto Query Language (KQL). For example: `requests | where timestamp > ago(24h) | summarize count() by resultCode`. For classic Application Insights, use the 'Logs' blade within the Application Insights resource, which also uses KQL. You can also query across workspaces using `union`.
Adaptive sampling automatically adjusts the sampling rate to maintain a target rate (default 5 events/sec). It reduces volume during high traffic and increases during low traffic. Fixed-rate sampling lets you set a fixed percentage (e.g., 10%) of telemetry to keep. Adaptive sampling is easier to manage, but fixed-rate gives predictable data volume and is better for critical endpoints. Both can be configured in the SDK or in the portal for ingestion sampling.
Use the TelemetryClient.TrackEvent() method. For example, in C#: `telemetry.TrackEvent("OrderPlaced", new Dictionary<string, string> { {"OrderId", "123"} });`. You can also add metrics. Custom events are not sampled by default, so you may want to enable sampling for them to control costs. In the portal, you can query custom events using the `customEvents` table.
Yes, Application Insights can monitor applications hosted on-premises, in other clouds, or on VMs. You need to install the Application Insights SDK or use the Application Insights Agent (for .NET) to send telemetry to Azure. Ensure outbound connectivity to the Application Insights ingestion endpoint. The agent can be used without code changes for .NET applications.
You've just covered Application Insights — now see how well it sticks with free AZ-204 practice questions. Full explanations included, no account needed.
Done with this chapter?