Azure  

Monitoring Application Performance Using Azure Application Insights

In modern software applications, ensuring high performance, reliability, and a smooth user experience is critical. However, with complex distributed systems, identifying issues like slow response times, exceptions, or performance bottlenecks can be challenging.

This is where Azure Application Insights comes in. It is a powerful monitoring and telemetry platform that provides deep insights into application behavior, usage patterns, and infrastructure performance.

In this article, we will cover:

  1. Overview of Azure Application Insights

  2. Key telemetry types

  3. Instrumenting applications (.NET Core, Angular, and JavaScript)

  4. Monitoring performance and detecting issues

  5. Real-world best practices and tips

  6. Dashboards, alerts, and proactive monitoring

This guide is intended for senior developers, DevOps engineers, and technical leads looking to implement robust application monitoring.

1. Overview of Azure Application Insights

Azure Application Insights is a part of Azure Monitor that helps you:

  • Detect application issues early.

  • Analyze performance metrics like response times and dependency latencies.

  • Track user interactions and usage patterns.

  • Integrate monitoring for backend APIs and frontend apps.

  • Set up alerts to proactively notify the team when problems occur.

It supports multiple platforms:

  • .NET and .NET Core applications

  • Java, Node.js, Python

  • Frontend apps using JavaScript or Angular

  • Containers and serverless applications

2. Key Telemetry Types

Application Insights collects various telemetry types:

  1. Request Telemetry

    • Tracks HTTP requests to your backend APIs or web apps.

    • Metrics: response time, success/failure rate, request count.

  2. Dependency Telemetry

    • Monitors calls to databases, APIs, external services, or caches.

    • Helps detect slow or failing dependencies.

  3. Exception Telemetry

    • Automatically captures unhandled exceptions.

    • Provides stack trace, method, and line number information.

  4. Trace Telemetry

    • Logs custom trace messages from your application.

    • Useful for debugging and logging application flow.

  5. Custom Events

    • Capture specific user actions like button clicks, page visits, or transactions.

  6. Metrics

    • CPU usage, memory, response time distributions, and request rates.

3. Instrumenting Applications

3.1 Instrumenting a .NET Core Application

  1. Install NuGet Packages:

dotnet add package Microsoft.ApplicationInsights.AspNetCore
  1. Configure Application Insights in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add Application Insights
builder.Services.AddApplicationInsightsTelemetry(options =>
{
    options.ConnectionString = "InstrumentationKey=<YOUR-INSTRUMENTATION-KEY>";
});

var app = builder.Build();
  1. Track Custom Events and Metrics:

using Microsoft.ApplicationInsights;

public class OrderService
{
    private readonly TelemetryClient _telemetry;

    public OrderService(TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

    public void PlaceOrder(Order order)
    {
        try
        {
            // Business logic
            _telemetry.TrackEvent("OrderPlaced", new Dictionary<string, string>
            {
                { "ProductId", order.ProductId.ToString() },
                { "CustomerId", order.CustomerId.ToString() }
            });
        }
        catch (Exception ex)
        {
            _telemetry.TrackException(ex);
            throw;
        }
    }
}

3.2 Instrumenting Angular Applications

  1. Install the Application Insights JavaScript SDK:

npm install @microsoft/applicationinsights-web
  1. Configure in app.module.ts or a dedicated service:

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AppInsightsService {
  private appInsights: ApplicationInsights;

  constructor() {
    this.appInsights = new ApplicationInsights({
      config: {
        connectionString: 'InstrumentationKey=<YOUR-INSTRUMENTATION-KEY>'
      }
    });
    this.appInsights.loadAppInsights();
  }

  trackPageView(name?: string, url?: string) {
    this.appInsights.trackPageView({ name, uri: url });
  }

  trackEvent(name: string, properties?: { [key: string]: string }) {
    this.appInsights.trackEvent({ name }, properties);
  }

  trackException(exception: Error) {
    this.appInsights.trackException({ exception });
  }
}
  1. Track page views and user actions:

constructor(private appInsightsService: AppInsightsService) {}

ngOnInit() {
  this.appInsightsService.trackPageView('HomePage', window.location.href);
}

onButtonClick() {
  this.appInsightsService.trackEvent('CheckoutButtonClicked');
}

3.3 Instrumenting API Dependencies

Application Insights automatically tracks SQL Server and HTTP dependencies, but you can also log custom dependencies:

_telemetry.TrackDependency("SQL", "GetOrders", commandText, startTime, duration, success);

4. Monitoring Performance and Detecting Issues

4.1 Key Metrics to Track

  1. Request duration – identify slow endpoints.

  2. Failure rate – track HTTP 5xx or 4xx responses.

  3. Dependency duration – monitor database or API call latency.

  4. CPU, memory, and disk usage – monitor infrastructure health.

  5. User interactions – track adoption and user engagement.

4.2 Live Metrics Stream

  • Application Insights provides real-time telemetry through Azure Portal.

  • Useful for monitoring deployments and production incidents.

4.3 Detecting Performance Bottlenecks

  • Use Application Map to visualize dependencies.

  • Identify slow API calls or database queries causing high response times.

  • Drill down into individual request traces for root cause analysis.

5. Real-World Best Practices

  1. Always use the Connection String instead of Instrumentation Key for newer setups.

  2. Track custom events and metrics for business KPIs, not just technical metrics.

  3. Set telemetry sampling to avoid overwhelming Application Insights with high-volume requests:

builder.Services.AddApplicationInsightsTelemetry(options =>
{
    options.ConnectionString = "<CONNECTION_STRING>";
    options.EnableAdaptiveSampling = true;
});
  1. Use dependency tracking to monitor database calls and external services.

  2. Integrate with Azure Monitor and Log Analytics for advanced querying.

  3. Protect sensitive data – avoid sending PII (Personally Identifiable Information).

  4. Use alerts and automated actions to proactively respond to anomalies.

6. Dashboards and Alerts

6.1 Custom Dashboards

  • Create dashboards in Azure Portal combining request rates, response times, failures, and user metrics.

  • Share dashboards with developers, support teams, and management.

6.2 Setting Alerts

  • Use metric alerts for thresholds (e.g., request duration > 2 seconds).

  • Use log alerts for exceptions or specific error codes.

  • Configure action groups to send notifications via email, Teams, or webhook.

Example: Alert on high 500 HTTP responses:

requests
| where resultCode == "500"
| summarize count() by bin(timestamp, 5m)
| where count_ > 5

7. Advanced Features

  1. Application Map: visualize all components and dependencies.

  2. Smart Detection: automatically detect anomalies in request rates or response times.

  3. Continuous Export: export telemetry to storage accounts or SIEM solutions.

  4. Performance Counters: track CPU, memory, and custom performance counters.

  5. Integration with DevOps: associate telemetry with deployment pipelines for root cause analysis.

8. Security Considerations

  • Limit telemetry of sensitive user data.

  • Use role-based access control in Azure Portal.

  • Audit who can view and manage Application Insights data.

  • Enable HTTPS and secure endpoints for telemetry ingestion.

Summary

Azure Application Insights allows developers and DevOps teams to monitor, analyze, and optimize application performance in real time. Key points:

  1. Collect request, dependency, exception, and custom telemetry.

  2. Instrument .NET Core APIs, Angular frontend, and dependencies.

  3. Track performance metrics, detect bottlenecks, and analyze usage patterns.

  4. Build dashboards and alerts for proactive monitoring.

  5. Apply real-world best practices: sampling, sensitive data protection, and integration with DevOps workflows.

With Azure Application Insights, teams can deliver reliable, high-performing applications, improve customer satisfaction, and reduce mean time to detect and resolve issues.