monitoring
308 TopicsLessons Learned #542: Reviewing Historical Azure SQL Database Storage Growth
This week I worked on a service request where our customer needed to understand how an Azure SQL Database had grown over time. This information can be useful for capacity planning, cost analysis, and performance reviews. There are several possible approaches, depending on whether we need to review recent historical data that is still available in Azure Monitor, or whether we need to start collecting long-term historical data from now on. In this lesson learned, I would like to summarize some of the options available. 1. Reviewing recent historical data using Azure Monitor metrics The first point to clarify is how Azure Monitor metrics retention works. Most Azure platform metrics are retained for up to 93 days. However, a single Azure Monitor Metrics chart can query no more than 30 days of data at a time. This means that, if the data is still within the Azure Monitor retention window, we might need to review the metric in 30-day intervals. For Azure SQL Database storage usage, the metric commonly used is Data space used 2. Exporting metrics to Log Analytics for long-term analysis If the requirement is to perform long-term analysis, I would like to recommended option is to enable Diagnostic Settings on the Azure SQL Database and send the metrics to a Log Analytics workspace. Azure SQL Database diagnostic telemetry can be exported to different destinations, including: Log Analytics workspace Storage Account Event Hubs Using Log Analytics provides a very flexible way to query, aggregate, and visualize the data by using KQL. Once the metrics are available in Log Analytics, we can calculate the monthly database growth. For example: AzureMetrics | where ResourceProvider =~ "MICROSOFT.SQL" | where ResourceId == "/SUBSCRIPTIONS/your subscription/RESOURCEGROUPS/yourresourcegroup/PROVIDERS/MICROSOFT.SQL/SERVERS/yourserver/DATABASES/yourdatabase" | where MetricName == "storage" | summarize arg_max(TimeGenerated, Average) by Month = startofmonth(TimeGenerated) | project Month, DataSpaceUsedGB = round(Average / 1024 / 1024 / 1024, 2) | order by Month asc This query takes the last available value for each month and converts the metric from bytes to GB. Depending on the analysis requirements, the query can be customized. 3. Creating a custom database space usage history process If we need more control, or if we want to collect more granular database-level information, another option is to create a custom process that periodically captures the current database space usage into a table. This approach can be useful when we want to keep the information inside the database itself and avoid depending on external telemetry storage for this specific requirement. For example, the following table can be used to store daily or weekly snapshots: CREATE TABLE dbo.DatabaseSpaceUsageHistory ( SnapshotTimeUtc datetime2(3) NOT NULL DEFAULT SYSUTCDATETIME(), DatabaseName sysname NOT NULL, DataAllocatedMB decimal(19,2) NULL, DataUsedMB decimal(19,2) NULL, DataUnusedMB decimal(19,2) NULL, LogAllocatedMB decimal(19,2) NULL ); --Example collection query: INSERT INTO dbo.DatabaseSpaceUsageHistory ( DatabaseName, DataAllocatedMB, DataUsedMB, DataUnusedMB, LogAllocatedMB ) SELECT DB_NAME() AS DatabaseName, SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8.0 / 1024 AS DataAllocatedMB, SUM(CASE WHEN type_desc = 'ROWS' THEN FILEPROPERTY(name, 'SpaceUsed') END) * 8.0 / 1024 AS DataUsedMB, ( SUM(CASE WHEN type_desc = 'ROWS' THEN size END) - SUM(CASE WHEN type_desc = 'ROWS' THEN FILEPROPERTY(name, 'SpaceUsed') END) ) * 8.0 / 1024 AS DataUnusedMB, SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8.0 / 1024 AS LogAllocatedMB FROM sys.database_files; This process can be executed daily, weekly, or monthly using the automation method that best fits the environment. This approach provides more control over the data collected, the retention period, and the frequency of collection.125Views0likes0CommentsYour on-call rotation has a new member: 10 production incidents, end to end, with Azure SRE Agent
What this post is. A hands-on, reproducible walkthrough of ten real production failure modes — App Service, AKS, Azure SQL, Cosmos DB, VMs, VM Scale Sets, Application Gateway, and Service Bus — each one driven end to end by Azure SRE Agent: detection, hypothesis-driven investigation, ITSM ticketing, bounded remediation, recovery validation, and follow-up records. What this post is not. A claim that you install SRE Agent and all of this happens on day one. Every workflow below needs telemetry, scoped RBAC, a response plan, an approved action surface, and an ITSM integration. I'll be explicit about which parts are documented product behavior and which parts you have to wire yourself — because that distinction is the difference between a demo that works on stage and one that works at 3 AM. TL;DR The pattern Alert → agent investigates read-only → agent opens/updates the ticket with evidence → agent proposes a bounded action → human approves → agent executes → agent validates recovery → agent files the follow-up record The unlock Not "AI fixes prod." The unlock is that investigation — the 20 minutes of tab-switching between Azure Monitor, App Insights, deployment history, and Activity Log — is fully automated and consistent, and the fix arrives pre-justified with an evidence chain The guardrail Read-only automatic. Ticketing automatic. Production writes in Review mode. Guest-OS work through fixed-purpose runbooks, never a shell prompt The reality check SRE Agent hard-blocks delete / remove and all az keyvault commands, respects Azure management locks, and only one incident platform can be active at a time. Several patterns in this post need a custom tool or MCP server to complete the loop Time to first value One resource group, one alert rule, one response plan. You can reproduce use case #1 in an afternoon 1. Why the "investigation" half is the real prize Every conversation about AI in operations goes straight to remediation. "Will it restart my app?" That's the least interesting question, and it's the one with the most downside risk. Think about what actually consumes the minutes during a Sev1. The alert fires. Someone acknowledges. Then: Open Azure Monitor, confirm the metric is real and not a probe artifact Open Application Insights, find the dominant exception Open the deployment pipeline, find what shipped and when Open Activity Log, check whether someone changed configuration Open Resource Health, rule out a platform incident Open the other environment, confirm the previous version is healthy Assemble all of that into a sentence a human can act on That's twenty minutes of context assembly performed by a tired human, differently every time, with quality that depends entirely on who happens to be on call. It is the single most automatable part of incident response and the part nobody automates, because scripts can't reason about which of six hypotheses fits the evidence. This is exactly what root cause analysis in SRE Agent is designed for. The agent doesn't grep logs — it forms hypotheses and invalidates them: HYPOTHESIS 1: Recent deployment broke something ├─ Checked: Last deployment was 3 days ago ├─ Evidence: Error rate stable until 30 minutes ago └─ Result: INVALIDATED HYPOTHESIS 2: Database overloaded ├─ Checked: Azure SQL metrics (CPU, DTU, connections) ├─ Evidence: DTU at 98%, query duration 4x normal ├─ Traced: SELECT * FROM orders WHERE... taking 8.2s └─ Result: VALIDATED ROOT CAUSE: Orders table missing index on customer_id column. Query plan shows full table scan on 2.1M rows. RECOMMENDED ACTION: Add index on orders.customer_id Similar fix applied in INC-2341 (3 weeks ago) That last line — recalling a similar incident from three weeks ago — is the compounding part. Every thread produces a session insight: symptoms observed, steps that worked, root cause, and pitfalls to avoid. Thirty minutes after a thread goes quiet, the agent indexes those learnings. Next time the same resource misbehaves, that history surfaces first. So the framing for the rest of this post: remediation is the punchline, but investigation is the product. Every one of the ten use cases below has a large read-only phase you can turn on tomorrow with zero write permissions, and a small write phase you should gate behind approval for a long time. 2. What Azure SRE Agent actually does Before the use cases, here is the honest capability map, drawn from the product documentation rather than from a keynote. The three primary use cases Use case What it means Automate incidents Alert fires → agent queries monitoring tools, correlates signals across systems, identifies probable root cause, proposes mitigations Automate scheduled workflows Proactive health checks, compliance sweeps, and routine tasks on a schedule, with results routed to your incident platform or notification channel Investigate and advise Natural-language questions — "what changed in the last hour?" — answered with grounded citations The five extension primitives Everything you customize sits in one of five buckets: Primitive What it is When you reach for it Skills Procedural guidance ( SKILL.md ) plus optional attached tools; auto-loaded when relevant Team troubleshooting runbooks that should also execute Subagents / custom agents Purpose-built specialists invoked via /agent or routed to by a response plan A DatabaseExpert that owns every SQL incident Python tools Custom logic, transformations, API calls Anything that needs code, e.g. writing to the ServiceNow Table API MCP servers 40+ managed connectors (Datadog, New Relic, Splunk, Elastic, Dynatrace…) plus any custom MCP tool Bringing your non-Azure telemetry and your ITSM write surface into the loop Agent hooks Event-triggered automations at Stop and PostToolUse Policy enforcement, audit emission, blocking risky commands Six generic subagents ship built in — Explore, Plan, CodeReview, Bash, Verification, GeneralPurpose — and the agent can parallelize investigation, planning, review, shell, and verification work across them. A permission gate sits in front of all five primitives and evaluates every proposed tool call before it runs. Integrations you can assume Category Supported Monitoring Azure Monitor (metrics, logs, alerts, workbooks), Application Insights, Log Analytics, Grafana Incident platforms Azure Monitor Alerts, PagerDuty, ServiceNow — only one active at a time Source control / CI GitHub (repos, issues), Azure DevOps (repos, work items) Data Azure Data Explorer (Kusto), MCP servers Comms Slack, Microsoft Teams ⚠️ Design constraint worth internalizing early. Only one incident platform can be active at a time, and switching disconnects the current one. If your org runs PagerDuty for paging and ServiceNow for records of truth, you must pick which one the agent is bound to and reach the other through a connector or custom tool. Every use case below assumes ServiceNow is the bound platform. Skills vs. custom agents vs. knowledge files The three are constantly confused. This table settles it: Skills Custom agents Knowledge files Access Automatic when relevant Explicit ( /agent ) or routed by response plan Automatic search Tools Can attach Has its own None Context Uses thread context Shares thread context (no clean slate) Reference only Best for Team procedures with execution Domain specialists Runbooks, architecture docs Practical limits: a maximum of five concurrent active skills (oldest auto-unloads), knowledge base uploads up to 16 MB per file, and custom agent knowledge bases up to 1,000 files. 3. Anatomy of an agent-run incident Every use case in section 6 is an instance of this one shape. Learn it once. [[INCIDENT_FLOW_IMAGE]] Five properties make this shape safe, and they're worth stating as rules: The read phase has no blast radius. Turn it on everywhere, immediately, with Reader . One action per incident. Not "roll back and scale and restart." One bounded, reversible step, then re-measure. The proposed action is always the smallest reversible one. Swap a slot, don't redeploy. Bump one service tier, don't resize the cluster. Validation is a first-class phase, not a vibe. Define the metric, the threshold, and the duration before you approve. Technical recovery ≠ business recovery. Use case #10 makes this painfully clear. 4. Build the demo lab Everything below runs in a single throwaway resource group. Nothing here should touch a subscription you care about. 🧪 Lab hygiene. Create it, demo it, delete it. az group delete -n rg-sre-agent-demo --yes --no-wait when you're done. Several of these use cases deliberately break things. 4.1 Resource group and agent LOC=eastus2 RG=rg-sre-agent-demo az group create -n $RG -l $LOC Create the SRE Agent from the Azure portal and point it at $RG . Three things are created for you automatically: an Application Insights instance (this is where your audit trail lands), a Log Analytics workspace, a user-assigned managed identity (UAMI) — the identity every action runs as. 4.2 Choose a permission level deliberately At creation you pick one of two levels: Level Grants Use it when Reader Core monitoring roles + resource-type reader roles. Prompts for temporary elevation via on-behalf-of when it needs to act Start here. Production. Weeks 1–4 of any pilot Privileged Core monitoring roles + resource-type contributor roles Non-production, or after a proven pilot Regardless of level, these are always assigned: Role Scope Why Reader Resource group See resources and properties Log Analytics Reader Resource group Query logs and workspaces Monitoring Reader Resource group Read metrics Monitoring Contributor Subscription Acknowledge and close Azure Monitor alerts Grant additional access explicitly and narrowly: SUB=$(az account show --query id -o tsv) AGENT_MI=<agent-managed-identity-principal-id> # Read everywhere you want visibility az role assignment create \ --assignee $AGENT_MI \ --role "Reader" \ --scope "/subscriptions/$SUB" # Write ONLY where you intend the agent to act az role assignment create \ --assignee $AGENT_MI \ --role "Website Contributor" \ --scope "/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.Web/sites/app-checkout-demo"</agent-managed-identity-principal-id> 📌 A sharp edge. You can't remove individual permissions from an agent — only entire resource groups. Removing a resource group from the agent's scope revokes all access to it. Plan your resource group boundaries as your blast-radius boundaries, because that's exactly what they are. 4.3 Connect ServiceNow Use a dedicated, least-privileged integration user — not a shared admin account. Method When What you need Basic auth Quick setup, PDI, testing Username + password, itil or admin role OAuth 2.0 Production ServiceNow OAuth app (client ID + secret); register redirect https://logic-apis-{region}.consent.azure-apim.net/redirect Scope the connection so you don't drown: Assignment group — essential on a shared enterprise instance Priority — Critical through Planning Category Scanner defaults worth knowing: Setting Value Scan interval 1 minute Incidents per page 20 Max incidents per cycle 220 (11 pages) Initial lookback 30 days Setup performs a real connectivity check by fetching an actual incident, so credential and endpoint mistakes surface immediately instead of six hours later when nothing syncs. 🚨 Delete the quickstart plan. Connecting an incident platform auto-creates a quickstart_handler response plan that runs in fully autonomous mode across all impacted services. If you then build your own plans, incidents get routed twice or to the wrong agent. Go to Builder → Incident response plans → Table view and delete it before you do anything else. 4.4 Connect deployment correlation Half the use cases below hinge on "what shipped three minutes before the spike." That correlation requires a source control connector: GitHub — repositories and issues Azure DevOps — repos and work items Connect one. Without it, the agent can still read Azure Activity Log and deployment history, but it can't reach commits, PRs, or work items. 4.5 Create the demo resources # 1 · App Service with a staging slot (use cases 1) az appservice plan create -g $RG -n plan-demo --sku P1V3 --is-linux az webapp create -g $RG -p plan-demo -n app-checkout-demo --runtime "DOTNETCORE:8.0" az webapp deployment slot create -g $RG -n app-checkout-demo --slot previous # 2 · AKS (use case 2) az aks create -g $RG -n aks-demo --node-count 3 --generate-ssh-keys --enable-addons monitoring # 3 · Azure SQL (use case 3) az sql server create -g $RG -n sqlsrv-sre-demo -u sqladmin -p "<use-a-generated-password>" az sql db create -g $RG -s sqlsrv-sre-demo -n db-customer --service-objective S1 # 4 · Cosmos DB (use case 4) az cosmosdb create -g $RG -n cosmos-sre-demo az cosmosdb sql database create -g $RG -a cosmos-sre-demo -n catalog az cosmosdb sql container create -g $RG -a cosmos-sre-demo -d catalog \ -n products --partition-key-path /category --throughput 400 # 5–7 · VMs (use cases 5, 6, 7) az vm create -g $RG -n vm-payments-linux --image Ubuntu2204 --size Standard_B2s --generate-ssh-keys az vm create -g $RG -n vm-claims-win --image Win2022Datacenter --size Standard_B2ms \ --admin-username azureadmin --admin-password "<use-a-generated-password>" # 8 · VM Scale Set (use case 8) az vmss create -g $RG -n vmss-api-demo --image Ubuntu2204 --instance-count 12 \ --upgrade-policy-mode automatic --generate-ssh-keys # 10 · Service Bus (use case 10) az servicebus namespace create -g $RG -n sb-sre-demo --sku Standard az servicebus queue create -g $RG --namespace-name sb-sre-demo -n order-events \ --enable-dead-lettering-on-message-expiration true</use-a-generated-password></use-a-generated-password> Install the Azure Monitor Agent on the VMs and associate a data collection rule — without guest telemetry, use cases 5, 6, and 7 have nothing to detect. 4.6 One custom agent per domain Don't build a single mega-agent. Build specialists and let response plans route to them: Custom agent Owns Attached tools DeploymentAnalyzer App Service, AKS, anything release-correlated RunAzCliReadCommands , GitHub connector, Kusto DatabaseExpert Azure SQL, Cosmos DB RunAzCliReadCommands , Kusto, read-only SQL diagnostics tool GuestOSResponder VM / VMSS / IIS RunAzCliReadCommands , fixed-purpose runbook tools only NetworkPathExpert Application Gateway, NSG, DNS, TLS RunAzCliReadCommands IntegrationExpert Service Bus, Event Hubs RunAzCliReadCommands , Kusto A custom agent definition is small: name: database_expert system_prompt: | You are a database specialist for this estate. Analyze query performance, diagnose connection and saturation issues, and recommend the smallest reversible mitigation. Never propose schema changes, index changes, plan forcing, or session termination — those are DBA-owned and require a change record. handoff_description: Handles Azure SQL and Cosmos DB troubleshooting tools: - execute_kusto_query - RunAzCliReadCommands allowed_skills: - azure-sql-saturation-runbook - cosmos-throughput-runbook Note what that system_prompt is really doing: it is narrowing the action space. Half of production safety with an agent is telling it, in plain English, which categories of fix are off the table. 4.7 Response plans Create one plan per domain, all starting in Review: Plan Filter Custom agent Mode appsvc-p1 Priority 1 + 2, service checkout DeploymentAnalyzer Review aks-p1 Priority 1, service orders-api DeploymentAnalyzer Review db-critical Priority 1 + 2, service customer-api DatabaseExpert Review vm-guest Priority 1 + 2, title contains disk , memory , CPU GuestOSResponder Review network-p1 Priority 1, title contains 502 , backend NetworkPathExpert Review integration-p1 Priority 1, service fulfillment IntegrationExpert Review Filters available: severity/priority (multiselect), impacted service, incident type, and title contains. Plans can be turned off without deleting them, which is exactly what you want during maintenance windows. 5. Set your guardrails before your first incident If you read only one section of this post, read this one. The guardrails are not paperwork; they are the reason this is deployable. 5.1 Run modes Mode Behavior Default Review Agent proposes; you approve or deny Agent-level default Autonomous Agent executes immediately and reports Per-plan and per-task default Two subtleties that bite people: Run modes are set per response plan and per scheduled task, not globally. The agent-level setting is only a fallback. And per-plan the default is Autonomous — so if you don't set it, you get autonomy. Review mode shows Approve/Deny only for Azure infrastructure operations (Azure CLI, ARM writes). Sending an email, posting to Teams, or querying an external source proceeds based on the agent's reasoning. To gate those, you need hooks or tool access policies. Only users holding the SRE Agent Administrator role can approve. Standard users cannot, and personal Microsoft accounts can't authorize on-behalf-of at all — it requires a work or school (Entra ID) account. 5.2 What the product blocks for you These are enforced at the command level, independent of your RBAC: Guardrail Behavior Delete operations The agent never runs delete or remove commands. It returns an error pointing you at the portal Key Vault All az keyvault commands are blocked, to prevent credential exposure Management locks Resources with ReadOnly locks can't be modified, regardless of permissions or run mode Subscription validation Subscription IDs are validated as well-formed GUIDs before execution 💡 Use the delete block architecturally. Put a ReadOnly management lock on anything that must never change during an incident — your Key Vaults, your production databases, your golden images. That lock is respected before every modification, which gives you a control that survives RBAC drift and misconfigured response plans. 5.3 Hooks: the guardrail you write yourself Two events are supported — Stop (agent about to return a final response) and PostToolUse (a tool finished). Hooks run as an LLM prompt or a sandboxed command script. Here is the single most useful hook for this entire post — a deterministic policy gate on shell execution: hooks: PostToolUse: - type: command matcher: "Bash|ExecuteShellCommand" timeout: 30 failMode: block script: | #!/usr/bin/env python3 import sys, json, re context = json.load(sys.stdin) command = context.get('tool_input', {}).get('command', '') dangerous = [ r'\brm\s+-rf\b', r'\bsudo\b', r'\bchmod\s+777\b', r'\bmkfs\b', r'\bdd\s+if=', r'\btruncate\b', r'\bDROP\s+TABLE\b', ] for pattern in dangerous: if re.search(pattern, command, re.IGNORECASE): print(json.dumps({"decision": "block", "reason": f"Blocked by policy: {pattern}"})) sys.exit(0) print(json.dumps({"decision": "allow"})) And a Stop hook that refuses to let the agent declare victory without evidence: hooks: Stop: - type: prompt model: ReasoningFast timeout: 30 prompt: | Review the agent's final response. $ARGUMENTS It is only acceptable if it contains ALL of: 1. The specific resource acted upon (full name or resource ID) 2. Metric values BEFORE and AFTER the action 3. The observation window over which recovery was confirmed 4. Who approved the action and at what UTC timestamp Respond with: {"ok": true} {"ok": false, "reason": "<what is="" missing="">"}</what> Hook mechanics you'll want on hand: Setting Default Range / notes timeout 30s 1–300s failMode allow allow or block maxRejections 3 1–25; prompt-type Stop hooks only matcher — Regex, anchored ^(pattern)$ , case-sensitive; * matches all Script size — 64 KB max Shebangs — #!/bin/bash , #!/usr/bin/env python3 ⚠️ The footgun: for Stop hooks, a rejection without a reason field is treated as approval. Always populate reason . Agent-level hooks and custom-agent-level hooks both run when both match; agent-level fires first. 5.4 The recommended production policy This is the policy I'd put in front of a change board: Allow read-only investigation automatically, everywhere. Allow automatic incident creation and work-note updates — after sanitization. Use Review mode for all production remediation. Require human approval for every production write. Use fixed-purpose runbooks instead of unrestricted VM shell access. Require separate approval for destructive or data-affecting actions. Initially require human confirmation before resolving an incident. 6. The ten use cases Each use case follows the same seven-part structure so you can skim to the one you're firefighting: What happened → How Azure Monitor detected it → How the agent found the cause → Agent action table → Recovery note → Try it yourself → Guardrails In the action tables, Type is one of: Type Meaning Read No blast radius. Safe to run automatically Decision Agent reasoning or an approval gate. No resource change Write (ITSM) Ticket create/update. Sanitized Write (Azure) Azure control-plane change. Approval required in production Write (Guest OS) Inside the VM, via a fixed-purpose runbook. Approval required Write (K8s/DevOps) Cluster or pipeline change. Approval required Validation Post-action measurement against defined thresholds Use case #1 — App Service: HTTP 500 after deployment The one you should build first. Clean trigger, bounded action, unambiguous validation. What happened Release 2026.03.12.4 was deployed to a production checkout App Service. The new code referenced an application setting that was never defined in the production slot. The application started fine — which is what makes this class of failure nasty — but every checkout operation that touched that setting returned HTTP 500. How Azure Monitor detected it Azure Monitor and Application Insights fired on a composite condition, not a single metric: HTTP 5xx rate above the operational threshold Failed availability tests Increased application exceptions Increased dependency failures Request latency above baseline P1 – Checkout App Service returning elevated HTTP 500 responses How the agent found the cause Identified the affected App Service and slot. Queried HTTP response and latency metrics. Queried Application Insights failed requests and exceptions. Identified the missing-setting exception as the dominant failure. Reviewed deployment history and Azure Activity Log. Correlated the error increase with release 2026.03.12.4 . Compared production against the previous deployment slot. Confirmed the previous slot remained healthy. Confirmed no matching Azure platform incident. Agent finding: HTTP 500 responses increased from 0.4% to 18% within three minutes of release 2026.03.12.4. Most failures reference a missing application setting. The previous deployment slot passes availability and dependency checks. Notice the shape of that sentence: a delta, a time correlation, and a known-good comparison. That's what makes it actionable rather than merely true. Agent action table # Action Type Detail 1 Investigate alert Read Reads HTTP 5xx rate, failed requests, latency, availability-test results 2 Analyze exceptions Read Identifies missing-configuration exception as dominant failure 3 Correlate deployment Read Finds release 2026.03.12.4 deployed three minutes before the spike 4 Compare slots Read Confirms previous slot healthy while production is failing 5 Rule out platform issue Read Checks Azure Resource Health and dependency health 6 Assess blast radius Read Determines checkout affected, unrelated services healthy 7 Create SNOW INC Write (ITSM) P1 against the Checkout CI, assigned to Application Operations 8 Update INC evidence Write (ITSM) Adds exceptions, deployment correlation, resource links, affected operations 9 Classify response Decision Classifies as deployment-caused; selects rollback 10 Pause release Write (DevOps) Pauses the failed release pipeline 11 Request approval Decision Requests approval to swap the previous healthy slot into production 12 Swap slot Write (Azure) Performs the approved swap only on the named App Service 13 Validate recovery Validation Confirms 5xx, latency, exceptions, dependencies, availability recover 14 Update/resolve INC Write (ITSM) Records approval, rollback, timestamps, recovery evidence 15 Create SNOW PRB Write (ITSM) Problem record for configuration-validation improvements Recovery note Production was reverted to the previous healthy deployment slot at 14:26 UTC. HTTP 500 responses declined from 18% to below 1%, and availability tests passed for 15 consecutive minutes. Preliminary cause: missing production configuration in release 2026.03.12.4. Try it yourself Break it: # Put a healthy build in the 'previous' slot first, then break production # by deploying code that reads an app setting which only exists in staging. az webapp config appsettings delete -g $RG -n app-checkout-demo \ --setting-names Checkout__PaymentProviderKey az webapp restart -g $RG -n app-checkout-demo Alert it: az monitor metrics alert create -g $RG -n "alert-checkout-5xx" \ --scopes "/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.Web/sites/app-checkout-demo" \ --condition "total Http5xx > 20" \ --window-size 5m --evaluation-frequency 1m --severity 1 \ --description "P1 – Checkout App Service returning elevated HTTP 500 responses" Ask it (before the alert, to see the read phase in isolation): app-checkout-demo is returning HTTP 500s. Do not change anything. Investigate and tell me: 1. the dominant exception and its share of total failures 2. what deployed in the 30 minutes before the error rate changed 3. whether the 'previous' slot is healthy right now 4. whether Azure Resource Health shows a platform issue Give me the evidence chain and the smallest reversible mitigation. Expect it to propose: Proposed action: Swap slot 'previous' into production on app-checkout-demo Risk: brief connection drain (~10s). Fully reversible by swapping back. Validation: Http5xx < 1% and availability test passing for 15 minutes. [Approve] [Deny] Verify it: requests | where timestamp > ago(1h) | summarize failed = countif(success == false), total = count() by bin(timestamp, 1m) | extend failureRate = 100.0 * failed / total | render timechart 🎬 Best thing to record for a demo: the moment the Approve button appears with the evidence already attached. That single screen is the whole value proposition. Guardrails Scope write permissions to the named App Service, not the resource group. Verify the previous slot is healthy before swapping — a swap into a broken slot doubles the outage. Require human approval for production slot swaps. Preserve the failed deployment for analysis; don't let the pipeline overwrite it. Never grant subscription-level Contributor or Owner. Use case #2 — AKS: pods in CrashLoopBackOff What happened Image orders-api:4.18.0 referenced a configuration key that didn't exist in the production namespace. Eight of ten pods entered CrashLoopBackOff . The two survivors couldn't carry production traffic, producing latency and ingress 5xx. How Azure Monitor detected it Managed Prometheus / Container Insights detected: Unavailable replicas Increasing container restart count CrashLoopBackOff pod state Failed readiness and liveness checks Elevated ingress HTTP 5xx Reduced successful-request rate P1 – Orders API unavailable replicas in production AKS How the agent found the cause Identified the cluster, namespace, and deployment. Reviewed deployment availability and pod states. Examined logs from failing containers. Reviewed Kubernetes warning events. Compared current and previous ReplicaSets. Correlated the failure with revision 42. Identified the missing configuration key. Confirmed revision 41 was previously healthy. Checked node CPU, memory, storage, networking, status. Determined AKS infrastructure was healthy. Agent finding: Eight of ten Orders API pods entered CrashLoopBackOff during rollout of revision 42. Container logs show a missing configuration key. Revision 41, using image 4.17.6, was healthy. Step 10 is the one people skip. "Rule out the infrastructure" is what stops you from spending an hour on a node pool that was never the problem. Agent action table # Action Type Detail 1 Investigate workload Read Deployment status, unavailable replicas, readiness, restart counts 2 Analyze pod logs Read Startup failure from a missing configuration key 3 Analyze events Read Image pulls, mounts, scheduling, probes, container events 4 Correlate rollout Read Revision 42 deployed immediately before failure 5 Compare ReplicaSets Read Revision 41 was the previous healthy workload 6 Rule out infrastructure Read Nodes, memory, CPU, networking, storage healthy 7 Assess blast radius Read Eight of ten replicas unavailable 8 Create SNOW INC Write (ITSM) P1 against the Orders API CI 9 Update INC evidence Write (ITSM) Namespace, image, revision, errors, rollout correlation 10 Classify response Decision Application/configuration-caused 11 Request approval Decision Approval to pause and roll back revision 42 12 Pause failed rollout Write (K8s/DevOps) Prevents the release progressing or being reapplied 13 Roll back deployment Write (K8s) Rolls back only the named deployment to revision 41 14 Validate replicas Validation All expected replicas ready and stable 15 Validate application Validation Ingress errors decline; synthetic orders succeed 16 Update/resolve INC Write (ITSM) Revision, approval, rollback, recovery evidence 17 Create defect/task Write (ITSM) Add configuration validation to CI/CD Recovery note Orders API was rolled back from revision 42 to revision 41. All ten replicas are ready, restart counts have stabilized, ingress HTTP 5xx responses are below threshold, and synthetic order transactions are succeeding. Try it yourself Break it: az aks get-credentials -g $RG -n aks-demo kubectl create namespace orders kubectl create deployment orders-api -n orders --image=nginx:1.25 --replicas=10 kubectl rollout status deployment/orders-api -n orders # revision 41 equivalent, healthy # Now break it: point at an image whose entrypoint requires a missing env var kubectl set image deployment/orders-api -n orders orders-api=busybox:1.36 kubectl patch deployment orders-api -n orders --type=json -p='[ {"op":"add","path":"/spec/template/spec/containers/0/command", "value":["sh","-c","test -n \"$ORDERS_CONFIG_KEY\" || (echo \"FATAL: missing ORDERS_CONFIG_KEY\" >&2; exit 1); sleep 3600"]} ]' Watch it break: kubectl get pods -n orders -w kubectl rollout history deployment/orders-api -n orders Ask it: Pods in namespace 'orders' on aks-demo are crash looping. Read-only. Tell me: which revision introduced it, the exact container error, whether the node pool is healthy, and how many replicas are actually serving. Then tell me the last known-good revision and why you believe it was healthy. Expect it to propose: kubectl rollout undo deployment/orders-api -n orders --to-revision= scoped to that single deployment. Verify it: kubectl get deployment orders-api -n orders \ -o jsonpath='{.status.readyReplicas}/{.status.replicas}{"\n"}' kubectl get pods -n orders --no-headers | awk '{print $4}' | sort | uniq -c Guardrails Restrict access to the required cluster, namespace, and deployment. Do not grant cluster-admin . Require approval for rollback. Coordinate with GitOps reconciliation. If Flux or Argo owns that deployment, a kubectl rollout undo gets reverted within minutes and you've created a flapping outage. Either pause reconciliation first or roll back through Git. Do not permit namespace, persistent-volume, or cluster deletion. Use case #3 — Azure SQL Database: CPU saturation and timeouts The use case where the agent's job is to buy time, not to fix the problem. What happened A query execution plan changed after an application release. The new plan consumed substantially more CPU and workers. The database saturated, producing SQL dependency timeouts and failed customer requests. How Azure Monitor detected it Sustained CPU saturation Worker or session pressure Increased connection failures SQL dependency timeouts Query-duration deviation from baseline Degraded customer API success rate P1 – Customer API database saturation causing request timeouts How the agent found the cause Reviewed database CPU, workers, sessions, connections. Reviewed application SQL dependency failures. Checked for blocking and deadlocks. Ran approved read-only Query Store diagnostics. Identified the primary CPU-consuming query. Detected a recent execution-plan change. Correlated with an application release. Ruled out Azure service health and storage issues. Determined a temporary scale operation could restore service. Left permanent query remediation to the DBA team. Agent finding: Database CPU has remained saturated for 17 minutes. One query accounts for most recent CPU consumption and changed execution plan shortly before the incident. Application SQL dependency timeout rate is 23%. Step 10 is the design decision that makes this safe. The agent correctly diagnoses a plan regression and then deliberately does not fix it, because forcing a plan or dropping an index is a permanent, DBA-owned, change-controlled action. It buys capacity instead. Agent action table # Action Type Detail 1 Investigate database Read CPU, workers, sessions, connections, storage, availability 2 Analyze app impact Read SQL dependency latency, failures, affected API operations 3 Check blocking Read Approved diagnostics for blocking, deadlocks, connection growth 4 Analyze Query Store Read Highest-impact query and recent plan change 5 Correlate changes Read Recent application and database deployments 6 Rule out platform issue Read Service health, storage, database availability 7 Assess blast radius Read Affected applications; other databases healthy 8 Create SNOW INC Write (ITSM) P1 against the production database CI 9 Update INC evidence Write (ITSM) Utilization, query ID, timeouts, change correlation 10 Classify response Decision Scaling is mitigation; query changes remain DBA-owned 11 Calculate bounded scale Read Selects the smallest pre-approved capacity increase 12 Request approval Decision Database owner or incident commander 13 Scale database Write (Azure) Increases the affected database by one approved service step 14 Validate recovery Validation CPU, workers, timeouts, application success recover 15 Update INC Write (ITSM) Previous/new capacity, approval, timing, results 16 Create SNOW PRB Write (ITSM) Permanent query-remediation work 17 Create scale-down task Write (ITSM) Task/change to restore normal capacity after stability Recovery note Azure SQL capacity was temporarily increased by one approved service step. CPU declined from sustained saturation to 54%, and SQL dependency timeouts returned to baseline. Query Store indicates a probable execution-plan regression requiring permanent DBA remediation. Try it yourself Break it — generate a saturating workload against db-customer (an unindexed LIKE '%...%' scan in a tight loop from a container in the same region works fine on an S1). Alert it: az monitor metrics alert create -g $RG -n "alert-sql-cpu" \ --scopes "/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.Sql/servers/sqlsrv-sre-demo/databases/db-customer" \ --condition "avg cpu_percent > 90" \ --window-size 5m --evaluation-frequency 1m --severity 1 \ --description "P1 – Customer API database saturation causing request timeouts" Ask it: db-customer is saturated. Read-only investigation. Identify the top CPU-consuming query, whether its plan changed recently, and what application release correlates. Do NOT propose index, schema, plan-forcing, or session-kill actions. Propose only the smallest temporary capacity step that restores service, and tell me what it costs per day and when we should scale back down. Read-only Query Store diagnostics the agent should run: SELECT TOP 10 qsq.query_id, qsp.plan_id, qsp.last_execution_time, SUM(qsrs.count_executions) AS executions, SUM(qsrs.avg_cpu_time * qsrs.count_executions) AS total_cpu_us FROM sys.query_store_query AS qsq JOIN sys.query_store_plan AS qsp ON qsp.query_id = qsq.query_id JOIN sys.query_store_runtime_stats AS qsrs ON qsrs.plan_id = qsp.plan_id JOIN sys.query_store_runtime_stats_interval AS qsrsi ON qsrsi.runtime_stats_interval_id = qsrs.runtime_stats_interval_id WHERE qsrsi.start_time > DATEADD(hour, -2, GETUTCDATE()) GROUP BY qsq.query_id, qsp.plan_id, qsp.last_execution_time ORDER BY total_cpu_us DESC; Expect it to propose: az sql db update -g $RG -s sqlsrv-sre-demo -n db-customer --service-objective S2 — exactly one step, on exactly that database. Guardrails Restrict scaling to the named database. Define minimum and maximum capacity. Require approval for scale-up and scale-down. Time-limit temporary capacity — an un-reversed emergency scale-up is how a P1 becomes a budget incident. Do not autonomously force plans, terminate sessions, modify indexes, or change schema. Track the temporary cost impact with an Azure Cost Management alert. Use case #4 — Azure Cosmos DB: HTTP 429 throttling The one where the correct root cause is "we're succeeding." What happened A marketing campaign increased Product Catalog traffic by roughly 40%. The Cosmos DB container hit its provisioned throughput ceiling. HTTP 429s increased, and client retries amplified application latency. How Azure Monitor detected it High normalized RU consumption Increased HTTP 429 responses Elevated server-side latency Application dependency failures Sustained operation near the throughput limit P2 – Cosmos DB throttling affecting Product Catalog requests How the agent found the cause Reviewed normalized RU consumption and throttled requests. Identified the affected database and container. Reviewed regional and partition behavior. Checked for hot-partition evidence. Reviewed application retry telemetry. Compared current traffic with the historical baseline. Correlated demand with the marketing campaign. Checked recent application deployments. Checked Azure service health. Determined the primary cause was legitimate demand. Agent finding: The Product Catalog container is at its configured throughput ceiling, and 21% of requests are being throttled. Traffic increased by approximately 40% following a campaign launch. No deployment or regional platform issue correlates with the event. Step 4 is the fork in the road. If consumption is uneven across partitions, more RU/s is money set on fire — the correct answer is an architecture change, not a scale-up. The agent has to check before it recommends. Agent action table # Action Type Detail 1 Investigate throttling Read RU consumption, 429 rate, latency, requests, availability 2 Identify scope Read Account, database, container, operations, regions 3 Analyze demand Read Compares traffic and RU consumption with historical patterns 4 Check partitions Read Looks for uneven partition consumption where telemetry permits 5 Analyze retries Read Determines whether client retries are amplifying the incident 6 Correlate events Read Links demand to campaign traffic; excludes release/platform issues 7 Assess blast radius Read Affected catalog operations; unaffected containers 8 Create SNOW INC Write (ITSM) P2 against the Product Catalog CI 9 Update INC evidence Write (ITSM) RU, throttling, latency, traffic, partition evidence 10 Classify response Decision Demand-driven unless hot-partition evidence exists 11 Calculate throughput Read Smallest increase within the cost ceiling 12 Request approval Decision Approval for a temporary throughput increase 13 Increase throughput Write (Azure) Raises throughput only to the approved maximum 14 Validate recovery Validation 429 rate and latency recover 15 Update/resolve INC Write (ITSM) Throughput, approval, cost implication, recovery 16 Create capacity task Write (ITSM) Work to return throughput to normal 17 Create SNOW PRB Write (ITSM) Partition or retry improvements, if required Recovery note Provisioned throughput was increased within the approved production limit. HTTP 429 responses declined from 21% to below 1%, and Product Catalog latency returned to baseline. The increase is temporary and will be reviewed after campaign traffic subsides. Try it yourself Break it: the container was created at 400 RU/s. Drive a few hundred reads per second at it and you'll be throttled within seconds. Alert it: az monitor metrics alert create -g $RG -n "alert-cosmos-429" \ --scopes "/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.DocumentDB/databaseAccounts/cosmos-sre-demo" \ --condition "total TotalRequests where StatusCode == 429 > 100" \ --window-size 5m --evaluation-frequency 1m --severity 2 \ --description "P2 – Cosmos DB throttling affecting Product Catalog requests" Ask it: cosmos-sre-demo container 'products' is throttling. Read-only. Before recommending anything, tell me whether RU consumption is EVEN across physical partitions or concentrated. If it is concentrated, do not recommend a throughput increase — recommend an architecture problem record instead. If it is even, tell me the smallest RU/s that clears throttling and the daily cost delta. That prompt is the whole use case. Getting the agent to refuse the easy answer under a stated condition is the skill. Verify it: AzureDiagnostics | where ResourceProvider == "MICROSOFT.DOCUMENTDB" | where Category == "DataPlaneRequests" | summarize throttled = countif(statusCode_s == "429"), total = count() by bin(TimeGenerated, 1m) | extend throttleRate = 100.0 * throttled / total | render timechart Guardrails Define a maximum throughput ceiling the agent may not exceed. Restrict changes to the named container. Require approval for increases and reductions. Do not permit deletion, consistency-level changes, or region changes. Create cost alerts for prolonged increased throughput. Treat persistent hot partitions as an architecture issue, never as a scaling issue. Use case #5 — Azure VM: OS/root disk full The most operationally dangerous use case in this post, and the one with the most interesting guardrail design. What happened A legacy payment application generated excessive trace logs. Log rotation stopped working and the root filesystem filled. The VM stayed available at the Azure platform layer — heartbeat green, Resource Health fine — but the application stopped, because it could no longer write to disk. This is the classic "green dashboard, dead service" failure. Platform-layer monitoring alone will never catch it. How Azure Monitor detected it Azure Monitor Agent and guest telemetry detected: Critically low filesystem free space Rapid filesystem consumption Application process stopped Failed availability tests Elevated HTTP 5xx Healthy VM heartbeat but unhealthy application P1 – Legacy payment application unavailable due to full VM OS disk How the agent found the cause Confirmed the VM was online. Confirmed Azure Monitor Agent heartbeat. Identified the affected root/OS filesystem. Reviewed the free-space trend. Correlated application failure with disk exhaustion. Found 86 GB of growth in the application trace directory. Reviewed recent deployments and logging changes. Checked log-rotation status. Confirmed the files matched the approved cleanup policy. Excluded customer data, database files, audit logs, and system files. Agent finding: The VM is healthy at the Azure platform layer, but the OS volume has less than 1% free space. The approved application trace directory grew by 86 GB in six hours. The payment service stopped when it could no longer write to disk. Agent action table # Action Type Detail 1 Investigate VM Read VM, agent heartbeat, Azure platform health 2 Analyze filesystem Read Root volume and free-space trend 3 Correlate app failure Read Service stopped after disk exhaustion 4 Identify disk consumer Read Abnormal growth in an approved trace directory 5 Check changes Read Deployments, logging changes, rotation, scheduled tasks 6 Validate cleanup scope Read Candidate files meet approved path, type, and age rules 7 Protect data Decision Excludes databases, customer data, security logs, unknown files 8 Create SNOW INC Write (ITSM) P1 against the payment VM/application CI 9 Update INC evidence Write (ITSM) Disk usage, growth timeline, service impact, cleanup scope 10 Request approval Decision Approval for the restricted recovery runbook 11 Archive logs Write (Guest OS) Archives eligible files to protected Azure Storage 12 Remove eligible files Write (Guest OS) Removes only successfully archived, allowlisted files 13 Run log rotation Write (Guest OS) Executes the approved rotation operation 14 Restart service Write (Guest OS) Restarts only the named payment service if necessary 15 Validate recovery Validation Disk, application, archive, availability, growth stabilization 16 Update/resolve INC Write (ITSM) Bytes processed, exclusions, approval, results 17 Create SNOW PRB Write (ITSM) Permanent logging and rotation remediation Recovery note The approved recovery runbook archived and removed 82 GB of eligible application trace files. OS-volume free space is now 31%. The payment service was restarted and has passed health checks for 15 minutes. No database, customer, security, or system files were modified. That last sentence is not decoration. It is the sentence your auditor will read. Try it yourself Break it (lab VM only — this fills the root disk): az vm run-command invoke -g $RG -n vm-payments-linux \ --command-id RunShellScript --scripts " mkdir -p /var/log/payments/trace fallocate -l 24G /var/log/payments/trace/trace-$(date +%s).log df -h / " Ask it: vm-payments-linux root filesystem is nearly full and the payment service is down. Read-only first. Tell me: - exactly which directory grew, by how much, over what window - whether log rotation is configured and when it last ran - what changed in the last 24 hours that would explain it Then tell me which files are inside the approved cleanup allowlist (/var/log/payments/trace/*.log, older than 2h) and which are NOT, and confirm no database, audit, or customer data files are in scope. Do not delete anything. The critical design point. SRE Agent blocks delete and remove commands outright. You cannot have it rm those files through its Azure CLI surface, and you should be glad. The correct implementation is a fixed-purpose, version-controlled runbook that the agent invokes with tightly bounded parameters: # What the agent is allowed to call — one runbook, allowlisted parameters, nothing else az automation runbook start \ -g $RG --automation-account-name aa-sre-runbooks \ -n "Reclaim-TraceDiskSpace" \ --parameters vmName=vm-payments-linux \ allowedPath=/var/log/payments/trace \ pattern='*.log' \ minAgeHours=2 \ maxBytes=90000000000 \ archiveToContainer=payments-trace-archive \ requireArchiveBeforeDelete=true \ dryRun=false The runbook — not the agent — owns the destructive logic, and it enforces: path allowlist (refuse anything outside allowedPath ) filename pattern allowlist minimum file age maximum total bytes per execution successful archive verified before any deletion hard-refuse if any candidate file is unknown, or matches a protected pattern ( *.mdf , *.bak , /var/log/audit/* , *.key , *.pem ) a cooldown that prevents re-execution within N hours Verify it: az vm run-command invoke -g $RG -n vm-payments-linux \ --command-id RunShellScript \ --scripts "df -h /; systemctl is-active payments.service; ls -la /var/log/payments/trace | head" Guardrails Do not give SRE Agent unrestricted SSH or shell access. Ever. This is the single highest-leverage rule in this post. Use a version-controlled, fixed-purpose runbook. Allowlist paths, patterns, file ages, and maximum cleanup size. Stop if the responsible files are unknown. A disk filled by something you can't identify is a security event until proven otherwise. Require successful archival before deletion. Prevent repeated execution with a cooldown. Treat cleanup as temporary mitigation — the problem record is the fix. Use case #6 — Linux VM: anomalous CPU saturation Where "anomalous" is doing all the work. What happened Release 7.3.1 introduced an immediate retry loop when an inventory dependency failed. The application retried continuously without backoff, consuming nearly all VM CPU and causing request timeouts. How Azure Monitor detected it The alert deliberately combined conditions rather than firing on a threshold: CPU significantly outside the historical baseline Persistent saturation over multiple evaluations Increased request latency Increased dependency failures No approved maintenance or batch workload active P1 – Production order-processing Linux VM experiencing anomalous CPU saturation A static "CPU > 90%" rule on a batch-processing VM is a pager that everyone learns to ignore. The composite condition is what makes the alert worth waking someone — or an agent — for. How the agent found the cause Confirmed the VM was online. Compared current CPU with historical behavior. Identified the order-processing service as the main CPU consumer. Reviewed application request latency. Reviewed downstream dependency failures. Analyzed application retry logs. Correlated CPU growth with release 7.3.1. Excluded expected batch jobs. Excluded Azure maintenance or platform issues. Confirmed other application instances had sufficient capacity. Agent finding: CPU increased from a normal range of 35–50% to 98% four minutes after deployment 7.3.1. The order-processing service is repeatedly calling a failed dependency without backoff. No expected batch job or platform maintenance is active. Agent action table # Action Type Detail 1 Confirm anomaly Read Compares current CPU with the historical baseline 2 Analyze impact Read Latency, timeouts, availability, dependencies 3 Identify process Read Named order service is the primary CPU consumer 4 Correlate deployment Read Release 7.3.1, four minutes before saturation 5 Analyze logs Read Dependency retry loop without backoff 6 Rule out expected work Read Excludes batch, backup, maintenance, scheduled processing 7 Assess blast radius Read Traffic and available capacity on other instances 8 Create SNOW INC Write (ITSM) P1 against the Order Processing CI 9 Update INC evidence Write (ITSM) CPU, process, dependency, release, customer impact 10 Classify response Decision Rollback, not VM resize or arbitrary process termination 11 Request approval Decision Approval to drain, roll back, restart the service 12 Drain VM Write (Azure) Removes the VM from load-balancer rotation 13 Restore prior release Write (Guest OS/DevOps) Restores known-good version or configuration 14 Restart named service Write (Guest OS) Restarts only orders-service 15 Validate recovery Validation CPU, retries, latency, dependencies, health recover 16 Return to rotation Write (Azure) Restores traffic only after successful validation 17 Update/resolve INC Write (ITSM) Drain, rollback, restart, approval, results 18 Create defect Write (ITSM) Retry, backoff, and circuit-breaker remediation Steps 12 and 16 are the pattern to steal: drain before you touch, restore traffic only after validation passes. Most homegrown automation restarts a service while it's still taking traffic and turns a degradation into an outage. Recovery note Release 7.3.1 introduced a retry loop when the inventory dependency failed. After approval, the VM was drained, the previous release was restored, and orders-service was restarted. CPU declined from 98% to 43%, and application latency returned to baseline. Try it yourself Break it: az vm run-command invoke -g $RG -n vm-payments-linux \ --command-id RunShellScript --scripts " nohup bash -c 'while true; do curl -s -m 1 http://127.0.0.1:9/inventory >/dev/null 2>&1; done' & nohup bash -c 'while true; do :; done' & echo started " Ask it: CPU on vm-payments-linux is at 98%. Read-only. First: is this actually anomalous, or is it consistent with this VM's historical pattern for this hour and day of week? Show me the baseline. If anomalous: which process, which dependency is it calling, at what rate, and what deployed immediately before? Do NOT propose killing the top process or resizing the VM. Expect it to propose a drain → restore → restart sequence, with the drain step as a separate approval from the restart. Guardrails Do not automatically terminate the highest-CPU process. It is very often a legitimate workload, and occasionally it's a security incident you just destroyed the evidence for. Allow operations only for named services. Drain before service restart where possible. Escalate unknown or suspicious processes to security rather than remediating them. Limit restart attempts. Do not permanently resize the VM when the evidence points to faulty code. Resizing to survive a retry storm is buying hardware to host a bug. Use case #7 — Windows VM with IIS: memory leak What happened Release ClaimsPortal 5.9.0 introduced a memory leak in the Claims IIS application pool. Memory consumption climbed over several hours, paging began, request queues grew, and IIS returned HTTP 503. How Azure Monitor detected it Azure Monitor Agent collected available memory, committed bytes, paging activity, process working set, IIS request queues, HTTP 500/503 responses, and availability-test results. The alert required sustained abnormal growth, not a brief spike. P1 – Memory exhaustion affecting production IIS application How the agent found the cause Confirmed the VM and monitoring agent were healthy. Compared memory behavior with the historical baseline. Identified the relevant w3wp.exe process. Mapped it to the Claims application pool. Reviewed paging and request queues. Correlated HTTP 503 errors with low available memory. Reviewed Windows Event Logs. Correlated the growth with release 5.9.0. Excluded antivirus and scheduled-reporting activity. Confirmed another instance could carry traffic. Agent finding: Available memory declined from 42% to 4% over three hours. The Claims application pool grew from 1.8 GB to 11.6 GB without releasing memory after traffic normalized. Paging and HTTP 503 errors followed. The pattern began after release 5.9.0. "Without releasing memory after traffic normalized" is the sentence that distinguishes a leak from load. Cache growth under load is normal; failure to return afterwards is not. Agent action table # Action Type Detail 1 Confirm anomaly Read Memory, committed bytes, paging vs. baseline 2 Identify process Read Maps growing w3wp.exe to the Claims pool 3 Analyze IIS health Read Pools, queues, HTTP errors, availability 4 Correlate release Read Links sustained growth to release 5.9.0 5 Rule out other causes Read Excludes scheduled jobs, antivirus, maintenance 6 Assess capacity Read Confirms another instance can serve traffic 7 Create SNOW INC Write (ITSM) P1 against the Claims Portal CI 8 Update INC evidence Write (ITSM) Memory, paging, pool, release, HTTP impact 9 Classify response Decision Targeted recycling, not a full VM restart 10 Request approval Decision Approval to drain and recycle the named pool 11 Drain VM Write (Azure) Removes VM from load-balancer rotation 12 Capture diagnostics Write (Guest OS) Captures approved diagnostics to a protected location 13 Recycle app pool Write (Guest OS) Recycles only the Claims application pool 14 Validate recovery Validation Memory, paging, queues, HTTP errors, availability recover 15 Return to rotation Write (Azure) Restores traffic after health checks pass 16 Update/resolve INC Write (ITSM) Memory before/after, approval, stability 17 Create SNOW PRB Write (ITSM) Memory-leak remediation Step 12 before step 13 matters: recycling the pool destroys the evidence. Capture first. Recovery note Abnormal memory growth was isolated to the Claims application pool following release 5.9.0. The VM was drained, the approved application pool was recycled, and health checks passed before traffic was restored. Available memory increased from 4% to 61%, and HTTP 503 responses stopped. Try it yourself Break it (lab VM only): az vm run-command invoke -g $RG -n vm-claims-win ` --command-id RunPowerShellScript --scripts " Install-WindowsFeature Web-Server -IncludeManagementTools New-WebAppPool -Name 'ClaimsPool' # Simulate the leak \$leak = New-Object System.Collections.ArrayList 1..40 | ForEach-Object { [void]\$leak.Add((New-Object byte[] 100MB)) ; Start-Sleep -Milliseconds 200 } " Ask it: vm-claims-win available memory is at 4%. Read-only. Map the growing process to an IIS application pool. Show me the memory curve for the last 6 hours and tell me whether memory was released after traffic dropped. Correlate with deployment history. Then propose the most targeted possible mitigation — I do not want a VM restart. Expect it to propose: Restart-WebAppPool -Name "ClaimsPool" …and nothing else on that machine. Guardrails Recycle only the named application pool. Avoid full VM restart as the first response — it's a bigger hammer with a longer outage and it destroys the leak evidence. Do not copy memory dumps into ServiceNow. They contain credentials, tokens, and customer data. Store diagnostics in a secured location; put the link in the ticket. Prevent repeated automatic recycling — a pool that needs recycling every 40 minutes is an incident, not a routine. Escalate if the leak returns during the observation period. Use case #8 — Virtual Machine Scale Set: unhealthy instance The most autonomy-ready use case in the list, and the reason is stateless workloads. What happened A configuration extension failed while VMSS instance 17 was being provisioned. The VM was running but its application service never started. The instance failed application health probes and caused intermittent errors. How Azure Monitor detected it Reduced healthy backend count Application Health extension failure Backend health-probe failure VM extension provisioning failure Instance-specific errors Elevated intermittent HTTP 5xx P2 – Unhealthy VM Scale Set instance causing intermittent API failures How the agent found the cause Reviewed the VMSS healthy-instance count. Identified instance 17 as the only unhealthy instance. Reviewed backend health. Compared instance 17 with healthy instances. Checked the image and VMSS model. Reviewed VM extension state. Found the configuration extension failure. Reviewed boot and application diagnostics. Confirmed the workload was stateless. Confirmed eleven instances could carry production traffic. Agent finding: Instance 17 is the only unhealthy member of the 12-instance scale set. Its application health probe has failed since 09:18 UTC. The configuration extension failed during provisioning, and the application service never started. Eleven healthy instances can maintain service. Agent action table # Action Type Detail 1 Investigate VMSS Read Instance health, provisioning state, healthy count 2 Identify instance Read Instance 17 is the only unhealthy member 3 Analyze backend health Read Confirms the instance fails application probes 4 Compare instances Read Image, model, extensions, configuration 5 Find extension failure Read Locates the failed configuration extension 6 Review diagnostics Read Boot, extension, and application diagnostics 7 Assess safe capacity Read Eleven instances can carry traffic 8 Confirm statelessness Decision Replacement won't destroy required local state 9 Create SNOW INC Write (ITSM) P2 against the VMSS/application CI 10 Update INC evidence Write (ITSM) Instance, extension error, health, capacity evidence 11 Classify response Decision Replacement or reimage per approved procedure 12 Request approval Decision Approval to isolate and replace instance 17 13 Isolate instance Write (Azure) Ensures the instance receives no production traffic 14 Preserve evidence Read/Write Stores approved diagnostic evidence securely 15 Replace instance Write (Azure) Reimages or replaces only instance 17 16 Validate provisioning Validation Image, model, and extensions deploy successfully 17 Validate service Validation Backend health, capacity, customer errors recover 18 Update/resolve INC Write (ITSM) Replacement, approval, diagnostics, recovery 19 Create SNOW PRB Write (ITSM) Extension and image-validation improvement work Steps 8 and 7 are the gate. Replacing a stateless instance with eleven healthy peers is genuinely low risk. Replacing a stateful instance, or replacing one when you're already at minimum capacity, is an outage. Both must be confirmed, not assumed. Recovery note VMSS instance 17 was isolated after its configuration extension failed and the application service did not start. Diagnostic evidence was captured, and the instance was replaced after approval. The replacement passed extension, application, and backend health checks. The scale set has returned to 12 healthy instances. Try it yourself Break it: INSTANCE_ID=$(az vmss list-instances -g $RG -n vmss-api-demo \ --query "[5].instanceId" -o tsv) az vmss extension set -g $RG --vmss-name vmss-api-demo \ --name CustomScript --publisher Microsoft.Azure.Extensions \ --settings '{"commandToExecute":"exit 1"}' Ask it: vmss-api-demo has an unhealthy instance. Read-only. Identify which instance, since when, and the specific extension error. Confirm for me: (a) the workload is stateless, (b) how many healthy instances remain, and (c) whether remaining capacity can carry current traffic with 20% headroom. Only if all three are satisfied, propose a reimage of that single instance. Capture diagnostics before proposing anything. Expect it to propose: az vmss reimage -g $RG -n vmss-api-demo --instance-id $INSTANCE_ID Verify it: az vmss get-instance-view -g $RG -n vmss-api-demo --instance-id $INSTANCE_ID \ --query "vmHealth.status.code" az vmss list-instances -g $RG -n vmss-api-demo -o table Guardrails Confirm the workload is stateless before any replacement. Confirm sufficient healthy capacity first. Preserve diagnostic evidence before replacement — the instance is your only copy of the failure. Restrict permissions to the named VMSS. Limit simultaneous replacements. One at a time. An agent that reimages six instances because six probes failed has just caused the outage it was investigating. Do not permit deletion of the entire scale set. Use case #9 — Application Gateway: HTTP 502 from unhealthy backends The cross-component change nobody coordinated. What happened Customer Portal release 9.2 changed the backend listener from port 443 to 8443. Application Gateway remained configured to connect on 443. All backend probes failed and customers received HTTP 502. How Azure Monitor detected it Increased Application Gateway HTTP 502 responses Increased failed requests Four unhealthy backends Reduced healthy-host count Failed synthetic availability tests P1 – Application Gateway returning HTTP 502 due to unhealthy backends How the agent found the cause Reviewed Application Gateway metrics. Retrieved backend health. Identified the affected pool. Reviewed probe path, protocol, host header, and port. Reviewed backend settings. Confirmed the application responded on 8443. Confirmed the gateway used 443. Correlated the mismatch with release 9.2. Reviewed NSG, route, DNS, certificate, and WAF changes. Excluded networking, certificate, and platform-health issues. Agent finding: HTTP 502 responses began at 16:07 UTC. All four Customer Portal backends are unhealthy. Release 9.2 changed the backend listener to port 8443, while Application Gateway continues to use port 443. No NSG, routing, or certificate issue correlates with the incident. Step 9 is what separates a real investigation from a lucky guess. A 502 has at least six plausible causes — NSG, UDR, DNS, expired cert, WAF rule, backend down. The agent has to exclude them, in writing, before you trust the conclusion. Agent action table # Action Type Detail 1 Investigate gateway Read HTTP 502, failed requests, latency, backend counts 2 Inspect backend health Read Identifies four unhealthy Customer Portal backends 3 Review configuration Read Settings, probes, protocol, port, TLS, routing 4 Test backend state Read App responds on 8443 while gateway uses 443 5 Correlate changes Read Links mismatch to Customer Portal release 9.2 6 Rule out networking Read NSGs, routes, DNS, TLS, WAF, platform health 7 Assess blast radius Read Confirms the Customer Portal pool is unavailable 8 Create SNOW INC Write (ITSM) P1 against the portal/gateway CI 9 Update INC evidence Write (ITSM) 502s, backend, port, deployment, known-good configuration 10 Classify response Decision Restore the known-good backend listener 11 Request approval Decision Approval to restore source-controlled configuration 12 Restore listener Write (Application) Restores the application listener to approved port 443 13 Validate backend health Validation All four backends become healthy 14 Validate application Validation HTTP 502 declines; synthetic transactions pass 15 Verify controls Read Confirms no WAF, TLS, routing, or NSG control was weakened 16 Update/resolve INC Write (ITSM) Cause, restoration, approval, recovery 17 Create SNOW CHG Write (ITSM) Coordinated change for the intended port migration 18 Create SNOW PRB Write (ITSM) Cross-component deployment-validation work Step 12 is a genuinely important choice. There were two ways to fix this: change the application back to 443, or change the gateway to 8443. The agent restores the application to the known-good, source-controlled state rather than mutating the gateway to match an unapproved change. One of those is a rollback; the other is ratifying an unreviewed change during an outage. Then step 17 files a proper change record for the migration the team clearly intended to do. Step 15 exists because the fastest way to make a 502 disappear is to disable TLS validation. The agent must prove it didn't take the fast way. Recovery note Customer Portal release 9.2 changed the backend listener from port 443 to 8443 without a coordinated gateway change. The application listener was restored to the previous configuration. All four backends are healthy, HTTP 502 responses returned to baseline, and synthetic login tests passed for 15 minutes. Try it yourself Ask it: appgw-portal is returning 502s and all backends are unhealthy. Read-only. Walk me through the exclusion, explicitly, for each of: NSG, UDR/route table, DNS resolution, backend TLS certificate, WAF rule blocking, backend process down, and probe configuration mismatch. State which you ruled out and the evidence for each. Then tell me the known-good configuration and where it is source-controlled. Verify it: az network application-gateway show-backend-health \ -g $RG -n appgw-portal \ --query "backendAddressPools[].backendHttpSettingsCollection[].servers[].{addr:address,health:health}" -o table Guardrails Do not disable TLS validation. Not to test, not temporarily, not "just to confirm." Do not weaken NSGs or WAF policies as a mitigation. Use source-controlled configuration as the definition of "known-good." Restore a known-good state during the incident; migrate through a change record afterwards. Require approval for gateway or backend changes. Validate full application transactions, not just health probes. A probe returning 200 on /health proves very little. Use case #10 — Azure Service Bus: queue and dead-letter backlog The one that teaches the most important lesson in the entire post. What happened Release fulfillment-worker:6.4.0 couldn't deserialize messages containing a new deliveryWindow field. Consumer throughput dropped by 92%. The active backlog grew rapidly, and incompatible messages entered the dead-letter queue. How Azure Monitor detected it Increasing active-message count Increasing oldest-message age Dead-letter growth Reduced completed-message rate Consumer application errors Delayed downstream business processing P1 – Production order-event backlog delaying fulfillment How the agent found the cause Reviewed active, incoming, outgoing, and dead-letter counts. Calculated message arrival and completion rates. Confirmed the backlog was growing. Reviewed consumer instance health. Reviewed consumer errors and restarts. Checked downstream dependency health. Checked Service Bus authentication and authorization. Correlated the throughput decline with release 6.4.0. Found deserialization errors for the new field. Determined scaling more broken consumers would amplify failures. Agent finding: The order-events queue grew from 3,000 to 185,000 active messages in 35 minutes. Consumer throughput dropped by 92% immediately after release fulfillment-worker:6.4.0. Application logs show deserialization failures involving the new deliveryWindow field. Step 10 is the whole reason to use a reasoning agent instead of an autoscale rule. Every metric here screams "scale out the consumers." An HPA would have done exactly that, and every new replica would have dead-lettered messages faster. Agent action table # Action Type Detail 1 Investigate queue Read Active, incoming, outgoing, scheduled, DLQ counts 2 Calculate flow rates Read Confirms arrival exceeds completion; backlog growing 3 Inspect consumers Read Health, instance count, scaling, errors, dependencies 4 Analyze failures Read Deserialization exceptions involving the new field 5 Correlate release Read Links the 92% throughput reduction to release 6.4.0 6 Rule out Service Bus Read Health, authorization, throttling, networking, service status 7 Assess blast radius Read Backlog age and fulfillment impact 8 Protect message data Decision Prevents payloads or personal data entering ServiceNow 9 Create SNOW INC Write (ITSM) P1 against the fulfillment integration CI 10 Update INC evidence Write (ITSM) Backlog, age, flow, exception, release, business impact 11 Classify response Decision Rollback, not scaling broken consumers 12 Request approval Decision Approval to restore consumer 6.3.7 13 Roll back consumer Write (Azure/K8s) Rolls back through the approved deployment platform 14 Restore capacity Write (Azure/K8s) Restores approved consumer instance count 15 Validate processing Validation Consumer and downstream health 16 Validate backlog Validation Completion exceeds arrival; DLQ growth stops 17 Update INC Write (ITSM) Rollback, rates, estimated drain time, approval 18 Maintain incident Decision Keeps the incident open until backlog age meets the objective 19 Create SNOW CHG Write (ITSM) Separate controlled change for DLQ replay 20 Create SNOW PRB Write (ITSM) Message-contract compatibility remediation Recovery note Consumer release 6.4.0 could not deserialize messages containing the new deliveryWindow field. The fulfillment worker was rolled back to 6.3.7. Consumer throughput recovered, new dead-letter growth stopped, and the active backlog is draining at approximately 7,500 messages per minute. Dead-letter replay requires a separately approved procedure. The lesson: technical recovery is not business recovery Step 18 is the most important row in this entire post. At the moment of rollback, every technical signal is green. Consumers are healthy. Throughput has recovered. The DLQ has stopped growing. An agent optimizing for metrics would resolve the incident right there and go back to sleep. But there are still 185,000 unshipped orders and a dead-letter queue full of messages that need a separately approved replay procedure. Customers are still affected. The incident stays open until backlog age meets the business objective, not until the graphs look nice. Encode this in the response plan explicitly: Do not resolve this incident when consumer health recovers. Resolution criteria: 1. Completion rate exceeds arrival rate for 15 consecutive minutes, AND 2. Oldest active message age is under 5 minutes, AND 3. Dead-letter count has not increased for 30 minutes. DLQ replay is out of scope for this incident. File a separate change record. Try it yourself Break it: # Flood the queue while no consumer is running for i in $(seq 1 5000); do az servicebus queue message send -g $RG --namespace-name sb-sre-demo \ -q order-events --body "{\"orderId\":$i,\"deliveryWindow\":\"2026-08-09T10:00Z\"}" 2>/dev/null done az servicebus queue show -g $RG --namespace-name sb-sre-demo -n order-events \ --query "countDetails" -o json Ask it: order-events on sb-sre-demo has a growing backlog. Read-only. Give me: arrival rate, completion rate, current active count, oldest message age, DLQ count and DLQ growth rate, and the projected drain time at current rates. Then tell me why scaling out consumers is or is not the correct action here. Do not include any message payloads or customer data in your answer. That last line is not optional. Message bodies routinely contain names, addresses, and payment references — and everything the agent writes goes into a ticket. Verify it: az servicebus queue show -g $RG --namespace-name sb-sre-demo -n order-events \ --query "{active:countDetails.activeMessageCount, dlq:countDetails.deadLetterMessageCount}" -o json Guardrails Never automatically purge queues. Do not automatically replay dead-letter messages. Replay without idempotency guarantees means duplicate charges and duplicate shipments. Do not place message payloads in ServiceNow. Confirm idempotency before replay. Scale consumers only when the processing path is healthy. Require separate approval for replay or queue configuration changes. Keep the incident open until business recovery is confirmed. 7. The ITSM integration model Recommended incident fields Field Example Short description Production Orders API pods failing after deployment Configuration item prod-aks-orders-api Assignment group Container Platform Operations Impact High Urgency High Environment Production Azure resource ID Full affected Azure resource ID Azure alert ID Azure Monitor alert correlation identifier SRE investigation Link to the SRE Agent investigation thread Current impact Eight of ten replicas unavailable Probable cause Missing configuration in latest release Confidence High Proposed action Roll back to revision 41 Approval Approver and UTC timestamp Validation Ten replicas ready and synthetic tests passing Resolution Service restored through rollback The Confidence field earns its place. An agent that says "probable cause: missing configuration (confidence: low)" is far more useful than one that always sounds certain, because it tells the human how much to verify before approving. Fields the agent can set directly (preview): assignment_group , category , subcategory , impact , urgency , priority , short_description , and any custom u_* field. It cannot change incident state through field updates — acknowledge and resolve are separate, dedicated tools. Recommended agent-generated timeline Every work note should carry: Element Example Timestamp 2026-03-18 14:26 UTC Observation HTTP 500 rate increased to 18% Evidence Link to the Application Insights query Change correlation Incident started three minutes after deployment Probable cause Missing production application setting Confidence High Proposed action Swap to previous healthy slot Risk Temporary deployment rollback Approval Incident commander and timestamp Execution Slot-swap operation and result Validation 5xx below 1% for 15 minutes Follow-up Problem record for configuration validation Note that Evidence is a link, not a paste. This is a deliberate data-protection pattern: the ticket carries a pointer to the query, and the query results stay in the system that already has the right access controls. Deduplication strategy Do not create one incident per alert, pod, queue, or VMSS instance. Correlate on: application/business service + Azure resource ID + environment (production) + alert-rule family + active incident time window Related alerts attach to the existing incident as evidence or child alerts. Azure Monitor already merges recurring alerts into a single thread when it's the bound platform; for ServiceNow, this correlation key is yours to implement. Get this wrong and your first AKS incident produces eight incidents, eight investigations, and eight rollback proposals for the same deployment. Record responsibilities Record Purpose Example Incident (INC) Restore service quickly and safely App Service HTTP 500 outage Problem (PRB) Identify and remove the underlying cause Missing deployment configuration validation Change (CHG) Govern permanent or higher-risk production changes Coordinated Application Gateway port migration Engineering defect/task Correct application or automation behavior Add retry backoff to the Linux application The agent must clearly distinguish temporary mitigation from permanent correction. Every single use case above ends with a follow-up record, and that's not bureaucratic theatre — an agent that mitigates flawlessly and never files a problem record is an agent that lets the same outage recur forever while making the metrics look great. 8. Reality check: where you have to build This is the section that will save you a month. The PDF this post is built from is explicit that these are target response patterns, not guaranteed zero-configuration behavior. Having now checked each pattern against the product documentation, here is exactly where the gaps are and what fills them. # The pattern assumes What's actually documented What you must build 1 Agent creates a ServiceNow INC ServiceNow is an inbound platform. Documented writes: post discussion entries, acknowledge, resolve, plus field updates (preview) Incidents should originate in ServiceNow (via its own Azure Monitor integration) and flow in. If you truly need agent-initiated creation, add a Python tool or MCP server against the ServiceNow Table API 2 Agent creates PRB / CHG / defect records Not a documented first-class ServiceNow action Same: a custom tool against /api/now/table/problem and /change_request . This is ~30 lines of Python and worth doing properly, with a least-privileged integration user 3 ServiceNow and PagerDuty both connected Only one incident platform active at a time; switching disconnects the other Bind the agent to your system of record (ServiceNow). Reach the pager through a connector, Teams/Slack, or a webhook 4 Agent runs guest-OS cleanup ( rm , rotate, restart) delete and remove commands are blocked outright. az keyvault blocked. Management locks respected Wrap all guest-OS work in fixed-purpose Azure Automation runbooks or a constrained az vm run-command script, invoked with allowlisted parameters. See use case #5 5 Agent "pauses the release pipeline" Requires the GitHub or Azure DevOps connector, plus permissions on that pipeline Connect source control; grant pipeline permissions explicitly; test the pause path before you need it 6 Approval gate on every action Review mode shows Approve/Deny only for Azure infrastructure operations. Emails, Teams posts, and external queries proceed on the agent's reasoning Use hooks or tool access policies to gate non-Azure actions 7 Agent resolves incidents Supported — but during a pilot you don't want it Require human confirmation before resolve. Encode it in the response plan and enforce it with a Stop hook 8 One agent handles everything Response plans route to custom agents; skills cap at five concurrent active Build domain specialists (§4.6). A single mega-agent thrashes its skill budget 9 Autonomous mode by default is fine Per-plan default is Autonomous, and connecting a platform auto-creates an autonomous quickstart_handler Delete the quickstart plan. Set every plan to Review explicitly 10 Agent has broad subscription rights You can't remove individual permissions — only whole resource groups Design resource groups as blast-radius boundaries before onboarding None of these are blockers. All of them are a week of work you'd rather discover now than during your pilot readout. 9. Approval and autonomy policy The policy I would actually ship: Action category Recommended initial policy Read metrics, logs, traces, resource health Automatic Correlate deployments and configuration changes Automatic Create a ServiceNow incident Automatic after deduplication Add sanitized work notes Automatic Prepare a remediation plan Automatic Create a draft ServiceNow change Automatic, but not approve it Modify an Azure production resource Human approval required Execute a VM guest runbook Human approval required Roll back an application Human approval required Delete or replace a stateless VMSS instance Human approval required Resolve a ServiceNow incident Human confirmation during the pilot Delete data, purge queues, replay DLQ messages Separate explicit approval Autonomous remediation Only after a proven, bounded pilot Two notes on making this real: Start in Review and stay there longer than feels necessary. The documented recommendation is to observe for two to four weeks and then promote specific triggers you consistently approve. Not the agent — the triggers. Promotion should be per-response-plan and evidence-based: "we approved this exact rollback proposal eleven times without modification" is a reason to go autonomous. "It seems good" is not. Autonomy should be earned per action type, not per environment. "Autonomous in staging" is a fine starting rule, but the durable version is "autonomous for VMSS single-instance reimage where the workload is stateless and healthy capacity exceeds 80%" — a narrow, well-characterized action with a mechanical precondition. 10. Cross-cutting security controls Use a dedicated managed identity for SRE Agent. Scope Azure roles to selected resources or resource groups. Avoid broad Contributor and Owner assignments. Use fixed-purpose Automation runbooks for guest operations. Do not provide unrestricted SSH, shell, or PowerShell execution. Use a dedicated least-privileged ServiceNow integration identity. Prefer OAuth or a managed connector over stored credentials. Store required secrets in Key Vault — never in prompts. (The agent blocks az keyvault commands entirely, which helps.) Sanitize logs before posting them into ServiceNow. Do not post tokens, personal data, SQL text, message payloads, or memory dumps. Record every approval and production action. Define remediation cooldowns and maximum retry counts. Require post-action application validation. Retain existing manual runbooks as fallback. Use Azure Cost Management alerts for temporary scaling actions. What the platform gives you for free Worth knowing so you don't rebuild it: Layer Isolation model Compute Dedicated sandbox (micro VM) per agent; tool execution separate from the reasoning loop Database Separate database per agent Blob storage Separate blob storage per agent Network Per-agent proxy instance validating every outbound request Credentials Identity sidecar issues short-lived, per-call tokens; credentials never enter the reasoning context Token lifetimes: managed identity ~1 hour (auto-refreshed), OAuth refreshed 20 minutes before expiry, per-tool-call action tokens are single-use, blob SAS 1 hour refreshed at 45 minutes. Each tool invocation launches a fresh process whose entire tree terminates on completion — there are no persistent process pools, so one tool call cannot see another's environment. The audit trail Every az command is logged to your Application Insights as an AgentAzCliExecution custom event. This is your evidence for change management: customEvents | where name == "AgentAzCliExecution" | where timestamp > ago(30d) | project timestamp, command = tostring(customDimensions.command), resource = tostring(customDimensions.resourceId), succeeded = tostring(customDimensions.success), thread = tostring(customDimensions.threadId) | order by timestamp desc Run that query in front of your auditor once and most of the "but can we prove what it did" conversation ends. 11. A 30/60/90 pilot that survives contact with your CAB Phase Enabled capability 1 Detect Azure Monitor alerts 2 Create or correlate ServiceNow incidents 3 Perform read-only investigation 4 Add sanitized findings to ServiceNow 5 Recommend remediation without execution 6 Execute bounded actions after approval in Review mode 7 Validate technical and business recovery 8 Prepare incident resolution and follow-up records 9 Consider autonomy only for proven low-risk actions Phases 1–5 have zero production write risk and deliver most of the MTTR reduction. Do not rush past them to get to the demo-friendly part. The best first five candidates App Service deployment-slot rollback — clean trigger, reversible action, unambiguous validation AKS deployment rollback — same shape, one GitOps caveat VMSS unhealthy-instance replacement — stateless, bounded, easy precondition check Restricted VM disk-recovery runbook — high toil, high value, forces you to build the runbook pattern properly Automatic ServiceNow incident creation and timeline updates — the compounding one; every incident from here on is better documented than any incident before it These five share the properties you want: clear triggers, tightly bounded actions, measurable validation criteria, and practical escalation paths. What to measure in week one Before you enable a single write action, capture your baseline: Median time from alert to first accurate human diagnosis Percentage of incidents where the first hypothesis was wrong Median time from diagnosis to mitigation Percentage of incidents with a complete timeline in the ticket Percentage of incidents that produced a follow-up problem record The read-only phase moves the first, second, and fourth of those immediately. If it doesn't, your telemetry is the problem, not the agent — and that's a genuinely useful thing to discover in week one rather than week twelve. 12. Measuring whether it's actually working Under Monitor → Incident metrics: Metric What it shows Incidents reviewed Total incidents the agent processes Mitigated by agent Resolved autonomously Assisted by agent Agent helped; a human completed it Mitigated by user Human resolved using agent-provided information Pending user action Waiting on a human The counter-intuitive read: "Assisted by agent" and "Mitigated by user" are the healthy numbers during a pilot. A high "Mitigated by agent" count in month one means someone left autonomy on. Watch Pending user action closely. A growing queue there means either your approval routing is broken or the agent is proposing things nobody is comfortable approving — both are important signals, and both are invisible without this dashboard. Also check Monitor → Session insights periodically. Each insight card links back to the thread that generated it, so you can trace any learned pattern to its origin. If the agent has learned something wrong, this is where you find it — and #forget is how you fix it. 13. Resources Core documentation Overview of Azure SRE Agent Security and trust model Agent permissions Run modes Incident response Incident management platforms Incident response plans ServiceNow incident indexing Root cause analysis Execute mitigations Extensibility Custom agents Skills Agent hooks Scheduled tasks Memory and knowledge Closing The framing that makes this work isn't "AI runs my production." It's this: Your agent is the most junior person on the rotation — and the most thorough. It will never skip the Resource Health check. It will never forget to compare against the previous slot. It will never write "restarted it, seems fine" in a work note at 4 AM. And it will never, ever be allowed to rm -rf anything. Every guardrail in this post exists to keep it in that role. Scope the identity to resource groups. Keep production writes in Review. Wrap guest-OS work in runbooks with allowlists. Never let it purge a queue or replay a dead-letter message on its own. Keep the incident open until customers are actually served, not until the graphs look nice. Do that, and the ten workflows above stop being a slide deck and start being your Tuesday. Start with use case #1. One App Service, one slot, one alert rule, one response plan in Review mode. Watch it assemble an evidence chain you'd have spent twenty minutes building by hand, and then decide how much further you want to go. The ten scenarios in this post are target response patterns. Each one requires appropriate telemetry, scoped Azure RBAC, response-plan instructions, approved remediation tooling, and ITSM integration. Confirm current Azure SRE Agent and ServiceNow connector capabilities against Microsoft documentation before implementing — the product is moving quickly, and several capabilities referenced here are in preview.428Views1like0CommentsYour Sentinel AMA Logs & Queries Are Public by Default - AMPLS Architectures to Fix That
When you deploy Microsoft Sentinel, security log ingestion travels over public Azure Data Collection Endpoints by default. The connection is encrypted, and the data arrives correctly — but the endpoint is publicly reachable, and so is the workspace itself, queryable from any browser on any network. For many organisations, that trade-off is fine. For others — regulated industries, healthcare, financial services, critical infrastructure — it is the exact problem they need to solve. Azure Monitor Private Link Scope (AMPLS) is how you solve it. What AMPLS Actually Does AMPLS is a single Azure resource that wraps your monitoring pipeline and controls two settings: Where logs are allowed to go (ingestion mode: Open or PrivateOnly) Where analysts are allowed to query from (query mode: Open or PrivateOnly) Change those two settings and you fundamentally change the security posture — not as a policy recommendation, but as a hard platform enforcement. Set ingestion to PrivateOnly and the public endpoint stops working. It does not fall back gracefully. It returns an error. That is the point. It is not a firewall rule someone can bypass or a policy someone can override. Control is baked in at the infrastructure level. Three Patterns — One Spectrum There is no universally correct answer. The right architecture depends on your organisation's risk appetite, existing network infrastructure, and how much operational complexity your team can realistically manage. These three patterns cover the full range: Architecture 1 — Open / Public (Basic) No AMPLS. Logs travel to public Data Collection Endpoints over the internet. The workspace is open to queries from anywhere. This is the default — operational in minutes with zero network setup. Cloud service connectors (Microsoft 365, Defender, third-party) work immediately because they are server-side/API/Graph pulls and are unaffected by AMPLS. Azure Monitor Agents and Azure Arc agents handle ingestion from cloud or on-prem machines via public network. Simplicity: 9/10 | Security: 6/10 Good for: Dev environments, teams getting started, low-sensitivity workloads Architecture 2 — Hybrid: Private Ingestion, Open Queries (Recommended for most) AMPLS is in place. Ingestion is locked to PrivateOnly — logs from virtual machines travel through a Private Endpoint inside your own network, never touching a public route. On-premises or hybrid machines connect through Azure Arc over VPN or a dedicated circuit and feed into the same private pipeline. Query access stays open, so analysts can work from anywhere without needing a VPN/Jumpbox to reach the Sentinel portal — the investigation workflow stays flexible, but the log ingestion path is fully ring-fenced. You can also split ingestion mode per DCE if you need some sources public and some private. This is the architecture most organisations land on as their steady state. Simplicity: 6/10 | Security: 8/10 Good for: Organisations with mixed cloud and on-premises estates that need private ingestion without restricting analyst access Architecture 3 — Fully Private (Maximum Control) Infrastructure is essentially identical to Architecture 2 — AMPLS, Private Endpoints, Private DNS zones, VPN or dedicated circuit, Azure Arc for on-premises machines. The single difference: query mode is also set to PrivateOnly. Analysts can only reach Sentinel from inside the private network. VPN or Jumpbox required to access the portal. Both the pipe that carries logs in and the channel analysts use to read them are fully contained within the defined boundary. This is the right choice when your organisation needs to demonstrate — not just claim — that security data never moves outside a defined network perimeter. Simplicity: 2/10 | Security: 10/10 Good for: Organisations with strict data boundary requirements (regulated industries, audit, compliance mandates) Quick Reference — Which Pattern Fits? Scenario Architecture Getting started / low-sensitivity workloads Arch 1 — No network setup, public endpoints accepted Private log ingestion, analysts work anywhere Arch 2 — AMPLS PrivateOnly ingestion, query mode open Both ingestion and queries must be fully private Arch 3 — Same as Arch 2 + query mode set to PrivateOnly One thing all three share: Microsoft 365, Entra ID, and Defender connectors work in every pattern — they are server-side pulls by Sentinel and are not affected by your network posture. Please feel free to reach out if you have any questions regarding the information provided.593Views3likes2CommentsEvoluindo a Resposta a Incidentes em AKS com Azure SRE Agent - Parte 1
Resumo executivo Em aplicações executadas no Azure Kubernetes Services (AKS), eventos OOMKilled estão entre as causas recorrentes de reinicialização de contêineres e indisponibilidade intermitente em aplicações web. A observabilidade fornecida por Azure Monitor, Container Insights, Log Analytics e métricas Prometheus permite detectar o sintoma, registrar o evento e disparar o alerta. A detecção isolada, porém, ainda deixa para a equipe de plantão o trabalho mais caro: correlacionar métricas, logs, eventos, alterações recentes e limites de recursos até chegar a uma hipótese defensável. Sobre essa base de observabilidade, o Azure SRE Agent adiciona uma camada de raciocínio e execução governada. Ao receber o incidente, ele coleta evidências nas fontes conectadas, valida hipóteses e produz um diagnóstico explicável. Em seguida, recomenda a ação de menor risco e, conforme o modo de execução configurado, solicita aprovação humana ou executa uma remediação pré-autorizada. O resultado é um fluxo mais rápido e rastreável, sem eliminar os controles de acesso e aprovação. Este whitepaper documenta o padrão em um laboratório reproduzível. No cenário, um pod em CrashLoopBackOff por limite de memória subdimensionado (20 Mi de limite, 10 Mi de solicitação) é investigado, diagnosticado e corrigido pelo agente sob aprovação humana, com verificação posterior e disparo automatizado por alerta do Azure Monitor. Além do passo a passo, o documento aprofunda a mecânica que sustenta o diagnóstico, cgroups v2, o OOM killer do kernel, classes de QoS, working set versus RSS e o comportamento de heap dos runtimes, porque a qualidade da resposta assistida depende diretamente da qualidade dos sinais que a alimentam. O que este documento entrega A anatomia técnica de um evento OOMKilled em AKS, do cgroup ao status do pod. Consultas KQL e PromQL prontas para detecção e para o desenho da regra de alerta. O modelo operacional do Azure SRE Agent: fontes de contexto, modos de execução, permissões, hooks e políticas de acesso a ferramentas. Um laboratório completo, do provisionamento do agente à recuperação verificada do workload. Um enquadramento de governança, auditoria e segurança para operações agênticas. O que este documento não cobre Disparo totalmente automatizado a partir do alerta e integração com o processo de gestão de incidentes, tema da Parte 2. Ajuste fino de capacidade em escala de frota (VPA/HPA em produção), tratado apenas como método. Valores de preço vigentes; o modelo de cobrança é descrito de forma qualitativa. 1. Introdução Aplicações nativas de nuvem distribuem o processamento entre pods, serviços, dependências e nós. Essa elasticidade melhora a escala, mas amplia a complexidade da investigação quando uma falha ocorre. Em um incidente de memória, o primeiro sinal pode ser um pod reiniciado, uma elevação de erros HTTP, aumento de latência ou degradação parcial de uma jornada específica. O problema raramente é a ausência de dados. É o custo cognitivo de atravessar métricas, logs, eventos do Kubernetes, histórico de implantação e manifestos sob pressão de tempo, para só então formular uma hipótese. Esse custo é pago integralmente a cada incidente, e não se acumula como conhecimento reutilizável. Este whitepaper apresenta um padrão de resposta a incidentes em que o Azure Monitor sustenta a detecção e a telemetria, enquanto o Azure SRE Agent converte sinais em contexto operacional acionável, preservando a decisão humana onde ela é necessária. 2. Contexto e desafio operacional O cenário considera uma aplicação web em AKS instrumentada com Container Insights, Log Analytics, métricas Prometheus e alertas do Azure Monitor. O desafio não é apenas saber que um contêiner foi encerrado, é determinar por que a memória ultrapassou o limite, qual versão e qual carga estavam envolvidas, qual foi o impacto ao usuário e qual ação reduz risco sem ocultar a causa raiz. Ou seja, transformar sinais distribuídos em uma decisão defensável sobre pressão de tempo. Telemetria distribuída entre métricas, logs, eventos e histórico de implantação. Pressão de tempo para restaurar o serviço antes da violação do SLO. Risco de reinicializações repetitivas que mascaram a ausência de correção estrutural. Necessidade de aprovação, rastreabilidade e segregação de funções em ambientes regulados. Há ainda um viés operacional relevante: sob pressão, o caminho mais curto, reiniciar o pod ou ampliar o limite de memória, quase sempre funciona no curto prazo. Isso torna difícil distinguir, retrospectivamente, um limite subdimensionado de um vazamento de memória lento, porque a evidência que separaria os dois é descartada junto com o contêiner encerrado. 3. Anatomia técnica do evento OOMKilled Antes de delegar a investigação a um agente, é necessário estabelecer com precisão o que o sinal significa. Boa parte dos diagnósticos incorretos de memória em Kubernetes nasce da confusão entre três mecanismos distintos: o OOM killer do kernel atuando no cgroup do contêiner, o despejo (eviction) decidido pelo kubelet por pressão no nó, e o encerramento por falha da aplicação. 3.1 O caminho do kernel: cgroups v2, memory.max e o OOM killer Quando um contêiner declara resources.limits.memory, o kubelet traduz esse valor para o controlador de memória do cgroup correspondente. Em nós AKS com imagens baseadas em Ubuntu 22.04 ou superior e Azure Linux 3.0, padrão em versões recentes do Kubernetes, o runtime opera sobre cgroup v2, e o limite é materializado no arquivo memory.max do cgroup do contêiner. A partir daí, o comportamento é do kernel Linux, não do Kubernetes. Quando as páginas anônimas do cgroup não podem mais ser recuperadas e a alocação ultrapassaria memory.max, o kernel invoca o OOM killer restrito àquele cgroup, escolhe um processo e envia SIGKILL. O contador correspondente é incrementado em memory.events, no campo oom_kill. # Dentro do nó, inspecionando o cgroup do contêiner (cgroup v2) cat /sys/fs/cgroup/.../memory.max # limite efetivo (bytes) cat /sys/fs/cgroup/.../memory.high # ponto de throttling por reclaim cat /sys/fs/cgroup/.../memory.current # uso corrente cat /sys/fs/cgroup/.../memory.events # low / high / max / oom / oom_kill Vale distinguir dois campos frequentemente confundidos em memory.events: max conta quantas vezes a alocação esbarrou no teto e forçou reclaim, enquanto oom_kill conta quantos processos foram efetivamente encerrados. Um valor alto em max com oom_kill igual a zero indica um contêiner operando permanentemente no limite: degradado, porém vivo. É exatamente o estado que antecede o incidente e que raramente dispara alerta. Como o processo recebe SIGKILL (sinal 9), o código de saída observado é 137, resultado da convenção POSIX 128 + número do sinal. O kubelet então registra o término e reinicia o contêiner conforme a restartPolicy. É por isso que a evidência canônica não está no status corrente do pod, mas no estado anterior do contêiner: kubectl get pod <pod> -n pets -o jsonpath='{.status.containerStatuses[0].lastState.terminated}' | jq # Saída esperada em um OOMKill: # { # "exitCode": 137, # "reason": "OOMKilled", # "startedAt": "...", # "finishedAt": "..." # } Reinícios sucessivos levam o pod a CrashLoopBackOff, em que o kubelet aplica um atraso exponencial entre tentativas, iniciando na ordem de dezenas de segundos e dobrando até um teto de poucos minutos, cujo valor padrão vem sendo revisado em versões recentes do Kubernetes. Esse atraso é o motivo pelo qual a indisponibilidade percebida cresce ao longo do incidente mesmo sem agravamento da causa raiz. 3.2 OOMKilled não é eviction: dois mecanismos, duas correções A distinção é operacionalmente decisiva porque as correções divergem: um OOMKill se resolve no manifesto do workload; um despejo se resolve na capacidade ou no agendamento do nó. Dimensão OOMKilled (cgroup) Eviction (kubelet) Gatilho Alocação excede memory.max do cgroup do contêiner memory.available do nó abaixo do limiar evictionHard/evictionSoft Quem decide Kernel Linux (OOM killer restrito ao cgroup) kubelet, ordenando os pods por QoS e excesso sobre requests Escopo Um contêiner O pod inteiro, podendo atingir vários pods do nó Sinal SIGKILL → exit code 137 Encerramento do pod; sem exit code 137 característico Evidência lastState.terminated.reason = OOMKilled status.phase = Failed, reason = Evicted Objeto do pod Preservado; contêiner reinicia no mesmo pod Pod permanece como registro de falha e é reagendado por seu controlador Correção típica Ajustar limits/requests ou o consumo da aplicação Capacidade do nó, requests coerentes, limiares de despejo, distribuição Nota. Um terceiro caso é frequentemente confundido com ambos: o encerramento do processo principal por erro da aplicação, que produz códigos de saída próprios (1, 2, 143 para SIGTERM). Verificar exitCode e reason antes de concluir por memória evita corrigir o sintoma errado. 3.3 Classes de QoS e a ordem em que os pods são sacrificados O Kubernetes deriva a classe de Quality of Service de cada pod a partir da relação entre requests e limits. Essa classe não é apenas rótulo: ela determina a prioridade de despejo e influencia diretamente o valor de oom_score_adj atribuído aos processos do contêiner. Classe de QoS Condição Prioridade de despejo Guaranteed requests iguais a limits para CPU e memória em todos os contêineres Última a ser despejada Burstable Pelo menos um request ou limit definido, sem igualdade entre eles Intermediária, proporcional ao excesso sobre o request BestEffort Nenhum request ou limit definido Primeira a ser despejada Para pods Burstable, o kubelet calcula oom_score_adj em função da fração da memória do nó reservada pelo request: quanto menor o request em relação à capacidade do nó, maior o score e mais atraente o processo se torna para o OOM killer. Pods Guaranteed recebem um valor fortemente negativo, e pods BestEffort recebem o valor máximo. Aplicação ao laboratório O order-service deste cenário declara requests de 10 Mi e limits de 20 Mi. A desigualdade entre os dois o classifica como Burstable, e o request muito baixo em relação à capacidade do nó eleva seu oom_score_adj. O workload é, portanto, simultaneamente o mais provável de estourar o próprio limite e um dos primeiros candidatos ao OOM killer sob pressão do nó, combinação que o torna um caso de teste representativo. Há uma consequência de projeto pouco explorada: elevar apenas o limit sem elevar o request melhora a sobrevivência ao OOMKill do cgroup, mas mantém o pod vulnerável em cenários de pressão do nó, porque o agendador continua reservando pouca memória para ele. Foi exatamente por isso que a recomendação do agente no laboratório ajustou os dois valores, e não apenas o limite. 3.4 Working set, RSS e por que o dashboard pode enganar A métrica que melhor aproxima a decisão do OOM killer é o working set, e não o RSS. Em cAdvisor, a fonte de container_memory_working_set_bytes e da métrica memoryWorkingSetBytes exposta pelo Container Insights, o working set corresponde ao uso total do cgroup menos o page cache inativo, isto é, a porção da memória que o kernel não conseguiria liberar trivialmente sob pressão. Métrica O que representa Uso recomendado container_memory_working_set_bytes Uso do cgroup menos page cache inativo Referência para alertas e para dimensionar limits container_memory_rss Páginas anônimas residentes do processo Investigação de vazamento no heap da aplicação container_memory_usage_bytes Uso total, incluindo page cache reclaimável Diagnóstico; superestima a pressão real container_memory_cache Page cache atribuído ao cgroup Explicar divergência entre usage e working set A armadilha prática: um painel construído sobre container_memory_usage_bytes pode indicar uso próximo ao limite sem risco real, porque boa parte é cache recuperável. Inversamente, um painel com média de 5 minutos pode mostrar 60% de uso e ainda assim o contêiner ser encerrado, porque o OOM killer reage a um pico instantâneo que a agregação suavizou. Alertas de memória devem usar working set e agregação por máximo, não por média. 3.5 Heap do runtime versus limite do contêiner Uma causa frequente de OOMKilled não está no limite em si, mas no desalinhamento entre o limite do cgroup e a política de heap do runtime. Runtimes que dimensionam o heap a partir da memória visível do host, e não do limite do cgroup, planejam crescer muito além do que o contêiner pode alocar, e o kernel encerra o processo antes que o coletor de lixo julgue necessário agir. Runtime Controle recomendado Observação Node.js --max-old-space-size (MB) Fixar abaixo do limite do contêiner; o order-service deste laboratório é Node.js JVM -XX:MaxRAMPercentage com UseContainerSupport Reservar espaço para metaspace, threads e buffers fora do heap .NET DOTNET_GCHeapHardLimitPercent; avaliar Server GC Server GC eleva o consumo por número de núcleos visíveis Go GOMEMLIMIT Limite flexível: intensifica a coleta em vez de abortar Python Limitar workers e pool de conexões Sem heap gerenciado; o consumo escala com concorrência Regra prática: o limite do contêiner deve acomodar o heap máximo do runtime somada a memória fora do heap, pilhas de threads, buffers de I/O, conexões, bibliotecas nativas e o próprio page cache anônimo. Dimensionar o heap igual ao limite do contêiner é uma causa clássica de OOMKilled sob carga. 3.6 Causas frequentes Limite subdimensionado: o consumo legítimo da carga excede o valor configurado, como ocorre neste laboratório. Vazamento de memória: o processo retém memória de forma progressiva entre requisições. Pico de tráfego ou payload atípico: a demanda transitória ultrapassa a capacidade provisionada. Concorrência excessiva: workers, filas ou caches locais ampliam o working set de forma não linear. Requests e limits incoerentes: o agendamento e a contenção não refletem o perfil real de consumo. Heap do runtime maior que o limite do cgroup: o processo planeja crescer além do permitido. Valores herdados de um dimensionamento anterior que nunca foi revisado após mudanças de código ou de carga. 4. Impactos para aplicações web em AKS Dimensão Impacto potencial Usuário Erros HTTP 5xx, timeouts, perda de sessão e latência elevada. Aplicação Interrupção de requisições em andamento, reprocessamento e perda de cache local. Plataforma CrashLoopBackOff, aumento de restarts e pressão sobre outros pods ou nós. Negócio Violação de SLO, risco à receita e degradação da experiência digital. Operações Escalonamento de plantão, investigação manual e aumento do MTTR. Um agravante específico do OOMKilled é o efeito em cascata: ao reiniciar, o contêiner reconstrói caches e refaz conexões, produzindo um pico de consumo de memória e CPU justamente no momento em que a capacidade agregada do serviço está reduzida. Isso pode encadear novos encerramentos em réplicas ainda saudáveis e transformar uma falha localizada em degradação do serviço. 5. Detecção: sinais, consultas e desenho do alerta A qualidade da investigação assistida depende da qualidade dos sinais disponíveis. Esta seção consolida as consultas usadas para detectar OOMKilled em AKS e o desenho da regra de alerta empregada no laboratório. 5.1 Sinais canônicos # Estado atual e contagem de reinícios kubectl get pods -n pets -o wide # Razão do término anterior, a evidência decisiva kubectl get pods -n pets -o custom-columns=\ NAME:.metadata.name,\ STATUS:.status.phase,\ RESTARTS:.status.containerStatuses[0].restartCount,\ REASON:.status.containerStatuses[0].lastState.terminated.reason,\ EXIT:.status.containerStatuses[0].lastState.terminated.exitCode # Limites efetivamente aplicados ao contêiner kubectl get deployment order-service -n pets \ -o jsonpath='{.spec.template.spec.containers[0].resources}' # Eventos correlatos na janela do incidente kubectl get events -n pets --sort-by=.lastTimestamp 5.2 Consultas KQL no Log Analytics Com Container Insights habilitado, o inventário de pods carrega o estado anterior de cada contêiner em formato JSON, o que permite isolar terminações por OOMKilled diretamente na consulta: // Contêineres encerrados por OOMKilled nas últimas 6 horas KubePodInventory | where TimeGenerated > ago(6h) | where isnotempty(ContainerLastStatus) | extend LastStatus = parse_json(ContainerLastStatus) | where tostring(LastStatus.reason) == "OOMKilled" | project TimeGenerated, ClusterName, Namespace, Name, ContainerName = ContainerName, ExitCode = toint(LastStatus.exitCode), RestartCount = ContainerRestartCount, FinishedAt = todatetime(LastStatus.finishedAt) | summarize Ocorrencias = count(), Ultima = max(FinishedAt), MaxRestarts = max(RestartCount) by ClusterName, Namespace, ContainerName | order by Ocorrencias desc Os eventos do Kubernetes oferecem uma segunda camada de confirmação, útil quando o intervalo de coleta do inventário perde uma terminação de curta duração: // Eventos de OOM e falhas de inicialização correlatas KubeEvents | where TimeGenerated > ago(6h) | where Reason in ("OOMKilling", "OOMKilled", "BackOff", "Failed") | project TimeGenerated, ClusterName, Namespace, Name, Reason, Message | order by TimeGenerated desc Para separar limite subdimensionado de vazamento, a consulta relevante é a tendência do working set contra o limite declarado. Um platô estável junto ao teto sugere subdimensionamento; uma inclinação positiva sustentada entre reinícios sugere retenção progressiva: // Working set máximo por contêiner, em janelas de 5 minutos Perf | where TimeGenerated > ago(24h) | where ObjectName == "K8SContainer" | where CounterName == "memoryWorkingSetBytes" | summarize MaxWorkingSetMi = max(CounterValue) / 1024 / 1024 by bin(TimeGenerated, 5m), InstanceName | render timechart 5.3 Equivalentes em PromQL Em clusters com Azure Monitor managed service for Prometheus, os mesmos sinais ficam disponíveis como séries temporais, o que facilita alertas baseados em razão de utilização: # Razão entre working set e limite declarado, por pod max by (namespace, pod, container) ( container_memory_working_set_bytes{namespace="pets", container!=""} ) / max by (namespace, pod, container) ( kube_pod_container_resource_limits{namespace="pets", resource="memory"} ) # Contêineres cuja última terminação foi OOMKilled kube_pod_container_status_last_terminated_reason{reason="OOMKilled"} == 1 # Taxa de reinícios na última hora increase(kube_pod_container_status_restarts_total{namespace="pets"}[1h]) > 0 Nota. Um alerta preventivo sobre a razão working set / limite acima de 0,85 por vários minutos antecipa o incidente antes do primeiro OOMKill, transformando uma interrupção em uma tarefa de dimensionamento planejada. Essa é a regra que mais reduz incidentes desta classe. 5.4 Desenho da regra de alerta utilizada no laboratório A regra empregada no cenário é uma Log Alert V2 sobre o workspace do Log Analytics, avaliando a consulta de OOMKilled e disparando quando a contagem de resultados é maior que zero. Parâmetro Valor no laboratório Consideração de produção Tipo Log search alert (Log Alerts V2) Consultas sobre logs; considerar alerta de métrica para latência menor Escopo Workspace do Log Analytics do cluster Escopo por cluster ou por assinatura, conforme o modelo de plantão Lógica Contagem de resultados maior que 0 Aumentar o limiar para tolerar reinícios isolados e evitar ruído Severidade 1, Error Alinhar à criticidade do serviço e à política de plantão Frequência / janela Avaliação periódica sobre janela curta Janela igual ou maior que a frequência, para não perder eventos Ação Action group com notificação por e-mail Encaminhar também a ITSM/PagerDuty e ao gatilho do agente Auto-resolução Padrão da regra Habilitar para incidentes transitórios; desabilitar se exigir baixa manual Latência esperada de ponta a ponta No laboratório, o pod entrou em OOMKilled às 17h45 e a notificação chegou às 17h47. Esses dois minutos somam ingestão no Log Analytics, período de avaliação da regra e entrega pelo action group. Alertas baseados em log carregam essa latência por construção, um dado relevante ao definir SLOs de detecção e ao decidir entre alerta de log e alerta de métrica. 6. O processo tradicional e seus limites 6.1 Fluxo típico de resposta O Azure Monitor dispara o alerta e notifica o plantão. O plantonista abre o portal, os dashboards e o Log Analytics. Executa comandos kubectl para localizar o pod e confirmar a razão do término. Compara consumo, limite, reinícios, eventos e alterações recentes. Formula uma hipótese, reinicia ou reimplanta o workload e acompanha a recuperação. Registra evidências e ações no sistema ITSM. 6.2 Limitações do modelo reativo Esse fluxo depende da experiência individual, exige alternância constante entre ferramentas e produz decisões inconsistentes entre plantonistas. Um restart reduz o sintoma, mas não distingue vazamento de memória, limite inadequado ou pico legítimo de carga. Sob pressão, cresce também o risco de ampliar recursos sem validação, perder evidências ao encerrar o contêiner afetado ou executar ações privilegiadas fora do processo de mudança. O custo mais alto, porém, é invisível: o conhecimento produzido durante a investigação permanece no indivíduo e não fica disponível para o próximo incidente da mesma classe. 7. Azure SRE Agent: arquitetura e modelo operacional O Azure SRE Agent é um agente de confiabilidade que conecta fontes de observabilidade, plataformas de incidente, repositórios de código e conhecimento operacional. Ele investiga causas prováveis, propõe mitigações e automatiza respostas orientadas por planos e runbooks, dentro de guardrails e fluxos de aprovação. Princípio de arquitetura O Azure Monitor permanece como fonte de detecção e evidência. O SRE Agent atua como camada de investigação, decisão e orquestração governada. O agente não substitui a observabilidade: ele consome e correlaciona o que ela produz. 7.1 Fontes de contexto A qualidade do diagnóstico é função direta das fontes conectadas. Durante a configuração, o agente solicita explicitamente a associação de quatro categorias de contexto. Fonte O que habilita Uso no cenário OOMKilled Recursos do Azure Consultar e operar recursos por meio da identidade do agente Ler o estado do cluster AKS e aplicar a mitigação aprovada Logs Consultar workspaces do Log Analytics Correlacionar eventos, inventário de pods e métricas de working set Código Acessar repositórios e artefatos de engenharia Relacionar o limite aplicado ao manifesto de origem Incidentes Integrar Azure Monitor, ServiceNow e PagerDuty Receber o alerta e vincular a investigação ao incidente 7.2 Execução por ferramentas e classificação de risco O agente não age por um canal opaco, cada passo é uma chamada de ferramenta explícita, um comando da CLI do Azure, uma consulta KQL, um comando kubectl, apresentada na thread com o comando exato e uma classificação de risco associada. No laboratório, comandos de leitura como az aks show aparecem marcados como Safe, enquanto operações como kubectl get deployments e kubectl patch recebem a marcação Medium risk. Essa transparência tem duas consequências práticas. A primeira é auditoria: a thread registra a sequência exata de comandos, permitindo reconstruir a investigação. A segunda é revisão: o operador avalia o comando concreto, não uma descrição em linguagem natural do que o agente pretende fazer. 7.3 Modos de execução (Run Modes) Os modos de execução controlam o fluxo de aprovação, isto é, se o agente pergunta antes de agir. É importante separar esse conceito das permissões, que controlam o acesso ao recurso. O agente precisa das duas condições satisfeitas para executar uma ação. Modo Comportamento Indicação Review O agente propõe a ação e aguarda Approve ou Deny Produção, infraestrutura crítica, alertas de segurança Autonomous O agente executa imediatamente e relata o que fez Ambientes de não produção e tarefas recorrentes confiáveis Três detalhes que mudam o desenho de governança Primeiro: o modo de execução é definido por plano de resposta e por tarefa agendada, não no nível do agente; a configuração do agente serve apenas como padrão de fallback. Segundo: os botões Approve e Deny aparecem para operações de infraestrutura do Azure; outras ações, como enviar e-mail, publicar no Teams ou consultar fontes externas, seguem a instrução do plano de resposta e exigem hooks ou políticas de acesso a ferramentas para receber controle equivalente. Terceiro: apenas administradores do SRE Agent podem aprovar ações, o que materializa a segregação de funções. Uma observação de adoção relevante: os planos de resposta e as tarefas agendadas assumem Autonomous como padrão, enquanto o agente é criado em Review. Assumir que criar o agente em Review protege automaticamente todos os fluxos é um erro de configuração fácil de cometer e caro de descobrir. 7.4 Permissões, escopo e elevação sob demanda O agente opera por meio de uma identidade gerenciada, e o que ele consegue fazer é delimitado pelas atribuições RBAC dessa identidade e pelo escopo em que foram concedidas. Quando o agente não possui a permissão necessária para uma operação, ele solicita acesso temporário por meio do fluxo On-Behalf-Of do Microsoft Entra, em vez de falhar silenciosamente. Esse comportamento é arquiteturalmente importante: ele permite conceder à identidade do agente um conjunto mínimo e permanente de permissões de leitura, deixando as operações de escrita dependentes de uma elevação explícita e rastreável. É o oposto do padrão adotado no laboratório, que concede permissões amplas por conveniência de demonstração. 7.5 Hooks e políticas de acesso a ferramentas Hooks são pontos de verificação personalizados que validam, auditam ou bloqueiam o comportamento do agente em momentos específicos do fluxo. Eles complementam os modos de execução: enquanto os modos controlam quando o agente pode agir, os hooks controlam o que acontece antes e depois de cada ação. Evento Quando dispara Aplicações típicas PostToolUse Após a execução de uma ferramenta Auditar o uso, bloquear ou sinalizar operações inseguras, injetar contexto adicional no resultado Stop Quando o agente vai devolver a resposta final Validar completude, exigir formato, rejeitar a resposta e forçar continuidade da investigação Tipos de execução: Prompt, avaliado pelo modelo para verificações que exigem julgamento; e Command, script determinístico para auditoria e aplicação de política. Escopos de configuração: no nível do agente, aplicando-se a todas as threads; ou no nível de um agente personalizado. Quando ambos correspondem, os dois executam. Políticas de acesso a ferramentas complementam os hooks ao restringir previamente quais ferramentas podem ser invocadas em cada contexto. 7.6 Provedor de modelo e residência de dados O provedor de modelo é escolhido na criação do agente e pode ser alterado depois, sem recriar o recurso. Há duas famílias disponíveis, com perfis distintos: modelos do Azure OpenAI e modelos Anthropic Claude. Para organizações reguladas, essa escolha ultrapassa o critério de qualidade de raciocínio e entra no domínio de conformidade: os provedores diferem quanto à cobertura de requisitos de residência de dados, incluindo o EU Data Boundary, e a disponibilidade varia por região. A recomendação é validar os requisitos de residência e a lista de regiões suportadas na documentação vigente antes de padronizar o provedor para cargas de produção. 7.7 Modelo de consumo O consumo do agente é medido em Azure Agent Units e combina dois componentes: um fluxo contínuo, associado à existência do agente e ao monitoramento de base, e um fluxo ativo, proporcional aos tokens processados durante investigações. Modelos com janelas de contexto maiores tendem a consumir mais no fluxo ativo. A implicação de FinOps é direta: o custo escala com o volume de investigações e com a profundidade do contexto conectado, não com o número de recursos monitorados. Reduzir alertas ruidosos diminui o custo do agente pelo mesmo mecanismo que reduz a fadiga do plantão. Consulte a página de preços para os valores vigentes. 8. Processo de resposta com o SRE Agent Receber e classificar: consumir o incidente do Azure Monitor e aplicar filtros por severidade, serviço e título. Coletar evidências: consultar Log Analytics, métricas, eventos do Kubernetes, estado do pod, histórico de implantação e runbooks. Formar hipóteses: comparar limite versus uso, tendência temporal, payload, versão implantada e eventos correlatos. Validar: sustentar cada hipótese com evidência observável e registrar as alternativas descartadas. Recomendar: apresentar ação imediata, correção estrutural, risco associado e critérios de rollback. Agir sob governança: executar apenas ações pré-autorizadas ou aguardar aprovação, conforme o modo de execução do plano. Verificar e aprender: confirmar a estabilidade, documentar o resultado e enriquecer a memória operacional. A etapa 4 é a que mais diferencia uma investigação assistida de uma sugestão genérica. Um diagnóstico útil não afirma apenas qual é a causa provável: registra qual evidência sustenta a conclusão, qual hipótese foi descartada e por quê. É esse registro que permite ao operador revisar a decisão em segundos, em vez de refazer a investigação. 9. Cenário do incidente 9.1 Situação O serviço order-service, no namespace pets, processa requisições de uma aplicação web de comércio eletrônico. Após aumento de tráfego e uso de payloads maiores, as réplicas passam a reiniciar. O Azure Monitor detecta a elevação na contagem de reinicializações e a ocorrência de eventos OOMKilled. 9.2 Linha de investigação # Evidência buscada Interpretação 1 reason igual a OOMKilled e exitCode 137 em lastState Encerramento pelo kernel por ultrapassagem do limite do cgroup, não falha da aplicação. 2 Working set atingindo o limite declarado Distinguir limite inadequado de crescimento anômalo entre requisições. 3 Pico correlacionado a tráfego ou tamanho de payload Avaliar comportamento legítimo versus retenção progressiva de memória. 4 Implantação recente do workload Determinar se houve regressão em código ou em configuração de recursos. 5 Contagem de restarts e erros HTTP Quantificar impacto ao usuário e urgência da mitigação. 6 Classe de QoS e relação requests/limits Avaliar exposição adicional a despejo por pressão no nó. 9.3 Formato do diagnóstico assistido O agente entrega um resumo com causa provável, grau de confiança, evidências que a sustentam, alternativas descartadas e plano de mitigação com critério de reversão. A estrutura importa tanto quanto o conteúdo: ela permite que a revisão humana seja auditoria, e não repetição do trabalho. O contêiner atingiu repetidamente o limite de memória durante o processamento de payloads acima do padrão histórico. Não há evidência suficiente de crescimento contínuo entre requisições; a hipótese principal é limite subdimensionado para a nova carga. Mitigação proposta: elevar limits e requests de memória, com verificação do consumo após a alteração. 10. Implementação e validação do cenário no AKS A seguir, o padrão conceitual é aplicado a um ambiente AKS de demonstração. O objetivo é conectar o cluster ao SRE Agent, conceder as permissões necessárias, integrar as fontes de observabilidade e validar o fluxo de diagnóstico e recuperação de um pod afetado por OOMKilled. Preparar o ambiente: validar o cluster AKS, a aplicação de demonstração e o estado inicial do workload. Criar o SRE Agent: provisionar o agente e selecionar o provedor de modelo conforme os requisitos do ambiente. Conectar as fontes de dados: integrar o cluster, o Azure Monitor e o Log Analytics para disponibilizar alertas, logs e métricas. Conceder permissões: atribuir à identidade gerenciada do agente o acesso necessário para investigar e, no laboratório, executar a remediação aprovada. Validar diagnóstico e recuperação: provocar o evento OOMKilled, acompanhar a investigação, aprovar a recomendação e confirmar a recuperação do pod. Escopo do laboratório As permissões concedidas nesta seção são deliberadamente amplas para reduzir o atrito da demonstração. Elas não representam uma configuração recomendada para produção. A seção 10.5 apresenta o desenho de menor privilégio equivalente, e a seção 12 detalha as implicações de segurança. 10.1 Ambiente e pré-requisitos A aplicação utilizada é o AKS Store Demo, exemplo de referência da Microsoft que representa uma loja de comércio eletrônico decomposta em microsserviços poliglotas. A tabela a seguir consolida a configuração do ambiente, para permitir a reprodução do cenário. Componente Configuração no laboratório Cluster AKS-SRE-Demo-Cluster, SKU Base, tier Free, 1 node pool Versão do Kubernetes 1.35.6 Região East US 2 Rede Azure CNI Overlay Observabilidade Container Insights habilitado, enviando logs e métricas ao Log Analytics Aplicação AKS Store Demo, namespace pets, exposta por Service do tipo LoadBalancer Workload em falha order-service (Node.js), requests 10 Mi / limits 20 Mi de memória Alerta Alert-OOMKilled-Pods, Log Alerts V2, severidade 1, Error Agente Azure SRE Agent provisionado no grupo de recursos Azure-SRE-RG A arquitetura da aplicação é relevante para o diagnóstico: o order-service recebe pedidos do store-front e os publica em uma fila RabbitMQ, consumida pelo makeline-service. Um serviço que faz buffer de mensagens antes de publicar é estruturalmente sensível ao tamanho do payload e à concorrência, precisamente o perfil que torna um limite de 20 Mi insustentável sob carga. 10.2 Arquitetura e estado inicial da aplicação Figura 1: Arquitetura do AKS Store Demo. O store-front e o store-admin consomem o order-service (Node.js), o product-service (Rust), o makeline-service (Go) e o ai-service (Python), com RabbitMQ como broker de mensagens e MongoDB como armazenamento de estado. Figura 2: Página inicial da aplicação de demonstração, publicada por meio de um Service do tipo LoadBalancer. O endereço IP público foi suprimido. Figura 3: Visão geral do cluster AKS antes da investigação: Kubernetes 1.35.6, região East US 2, configuração de rede Azure CNI Overlay e um único node pool. Identificadores de assinatura e o endereço do servidor de API foram suprimidos. A inspeção do namespace revela o estado que servirá de referência para todo o exercício. O pod do order-service encontra-se em CrashLoopBackOff, acumulando reinicializações sucessivas, o sintoma de superfície de um encerramento repetido pelo kernel. Figura 4: Saída de kubectl get all -n pets. O pod do order-service aparece em CrashLoopBackOff com reinicializações acumuladas, enquanto os demais serviços do namespace permanecem íntegros. Endereços IP públicos foram suprimidos. Nota. Observe que apenas um serviço está afetado. Essa assimetria já elimina hipóteses de escopo mais amplo, pressão de memória no nó, falha do runtime de contêiner ou problema de rede, e concentra a investigação na configuração ou no comportamento daquele workload específico. 10.3 Criação do agente e escolha do provedor de modelo O agente é provisionado no portal do SRE Agent, em sre.azure.com. Figura 5: Portal do Azure SRE Agent. A criação inicia pela opção Create Agent. No formulário, define-se o grupo de recursos, o nome do agente e o provedor de modelo. É possível escolher entre Azure OpenAI, com a família GPT-5, e Anthropic, com a família Claude, e alterar essa opção posteriormente sem recriar o recurso. Conforme discutido na seção 7.6, essa escolha deve considerar também os requisitos de residência de dados da organização. Figura 6: Formulário de criação do agente, com a seleção do grupo de recursos, do nome e do provedor de modelo. Figura 7: Revisão da configuração antes da confirmação. Nomes de assinatura foram suprimidos. Figura 8: Provisionamento do agente em andamento. Figura 9: Agente criado. A opção Set up your agent conduz à configuração das fontes de contexto. 10.4 Conexão das fontes de contexto O objetivo do agente é investigar as aplicações em execução no cluster AKS. Para isso, conecta-se primeiro o recurso do cluster. Figura 10: Associação do recurso do cluster AKS ao agente. Figura 11: Seleção do grupo de recursos onde o cluster AKS está provisionado. Figura 12: Confirmação do escopo selecionado. Nomes de assinatura foram suprimidos. Neste laboratório, o agente receberá permissões ampliadas para executar tarefas específicas no cluster. Essa configuração é restrita ao ambiente de demonstração. Em produção, recomenda-se aplicar o princípio do menor privilégio, limitar o escopo das funções, exigir aprovação para ações de maior impacto e validar previamente operações autorizadas, como alterar um pod ou recuperar um nó com estado desconhecido. Figura 13: Definição do nível de permissão concedido ao agente sobre os recursos conectados. Em seguida, integra-se o agente ao Azure Monitor, para que ele acesse os alertas configurados e inicie uma investigação quando o incidente correspondente for emitido. Figura 14: Integração com o Azure Monitor, habilitando o consumo de alertas como gatilho de investigação. Além do Azure Monitor, o agente pode ser integrado ao ServiceNow e ao PagerDuty para apoiar fluxos de investigação e gestão de incidentes, permitindo que a thread da investigação seja correlacionada ao registro formal do incidente. Figura 15: Integrações disponíveis com plataformas de gestão de incidentes. O cluster tem o Container Insights habilitado e envia logs e métricas ao workspace do Log Analytics. Conectar esse workspace é o que permite ao agente executar as consultas KQL apresentadas na seção 5 durante a investigação. Figura 16: Início da conexão com o Log Analytics. Figura 17: Seleção do workspace do Log Analytics associado ao cluster. Figura 18: Preenchimento dos dados do workspace. Identificadores de assinatura foram suprimidos. Figura 19: Conclusão da conexão com o Log Analytics. Figura 20: Painel de configuração das fontes de contexto, consolidando código, logs, recursos do Azure e incidentes. A amplitude do contexto conectado determina diretamente a profundidade possível do diagnóstico. 10.5 Identidade gerenciada e atribuições RBAC Neste ponto o agente já é funcional para investigação. Para que ele também possa executar a remediação no cluster, atribuem-se funções à sua identidade gerenciada. O primeiro passo é identificar essa identidade. Figura 21: Identidade gerenciada associada ao agente. Os identificadores de cliente, de principal e de assinatura foram suprimidos. No laboratório, foram atribuídas as funções Azure Kubernetes Service Cluster Admin Role e Azure Kubernetes Service Contributor Role, com escopo no grupo de recursos do cluster. az role assignment create ` --assignee "<uami-client-id>" ` --role "Azure Kubernetes Service Cluster Admin Role" ` --scope "/subscriptions/<subscription-id>/resourceGroups/Azure-SRE-RG" az role assignment create ` --assignee "<uami-client-id>" ` --role "Azure Kubernetes Service Contributor Role" ` --scope "/subscriptions/<subscription-id>/resourceGroups/Azure-SRE-RG" Figura 22: Resultado da atribuição da função Azure Kubernetes Service Cluster Admin Role. Identificadores de assinatura, de principal e da atribuição foram suprimidos. Figura 23: Resultado da atribuição da função Azure Kubernetes Service Contributor Role. A confirmação é feita no painel Access control (IAM) do cluster, localizando as atribuições concedidas à identidade gerenciada do agente. Figura 24: Painel de controle de acesso do cluster, confirmando as duas atribuições à identidade gerenciada do agente (destacadas). Identificadores de objeto e nomes de entidades de serviço do locatário foram suprimidos. Por que essa configuração não deve ir para produção A função Azure Kubernetes Service Cluster Admin Role autoriza a obtenção da credencial administrativa do cluster. Essa credencial é um certificado de cliente que opera fora da integração com o Microsoft Entra ID e da autorização RBAC do Kubernetes, ou seja, contorna exatamente os controles de identidade que a organização configurou no cluster. Some-se a isso a função Contributor no grupo de recursos, e a identidade do agente passa a acumular controle administrativo do plano de dados e amplo poder no plano de controle. O desenho equivalente sob menor privilégio troca esse par de funções por um conjunto mínimo, com escopo no cluster e não no grupo de recursos, apoiando-se no fluxo de elevação sob demanda descrito na seção 7.4 para as operações de escrita eventuais. Necessidade Função recomendada Escopo Obter kubeconfig respeitando o Entra ID Azure Kubernetes Service Cluster User Role Cluster Leitura no plano de dados do Kubernetes Azure Kubernetes Service RBAC Reader Cluster ou namespace Escrita controlada no plano de dados Azure Kubernetes Service RBAC Writer Namespace do workload Consultar métricas e logs Monitoring Reader Workspace do Log Analytics Operações de infraestrutura do cluster Elevação sob demanda via fluxo On-Behalf-Of Por operação, com registro Nota. As funções RBAC do Kubernetes (Reader, Writer, Admin) exigem que a autorização RBAC do Azure para Kubernetes esteja habilitada no cluster. Escopar por namespace, e não pelo cluster inteiro, reduz o raio de impacto de uma ação incorreta ao conjunto de workloads sob responsabilidade daquele agente. 10.6 Investigação assistida A primeira interação é deliberadamente simples: uma pergunta aberta sobre a saúde do cluster, sem indicar o problema. O objetivo é avaliar se o agente chega ao workload afetado por conta própria. Figura 25: Estado do pod do order-service imediatamente antes da investigação, usado como linha de base para validar diagnóstico e recuperação. Figura 26: O agente inicia a investigação executando comandos de inspeção. Cada chamada de ferramenta exibe o comando exato e a classificação de risco associada: Safe para az aks show e Medium risk para kubectl get deployments. Identificadores de assinatura foram suprimidos. A Figura 26 concentra o que diferencia esse modelo de uma automação convencional. O agente não executa um runbook fixo: ele escolhe o próximo comando a partir do resultado do anterior, e cada escolha fica registrada com o comando literal e sua classificação de risco. O operador acompanha a cadeia de raciocínio como uma sequência auditável de operações, não como uma caixa-preta que devolve uma conclusão. Figura 27: O agente identifica o pod do order-service em CrashLoopBackOff, com 13 reinicializações acumuladas. A partir do estado do pod, o agente correlaciona a razão do término com os limites declarados no manifesto e conclui que o limite de 20 Mi é insuficiente para a carga observada. A recomendação é elevar o limite para 128 Mi e a solicitação para 64 Mi, acompanhando o consumo após a alteração. Figura 28: Diagnóstico do agente: OOMKilled associado ao limite de 20 Mi e à solicitação de 10 Mi, com recomendação de elevação para 128 Mi e 64 Mi respectivamente. Figura 29: Continuação do diagnóstico, com o detalhamento das evidências e das alternativas consideradas. Leitura crítica da recomendação A recomendação ajusta requests e limits em conjunto, e não apenas o limite, o que, conforme a seção 3.3, preserva a classe Burstable com uma reserva de memória compatível e reduz a exposição a despejo por pressão no nó. O agente também sinaliza que valores maiores, como 256 Mi, só devem ser adotados após análise de métricas, testes de carga e investigação de possível vazamento. Essa ressalva é o que separa uma mitigação de uma correção: o número proposto restabelece o serviço, mas ainda não é um dimensionamento validado. 10.7 Mitigação aprovada e verificação A recomendação é apresentada como uma ação concreta a ser aprovada. O comando exibido é exatamente o que será executado: kubectl patch deployment order-service -n pets --type='json' -p='[ {"op":"replace", "path":"/spec/template/spec/containers/0/resources/limits/memory", "value":"128Mi"}, {"op":"replace", "path":"/spec/template/spec/containers/0/resources/requests/memory", "value":"64Mi"} ]' O efeito é alterar os recursos de memória do deployment order-service no namespace pets: o limite passa de 20 Mi para 128 Mi e a solicitação, de 10 Mi para 64 Mi. Como a alteração atinge o template do pod, o controlador executa um rollout, substituindo as réplicas existentes. Figura 30: Proposta de alteração apresentada para revisão. A ação é classificada como Medium risk e apresenta os controles Approve action e Cancel, com a indicação de que as permissões do agente serão utilizadas para concluí-la. Aprovada a ação, o agente a executa e passa espontaneamente à verificação, consultando o estado do novo pod em vez de declarar sucesso pela ausência de erro no comando. Figura 31: Após aplicar o patch, o agente consulta o estado do novo pod e aguarda a conclusão do startup probe antes de concluir. Esse detalhe merece destaque: o agente distingue a execução bem-sucedida de um comando da recuperação efetiva do serviço, e aguarda a passagem pelo startup probe antes de afirmar que o problema foi resolvido. É a mesma disciplina que se espera de um operador experiente. Figura 32: Comparação entre o estado anterior e o posterior apresentada pelo agente, acompanhada da ressalva sobre reconciliação com a fonte da verdade quando o deployment é gerenciado por GitOps, Helm ou pipeline de IaC. Dimensão Antes Depois Estado do pod CrashLoopBackOff, 13 reinicializações Running, Ready, 0 reinicializações Memória (request/limit) 10 Mi / 20 Mi 64 Mi / 128 Mi Classe de QoS Burstable, com reserva mínima Burstable, com reserva compatível Figura 33: Validação manual por kubectl: todos os objetos do namespace pets em execução, com o order-service estável e sem reinicializações. 10.8 Reconciliação com a fonte da verdade Um ponto levantado pelo próprio agente na Figura 32 merece tratamento explícito, porque é onde a maioria das remediações assistidas falha silenciosamente: a alteração foi aplicada diretamente ao objeto no cluster. Se o deployment for gerenciado por GitOps, Helm ou qualquer pipeline de infraestrutura como código, a fonte da verdade continua declarando 20 Mi. A próxima reconciliação do controlador, ou a próxima implantação, reverterá a correção e reintroduzirá o incidente, agora sem a memória do diagnóstico que o originou. O sintoma reaparece dias depois, aparentemente sem causa. Modelo de gestão Efeito do kubectl patch Ação obrigatória de fechamento Manifesto aplicado manualmente Persiste até a próxima aplicação Atualizar o manifesto no repositório Helm Revertido no próximo upgrade Atualizar o values.yaml e versionar o chart GitOps (Flux/Argo CD) Revertido na próxima reconciliação Abrir pull request na fonte da verdade Pipeline de IaC Revertido na próxima execução Atualizar o template e o registro de mudança Regra operacional Toda mitigação aplicada diretamente ao cluster deve gerar um item de acompanhamento na fonte da verdade antes do encerramento do incidente. Um incidente cuja correção existe apenas no cluster não está resolvido: está agendado para reincidir. 10.9 Do acionamento sob demanda ao disparo por alerta Até aqui, o agente foi acionado sob demanda. A etapa seguinte valida o caminho automatizado: um alerta do Azure Monitor configurado para disparar quando um pod apresentar terminação por OOMKilled. Figura 34: Regra de alerta configurada no Azure Monitor para detectar terminações por OOMKilled no cluster. Para provocar o evento de forma controlada, utiliza-se uma aplicação local que gera carga sobre o order-service até que o consumo ultrapasse o limite do cgroup. Figura 35: Painel local de simulação, com o gatilho de geração de carga sobre o order-service e o acompanhamento de pods íntegros, terminações por OOMKilled e alertas disparados. Às 17h45, o pod entra em estado OOMKilled com código de saída 137. Figura 36: Confirmação do estado por kubectl, evidenciando a terminação por OOMKilled. Dois minutos após o evento, a notificação do alerta chega ao destinatário configurado no action group, intervalo que corresponde à soma da ingestão no Log Analytics, do período de avaliação da regra e da entrega da notificação. Figura 37: Notificação recebida por e-mail às 17h47, referente à regra Alert-OOMKilled-Pods. Figura 38: Detalhe da notificação, indicando a condição atendida: contagem de resultados maior que zero, com o valor alcançado igual a 1. O disparo é então confirmado no portal do Azure, com a severidade e o tipo de sinal registrados. Figura 39: Alerta registrado no portal do Azure com estado Fired. Figura 40: Detalhes do alerta: severidade 1, Error, tipo de sinal Log Alerts V2 e horário de disparo consistente com o evento observado no cluster. Com esse alerta emitido e o agente integrado ao Azure Monitor, o gatilho necessário para a automação completa está validado. A Parte 2 tratará da transição do acionamento assistido para o fluxo disparado automaticamente pelo alerta, incluindo planos de resposta, modos de execução por plano e a integração com o processo de gestão de incidentes. 10.10 Do restabelecimento ao dimensionamento correto O laboratório encerra com o serviço estável, mas os valores aplicados são uma mitigação informada, não um dimensionamento validado. Fechar o ciclo exige um método, e esse método é independente do agente. Estabelecer a linha de base: medir o working set em percentil 95 e 99 sobre uma janela que cubra o ciclo completo de carga do serviço, incluindo picos previsíveis. Definir o request pelo consumo típico: o percentil 95 do working set em regime normal, valor que o agendador usará para reservar capacidade. Definir o limit com folga sobre o pico: o percentil 99 acrescido de margem para transientes, tipicamente entre 25% e 50%, evitando folga excessiva que desperdiça capacidade do nó. Alinhar o runtime: ajustar o heap máximo conforme a seção 3.5, reservando espaço para memória fora do heap. Validar sob carga: reproduzir o cenário que originou o incidente e confirmar que o working set permanece abaixo do limite com margem estável. Descartar vazamento: comparar a inclinação do consumo entre reinícios; crescimento sustentado sem correlação com a carga indica retenção progressiva, que nenhum aumento de limite resolve. Automatizar a revisão: usar o Vertical Pod Autoscaler em modo recomendação para acompanhar a adequação dos valores ao longo do tempo, sem aplicação automática. Nota. Elevar o limite de memória é uma resposta legítima quando a evidência aponta subdimensionamento, e ilegítima quando serve para adiar a investigação de um vazamento. A diferença entre as duas situações está na inclinação do consumo entre reinícios, um dado que só existe se a telemetria for retida além do ciclo de vida do contêiner. 11. Governança, aprovação e rastreabilidade Esta seção separa deliberadamente dois planos: capacidades do produto, que podem ser verificadas na documentação, e recomendações de arquitetura, que cada organização deve validar e adaptar às próprias políticas. Nota. Nomenclaturas, opções e comportamentos evoluem. Antes de aplicar este padrão em produção, valide a documentação vigente, os controles disponíveis no ambiente e os requisitos internos de segurança, auditoria e mudança. 11.1 O que foi observado no laboratório O agente coletou métricas, eventos e o estado dos pods para investigar o incidente, com cada comando registrado na thread. Identificou que os valores de memória estavam subdimensionados para a carga observada. Propôs um comando kubectl patch explícito, exibindo a alteração de 20 Mi para 128 Mi no limite e de 10 Mi para 64 Mi na solicitação. Apresentou a ação para revisão humana, classificada como Medium risk, e aguardou aprovação antes de executar. Após a aprovação, executou a alteração e verificou a recuperação do pod antes de concluir. Sinalizou espontaneamente o risco de reversão da correção em cenários gerenciados por GitOps ou Helm. Esse comportamento reflete o cenário demonstrado e não estabelece regra universal para todas as ferramentas, comandos ou ambientes. 11.2 Referência de governança para a organização A tabela a seguir é uma recomendação de desenho, não uma matriz fixa nem garantia de comportamento do produto. Categoria Exemplos Política sugerida Leitura get, list, show, describe, consultas KQL Permitir quando escopo e RBAC forem compatíveis com a investigação. Escrita patch, update, scale, restart Exigir revisão humana em ambientes críticos por meio de Review Mode no plano de resposta ou de hooks. Alto impacto delete, redução de capacidade, mudanças destrutivas Restringir por RBAC e por política de acesso a ferramentas; submeter a processo formal de mudança ou negar conforme o risco. A classificação de risco deve ser definida pela organização conforme o ambiente, o tipo de recurso, a criticidade do serviço e os requisitos regulatórios. A documentação do produto não deve ser interpretada como regra universal de que toda leitura é sempre permitida, toda escrita sempre exige aprovação ou todo delete é sempre negado. 11.3 Camadas de evidência para auditoria Nenhuma fonte isolada reconstrói o incidente por completo. A rastreabilidade útil vem da correlação entre camadas com escopos distintos. Camada O que registra Limitação Thread do agente Comandos executados, evidências, proposta e aprovação Escopo da conversa; confirmar retenção e exportação no ambiente Telemetria de auditoria do agente Atividade do agente para acompanhamento e conformidade Confirmar granularidade e campos disponíveis no ambiente Log de auditoria do Kubernetes Chamadas ao servidor de API do cluster Requer habilitação e destino de coleta configurados Azure Activity Log Operações do plano de controle do Azure Não cobre alterações internas do Kubernetes Sistema de ITSM Registro formal de incidente e mudança Depende da integração e da disciplina de preenchimento Recomenda-se correlacionar, conforme disponibilidade: horário da proposta e da execução; a ação ou comando apresentado ao operador; o estado anterior e posterior do recurso; o resultado da ferramenta e mensagens de erro relevantes; os identificadores do agente, recurso, alerta, incidente e mudança; e as informações de aprovação expostas pelos mecanismos disponíveis. 11.4 Fluxo recomendado para este cenário Etapa Aplicação no laboratório Controle recomendado 1. Diagnóstico e proposta O agente consulta métricas, eventos e estado do cluster e apresenta a ação recomendada. RBAC de menor privilégio, escopo por namespace e evidências observáveis. 2. Revisão humana Em Review Mode, o operador analisa o comando, o impacto e o escopo antes da execução. Critérios de aprovação e rollback definidos; aprovação restrita a administradores do agente. 3. Execução controlada Após a aprovação, o agente executa a alteração dentro das permissões concedidas. Identidade gerenciada, escopo mínimo, hooks de PostToolUse para auditoria. 4. Verificação O agente valida a recuperação antes de concluir. Critério de sucesso objetivo, baseado em estado observado e não em ausência de erro. 5. Reconciliação Não aplicável ao laboratório; a alteração permaneceu no cluster. Atualizar a fonte da verdade e vincular ao registro de mudança. 6. Registro O resultado é apresentado na thread do agente. Correlação entre telemetria, logs do cluster, registros do Azure e ITSM. Enquadramento Os modos de execução, os controles de acesso, os hooks e a telemetria são capacidades do produto. A matriz de risco, as evidências exigidas, as convenções de repositório e as integrações de auditoria são decisões de governança da organização. Manter essa separação explícita evita transformar recomendações de arquitetura em garantias de produto. 12. Considerações de segurança para operações agênticas Introduzir um agente com capacidade de execução no caminho de resposta a incidentes altera o modelo de ameaças da plataforma. As considerações a seguir derivam diretamente da configuração demonstrada. Consideração Risco Mitigação Privilégio excessivo Cluster Admin Role concede credencial que contorna o Entra ID e o RBAC do Kubernetes Substituir por Cluster User + RBAC Reader/Writer com escopo por namespace; elevar sob demanda Escopo amplo demais Funções no grupo de recursos alcançam recursos não relacionados ao incidente Escopar no recurso, não no grupo de recursos Segregação de funções Quem opera aprova a própria ação Restringir aprovação a administradores do agente distintos de quem aciona a investigação Conteúdo não confiável no contexto Logs e eventos podem carregar texto capaz de influenciar o raciocínio do agente Hooks de PostToolUse e políticas de acesso a ferramentas; revisão humana para ações de escrita Raio de impacto Uma ação incorreta atinge o cluster inteiro Escopo por namespace, janelas de mudança e critérios de rollback definidos previamente Residência de dados O provedor de modelo determina onde o contexto é processado Selecionar o provedor conforme os requisitos regulatórios e as regiões suportadas Exposição em capturas e threads Identificadores e segredos aparecem em evidências compartilhadas Revisar artefatos antes de circular; suprimir identificadores, como feito neste documento O item sobre conteúdo não confiável merece atenção particular. Durante a investigação, o agente lê logs e eventos produzidos pela aplicação, dados que, em última instância, podem ser influenciados por entradas de usuários. Tratar esse conteúdo como dado, e não como instrução, é responsabilidade compartilhada entre o produto e o desenho de governança: manter operações de escrita sob revisão humana em ambientes críticos é a defesa mais direta contra essa classe de risco. Princípio de composição Nenhum controle isolado é suficiente. A defesa em profundidade nesse modelo compõe quatro camadas independentes: RBAC delimita o que a identidade alcança; os modos de execução determinam se há aprovação humana; a classificação de risco por chamada de ferramenta informa a decisão do revisor; e os hooks aplicam política e auditoria antes e depois de cada ação. Remover qualquer uma delas transfere risco às demais. 13. Métricas para avaliar a adoção A adoção de resposta assistida deve ser avaliada por evidência, não por percepção. As métricas a seguir permitem comparar o antes e o depois de forma objetiva. Métrica O que mede Sinal de maturidade MTTD Tempo entre o evento e a detecção Estável; limitado pela latência de ingestão e avaliação MTTA Tempo entre o alerta e o início da investigação Redução acentuada com investigação automática MTTR Tempo entre o alerta e a recuperação verificada Redução sustentada, sem aumento de reincidência Taxa de aprovação sem alteração Recomendações aprovadas sem ajuste pelo operador Crescente; habilita migração seletiva para modo autônomo Taxa de reincidência em 30 dias Incidentes da mesma classe que retornam Decrescente; indica correção estrutural e não apenas mitigação Aderência à reconciliação Mitigações refletidas na fonte da verdade Próxima de 100%; principal defesa contra reincidência Ações autônomas por classe de risco Distribuição entre leitura, escrita e alto impacto Crescimento apenas nas classes com histórico consistente A recomendação de adoção é conservadora e apoiada na própria documentação do produto: iniciar em Review Mode, observar as recomendações por algumas semanas e migrar para modo autônomo apenas os gatilhos cujo padrão de aprovação já se mostrou consistente. A taxa de aprovação sem alteração é o indicador que sustenta essa decisão com dados. 14. Limitações e armadilhas observadas A mitigação foi aplicada diretamente ao cluster. Em ambientes gerenciados por GitOps, Helm ou IaC, a correção será revertida se a fonte da verdade não for atualizada. Os valores de 128 Mi e 64 Mi restabeleceram o serviço, mas constituem mitigação informada, não dimensionamento validado por testes de carga. As permissões concedidas no laboratório são amplas por conveniência de demonstração e contornam a integração com o Entra ID no plano de dados do cluster. Alertas baseados em log carregam latência de ingestão e de avaliação, dois minutos no laboratório, o que os torna inadequados para SLOs de detecção mais agressivos. Um restart bem-sucedido mascara a distinção entre limite subdimensionado e vazamento de memória; sem telemetria retida além do ciclo do contêiner, a diferença se perde. O modelo pode propor valores plausíveis, mas a validação por métricas e carga permanece responsabilidade da engenharia. O cenário cobre uma única classe de falha em um único workload; a generalização para outras classes exige validação própria. 15. Conclusão da Parte 1 O Azure Monitor e o Azure SRE Agent transformaram um evento OOMKilled em um fluxo governado de detecção, investigação, recomendação, aprovação e recuperação verificada. O resultado demonstra valor não apenas por restabelecer o pod, mas por correlacionar evidências, manter a decisão explicável e executar a remediação dentro dos limites de acesso definidos. Três observações se destacam do exercício. A primeira é que a transparência por chamada de ferramenta, com o comando literal e sua classificação de risco, transforma a revisão humana em auditoria rápida em vez de repetição do trabalho. A segunda é que o agente verificou a recuperação antes de concluir, distinguindo execução bem-sucedida de serviço restabelecido. A terceira é que ele sinalizou o risco de reversão por GitOps, armadilha que mais frequentemente converte uma correção em incidente recorrente. A conclusão arquitetural permanece: a observabilidade continua sendo a base. O agente amplifica o valor de uma telemetria bem construída, e amplifica igualmente as lacunas de uma telemetria pobre. Investir em sinais corretos, como working set em vez de uso bruto, agregação por máximo em vez de média e retenção além do ciclo de vida do contêiner, é pré-requisito, não consequência. Na Parte 2, o fluxo evoluirá do acionamento assistido para o disparo automatizado por alertas, com planos de resposta, definição de modos de execução por plano, hooks de auditoria e integração com o processo de gestão de incidentes. 16. Referências Azure SRE Agent Documentação do Azure SRE Agent Run Modes in Azure SRE Agent Agent Hooks in Azure SRE Agent Tutorial: Configure Agent Hooks Model Provider Selection in Azure SRE Agent Execute Mitigations in Azure SRE Agent Set up ServiceNow incident indexing Azure SRE Agent: preços Azure Monitor e observabilidade de contêineres Azure Monitor overview Overview of Azure Monitor alerts Container insights overview Consultas de exemplo para KubePodInventory Azure Monitor managed service for Prometheus Kubernetes e AKS Configure Quality of Service for Pods Node-pressure Eviction Resource Management for Pods and Containers Access and identity options for AKS AKS Store Demo: code sample226Views4likes1CommentLog Insights in Minutes: A Simpler pgBadger Workflow
Sometimes the fastest way to understand a PostgreSQL workload is not another dashboard. It is a good log report. pgBadger is a PostgreSQL log analysis tool that turns raw PostgreSQL logs into an interactive HTML report. It helps summarize query activity, connection patterns, errors, temporary files, lock waits, autovacuum activity, and more. Earlier guidance for generating pgBadger reports from Azure Database for PostgreSQL Flexible Server focused on exporting logs through Diagnostic Settings, storing them in a storage account, and then using tools such as BlobFuse and jq to extract PostgreSQL log lines from JSON files. That workflow is still useful when customers centralize logs across multiple servers. However, if you are already using the Server logs feature in Azure Database for PostgreSQL Flexible Server, there is a much simpler path. In this post: You’ll learn how to generate a pgBadger HTML report from Azure Database for PostgreSQL Flexible Server by downloading native PostgreSQL .log files directly from the Azure portal. No storage account, BlobFuse mount, or JSON extraction required. Fast path Configure log_line_prefix . Enable Server logs for download. Download the PostgreSQL .log files. Run pgBadger with the matching prefix. Open pgbadger-report.html . Why use this workflow? With Server logs, you can download native PostgreSQL .log files directly from the Azure portal and run pgBadger locally. Older path Simpler path in this blog Diagnostic Settings → Storage account → BlobFuse → JSON extraction → pgBadger Server logs → Download .log files → pgBadger Area Older Diagnostic Settings workflow Server logs workflow Export path Diagnostic Settings to storage account Download .log files directly from the portal Format JSON payloads need extraction Native PostgreSQL .log files Extra tooling BlobFuse and jq JSON parsing None Best suited for Centralized or multi-server logging Quick per-server analysis Outcome Flexible, but more setup Faster path to pgBadger Recommended: Use the Server logs workflow when you want a fast, low-friction way to generate a pgBadger report from one Azure Database for PostgreSQL Flexible Server. When should you use this workflow? Use this workflow when... Use Diagnostic Settings when... You need a quick report for one Flexible Server. You centralize logs from many servers. You want to run pgBadger locally. You need long-term retention or workspace-level querying. You want to avoid JSON extraction. You already have automated log export pipelines. Before you start A machine where you can install or run pgBadger. A working Perl runtime. Git Bash on Windows, so the multi-line shell commands work as shown. Portal access to your Azure Database for PostgreSQL Flexible Server. Permission to update server parameters and enable Server logs. Important: pgBadger can only analyze what PostgreSQL logs capture. To populate query timing and slow-query sections in the report, enable log_min_duration_statement before collecting logs. Logs collected before that change will not include duration data. Workflow overview Task Type Rough effort Install or prepare pgBadger One-time setup per analysis machine 5–10 minutes Configure log_line_prefix One-time setup per server 2–3 minutes Enable Server logs One-time setup per server 2–3 minutes Download logs and run pgBadger Repeatable 2–5 minutes Install or prepare pgBadger on the machine where you will analyze logs. Configure log_line_prefix so pgBadger can parse each log line. Enable Server logs, so PostgreSQL logs are available for download. Download the logs and run pgBadger locally. 💡Pro tip: Start with a narrow log window first. Use one or two hourly log files, confirm the report looks right, and then expand the analysis window if needed. Step 1: Install pgBadger Before generating a report, you need pgBadger available on the machine where you plan to analyze the downloaded PostgreSQL log files. Run this on a Linux VM, WSL, or another Linux-based environment where you can install packages. Note: Azure Cloud Shell may work for quick testing, but package installation and build-tool availability can vary by session. For repeatable analysis, use a Linux VM, WSL, or another environment you control. Copy and run sudo apt-get update && sudo apt-get install -y git perl make gcc && \ git clone https://github.com/darold/pgbadger.git && \ cd pgbadger && \ perl Makefile.PL && \ make && \ sudo make install && \ pgbadger -V What good looks like: The install command completes successfully and pgbadger -V returns the installed pgBadger version. Step 2: Configure log_line_prefix This is a one-time server configuration step. The log_line_prefix parameter controls the beginning of each PostgreSQL log line. pgBadger uses this prefix to extract useful fields such as timestamp, user, database, and process ID. In the Azure portal, open your Flexible Server and go to Server parameters. Search for: Parameter log_line_prefix Set this value %m user=%u db=%d pid=%p: Then select Save. In Server parameters, confirm that the custom value is saved for log_line_prefix . Figure 1: Set log_line_prefix so pgBadger can correctly parse timestamp, user, database, and process ID from each log line. Prefix tokens Token Meaning %m Timestamp with milliseconds %u Username %d Database name %p Process ID After this change, log lines should look like this: Example log line 2026-06-22 19:00:00.070 UTC user=pgadmin db=highcpu pid=3805603: LOG: statement: SELECT 1 FROM pg_extension WHERE extname='pg_stat_statements' The matching pgBadger prefix for this log format is: Matching pgBadger prefix %m user=%u db=%d pid=%p: You will use this same value later in the pgBadger command. What good looks like: The server parameter is saved, and new PostgreSQL log lines begin with timestamp, user, database, and process ID fields that match the pgBadger prefix. Step 3: Enable Server logs for download This is also a one-time setup step. In the Azure portal, open your Flexible Server and go to Server logs. Enable: Portal setting Capture logs for download Set the retention period based on how long you want logs to remain available for download. For example, a 7-day retention period keeps logs available for download for 7 days. In Server logs, enable Capture logs for download and choose the retention window. Figure 2: Enable Capture logs for download and set a retention period long enough to cover the analysis window you want to inspect. What good looks like: After Server logs are enabled, hourly PostgreSQL log files appear in the Server logs blade and can be downloaded from the Azure portal. Once enabled, hourly log files appear in the Server logs blade. The files are named by date and hour, for example: Example log files postgresql_2026_06_22_19_00_00.log postgresql_2026_06_22_20_00_00.log Step 4: Download and organize the logs locally From the Server logs page, select the .log files for the time window you want to analyze and download them. For example, to analyze activity between 19:00 and 21:00 UTC, download: Example files to download postgresql_2026_06_22_19_00_00.log postgresql_2026_06_22_20_00_00.log On your local machine, create a folder for that analysis window. A simple convention is to use the Mon-DD format. Folder name Jun-22 Place the downloaded .log files inside that folder. Your local folder structure should look like this: Folder structure pgbadger-13.1/ pgbadger Jun-22/ postgresql_2026_06_22_19_00_00.log postgresql_2026_06_22_20_00_00.log Step 5: Generate the pgBadger report Open Git Bash from the folder where pgBadger is located. For example, if pgBadger is inside the pgbadger-13.1 folder, open Git Bash from that folder. # Action Command 1 Set the folder FOLDER=Jun-22 2 Confirm files ls -lh ./$FOLDER 3 Run pgBadger Use the full command below. Copy and run FOLDER=Jun-22 ls -lh ./$FOLDER perl -X ./pgbadger -f stderr \ --prefix '%m user=%u db=%d pid=%p:' \ ./$FOLDER/*.log \ -o ./$FOLDER/pgbadger-report.html Command breakdown Part of command Purpose perl -X ./pgbadger Runs pgBadger and suppresses non-critical Perl warnings. -f stderr Parses PostgreSQL stderr log files. --prefix '%m user=%u db=%d pid=%p:' Matches the log_line_prefix set on the server. ./$FOLDER/*.log Analyzes every .log file in the selected folder. -o ./$FOLDER/pgbadger-report.html Writes the HTML report into the same folder. When the command completes successfully, you should see output like this: Expected output Parsed 12134249 bytes of 12134249 (100.00%), queries: 26684, events: 83 LOG: Ok, generating html report... What good looks like: pgBadger finishes parsing the logs and creates pgbadger-report.html in the selected folder. Step 6: Open the report Open the generated report: Copy and run start ./$FOLDER/pgbadger-report.html The report opens in your default browser. The final report is created here: Generated report path Jun-22/pgbadger-report.html What the report can show The pgBadger report gives you a quick view into the workload shape for the selected log window. For example, in a sample run across two hourly log files, pgBadger summarized: Total number of queries. Number of unique normalized queries. Query traffic over time. Events such as errors and fatal messages. Session and connection patterns. Once the report opens, start with Global Stats to confirm the time range, total queries, normalized queries, and query peak. Figure 3: Start with Global Stats to validate the selected time range, total query count, normalized query count, and query peak. Query volume and normalized queries Many raw queries can often reduce to a smaller number of normalized query patterns. This helps identify whether the workload is spread across many different query shapes or dominated by a smaller set of repeated statements. Example: In this sample run, 26,684 queries reduced to 59 normalized query shapes. That suggests the workload is mostly a small set of repeated statements, which can help focus tuning effort. Traffic patterns The SQL Traffic section helps identify spikes, quiet periods, and workload changes over time. Figure 4: Use SQL Traffic to identify query spikes, quiet periods, and workload changes during the selected log window. Figure 5: Review the query breakdown to compare read vs. write volume and query-type distribution for the selected Server logs window. For example, if the report shows a steady baseline followed by a sharp spike, that spike can be correlated with application activity, batch jobs, synthetic tests, or operational events during the same time window. Query duration If query duration shows 0 ms or the slow query sections are empty, it usually means duration logging was not enabled when the logs were collected. In that case, pgBadger can still show query counts and events, but it cannot calculate the slowest queries, total execution time, average duration, or maximum duration. To unlock those timing sections, enable log_min_duration_statement , collect fresh logs, and rerun pgBadger. What pgBadger cannot infer from missing logs pgBadger reports are only as complete as the log data you provide. If PostgreSQL did not log duration, lock waits, temporary files, or autovacuum activity during the selected time window, pgBadger cannot reconstruct those details later. To analyze... Enable before collecting logs Slow queries log_min_duration_statement Lock waits log_lock_waits Temporary files log_temp_files Autovacuum activity log_autovacuum_min_duration Repeatable copy/paste block Reusable command block Change only FOLDER for each new analysis window. Copy and run FOLDER=Jun-22 ls -lh ./$FOLDER perl -X ./pgbadger -f stderr \ --prefix '%m user=%u db=%d pid=%p:' \ ./$FOLDER/*.log \ -o ./$FOLDER/pgbadger-report.html start ./$FOLDER/pgbadger-report.html For another date, change only this line: Update this value FOLDER=Jun-22 Examples: Example folder values FOLDER=Jun-23 FOLDER=Jul-01 FOLDER=Aug-15 Optional: Improve report quality pgBadger can only analyze the information captured in PostgreSQL logs. The default logs may be enough for query frequency, connection activity, and errors. For deeper performance troubleshooting, consider enabling additional logging parameters based on your scenario. Scenario Parameter Suggested value Notes Slow query analysis log_min_duration_statement 1000 Logs statements slower than 1 second. Short controlled test log_min_duration_statement 0 Logs every statement. Use carefully. Lock troubleshooting log_lock_waits on Helps identify lock waits. Temporary file analysis log_temp_files 0 Logs all temporary files. Autovacuum visibility log_autovacuum_min_duration 0 Useful during focused analysis. Useful parameters include: Recommended logging parameters log_lock_waits = on log_temp_files = 0 log_autovacuum_min_duration = 0 To capture query durations, configure: Duration logging log_min_duration_statement = 1000 This logs statements that run longer than 1000 milliseconds. For short test runs, you can temporarily use: Short test run only log_min_duration_statement = 0 Caution: Use log_min_duration_statement = 0 carefully on busy production servers. It logs every statement and can generate a large volume of logs. Duration matters: If duration logging is not enabled, pgBadger can still show query counts and events, but slowest-query, total duration, average duration, and maximum duration sections will be limited or empty. Common mistakes and quick fixes Symptom Likely cause Fix Report is empty Prefix mismatch Match --prefix with log_line_prefix . No duration data Duration logging was not enabled Set log_min_duration_statement before collecting logs. No files visible Server logs disabled or retention expired Enable capture and check retention. pgBadger command fails pgBadger is not in the current folder or path Run pgbadger -V to confirm installation. Common troubleshooting FAQs 1. Report is created but empty This usually means the pgBadger prefix did not match the actual log format. Check the first few lines: Copy and run head -5 ./$FOLDER/*.log Make sure the pgBadger --prefix matches the server’s log_line_prefix . 2. Report shows queries but no duration PostgreSQL logged statements but did not log durations. Enable one of the following, collect fresh logs, and rerun pgBadger: Parameter options log_min_duration_statement = 1000 # or temporarily for testing log_min_duration_statement = 0 3. No .log files are visible Confirm that Server logs are enabled: Portal setting Capture logs for download Also check the retention period. If the retention period has expired, older logs may no longer be available for download. 4. pgBadger command fails Confirm that pgBadger is available in the current folder or installed in your path. Copy and run pgbadger -V If you are running pgBadger from the local folder, use: Copy and run perl -X ./pgbadger Summary For customers already using Azure Database for PostgreSQL Flexible Server logs, the pgBadger workflow is straightforward: Install pgBadger. Configure log_line_prefix . Enable Server logs for download. Download the .log files. Place them in a local date-based folder. Run pgBadger with the matching prefix. Open pgbadger-report.html . Bottom line: Server logs give you the shortest path from Azure Database for PostgreSQL Flexible Server logs to a pgBadger report. Download the native .log files, run pgBadger with the matching prefix, and open the generated HTML report. References pgBadger - source and documentation GitHub pgBadger - project site Azure - Download server logs from the portal Flexible Server Azure - Logging concepts Flexible Server Azure - Configure server parameters via the portal PostgreSQL - log_line_prefix and logging parameters524Views2likes0CommentsFrom Policy to Practice: Built-In CIS Benchmarks on Azure - Flexible, Hybrid-Ready
Security is more important than ever. The industry-standard for secure machine configuration is the Center for Internet Security (CIS) Benchmarks. These benchmarks provide consensus-based prescriptive guidance to help organizations harden diverse systems, reduce risk, and streamline compliance with major regulatory frameworks and industry standards like NIST, HIPAA, and PCI DSS. In our previous post, we outlined our plans to improve the Linux server compliance and hardening experience on Azure and shared a vision for integrating CIS Benchmarks. Today, that vision has turned into reality. We're now announcing the next phase of this work: Center for Internet Security (CIS) Benchmarks are now available on Azure for all Azure endorsed distros, at no additional cost to Azure and Azure Arc customers. With today's announcement, you get access to the CIS Benchmarks on Azure with full parity to what’s published by the Center for Internet Security (CIS). You can adjust parameters or define exceptions, tailoring security to your needs and applying consistent controls across cloud, hybrid, and on-premises environments - without having to implement every control manually. Thanks to this flexible architecture, you can truly manage compliance as code. How we achieve parity To ensure accuracy and trust, we rely on and ingest CIS machine-readable Benchmark content (OVAL/XCCDF files) as the source of truth. This guarantees that the controls and rules you apply in Azure match the official CIS specifications, reducing drift and ensuring compliance confidence. What’s new under the hood At the core of this update is kompli - a lightweight, open-source module developed by the Azure Core Linux team. It evaluates Linux systems directly against industry-standard benchmarks like CIS, supporting both audit and, in the future, auto-remediation. This enables accurate, scalable compliance checks across large Linux fleets. Here you can read more about kompli. Dynamic rule evaluation The new compliance engine supports simple fact-checking operations, evaluation of logic operations on them (e.g., anyOf, allOf) and Lua based scripting, which allows to express complex checks required by the CIS Critical Security Controls - all evaluated natively without external scripts. Scalable architecture for large fleets When the assignment is created, the Azure control plane instructs the machine to pull the latest Policy package via the Machine Configuration agent. kompli is integrated as a light-weight library to the package and called by Machine Configuration agent for evaluation – which happens every 15-30minutes. This ensures near real-time compliance state without overwhelming resources and enables consistent evaluation across thousands of VMs and Azure Arc-enabled servers. Future-ready for remediation and enforcement While the Public Preview starts with audit-only mode, the roadmap includes per-rule remediation and enforcement using technologies like eBPF for kernel-level controls. This will allow proactive prevention of configuration drift and runtime hardening at scale. Please reach out if you interested in auto-remediation or enforcement. Extensibility beyond CIS Benchmarks The architecture was designed to support other security and compliance standards as well and isn’t limited to CIS Benchmarks. The compliance engine is modular, and we plan to extend the platform with STIG and other relevant industry benchmarks. This positions Azure as a platform for a place where you can manage your compliance from a single control-plane without duplicating efforts elsewhere. Collaboration with the CIS This milestone reflects a close collaboration between Microsoft and the CIS to bring industry-standard security guidance into Azure as a built-in capability. Our shared goal is to make cloud-native compliance practical and consistent, while giving customers the flexibility to meet their unique requirements. We are committed to continuously supporting new Benchmark releases, expanding coverage with new distributions and easing adoption through built-in workflows, such as moving from your current Benchmark version to a new version while preserving your custom configurations. Certification and trust We can proudly announce that kompli has met all the requirements and is officially certified by the CIS for Benchmark assessment, so you can trust compliance results as authoritative. Minor benchmark updates will be applied automatically, while major version will be released separately. We will include workflows to help migrate customizations seamlessly across versions. Key Highlights Built-in CIS Benchmarks for Azure Endorsed Linux distributions Full parity with official CIS Benchmarks content and certified by the CIS for Benchmark Assessment Flexible configuration: adjust parameters, define exceptions, tune severity Hybrid support: enforce the same baseline across Azure, on-prem, and multi-cloud with Azure Arc Reporting format in CIS tooling style Supported use cases Certified CIS Benchmarks for all Azure Endorsed Distros - Audit only (L1/L2 server profiles) Hybrid / On-premises and other cloud machines with Azure Arc for the supported distros Compliance as Code (example via Github -> Azure OIDC auth and API integration) Compatible with GuestConfig workbook What’s next? Our next mission is to bring the previously announced auto-remediation capability into this experience, expand the distribution coverage and elevate our workflows even further. We’re focused on empowering you to resolve issues while honoring the unique operational complexity of your environments. Stay tuned! Get Started Documentation link for this capability Enable CIS Benchmarks in Machine Configuration and select the “Official Center for Internet Security (CIS) Benchmarks for Linux Workloads” then select the distributions for your assignment, and customize as needed. In case if you want any additional distribution supported or have any feedback for kompli – please open an Azure support case or a Github issue here Relevant Ignite 2025 session: Hybrid workload compliance from policy to practice on Azure Connect with us at Ignite Meet the Linux team and stop by the Linux on Azure booth to see these innovations in action: Session Type Session Code Session Name Date/Time (PST) Theatre THR 712 Hybrid workload compliance from policy to practice on Azure Tue, Nov 18/ 3:15 PM – 3:45 PM Breakout BRK 143 Optimizing performance, deployments, and security for Linux on Azure Thu, Nov 20/ 1:00 PM – 1:45 PM Breakout BRK 144 Build, modernize, and secure AKS workloads with Azure Linux Wed, Nov 19/ 1:30 PM – 2:15 PM Breakout BRK 104 From VMs and containers to AI apps with Azure Red Hat OpenShift Thu, Nov 20/ 8:30 AM – 9:15 AM Theatre THR 701 From Container to Node: Building Minimal-CVE Solutions with Azure Linux Wed, Nov 19/ 3:30 PM – 4:00 PM Lab Lab 505 Fast track your Linux and PostgreSQL migration with Azure Migrate Tue, Nov 18/ 4:30 PM – 5:45 PM PST Wed, Nov 19/ 3:45 PM – 5:00 PM PST Thu, Nov 20/ 9:00 AM – 10:15 AM PST1.6KViews0likes0CommentsNow Generally Available: Built-in CIS Benchmark Auditing for Linux on Azure
A few months ago, in From Policy to Practice: Built-in CIS Benchmarks on Azure – Flexible, Hybrid-Ready, we introduced a new way to bring Center for Internet Security (CIS) Benchmarks to your Linux estate using Azure Policy with Machine Configuration. It builds on the broader customizable security baseline policies in Machine Configuration capability. Today we're excited to share the next milestone: the audit capability for CIS Benchmarks on Linux is now Generally Available (GA). This release is officially powered by kompli - our native Linux compliance and hardening engine for CIS, STIG, and custom baselines. kompli is the evolution of the engine that drove the preview, now established as the dedicated home for this capability going forward. What "GA" means for you The audit experience is now ready for production use. You can continuously assess your Linux workloads against official, CIS-certified benchmarks - at scale, across Azure and hybrid environments through Azure Arc - and get clear, CIS-style compliance reporting directly in Azure Policy and Azure Resource Graph. If you've read the previous post, the how hasn't changed, so we'll keep this one short: Automated compliance assessment - continuously monitor Linux systems against official CIS benchmarks. Tailored benchmarks - customize evaluations with exceptions and custom parameters, no code changes required. Compliance reporting - detailed, CIS-style reports across your fleet. Hybrid-ready - the same baselines apply to Azure VMs and Arc-enabled servers on-premises or in other clouds. All supported benchmarks are CIS Benchmark Assessment Certified and stay in parity with the content published on the CIS website. Supported distributions and benchmark versions With this release, audit is GA across the following distributions, covering Level 1 + Level 2 Server profiles: Distribution CIS Benchmark Version(s) Profiles Audit Ubuntu 20.04 / 22.04 / 24.04 LTS + Pro v3.0.0 / v2.0.0 + v3.0.0 / v1.0.0 L1 + L2 Server ✓ Red Hat Enterprise Linux 8 / 9 / 10 v3.0.0 + v4.0.0 / v2.0.0 / v1.0.1 L1 + L2 Server ✓ AlmaLinux 8 / 9 v3.0.0 + v4.0.0 / v2.0.0 L1 + L2 Server ✓ Rocky Linux 8 / 9 v2.0.0 + v3.0.0 / v2.0.0 L1 + L2 Server ✓ Oracle Linux 8 / 9 v3.0.0 + v4.0.0 / v2.0.0 L1 + L2 Server ✓ Debian 11 / 12 v2.0.0 / v1.1.0 L1 + L2 Server ✓ SUSE Linux Enterprise 12 / 15 v3.2.1 / v2.0.1 L1 + L2 Server ✓ AKS Optimized Azure Linux 3 v1.0.0 L1 + L2 Server ✓ This GA covers the audit (assessment) capability. Looking ahead, STIG benchmarks are coming next, followed by a granular per-rule auto-remediation capability with dynamic scope assignments. You can run these benchmarks against your own hardened images, against CIS hardened images, and against custom images built on top of vanilla distros — as long as /etc/os-release retains its original content. We're also working with vendors to minimize deviations. Getting started Open Azure Policy in the Azure portal. Under Authoring, select the new Machine Configuration blade. Choose Official Center for Internet Security (CIS) Benchmarks for Linux Workloads, then Modify Settings to pick the distributions you want to assess. Full documentation, including per-distribution rule details, supported parameters, and any known deviations from the official CIS toolset, is available here: Overview: CIS Security Benchmarks for Linux Workloads Per-distribution references: AlmaLinux, Azure Linux, Debian, Oracle Linux, Red Hat Enterprise Linux, Rocky Linux, SUSE Linux Enterprise, and Ubuntu - all linked from the overview page. We're building this with you As part of this GA release, we've also expanded the set of exposed rule parameters compared to the preview - giving you more out-of-the-box customization across rules and distributions. That said, our customer-driven approach still stands: we keep the experience clean by enabling parameters based on real demand, so if there's a rule, benchmark version, or distribution you'd like parameters enabled for - or any feedback on rules, evaluations, or distro coverage - let us know: Open a GitHub issue in the kompli repository Open an Azure support case Try it out, tell us what you think, and help shape what we build next.404Views1like0CommentsAnnouncing the Open-Source Release of ML Video Codec (MLVC)
Video codecs compress video for transmission or storage, reducing bandwidth and storage requirements. MLVC is a modern machine-learning-based codec that uses substantially less bandwidth than conventional codecs, improving streaming and video-call quality—especially on constrained or unreliable networks—while lowering delivery and storage costs. MLVC is the product iteration of DCVC (Deep Contextual Video Compression) family of NVC (Neural Video Codec), open sourced by Microsoft Research since 2021, with improved compression efficiency, real-time performance on commodity Neural Processing Units (NPUs), and cross-platform support. We recently published this work in the paper MLVC: Multi-platform Learned Video Codec for Real-World Deployment. We are releasing the source code because we believe the next generation of video coding will be built openly, and we want the broader community — researchers, video codec engineers, platform vendors, product teams, as well as general developer community — to build it with us. Why MLVC Traditional video codecs (e.g., H.264/AVC, H.265/HEVC) have served the industry for a long time, but each generation requires enormous engineering effort for incremental gains and needs dedicated hardware which takes years to become commonly available. MLVC replaces conventional primitives — motion estimation, transforms, entropy modeling — with end-to-end learned neural compression, trained directly against rate-distortion objectives, and run on general-purpose NPU devices. The table below compares MLVC to popular video codecs, showing its lower bitrate and resulting savings in bandwidth and storage. Resolution vs H.264 vs H.265 360p 87.8% 75.5% 540p 82.7% 65.4% For example, for 360p video at 30 fps, where H.264 requires 1 Mbps, MLVC requires roughly 122 kbps for equivalent quality — about one-eight the bitrate under real-time conditions. The inference compute was kept approximately equal for the 360p and 540p resolutions. These results are based on a P.910 subjective test and are based on the Video Conferencing Dataset (VCD) dataset that we developed and also recently released as an open-source project. The following video demo illustrates the extent of quality enhancement achieved by MLVC relative to H.265/HEVC at the same bitrate of 200kbps (please watch by opening in a new window for better demonstration) \ Beyond video compression efficiency, MLVC also offers: NPU-first design. MLVC is built to run almost entirely on the AI accelerators already shipping in modern devices — Apple Neural Engine, Qualcomm and Intel NPUs — at no more than 50% NPU utilization, leaving NPU headroom for the rest of the system. Real-time execution at the targeted operating points. Demonstrated 540p at 30 fps on Apple, Intel, and Qualcomm hardware. A scaling-law trajectory. Empirically, MLVC's coding efficiency improves with increased model capacity and additional training compute. Content-adaptive behavior out of the box, without hand-tuned Rate Distortion Optimization heuristics. Already running in Microsoft Teams MLVC is more than just a research concept for Microsoft. We are currently rolling it out in Microsoft Teams, where it is being validated on real peer-to-peer video calls with active telemetry and A/B testing. The integration runs alongside fallback to conventional video codecs for hardware or reliability constraints — the kind of mixed-environment deployment that real products need. The scaling and reliability insights from this rollout are shaping the codec and its roadmap. We welcome your contributions We can not cover every use case, every device class, or every content domain by ourselves. That is why we are open sourcing MLVC. If you work on: Streaming, Video On Demand (VOD), or live broadcast Real-time communication and conferencing Cloud gaming or remote rendering Surveillance, drones, or robotics Mobile capture, Augmented Reality (AR) / Virtual Reality (VR), or volumetric video Codec hardware, NPUs, or inference runtimes We would love your help. Contributions of all kinds are welcome, including model improvements, training recipes, new platform ports and conversion targets, runtime backends, domain-specific fine-tunes, evaluation tooling, bug reports, and feedback on what is missing for your scenario. We particularly welcome platform ports that expand NPU coverage and efficiency improvements that push the rate-distortion frontier. What's in the release The MLVC repository is available at https://github.com/microsoft/mlvc and shared under the MIT License. It includes: MLVC model source code of the full network architecture. Trained model weights ready to run. Training scripts used to produce shipping models. Training data collection documentation to help reproduce and improve MLVC. Platform conversion scripts to target different NPUs and runtimes. Issues and pull requests will be open from day one. A follow-up release will add a C++ codec library, simplifying integration into real-world applications. Where we're heading Our long-term goal with MLVC is to create an open, learned video codec that meets or exceeds the coding efficiency of the best conventional codecs across the full range of video content, runs efficiently on the AI hardware already shipping in client and cloud devices, scales with compute the way modern ML systems do, and evolves in the open at the pace of the ML community rather than the pace of standardization cycles. In the near term that means stabilizing 540p real-time performance, expanding hardware coverage, and improving loss resilience. In the medium term: higher resolution, e.g., 1080p, and broader streaming scenarios. In the long term: an open video codec ecosystem that meaningfully replaces legacy stacks where it makes sense to. We can't create the future of MLVC alone. We're glad you're here, and we are looking forward to building the next-generation video codec with you. Who are we MLVC is brought to you by the following awesome folks working on the project at Microsoft: Ross Cutler, Ando Saabas, Tanel Pärnamaa, Ardi Loot, Haiyan Xie, Lauri Ehrenpreis, Andrei Znobishchev, Martin Lumiste, Evgenii Indenbom, Yan Lu, Bin Li, Jiahao Li, Naba Kumar, Babak Naderi, Juhee Cho, Badal Yadav, Jinxin Zhou, Tianyu Ding, Patrick Gregory. — The MLVC Team, Microsoft15KViews0likes4CommentsData Connectors Storage Account and Function App
Several data connectors downloaded via Content Hub has ARM deployment templates which is default OOB experience. If we need to customize we could however I wanted to ask community how do you go about addressing some of the infrastructure issues where these connectors deploy storage accounts with insecure configurations like infrastructure key requirement, vnet intergration, cmk, front door etc... Storage and Function Apps. It appears default configuration basically provisions all required services to get streams going but posture configuration seems to be dismissing security standards around hardening these services.202Views0likes1Comment