Home / Azure

AzureHow-toAdvanced

App Service auto-heal for memory leaks and hung requests: recycle the worker before users notice

Configure App Service auto-heal rules for slow requests, 5xx bursts and private bytes, understand proactive auto-heal, and prove a recycle happened, on Windows and Linux plans.

Deepak Bhardwaj7 min read

Applies toAzure App Service (Windows and Linux, Basic tier and above), Azure CLI 2.x, Log Analytics

The goal

An app on App Service slowly leaks memory or gets stuck on a downstream call. Every few days response times climb, requests start timing out, and someone restarts the app by hand. You want the platform to recycle the bad worker automatically, on the affected instance only, while the developers find the real leak.

That is what auto-heal does. You define triggers (slow requests, status codes, request count, memory) and an action (recycle, log an event, or run a custom action). This post sets it up from the CLI, covers the Linux differences, and shows how to confirm it fired.

Warning

Auto-heal hides symptoms. A rule that recycles every 20 minutes keeps the site up but also drops in-flight requests each time. Treat it as a safety net, and track how often it fires.

Step 1: Confirm the pattern before you write a rule

Pick triggers from data, not guesses. Pull memory and error metrics for the last few days:

RG=rg-web-prod
APP=app-orders-prod
APP_ID=$(az webapp show -g $RG -n $APP --query id -o tsv)

az monitor metrics list --resource $APP_ID \
  --metric "MemoryWorkingSet" "PrivateBytes" "Http5xx" "HttpResponseTime" \
  --interval PT15M --aggregation Average Maximum Total \
  --offset 3d -o table

Metric names vary by OS and over time. PrivateBytes is Windows-only, and older apps may show AverageResponseTime instead of HttpResponseTime. Run az monitor metrics list-definitions --resource $APP_ID -o table to see what your app has.

If HTTP logs go to Log Analytics, find the slow paths and the error spikes:

AppServiceHTTPLogs
| where TimeGenerated > ago(3d)
| where _ResourceId has "app-orders-prod"
| summarize requests = count(),
            slow = countif(TimeTaken > 30000),
            errors5xx = countif(ScStatus >= 500)
          by bin(TimeGenerated, 15m), ComputerName
| order by TimeGenerated asc

TimeTaken is in milliseconds. Grouping by ComputerName shows whether one instance goes bad while the others stay healthy. That is exactly the case auto-heal handles well.

What you see Likely cause Trigger to use
Memory climbs steadily, then 5xx or slowness Leak in the app or a cache with no limit privateBytesInKB (Windows)
One instance gets slow, the others are fine Thread pool starvation, deadlock, stuck connection slowRequests
Bursts of 500/502/503 on one path Downstream failure, worker crash statusCodes or statusCodesRange
Every instance degrades at the same time Shared dependency (database, API) Don't auto-heal. Fix the dependency

Step 2: Know what is already on: proactive auto-heal

Windows apps already have proactive auto-heal. It restarts a process when private bytes stay above 90% of the limit for more than 30 seconds, or when 80% or more of requests take 200 seconds or longer (at least 5 requests in a rolling 120-second window). If it restarts too often, it turns itself off for three hours.

Check whether someone has disabled it:

az webapp config appsettings list -g $RG -n $APP \
  --query "[?name=='WEBSITE_PROACTIVE_AUTOHEAL_ENABLED']" -o table

The setting is disabled when the value is False. Leave proactive auto-heal on unless you are capturing a memory dump and need the process to stay alive. Your own rules should fire earlier than these defaults.

Step 3: Write custom rules (Windows)

The current Azure CLI has no dedicated auto-heal command, so set the autoHealEnabled and autoHealRules properties on the site's config/web resource with az rest. Save this as autoheal.json:

{
  "properties": {
    "autoHealEnabled": true,
    "autoHealRules": {
      "triggers": {
        "privateBytesInKB": 2800000,
        "slowRequests": {
          "timeTaken": "00:01:00",
          "count": 20,
          "timeInterval": "00:05:00"
        },
        "statusCodes": [
          {
            "status": 503,
            "subStatus": 0,
            "win32Status": 0,
            "count": 50,
            "timeInterval": "00:02:00"
          }
        ]
      },
      "actions": {
        "actionType": "Recycle",
        "minProcessExecutionTime": "00:10:00"
      }
    }
  }
}

Apply it:

az rest --method patch \
  --url "https://management.azure.com${APP_ID}/config/web?api-version=2023-12-01" \
  --body @autoheal.json

az rest --method get \
  --url "https://management.azure.com${APP_ID}/config/web?api-version=2023-12-01" \
  --query "properties.{enabled:autoHealEnabled, rules:autoHealRules}"

How to choose the values:

  • privateBytesInKB: set it to about 75–80% of the process limit for your worker size and bitness. Proactive auto-heal then becomes the backstop at 90%.
  • slowRequests.timeTaken: set it above your slowest legitimate request (reports, exports). Use slowRequestsWithPath to scope a rule to one URL path.
  • count and timeInterval: require a real pattern. One slow request should never recycle a worker.
  • minProcessExecutionTime: the process must have run this long before the action fires. This stops recycle loops while the app is still warming up.

actionType can also be LogEvent (record only) or CustomAction. Start with LogEvent for a day if you are unsure about thresholds, then switch to Recycle.

Tip

Do this on a deployment slot first. config/web settings are slot-specific unless marked otherwise, so a swap takes the slot's rules with it. Check both slots after a swap.

Step 4: Linux plans

Auto-heal on Linux works differently:

  • You configure it in the portal under Diagnose and solve problems > Diagnostic Tools > Auto-Heal.
  • Triggers are request duration (optionally per path), request count and status codes (a single code or a range). There is no memory trigger.
  • The only action is Recycle the container.
  • There is an optional startup time setting that controls how soon the rule can fire again after the container starts. Set it longer than your container's normal startup time.

For memory leaks on Linux, set a container or runtime memory limit (for example the JVM -Xmx or Node.js --max-old-space-size) so the process fails clearly, then rely on the platform restart and the health check.

Step 5: Capture evidence before the recycle

A recycle destroys the state that explains the leak. On Windows, the portal Auto-Heal blade offers a custom action that collects a memory dump before restarting the process. Use it for a limited time while developers investigate. Dumps are large and the collection pauses the process.

For a one-off fix on one instance without restarting the whole app, use Diagnose and solve problems > Advanced Application Restart, which restarts selected instances one at a time. List instances first:

az webapp list-instances -g $RG -n $APP --query "[].name" -o tsv

Caution

az webapp restart restarts every instance at once. On a busy production app, that is an outage. Use the per-instance restart or let auto-heal act on the bad instance only.

Step 6: Prove it fired and how often

On Windows, auto-heal events show in Diagnose and solve problems (search for "Auto-Heal") and in the eventlog.xml under D:\home\LogFiles. On both OSes, restarts appear in the platform logs if diagnostic settings send them:

AppServicePlatformLogs
| where TimeGenerated > ago(7d)
| where _ResourceId has "app-orders-prod"
| where Message has_any ("recycl", "restart", "Auto Heal", "AutoHeal")
| project TimeGenerated, Level, Message
| order by TimeGenerated desc

Message wording varies by OS and platform version, so start with a broad match and narrow it down once you see the real text.

Set an alert on recycles per day. One a week is a safety net doing its job. Several a day means the leak is getting worse, or the thresholds are too low.

Prevent it next time

  • Keep auto-heal rules in IaC (siteConfig.autoHealEnabled and siteConfig.autoHealRules in Bicep or ARM) so a redeploy doesn't remove them.
  • Enable the App Service health check as well. It takes a bad instance out of load balancer rotation. Auto-heal restarts the process.
  • Run at least two instances so a recycle on one doesn't drop traffic.
  • Open a ticket every time auto-heal fires more than your agreed rate, and attach the dump or HTTP log query output.
  • Review thresholds after any worker size change, because the memory limit changes with it.