Cloud
Azure Application Gateway: validate connection draining before a rolling deployment
A production runbook for measuring in-flight requests, canarying backend removal, and choosing promotion or rollback without creating 502 errors during a rolling deployment.
A rolling deployment replaces backend instances without a declared outage. Azure Application Gateway probes stay green and the new release responds, yet a few clients receive a 502, lose a download, or see a WebSocket reset when an old instance leaves the pool.
The running case is an API behind Application Gateway v2 and a pool of VMs or a VM scale set. Some requests take several minutes and some clients use persistent connections. The objective is to prove that removing a backend stops new assignments while allowing existing connections to finish, then decide whether to continue the rollout, hold the canary, or roll back.
Freeze the deployment window
Tie the errors to one exact change. Preserve the deployment ID, application version, removed backend, UTC time of every Application Gateway operation, and representative affected requests. Do not diagnose draining from a 502 alone: TLS, probes, routing, saturation, and backend timeouts can produce the same status.
deployment:
change_id: CHG-4927
application_version: api-2026.10.15.3
backend_pool: api-prod-pool
backend_setting: api-https
canary_backend: 10.20.4.17
window_utc: 2026-10-15T08:30:00Z/2026-10-15T09:15:00Z
traffic_contract:
longest_request_seconds: 180
websocket_expected: true
cookie_affinity_enabled: false
error_budget_502: "no increase over baseline"
decision:
promote_when: "new requests avoid the draining backend and in-flight requests complete"
stop_when: "502 rises, a long request is cut, or backend health becomes unknown"
rollback_owner: platform-oncall Measure actual long request and transfer durations. A guessed timeout turns the rollout into a user test. The contract must also distinguish the request timeout, which limits how long the gateway waits for a backend response, from the connection draining timeout, which limits how long connections to a removed instance may survive.
Read the effective backend setting
Draining belongs to the backend HTTP setting referenced by a rule, not to the pool in isolation. Export deployed state and prove which rule references which setting. A correct value in Terraform or Bicep does not prove that the active path uses it.
RG="rg-edge-prod"
GATEWAY="agw-prod-weu"
az network application-gateway show --resource-group "$RG" --name "$GATEWAY" --query "{state:provisioningState,settings:backendHttpSettingsCollection[].{name:name,requestTimeout:requestTimeout,draining:connectionDraining},rules:requestRoutingRules[].{name:name,setting:backendHttpSettings.id,pool:backendAddressPool.id}}" --output json > appgw-before.json
az network application-gateway show-backend-health --resource-group "$RG" --name "$GATEWAY" --output json > backend-health-before.json Application Gateway accepts a connection draining timeout from 1 to 3,600 seconds when enabled. Set it above the maximum expected client transfer time with a justified margin. A very large value is not automatically safer: it extends configuration changes and delays removal of a faulty instance.
Check cookie-based affinity as a separate condition. Requests bound to a deregistering instance may continue to reach it. If the application relies on affinity, the canary must reuse the same cookie before and during removal instead of testing only fresh anonymous sessions.
Establish an access-log baseline
Confirm that Application Gateway access logs reach the intended workspace. The query must match the workspace schema, but it should at least compare response codes, URI, backend, and latency around the deployment.
let Start = datetime(2026-10-15T08:15:00Z);
let End = datetime(2026-10-15T09:30:00Z);
AGWAccessLogs
| where TimeGenerated between (Start .. End)
| extend Status = toint(HttpStatus),
BackendStatus = toint(ServerStatus)
| summarize Requests=count(),
Gateway502=countif(Status == 502),
Backend5xx=countif(BackendStatus between (500 .. 599)),
P95BackendTime=percentile(TimeTaken, 95)
by BackendPoolName, BackendSettingName, bin(TimeGenerated, 1m)
| order by TimeGenerated asc Column names vary with the table and diagnostic mode. Inspect the schema before adapting the query. Keep a healthy interval before the change and correlate errors with backend removal; a steady 502 rate that predates the deployment belongs to another diagnostic.
Application logs should add request ID, release, instance, start, completion, and graceful-shutdown state. Proving draining does not require logging tokens, cookies, or business payloads.
Canary one backend removal
Use a controlled instance and ensure that at least one other healthy instance can serve traffic. Start three cohorts before removal: repeated short requests, a long request with known duration, and a persistent connection when the protocol is used. Remove only the canary instance through the normal deployment mechanism.
canary:
short_requests:
rate_per_second: 5
expected: "no new request reaches the removed backend"
long_request:
duration_seconds: 180
started_before_removal: true
expected: "request completes with its original status"
websocket:
connected_before_removal: true
expected: "connection survives until normal client close within timeout"
affinity_session:
required: false
expected: "explicitly test when cookie affinity is enabled"
observe:
- gateway_502_rate
- backend_status
- request_duration
- backend_instance_and_version
- gateway_configuration_operations
abort:
- new_request_reaches_removed_backend
- in_flight_request_ends_before_application_completion
- websocket_is_reset
- healthy_capacity_falls_below_two_instances A healthy probe does not validate draining. It proves only that the members still being probed meet the health contract. The useful test watches the old connection, new assignments, and remaining capacity at the same time.
With AGIC, verify that the Ingress annotations produce the expected values in the generated backend HTTP setting. With a directly managed pool, check the property on Application Gateway after each deployment. In both cases, a gateway configuration update can itself invoke draining behavior, so keep its timestamp in the evidence.
Promote in bounded batches
After a successful canary, replace a bounded batch of instances. Wait for the timeout window and metric stabilization before the next batch. Remaining capacity must absorb both new requests and old connections still attached to draining instances.
Do not increase the timeout to hide an application that cannot shut down gracefully. The application should stop reporting readiness, reject new local work, complete accepted requests, and expose shutdown completion. The gateway protects a connection; it does not finish an incomplete business transaction.
If request duration exceeds an acceptable draining window, change the application contract: asynchronous operation, resumable download, checkpoint, or WebSocket reconnection. A gateway timeout is not a recovery strategy.
Decide promotion, hold, or rollback
Promote when no new request reaches the removed instance, in-flight requests finish inside the agreed window, WebSockets meet their contract, and the 502 rate does not exceed baseline. Preserve evidence for each batch with the Application Gateway configuration version.
Hold the canary when actual maximum duration is unknown, affinity is not covered, or healthy capacity would be insufficient during overlap. Fix the rollout plan or shutdown behavior first.
Roll back by stopping replacement, restoring the previous release, and returning only an instance whose application health has been proven. Restore the previous backend setting if the draining change itself is faulty. Replay the short, long, and persistent cohorts after rollback; a green probe alone is not a completed recovery.
Conclusion
Connection draining is not a checkbox that guarantees a zero-downtime rollout. It is a time-bound contract among Application Gateway, the removal mechanism, request duration, affinity, and application shutdown.
The production decision becomes testable: promote when new work avoids the removed backend and existing connections complete; hold when the contract is incomplete; roll back as soon as a transfer is cut or 502 errors exceed baseline.