Cloud / Azure Virtual Machine Scale Sets Interview questions
Last updated
1. What is an Azure Virtual Machine Scale Set?
An Azure Virtual Machine Scale Set (VMSS) is a compute resource that lets you create and manage a group of load-balanced virtual machines as one unit. The number of instances can grow or shrink automatically, based on demand or a schedule you define.
You describe the VM once (image, size, disks, network, extensions) and Azure stamps out as many copies as you ask for. That description is called the scale set model.
Scale sets are typically placed behind an Azure Load Balancer or Application Gateway, and they spread instances across fault domains or availability zones for resilience. There is no separate charge for the scale set itself, only for the VMs, disks and networking it uses.
Take quiz
Availability set
Proximity placement group
Virtual Machine Scale Set
Azure Reservation
One unique, hand-configured stateful server
A single jump box
A VM that needs a different OS on each node
Many identical instances serving the same application
2. What are the key benefits of using a scale set?
A scale set gives you elasticity, consistency and availability without managing each VM by hand.
- Autoscale: add or remove instances based on metrics or schedules, so you pay for what you need.
- Consistency: every instance is built from the same model, which removes configuration drift.
- High availability: instances are spread across fault domains or availability zones.
- Scale: a single scale set can hold up to 1,000 instances.
- Easy updates: change the model once, then roll it out manually, automatically or in rolling batches.
- Integration: works natively with Load Balancer, Application Gateway, Azure Monitor and managed identities.
Take quiz
Free Windows Server licensing
Unlimited vCPU quota
Faster disk throughput on every VM
Higher availability during hardware or zone failures
Autoscale
Reimage
Instance protection
Scale-in policy
3. What are the orchestration modes in VMSS?
A scale set supports two orchestration modes: Uniform and Flexible. You pick the mode when you create the scale set, and it cannot be changed afterwards.
Uniform runs identical instances that are managed through scale-set specific APIs. It suits large, stateless fleets where every VM is a clone of the model.
Flexible treats each instance as a regular Azure VM resource. You can use normal VM operations on them and, in some cases, mix VM configurations. Microsoft recommends Flexible for new deployments.
Take quiz
Uniform and Flexible
Manual and Automatic
Zonal and Regional
Basic and Standard
Uniform
Flexible
Neither mode
Only the retired Classic mode
4. What image sources can a scale set use?
A scale set can build instances from Azure Marketplace images, custom images you captured yourself, or images stored in an Azure Compute Gallery.
Marketplace images are the quickest start (for example Ubuntu or Windows Server). Compute Gallery is the better choice for production because it gives you image versions, replication across regions and RBAC-based sharing.
In the image reference you can pin a version (repeatable builds) or use latest (always the newest published version). Pinning is safer for controlled rollouts; latest is required for automatic OS image upgrades.
Take quiz
Azure Container Registry
Azure Compute Gallery
Azure Files share
Azure Blob static website
stable
current
latest
newest-gen
5. What is the scale set model versus the instance view?
The model is the desired configuration of the scale set: image, VM size, disks, network profile, extensions and so on. The instance view is the current runtime state of each VM: provisioning state, power state and extension status.
The two can differ. If you change the model (say a new image version) and the upgrade policy is manual, existing instances keep running the old configuration until you update them. In Uniform mode each instance reports whether it has the latest model applied.
az vmss show -g rg-demo -n web-vmss az vmss get-instance-view -g rg-demo -n web-vmss
Think of the model as the blueprint and the instance view as a health report on what was actually built.
Take quiz
Only current CPU usage
The billing history
The desired configuration applied to instances
The list of failed sign-ins
Model view
Cost view
Autoscale profile
Instance view
6. What is autoscaling in a scale set?
Autoscaling automatically changes the number of instances in a scale set to match load. It is provided by Azure Monitor autoscale, not by the scale set itself.
An autoscale setting contains one or more profiles. Each profile defines a minimum, maximum and default instance count, plus rules that say when to scale out or in. Autoscale never goes below the minimum or above the maximum.
This keeps performance steady at peak and cuts cost when demand drops. It works best with stateless instances that can be added or removed at any time.
Take quiz
Soft and hard quota
Fault domain and update domain counts
Cooldown and grace period
Minimum and maximum counts
Azure Monitor
Azure Policy
Azure Advisor
Microsoft Entra ID
7. What are the types of autoscale rules?
Scale sets support three approaches to automatic scaling:
| Type | Trigger | Typical use |
| Metric-based | A metric crosses a threshold (CPU %, memory, queue length, custom metric) | Reacting to real load |
| Schedule-based | Time of day, day of week or a fixed date | Known peaks such as business hours or month-end |
| Predictive | Forecast built from historical CPU load | Scaling out ahead of recurring demand |
You can combine them. A recurring profile can raise the minimum during working hours while metric rules still handle surprise spikes. Predictive autoscale needs a few days of history and can be run in forecast-only mode first to check its accuracy.
Take quiz
Schedule-based
Metric-based
Predictive only
Manual scaling
Manual capacity tickets
Historical CPU load patterns used to forecast demand
Billing alerts
Zone health events
8. How do you create a scale set using Azure CLI?
Use az vmss create. Create a resource group first, then give the command an image, a size, an instance count and credentials.
az group create -n rg-demo -l eastus az vmss create \ -g rg-demo -n web-vmss \ --image Ubuntu2204 \ --vm-sku Standard_D2s_v5 \ --instance-count 2 \ --orchestration-mode Flexible \ --admin-username azureuser \ --generate-ssh-keys \ --zones 1 2 3
The command also creates a virtual network and a load balancer if you do not point it at existing ones. Use --lb or --vnet-name and --subnet to reuse your own. Check the result with az vmss list-instances.
Take quiz
az vm scale-create
az vmss create
az scaleset new
az group vmss add
--vmss-type
--scale-mode
--orchestration-mode
--upgrade-mode
9. How do you scale a scale set manually?
Set a new capacity with az vmss scale, PowerShell's Update-AzVmss -SkuCapacity, or the Instances blade in the portal.
az vmss scale -g rg-demo -n web-vmss --new-capacity 5
Azure adds or deletes instances until the count matches. When scaling in, the scale-in policy decides which VMs go.
Be careful if autoscale is enabled. Autoscale enforces its own minimum and maximum, so a manual value outside that range will be corrected on the next evaluation. For a lasting manual change, adjust the autoscale limits or disable autoscale.
Take quiz
az vmss resize --count 5
az vmss start --capacity 5
az vmss scale --new-capacity 5
az vm scale --size 5
The maximum is raised automatically
Autoscale is deleted
Manual capacity always wins permanently
Autoscale pulls capacity back inside its min and max
10. What is a placement group in a scale set?
A placement group is an internal grouping of VMs, similar to an availability set, with its own fault domains and update domains. It mostly matters in Uniform mode.
By default a scale set uses a single placement group (singlePlacementGroup=true), which caps it at 100 instances. Setting it to false lets the scale set use multiple placement groups and grow to 1,000 instances.
Large multi-group scale sets need a Standard load balancer and Standard public IPs. Flexible mode handles spreading on its own through its fault domain count and zones, so you rarely tune placement groups there.
Take quiz
10
600
1,000
100
singlePlacementGroup set to false
Enable accelerated networking
Use a Basic load balancer
Disable autoscale
11. What does Azure charge for a scale set?
There is no extra charge for the scale set resource itself. You pay for the underlying resources it creates and runs.
- VM compute hours for each running instance (including OS licensing for Windows or paid Marketplace images)
- Managed disks, both OS and data disks
- Networking: load balancer, public IPs and outbound data transfer
- Optional services such as Azure Monitor logs and backup
Instances that are stopped (deallocated) stop billing for compute, but their disks still cost money. Reserved Instances, Savings Plans, Azure Hybrid Benefit and Spot pricing all apply to scale set VMs, and autoscale itself is free.
Take quiz
None, you pay for the underlying resources
A flat monthly fee per scale set
A per-instance orchestration fee
A per-rule autoscale fee
vCPU compute hours
Managed disk storage
Windows Server licensing hours
Hourly public IP bandwidth of the stopped VM
12. What is the role of a load balancer with a scale set?
A load balancer gives clients a single address and distributes inbound traffic across healthy instances. Without it, you would need to track every instance IP yourself.
- Load-balancing rules send traffic from a frontend port to the backend pool (the scale set).
- Health probes check each instance and remove failing ones from rotation.
- Inbound NAT rules can forward ports to individual instances for admin access.
- Outbound rules control SNAT for instances without public IPs.
Use the Standard SKU. Basic Load Balancer has been retired, and Standard supports zone redundancy and large scale sets. For HTTP routing or WAF, use Application Gateway instead.
Take quiz
Basic
Standard
Classic
Cloud Service
Resize the VM SKU
Install extensions
Decide which instances receive traffic
Rotate SSH keys
13. What is the Custom Script Extension used for in VMSS?
The Custom Script Extension downloads and runs a script on each instance after it is provisioned. It is the quickest way to install packages or configure an app when the base image is generic.
az vmss extension set -g rg-demo --vmss-name web-vmss \ --name CustomScript --publisher Microsoft.Azure.Extensions --version 2.1 \ --settings '{"commandToExecute":"apt-get update && apt-get install -y nginx"}'
The script runs once per instance at provisioning. To run it again, change the settings (for example with forceUpdateTag). Keep scripts idempotent, and put credentials in protectedSettings, which is encrypted, rather than in public settings.
For fast scale-out, baking the app into a custom image is better than running long scripts on every new VM.
Take quiz
Before Azure allocates the VM
On every incoming HTTP request
A script on the instance after provisioning
Only on the Azure control plane
Base64 encode them in public settings
Put them in the VM name
Store them in plain custom data
Use protectedSettings
14. Define horizontal and vertical scaling in the context of VMSS?
Horizontal scaling changes the number of instances (scale out and scale in). Vertical scaling changes the size of each instance (scale up and scale down).
| Horizontal | Vertical | |
| What changes | Instance count | VM SKU (CPU, RAM) |
| Downtime | None for existing instances | Restart or replacement of instances needed |
| Automation | Built-in autoscale | Update model, then roll out |
| Limit | Quota and max count | Largest SKU in the region |
Scale sets are designed for horizontal scaling. Vertical scaling means editing the SKU in the model and rolling the change through the instances, which is slower and disruptive.
Take quiz
Scale up (vertical scaling)
Reimaging
Zone balancing
Scale out (horizontal scaling)
Vertical scaling
Horizontal scaling
Overprovisioning
Instance protection
15. What are Spot VMs in a scale set?
Spot VMs use Azure's spare compute capacity at a deep discount (up to around 90 percent off), with the catch that Azure can evict them when it needs the capacity back or when your maximum price is exceeded.
You choose an eviction policy: Deallocate keeps the disks (and their cost) while Delete removes everything. Setting max price to -1 means you pay up to the on-demand price and are only evicted for capacity. Evictions give about 30 seconds of notice through Scheduled Events.
Spot suits stateless, interruptible work such as batch jobs, CI agents and render farms. In Flexible mode, Spot Priority Mix lets you keep a base of regular VMs and fill the rest with Spot.
Take quiz
Azure needs the capacity back or your price cap is exceeded
CPU stays under 30 percent
You add a data disk
The autoscale cooldown expires
A single primary SQL server
Stateless batch processing
A domain controller
A licensing server holding state
16. What is the difference between Uniform and Flexible orchestration?
Uniform manages identical instances through scale-set APIs, while Flexible exposes every instance as a normal Azure VM resource and gives you more control over how the group is composed.
| Aspect | Uniform | Flexible |
| Instance model | Identical clones of the scale set model | Regular VMs; configurations can differ |
| Management | Scale-set specific VM APIs and instance IDs | Standard VM APIs and VM names |
| Availability spread | Fault domains, update domains, placement groups | Spread across zones and fault domains by default |
| Spot plus regular mix | Not available | Spot Priority Mix supported |
| Recommended for | Existing large stateless fleets | New deployments |
Neither mode can be switched in place. If you want to move from Uniform to Flexible, plan on building a new scale set and shifting traffic to it.
Take quiz
Uniform
Flexible
Both, using identical settings
Neither
Hidden internal objects
Containers
Standard Azure VM resources
Only visible through ARM templates
17. How does autoscale decide when to scale out or in?
Autoscale evaluates each rule about once a minute. A rule has a metric, a time aggregation (such as average), a threshold and a look-back window (for example CPU above 70 percent for 10 minutes), plus an action and a cooldown.
- If any scale-out rule is true, autoscale scales out.
- Autoscale scales in only when all scale-in rules are true.
- Before scaling in, it estimates the result. If the smaller fleet would immediately trigger a scale-out, it skips the scale-in to avoid flapping.
- Counts always stay between the profile's minimum and maximum.
az monitor autoscale create -g rg-demo --resource web-vmss \ --resource-type Microsoft.Compute/virtualMachineScaleSets \ --name web-autoscale --min-count 2 --max-count 10 --count 2 az monitor autoscale rule create -g rg-demo --autoscale-name web-autoscale \ --condition "Percentage CPU > 70 avg 10m" --scale out 2 az monitor autoscale rule create -g rg-demo --autoscale-name web-autoscale \ --condition "Percentage CPU < 30 avg 10m" --scale in 1
Take quiz
Any one scale-in rule is true
The cooldown is disabled
All scale-in rules are satisfied
Memory exceeds 90 percent
All scale-out rules are true
Only the first listed rule is true
Every instance exceeds the threshold at once
Any scale-out rule is true
18. What is the cooldown period in autoscale?
The cooldown is the time autoscale waits after a scale action before it is allowed to act again. The portal default is 5 minutes.
It exists because a new instance needs time to boot, run extensions, pass health probes and start taking traffic. Until then, metrics still look the same as before, and autoscale could add more instances than needed.
- Too short: over-scaling and flapping between out and in.
- Too long: slow reaction to sudden spikes.
A good starting point is your measured time from instance creation to healthy-in-load-balancer, plus a small buffer. Set cooldown per rule, and use a longer one for scale-in than for scale-out.
Take quiz
Quota exhaustion
Image corruption
Zone failures
Flapping from back-to-back scale actions
Over-scaling before new instances take load
Failed image replication
Loss of managed identity
Higher licensing fees
19. How do you configure schedule-based autoscale?
Add a profile to the autoscale setting that is tied to a time window. In the portal: scale set, Scaling, Custom autoscale, Add a scale condition.
- Pick the instance count or rules the profile should use (for example min 6, max 12).
- Choose Repeat specific days and select the days.
- Set start and end times and the time zone.
- Keep a default profile for all other times, for example min 2, max 6.
If profiles overlap, a fixed-date profile beats a recurring one, which beats the default. A wrong time zone is the usual reason a schedule fires at the wrong hour, so always set it explicitly.
Take quiz
Fixed-date profile
Default profile
Recurring weekly profile
The profile created first
A larger OS disk
The correct time zone
A second NIC
Spot priority
20. How does a scale set differ from an availability set?
An availability set only spreads VMs you create manually across fault and update domains. A scale set also creates, configures and scales those VMs for you from a single model.
| Feature | Availability set | Scale set |
| VM creation | Each VM created and configured separately | Generated from one model |
| Autoscale | No | Yes |
| Availability zones | No, single datacenter group | Yes |
| Updates | Per VM | Manual, automatic or rolling for the whole group |
| Best for | A few distinct VMs, such as an app and its DB pair | Fleets of identical instances |
For new designs, zone-spread scale sets give stronger resilience than availability sets.
Take quiz
An availability set
A scale set
A single fault domain
An update domain
Fault domain spread
Update domain spread
Automatic instance-count scaling
Grouping for availability SLA
21. What are the upgrade policies in a scale set?
The upgrade policy decides how a model change reaches existing instances. There are three modes.
| Policy | Behavior | Risk |
| Manual | Nothing changes until you run an update on chosen instances | You control timing, but drift if you forget |
| Automatic | Azure upgrades instances on its own, with no health-gated ordering | Possible downtime if all instances restart together |
| Rolling | Upgrades in batches and checks health between batches | Slower, but safest for production |
Rolling upgrades need health signals from either a load balancer probe or the Application Health extension. If health checks are missing, Azure cannot tell whether a batch recovered, so rolling is not suitable without them.
Take quiz
Manual
Automatic
Rolling
Immediate
Applies instantly to all instances
Rolls back automatically
Is ignored permanently
Waits until you upgrade instances yourself
22. How do you apply a model update to existing instances?
Under a Manual policy, change the model first, then push it to instances with az vmss update-instances.
# 1. change the model az vmss update -g rg-demo -n web-vmss --set virtualMachineProfile.storageProfile.imageReference.version=1.0.2 # 2. roll it out to every instance (or give specific IDs) az vmss update-instances -g rg-demo -n web-vmss --instance-ids "*"
Changes like extensions or tags apply in place. Changes to the image replace the instance's OS disk, so anything stored there is lost. Data disks are kept.
To find instances that are behind, list them and check latestModelApplied (Uniform mode). Upgrade a few first, verify them, then continue with the rest.
Take quiz
az vmss reapply --all
az vmss sync
az vmss push-model
az vmss update-instances
The instance's OS disk
The attached data disks
The subnet
The load balancer
23. What are fault domains and update domains in a scale set?
A fault domain (FD) is a group of hardware that shares a power source and network switch, such as a rack. An update domain (UD) is a group of VMs that can be rebooted together during planned platform maintenance.
Azure spreads instances across FDs so a single rack failure takes out only part of the scale set. UDs ensure maintenance affects only one group at a time, which keeps the rest serving traffic.
In Uniform mode both concepts apply through placement groups. In Flexible mode you set the platformFaultDomainCount to control spreading, and zones give wider isolation than FDs. Using zones is generally preferred where the region supports them.
Take quiz
Hardware sharing power and network
A group of Azure subscriptions
A DNS zone
A billing scope
Which VMs share a public IP
Which VMs reboot together during planned maintenance
Which VMs get Spot pricing
Which VMs use ephemeral disks
24. How do availability zones work with scale sets?
When you set zones on a scale set (for example 1, 2, 3), Azure places instances in those physically separate datacenters within the region, so a single-zone outage does not take down the whole application.
- Instances are spread across the zones; zone balance keeps counts within one VM of each other (best-effort or strict).
- Pair with a zone-redundant Standard Load Balancer or Application Gateway v2.
- VMs placed in two or more zones qualify for the 99.99 percent VM availability SLA.
Plan capacity for failure: if one of three zones is lost, the remaining two must absorb the load, so autoscale maximums and quota should allow it. Zonal disks stay in the zone of their VM, so replicate data at the application layer or use zone-redundant storage.
Take quiz
99.5 percent
99.99 percent
99.9 percent
99.0 percent
All instances in zone 1
Equal disk sizes in every zone
Instance counts across zones within one of each other
Equal public IP counts per zone
25. How do you use Azure Compute Gallery images with a scale set?
Build a gallery, define the image, publish versions, and point the scale set at the image definition or a specific version.
- Create an Azure Compute Gallery.
- Add an image definition describing OS type, generalized state, publisher, offer and SKU.
- Publish image versions (for example 1.0.0, 1.0.1) from a VM or Packer build, and choose target regions and replica count.
- Reference the image ID in the scale set. Using the definition ID selects the latest version.
az vmss create -g rg-demo -n web-vmss --image "/subscriptions/<sub>/resourceGroups/rg-img/providers/Microsoft.Compute/galleries/myGallery/images/webImage" \ --admin-username azureuser --generate-ssh-keys
Increase the replica count for large scale-outs, otherwise many instances pulling one replica can be throttled and provisioning slows down.
Take quiz
The VM's public IP
An autoscale rule
Image metadata such as OS type, state, publisher, offer and SKU
Billing tags only
To get more fault domains
To reduce licensing cost
To shorten the cooldown
To avoid throttling when many VMs pull the image
26. How does application health monitoring work in VMSS?
Azure learns instance health from either a load balancer probe or the Application Health extension. The extension runs inside the VM and probes a local port or path, then reports Healthy, Unhealthy or Unknown to the platform.
{ "protocol": "http", "port": 80, "requestPath": "/health" }
That signal feeds rolling upgrades, automatic instance repairs and automatic OS image upgrades. Without it, those features cannot tell a broken instance from a working one.
Make the health endpoint cheap and honest: return success only when the app can really serve requests (dependencies reachable, warm-up done), and avoid heavy checks that make healthy instances look sick under load.
Take quiz
Custom Script Extension
Key Vault extension
Disk encryption extension
Application Health extension
Return success only when the app is ready to serve
Always return 200
Return only the OS version
Restart the VM on every call
27. How do automatic instance repairs work?
With automatic instance repairs enabled, the scale set watches the health signal and replaces instances that stay unhealthy, so you do not have to find and fix them manually.
- An instance reports Unhealthy.
- Azure waits for the grace period (minimum 10 minutes) so new or updated instances can finish starting.
- If it is still unhealthy, Azure performs the repair action: Replace (default, delete and recreate), Restart or Reimage.
- Repairs happen in batches so the whole fleet is not touched at once.
az vmss update -g rg-demo -n web-vmss \ --enable-automatic-repairs true --automatic-repairs-grace-period 10
Repairs require health monitoring (Application Health extension or load balancer probes). Pick a grace period longer than your slowest startup, or healthy-but-slow instances will be replaced in a loop.
Take quiz
Deleting and recreating it
Resizing it
Moving it to another region
Cloning its data disks
Reset the autoscale cooldown
Give new or updated instances time to become healthy
Rotate keys
Replicate gallery images
28. How do scale-in policies choose which VM to delete?
The scale-in policy ranks instances for deletion when capacity drops. There are three options.
| Policy | What it removes |
| Default | Balances across zones, then fault domains, then removes the VM with the highest instance ID (Uniform) |
| NewestVM | The most recently created instance |
| OldestVM | The oldest instance |
With NewestVM or OldestVM, zone balancing still applies first on zonal scale sets. Protected instances are skipped.
OldestVM is handy after a model update because scale-in naturally removes stale instances. NewestVM suits canary tests where the freshest VM is the one you want to discard.
Take quiz
OldestVM
NewestVM
Default
ZoneFirst
Smallest disk
Lowest CPU usage
Balancing across zones
Alphabetical VM name
29. What are instance protection options in a scale set?
Instance protection stops the scale set from touching a specific instance. There are two switches.
- Protect from scale-in: the instance cannot be deleted by a scale-in operation or autoscale.
- Protect from scale set actions: the instance is also excluded from model updates, reimage and other scale set operations.
A protected instance can still be deleted by an explicit delete on that VM or by deleting the scale set, and protection can be changed through the portal, PowerShell (Update-AzVmssVM) or REST.
A typical use is a worker that is halfway through a long job. Protect it when the job starts, then clear protection when the job ends so normal scaling resumes. Too many protected instances can leave a zonal scale set unbalanced.
Take quiz
All OS patching
Billing charges
Deletion by scale-in operations
Zone assignment
Reducing licensing costs
Enabling Spot discounts
Shrinking OS disks
Instances running long jobs that must finish
30. How do you attach data disks to scale set instances?
Define data disks in the model. Each instance then gets its own new, empty disk of the size you specify.
az vmss create -g rg-demo -n web-vmss --image Ubuntu2204 \ --data-disk-sizes-gb 128 256 # add a disk to an existing scale set az vmss disk attach -g rg-demo --vmss-name web-vmss --size-gb 128 --lun 2
The disk is raw. You still need to partition, format and mount it, usually through cloud-init or an extension, and mount by UUID so the path survives reboots.
Maximum disk count depends on the VM size. For data that must be shared or outlive instances, use Azure Files, a database or blob storage rather than per-instance disks.
Take quiz
As one shared disk
Pre-filled from the image
In another region
Per instance, as new empty disks
Partition, format and mount it
Reimage the instance
Change the SKU
Recreate the load balancer
31. When would you choose Application Gateway over Load Balancer?
Choose Application Gateway when you need HTTP-aware routing or a web application firewall in front of the scale set. Choose Load Balancer when you need fast, simple layer 4 distribution.
| Feature | Standard Load Balancer | Application Gateway v2 |
| OSI layer | Layer 4 (TCP/UDP) | Layer 7 (HTTP/HTTPS) |
| Routing | Port and protocol | URL path, host header, cookies |
| TLS termination | No | Yes |
| WAF | No | Yes |
| Subnet | None needed | Dedicated subnet |
Both accept a scale set as backend pool. Many designs use Application Gateway for the web tier and an internal Load Balancer for the next tier, or put Azure Front Door in front for global routing.
Take quiz
Application Gateway
Standard Load Balancer
Azure DNS
NAT Gateway
Layer 7
Layer 4
Layer 2 only
The application layer with cookies
32. How does cloud-init work with a scale set?
cloud-init configures Linux instances at first boot using the custom data you place in the scale set model. Every new instance runs it once as it starts.
#cloud-config package_upgrade: true packages: - nginx runcmd: - echo "Hello from $(hostname)" > /var/www/html/index.html - systemctl enable --now nginx
az vmss create -g rg-demo -n web-vmss --image Ubuntu2204 --custom-data cloud-init.txt
Custom data is limited to 64 KB and is not encrypted, so do not put secrets in it. On Windows, use the Custom Script Extension instead. For heavy installs, a prebuilt image starts faster than running cloud-init on every scale-out.
Take quiz
The autoscale profile
Custom data in the model
A load balancer rule
A scale-in policy
Package names
Systemctl commands
Secrets such as passwords
Static welcome-page text
33. What happens when you reimage a scale set instance?
A reimage replaces the instance's OS disk with a fresh copy of the image defined in the current model, then boots it again. The instance keeps its identity and network settings.
- Anything stored on the OS disk is lost (local files, logs, temp changes).
- Attached data disks are kept.
- Extensions and custom data run again after the reboot.
- The instance picks up the latest model, so it also acts as an update.
az vmss reimage -g rg-demo -n web-vmss --instance-id 3
Reimage is a quick way to reset a corrupted instance. It is faster than a delete and recreate, and with ephemeral OS disks it is especially quick since the disk is local.
Take quiz
Data disks
Subnet
OS disk with a fresh copy of the model image
Region
Preserved
Moved to a data disk
Backed up automatically
Lost
34. How do managed identities work with scale sets?
A managed identity gives instances a Microsoft Entra identity so code can call Azure services without storing passwords or keys. You assign RBAC roles to the identity, and the app asks for a token at runtime.
There are two types. A system-assigned identity is tied to the scale set's lifecycle. A user-assigned identity is a separate resource you can attach to several scale sets, and it can be granted access before the scale set exists. User-assigned is usually the better fit for scale sets.
az vmss identity assign -g rg-demo -n web-vmss --identities <identity-resource-id> # from inside an instance curl -H "Metadata: true" \ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net"
Typical uses: reading secrets from Key Vault, writing to Storage, or pulling images from Azure Container Registry.
Take quiz
It reads a password file in /etc
It asks the load balancer
It queries the autoscale API
It calls the IMDS endpoint with the header Metadata: true
It exists independently and can be pre-authorized and shared
It avoids RBAC entirely
It disables IMDS
It doubles the vCPU quota
35. How does VMSS relate to AKS node pools?
Each AKS node pool is backed by a virtual machine scale set. When AKS adds or removes nodes, it is changing the capacity of that scale set.
The scale sets live in the cluster's node resource group (usually named MC_...) and are owned by AKS. Editing them directly, for example changing the image or SKU, is unsupported and can be reverted or break upgrades. Make changes through the AKS API, CLI or Terraform.
Node scaling is handled by the AKS cluster autoscaler, which reacts to unschedulable pods and node usage within the pool's min and max. Do not attach Azure Monitor autoscale rules to those scale sets, because the two would fight each other.
Node image upgrades use surge nodes in the same scale set, so quota for the extra nodes must be available.
Take quiz
Virtual machine scale sets
Azure Batch pools
App Service plans
Logic Apps
Azure Monitor autoscale rules on the VMSS
The cluster autoscaler
A scale-in policy
A placement group
36. What are ephemeral OS disks and why use them?
An ephemeral OS disk keeps the OS on the VM's local storage (cache, temp or NVMe disk) instead of a remote managed disk. It exists only as long as the VM does.
- Lower latency for OS reads and writes, because the disk is local.
- Faster reimage and provisioning during scale-out.
- No OS disk storage cost.
The catch is that OS state is lost on reimage, redeploy or deallocation, and the image must fit in the available local space, which depends on the VM size. They are a great match for stateless web and worker tiers.
az vmss create -g rg-demo -n web-vmss --image Ubuntu2204 \ --vm-sku Standard_D4s_v5 --ephemeral-os-disk true --os-disk-caching ReadOnly
Take quiz
Azure Files
Local VM storage (cache, temp or NVMe)
A blob container
Key Vault
Higher storage cost
Slower boot times
OS state is lost on deallocation or reimage
No Linux support
37. How does overprovisioning work in Uniform mode?
With overprovisioning, Azure creates more VMs than you requested, keeps the first ones that deploy successfully, and deletes the extras. This raises the success rate of deployments and makes them finish sooner.
The extra VMs are not billed and do not count against your vCPU quota. It is on by default in Uniform mode and does not apply to Flexible.
Turn it off (--disable-overprovision) when the extra short-lived VMs would cause harm. For example, if your startup script registers each VM with an external system, the VMs that get deleted can leave stale registrations behind.
In Uniform mode this is why you may briefly see more instances than your requested capacity right after a create or scale-out.
Take quiz
Billed at half price
Kept as warm spares
Not billed and not counted toward quota
Converted to Spot
Flexible orchestration only
Availability sets
Application Gateway
Uniform orchestration
38. How do you monitor a scale set?
Combine host metrics, guest metrics and logs in Azure Monitor.
| Layer | What you get | How |
| Host metrics | CPU %, network, disk ops per scale set or per instance | Automatic, view in Metrics (split by instance) |
| Guest metrics | Memory, disk space, processes, app counters | Azure Monitor Agent with a data collection rule |
| Logs | Syslog, event logs, performance data, autoscale logs | Log Analytics workspace and diagnostic settings |
| Activity Log | Scale actions, updates, failures | Built in |
Create alerts for high CPU, unhealthy instances and failed scale operations. VM insights adds a ready-made dashboard and dependency map, and Application Insights covers request-level data.
Take quiz
Nothing, it is a default host metric
Autoscale rules only
The Activity Log
Azure Monitor Agent with a data collection rule
Autoscale diagnostic logs and the Activity Log
Key Vault audit log
NSG flow logs only
Storage analytics logs
39. Which is better and why: scale set or standalone VMs?
It depends on the workload. A scale set is better for many identical, stateless instances. Standalone VMs are better for unique servers that each need their own configuration.
| Factor | Scale set | Standalone VMs |
| Scaling | Autoscale, one-line capacity change | Create and configure each by hand |
| Consistency | One model for all | Drift is likely |
| Availability | Zone and FD spread built in | You design it yourself |
| Uniqueness | Instances are interchangeable | Each VM can differ |
| Good examples | Web tier, API nodes, batch workers | Domain controller, single-primary database |
The cost is the same for equivalent VMs. If you are unsure, Flexible orchestration blurs the line since it lets you manage instances as normal VMs while still giving you a scaling group.
Take quiz
A unique stateful server with custom configuration
A stateless web tier
Batch workers
Identical API nodes
A lower per-core price
One model and autoscale across identical instances
Immunity to zone outages
No need for any load balancer
40. Why is Flexible orchestration recommended for new deployments?
Flexible is where Microsoft is investing, and it fits most modern designs better than Uniform because instances are normal Azure VMs that happen to be grouped.
- Standard VM tooling: the same APIs, extensions and features you use on single VMs.
- Better spreading: instances are spread across zones and fault domains without placement-group tuning.
- Mixed capacity: Spot Priority Mix lets you combine regular and Spot VMs.
- More flexibility: you can add existing VMs and treat instances individually when needed.
Plan for explicit outbound connectivity (NAT Gateway, load balancer outbound rules or public IPs) rather than relying on default outbound access, and note that Uniform-only behaviors such as overprovisioning do not apply.
Uniform is still supported and fine for existing large stateless fleets, but a greenfield design should start with Flexible.
Take quiz
Uniform
Flexible
Classic
Manual
Overprovisioning
A single placement group of 100
Explicit outbound connectivity
A Basic load balancer only
41. How does automatic OS image upgrade work?
Automatic OS image upgrade lets the scale set replace each instance's OS disk with the newest published image version, in rolling batches and without you doing anything.
- A new version of the image is published (Marketplace or Compute Gallery).
- Azure checks the scale set is healthy, then upgrades a batch (20 percent by default).
- It waits for the batch to report healthy through the Application Health extension or load balancer probes.
- It continues with the next batch, or stops if too many instances are unhealthy.
az vmss update -g rg-demo -n web-vmss --set upgradePolicy.automaticOSUpgradePolicy.enableAutomaticOSUpgrade=true
The image reference must use latest, and health monitoring is required. Data disks are preserved but OS disk contents are replaced, so keep instances stateless.
Take quiz
All at once
Only during a nightly maintenance window
In batches while checking health
One region at a time
A fixed pinned version
A local VHD
No image at all
A latest version
42. Explain the execution flow of a rolling upgrade?
In a rolling upgrade, Azure applies the new model to a small slice of the scale set at a time, checks that slice is healthy, and only then moves on.
flowchart TD
A["New model applied"] --> B["Pre-check: unhealthy % within limit?"]
B -->|No| X["Upgrade does not start"]
B -->|Yes| C["Split instances into batches"]
C --> D["Upgrade next batch"]
D --> E{Batch healthy?}
E -->|Yes| F["Wait pause time"]
F --> G{More batches?}
G -->|Yes| D
G -->|No| H["Upgrade complete"]
E -->|No, limit exceeded| I["Upgrade stops"]
| Setting | Default | Meaning |
| maxBatchInstancePercent | 20 | Share of instances upgraded per batch |
| maxUnhealthyInstancePercent | 20 | Max unhealthy in the whole scale set |
| maxUnhealthyUpgradedInstancePercent | 20 | Max unhealthy among already upgraded instances |
| pauseTimeBetweenBatches | PT0S | Wait between batches |
If a threshold is breached the upgrade stops and the rest stay on the old model. Fix the cause, then check progress with az vmss rolling-upgrade get-latest and restart or cancel with start or cancel. On zonal scale sets, zones are upgraded one after another.
Take quiz
5
50
100
20
The upgrade stops
It continues faster
It switches to Automatic policy
The scale set is deleted
43. Explain the lifecycle of an autoscale scale-out event?
A scale-out event moves from metric to decision to new VM to live traffic.
sequenceDiagram participant VM as Instances participant AM as Azure Monitor participant AS as Autoscale engine participant CP as Compute platform participant LB as Load balancer VM->>AM: Emit metrics (every minute) AS->>AM: Read metric over look-back window AS->>AS: Rule true, cooldown over, below max? AS->>CP: Increase capacity by N CP->>VM: Create instances from model VM->>VM: Boot, run extensions or cloud-init LB->>VM: Health probe LB-->>VM: Add to rotation when healthy AS->>AS: Start cooldown, log action
- Metrics are aggregated across instances over the rule's window.
- If the condition is true, the cooldown has passed and the max count is not reached, autoscale raises capacity.
- Compute creates the VMs from the model, subject to quota and capacity.
- Each VM boots and runs its setup, and the health probe or extension marks it healthy.
- The load balancer starts sending it traffic and the cooldown timer protects against another action too soon.
Delays add up: metric lag, the look-back window, VM boot and warm-up. That is why a custom image and a sensible cooldown matter for spiky traffic.
Take quiz
Autoscale asks the compute platform to raise capacity
Instances are reimaged
The load balancer is deleted
The image is regenerated
Autoscale tags it blue
It passes the health probe
Its disk finishes encrypting
It is assigned a public IP
44. How do you troubleshoot autoscale that is not triggering?
Work through the usual causes in order, starting with the settings and moving to the data.
- Setting state: confirm autoscale is enabled and the right profile is active (a schedule or fixed-date profile may override the default).
- Bounds: check whether the scale set is already at its maximum, or at its minimum for scale-in.
- Metric source: confirm the rule points at this scale set and the metric is actually flowing. Guest metrics such as memory need an agent.
- Aggregation: the metric is averaged across instances over the look-back window, so one hot VM may not cross the threshold.
- Cooldown: a recent action may still be blocking another.
- Flapping protection: autoscale skips a scale-in if the smaller fleet would immediately breach the scale-out rule.
- Failures: quota or capacity errors stop the action even when the rule fires.
az monitor autoscale show -g rg-demo -n web-autoscale az monitor metrics list --resource <vmss-id> --metric "Percentage CPU" --interval PT1M
Then read the Activity Log and the autoscale diagnostic logs (evaluation and scale-action logs), which state why each rule did or did not act.
Take quiz
Too many fault domains
The scale set is already at its maximum count
The OS disk is ephemeral
The image version is set to latest
Too many zones
A Basic load balancer
No agent is publishing guest metrics
Spot eviction
45. What happens when scale-out exceeds your vCPU quota?
The scale-out fails. Azure returns a quota error (for example QuotaExceeded or a message about exceeding the approved regional cores), the scale set stays at its current size, and autoscale retries on a later evaluation.
Quotas apply at two levels: total regional vCPUs and per VM family vCPUs, and Spot has its own quota. Hitting either one blocks new instances.
| Error type | Cause | Fix |
| Quota exceeded | Subscription limit reached | Request a quota increase |
| Allocation failure | Region or zone has no capacity for that SKU | Try another size, zone or region; use Capacity Reservation |
az vm list-usage -l eastus -o table
Prevent surprises by alerting at around 80 percent of quota and by keeping quota above your autoscale maximum, including the extra headroom a zone failure would need. Overprovisioned extras in Uniform mode do not count toward quota.
Take quiz
Image not found
Invalid SSH key
QuotaExceeded on regional or VM family vCPUs
Probe failure
Raising the vCPU quota by itself
Reducing license costs
Changing orchestration mode
Guaranteeing compute capacity in a zone
46. How do you handle graceful shutdown during scale-in?
Use the scale set's terminate notification. It sends a Terminate Scheduled Event to the instance before deletion, so your app can drain connections, finish work and deregister.
"scheduledEventsProfile": { "terminateNotificationProfile": { "notBeforeTimeout": "PT10M", "enable": true } }
The delay can be between 5 and 15 minutes. Inside the VM, poll the metadata service and react when a Terminate event appears:
curl -s -H "Metadata:true" \ "http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01"
- Fail the health endpoint so the load balancer stops sending new requests.
- Finish in-flight requests or jobs and flush buffers.
- Optionally approve the event early so Azure proceeds right away.
For long jobs that cannot be interrupted, combine this with instance protection. Spot evictions use a similar Preempt event, but with only about 30 seconds of notice.
Take quiz
Freeze
Reboot
Redeploy
Terminate
5 to 15 minutes
30 seconds
1 hour
24 hours
47. How can you design zero-downtime deployments with scale sets?
Zero downtime comes from never taking all healthy capacity out at once and from being able to switch back quickly. There are three common patterns.
| Pattern | How it works | Rollback | Cost |
| Rolling upgrade | Upgrade in small batches with health checks | Slower, re-roll the old image | Lowest |
| Blue-green | Build a second scale set, then switch the backend pool or DNS | Fastest, switch back | Double capacity for a while |
| Canary | Send a small share of traffic to the new scale set via Application Gateway, Front Door or Traffic Manager | Fast, drop the canary | Slightly above normal |
Whichever you pick, a few basics must be in place:
- At least two instances, ideally across zones, plus spare capacity during the rollout.
- Reliable health signals (Application Health extension or probes).
- Immutable images from a Compute Gallery so every version is reproducible.
- Graceful drain on shutdown using terminate notifications.
- Backward-compatible database changes so old and new versions can run together.
Rolling is the simplest default. Use blue-green when rollback speed matters more than the extra cost.
Take quiz
Blue-green by switching traffic back
Rolling upgrade
In-place patching
Manual reimage of every instance
A single instance
Health signals and at least two instances
Spot priority
Ephemeral disks
48. How can you optimize scale set costs?
Match capacity to demand first, then lower the price of the capacity you do keep.
| Lever | Saving | Trade-off |
| Autoscale with real scale-in rules | Stops paying for idle instances | Needs tuned thresholds and cooldown |
| Schedule profiles | Low minimum overnight and weekends | Must match real traffic |
| Right-size the SKU | Removes unused CPU and RAM | Needs metric review |
| Spot VMs or Spot Priority Mix | Large discount on interruptible capacity | Evictions |
| Reserved Instances or Savings Plans | Discount on the steady baseline | Commitment |
| Azure Hybrid Benefit | Reuse existing licenses | License eligibility |
| Ephemeral OS disks | No OS disk cost | Stateless only |
| Arm-based sizes (Linux) | Better price per performance | App must support Arm |
Also clean up unattached disks and unused scale sets, remember that deallocated VMs still pay for disks, and review outbound data transfer. Use Cost Management with tags to see what each scale set really costs.
Take quiz
A longer cooldown
Reserved Instances or Savings Plans
More fault domains
A public IP on every VM
To increase quota
To create zones
To release capacity when demand is predictably low
To rotate keys
49. How do you secure a scale set?
Apply security at the network, identity, host and operations layers.
- Network: no public IP per instance, NSGs on the subnet, and a load balancer or Application Gateway with WAF as the only entry point.
- Admin access: Azure Bastion or just-in-time access instead of open RDP or SSH NAT rules; SSH keys instead of passwords.
- Identity: managed identities with least-privilege RBAC; secrets from Key Vault, not custom data or scripts.
- Host: Trusted Launch (secure boot and vTPM), encryption at host or disk encryption.
- Patching: automatic OS image upgrades or guest patching so instances stay current.
- Governance: Azure Policy to enforce settings and Microsoft Defender for Cloud for posture and threat detection.
Because instances are disposable, the best fix for a compromised or drifted VM is to delete it and let the scale set replace it from a clean, signed image.
Take quiz
A public IP on every VM
Disabling NSGs
Azure Bastion
A shared admin password
Ephemeral OS disks
Proximity placement groups
Instance protection
Trusted Launch
50. How do you deploy a scale set with Bicep?
Declare a Microsoft.Compute/virtualMachineScaleSets resource and set orchestrationMode to 'Flexible'. This minimal example creates three Linux instances in an existing subnet.
param location string = resourceGroup().location param subnetId string @secure() param adminSshKey string resource vmss 'Microsoft.Compute/virtualMachineScaleSets@2024-07-01' = { name: 'web-vmss' location: location sku: { name: 'Standard_D2s_v5' capacity: 3 } properties: { orchestrationMode: 'Flexible' platformFaultDomainCount: 1 virtualMachineProfile: { osProfile: { computerNamePrefix: 'web' adminUsername: 'azureuser' linuxConfiguration: { disablePasswordAuthentication: true ssh: { publicKeys: [ { path: '/home/azureuser/.ssh/authorized_keys' keyData: adminSshKey } ] } } } storageProfile: { imageReference: { publisher: 'Canonical' offer: '0001-com-ubuntu-server-jammy' sku: '22_04-lts-gen2' version: 'latest' } osDisk: { createOption: 'FromImage' managedDisk: { storageAccountType: 'Premium_LRS' } } } networkProfile: { networkApiVersion: '2020-11-01' networkInterfaceConfigurations: [ { name: 'nic' properties: { primary: true ipConfigurations: [ { name: 'ipconfig' properties: { subnet: { id: subnetId } } } ] } } ] } } } }
Flexible mode needs networkApiVersion: '2020-11-01' in the network profile. Add zones: ['1','2','3'] at the resource level to spread across zones, and a load balancer backend pool reference in the IP configuration to receive traffic.
az deployment group what-if -g rg-demo -f vmss.bicep --parameters subnetId=<id> adminSshKey="$(cat ~/.ssh/id_rsa.pub)" az deployment group create -g rg-demo -f vmss.bicep --parameters subnetId=<id> adminSshKey="$(cat ~/.ssh/id_rsa.pub)"
Run what-if first to preview changes without deploying, then create. Keep the file in source control so scale set changes are reviewed like application code.