TL;DR: Replace the Kubernetes Cluster Autoscaler with Karpenter so it can provision discounted AWS Spot Instances that fit your Node.js pods. With diversified multi-architecture NodePools, an SQS interruption queue for 2-minute Spot warnings, graceful shutdown and Pod Disruption Budgets, stateless services can run on Spot with large compute savings. AWS quotes Spot discounts of up to 90% versus On-Demand; your actual saving depends on how much of the fleet can move to Spot and how well pods bin-pack.
Key Takeaways
- Query your cluster with
kubectl get nodes -l eks.amazonaws.com/capacityType=ON_DEMANDto identify wasted compute and poor bin-packing in legacy static ASGs. - Deploy Karpenter v1 (chart version
1.15.1at the time of writing) via Helm and setsettings.interruptionQueueto an SQS queue that receives EventBridge Spot Interruption Warnings, giving a 2-minute window to drain pods. - Define a
karpenter.sh/v1NodePoolwithkarpenter.sh/capacity-type: ["spot"]and anodeClassRefto anEC2NodeClassso Karpenter provisions Spot capacity just in time. - Maximize Spot capacity pool availability by allowing both
amd64andarm64architectures alongside a broad mix of instance families (e.g.,c5,m6g,t4g). - Set
consolidationPolicy: WhenEmptyOrUnderutilizedwith aconsolidateAfterdelay so Karpenter removes empty nodes and replaces underutilized ones with cheaper, better-fitting nodes.
If your AWS EKS bill grows in step with your traffic peaks, you are probably paying for idle compute. You have dozens of Node.js microservices deployed, but to handle traffic spikes and ensure high availability, your engineering team has consistently over-provisioned On-Demand EC2 instances.
The traditional Kubernetes Cluster Autoscaler (CAS) is failing you. It operates by adjusting the desired capacity of AWS Auto Scaling Groups (ASGs). Because ASGs are statically configured to specific instance families, CAS cannot dynamically provision the cheapest or best-fitting compute for your workloads. If a single Node.js pod requires 500m of CPU and the only available ASG spins up m5.xlarge instances, you are paying for an entire instance just to host a tiny fraction of a workload.
We fix this by removing the Cluster Autoscaler, bypassing ASGs, and introducing Karpenter alongside Spot Instances and Pod Disruption Budgets (PDB).
This combination lets stateless Node.js workloads run on Spot capacity, which AWS prices at up to 90% below On-Demand, while keeping enough replicas healthy through interruptions. The rest of this guide walks through each layer. If you want help applying it to your own cluster, see our AWS DevOps and Kubernetes deployment services.
The Bottleneck of Legacy Cluster Autoscaling
The Cluster Autoscaler evaluates pending pods and increases the size of a node group whose instance template can fit them. It does not pick instance types per pod based on price or Spot capacity; that choice was made when the node group was defined.
You can get a first view of waste by listing your On-Demand managed node group nodes and comparing their allocated resources to their capacity.
# Check the age and instance type of your On-Demand nodes
kubectl get nodes -l eks.amazonaws.com/capacityType=ON_DEMAND \
-o custom-columns=NAME:.metadata.name,INSTANCE:.metadata.labels."node\.kubernetes\.io/instance-type",AGE:.metadata.creationTimestamp
# View allocated resources versus total node capacity
kubectl describe nodes | grep -A 2 -e "^Allocated resources"
If your nodes have been running for weeks and are sitting at 30% memory utilization, you are paying for capacity you do not use. Each Node.js process runs JavaScript on a single main thread, so services are usually scaled horizontally with many small replicas, which suits tightly packed, dynamically provisioned nodes better than fixed node groups.
Deploying Karpenter for Just-in-Time Compute
Karpenter is an open-source node provisioner that watches unschedulable pods, computes which instance types can fit them, and launches capacity through the EC2 Fleet API, typically within a minute or so rather than waiting on node group scaling.
Before installing, create the Karpenter controller IAM role (via EKS Pod Identity or IRSA), the node IAM role, and the SQS interruption queue with its EventBridge rules. The Karpenter getting-started guide ships a CloudFormation template for these. Then deploy Karpenter via Helm. Pin the chart version; it no longer uses a v prefix:
# Upgrade or install Karpenter using the AWS OCI registry
helm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter \
--version "1.15.1" \
--namespace kube-system \
--set "settings.clusterName=${CLUSTER_NAME}" \
--set "settings.interruptionQueue=${CLUSTER_NAME}" \
--wait
Production Note: The
interruptionQueuesetting matters for running Spot safely. It points Karpenter at an SQS queue that EventBridge rules feed with Spot Interruption Warnings, rebalance recommendations and instance state changes. On a warning, Karpenter taints and drains the node and starts a replacement, using the roughly 2-minute notice before AWS reclaims the instance. If you use IRSA instead of EKS Pod Identity, also setserviceAccount.annotations."eks\.amazonaws\.com/role-arn"to the controller role ARN.
Architecting Spot-First NodePools
With Karpenter installed, configure a NodePool (the v1 replacement for the old Provisioner). A NodePool defines the constraints for the compute Karpenter may launch, and it references an EC2NodeClass that holds AWS-specific settings such as the AMI, subnets, security groups and node role.
To push most compute onto Spot, configure a Spot NodePool. By allowing a broad set of instance families (for example c5, m5, r5 and their ARM64 Graviton equivalents), Karpenter can use the price-capacity-optimized allocation strategy to pick Spot pools that are both cheap and less likely to be interrupted.
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: spot-compute
spec:
template:
spec:
nodeClassRef:
group: karpenter.k8s.aws
kind: EC2NodeClass
name: default
expireAfter: 720h
requirements:
# Only launch Spot capacity from this NodePool
- key: karpenter.sh/capacity-type
operator: In
values: ['spot']
# Allow multi-architecture flexibility for maximum availability
- key: kubernetes.io/arch
operator: In
values: ['amd64', 'arm64']
# A broad list of instance families widens the Spot pools available
- key: karpenter.k8s.aws/instance-family
operator: In
values: ['c5', 'c6g', 'm5', 'm6g', 'r5', 'r6g', 't3', 't4g']
# Remove empty nodes and replace underutilized ones with cheaper nodes
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
consolidateAfter: 5m
budgets:
# Disrupt at most 10% of this NodePool's nodes at a time
- nodes: '10%'
Supplying both amd64 and arm64 architectures reduces the risk of having no Spot capacity available. If m5 Spot capacity is unavailable in us-east-1a, Karpenter can launch m6g (Graviton) instances instead. For critical services, add a second NodePool that allows on-demand as a fallback, or allow both capacity types in one NodePool; Karpenter prefers Spot when both are allowed.
Tip: Ensure your Docker images are built using multi-architecture manifests (
docker buildx) so your Node.js apps run natively on both x86 and Graviton nodes. An amd64-only image scheduled on an arm64 node fails with anexec format error.
Graceful Termination: Handling Spot Interruptions in Node.js
On Spot, AWS will eventually reclaim some of your nodes. When it does, AWS sends a 2-minute interruption notice. Karpenter receives it from the SQS queue, taints the node and evicts its pods, and the kubelet sends SIGTERM to each container.
If your Node.js service ignores SIGTERM, Kubernetes kills it with SIGKILL after terminationGracePeriodSeconds (30 seconds by default). In-flight requests are cut off, which shows up as 502 errors at the load balancer and interrupted database work.
Your Express server should catch the signal, stop accepting new connections, let in-flight requests finish, close database pools, and force an exit if that takes too long. Keep the total well under the grace period and the 2-minute Spot notice.
import express from 'express';
import { dbPool } from './database.js';
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/health', (req, res) => res.status(200).send('OK'));
const server = app.listen(PORT, () => {
console.log(`Node.js microservice listening on port ${PORT}`);
});
// Graceful shutdown sequence
const shutdown = (signal) => {
console.log(`${signal} received. Initiating graceful shutdown...`);
// Force exit if draining takes longer than 25s (grace period is 30s)
setTimeout(() => process.exit(1), 25_000).unref();
server.close(async (err) => {
if (err) {
console.error('Error closing HTTP server:', err);
process.exit(1);
}
console.log('HTTP server closed. No longer accepting new connections.');
try {
await dbPool.end(); // Cleanly close PostgreSQL/MySQL connections
console.log('Database connections closed.');
process.exit(0);
} catch (dbErr) {
console.error('Error closing database connections:', dbErr);
process.exit(1);
}
});
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
Kubernetes sends SIGTERM to PID 1 in the container. If PID 1 is npm start or a shell wrapper, the signal may never reach the Node.js process, and the container is killed when the grace period runs out. Start node directly, or use a small init such as dumb-init or tini that runs as PID 1, forwards signals to Node and reaps zombie processes:
FROM node:24-alpine
RUN apk add --no-cache dumb-init
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
# dumb-init forwards signals directly to the Node process
CMD ["dumb-init", "node", "server.js"]
Also add a short preStop hook (for example sleep 5) so the load balancer and kube-proxy stop routing to the pod before the app begins closing connections.
Protecting Uptime with Pod Disruption Budgets
A graceful shutdown handles in-flight requests, but what if Karpenter provisions a large r5.4xlarge Spot instance and the scheduler packs all 10 replicas of your authentication service onto that single node?
If that node gets interrupted, your entire authentication layer goes offline simultaneously.
To limit this, define a Pod Disruption Budget (PDB). A PDB tells the eviction API how many pods (or what percentage) must stay available during voluntary disruptions, such as Karpenter consolidating or draining a node.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: auth-service-pdb
namespace: microservices
spec:
# Keep at least 50% of replicas available during evictions
minAvailable: 50%
selector:
matchLabels:
app: auth-service
Karpenter drains nodes through the eviction API, so it honors PDBs. For consolidation this works well: if evicting a pod would drop available replicas below 50%, the eviction is rejected and Karpenter waits or picks another node. A Spot interruption is different. AWS reclaims the instance after about 2 minutes whether or not the PDB allows eviction, so the PDB can only slow the drain, not prevent pod loss. That is why spreading replicas across nodes and zones (next section) matters more for Spot than the PDB itself.
Enforcing High Availability with Topology Spread Constraints
To stop all replicas landing on a single node in the first place, tell the scheduler to distribute pods across nodes and Availability Zones.
This is achieved using Topology Spread Constraints. Karpenter takes these constraints into account when it provisions, so it launches capacity in several zones and nodes rather than one large instance.
apiVersion: apps/v1
kind: Deployment
metadata:
name: auth-service
spec:
replicas: 6
selector:
matchLabels:
app: auth-service
template:
metadata:
labels:
app: auth-service
spec:
topologySpreadConstraints:
# Do not allow more than 1 pod difference across nodes
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app: auth-service
# Spread evenly across Availability Zones
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: auth-service
containers:
- name: auth-node
image: my-registry/auth-service:v1.2.3
With this configuration, if Spot nodes in us-east-1a are reclaimed, replicas in us-east-1b and us-east-1c keep serving traffic while Karpenter replaces the lost capacity. Make sure the remaining replicas have enough headroom to absorb that load.
Right-Sizing Node.js Resource Requests
Karpenter sizes nodes from the CPU and memory requests of pending pods. If requests are missing or copied from another service, Karpenter provisions for the wrong shape and you either waste capacity or get pods throttled and OOM-killed.
A Node.js process runs JavaScript on one main thread but also uses libuv and V8 helper threads (for example for garbage collection), so short bursts above the request are normal. A tight CPU limit causes CFS throttling during those bursts and raises tail latency. A common approach is to set accurate CPU requests and memory requests and limits, and leave the CPU limit unset, relying on requests for fair sharing. Teams that need hard per-tenant CPU isolation may still choose limits.
resources:
requests:
# Tell Karpenter exactly what we need to schedule
cpu: '250m'
memory: '512Mi'
limits:
# Prevent memory leaks from taking down the node
memory: '1Gi'
# NO CPU LIMIT - prevents artificial CFS throttling
With a 250m CPU request, a node with 4 vCPUs could in theory hold 16 such pods, but allocatable CPU is lower after kubelet and system reservations and DaemonSets, so expect roughly 13 to 14 on a t3.xlarge. Note that t3 and t4g are burstable types that rely on CPU credits; for sustained load, prefer c or m families.
Measuring the FinOps Impact
Measure before and after. Tag Karpenter nodes (the EC2NodeClass can add tags) and compare EC2 spend in AWS Cost Explorer for the weeks before and after the migration. The saving you see depends on how much of the fleet moved from On-Demand to Spot, the Spot prices in your Regions and instance families, and how much idle capacity consolidation removes. A 60% reduction in compute spend is achievable for fleets that were mostly over-provisioned On-Demand, but it is not guaranteed.
You can watch Karpenter's disruption decisions through Kubernetes events and the controller logs:
# Watch Karpenter disruption decisions (consolidation, drift, interruption)
kubectl logs -f -n kube-system -l app.kubernetes.io/name=karpenter | grep -i "disrupting"
# See why a node could not be consolidated (for example a blocking PDB)
kubectl get events -A --field-selector reason=Unconsolidatable
When consolidation runs you will see Karpenter decide to delete empty nodes or replace several underutilized nodes with a cheaper one, then launch the replacement and drain the old nodes.
Moving to Spot instances on Kubernetes does not have to cost reliability. Karpenter's provisioning and consolidation, graceful Node.js shutdown, Pod Disruption Budgets and topology spread together let stateless APIs run on much cheaper capacity. Keep stateful workloads and anything that cannot tolerate a 2-minute notice on On-Demand nodes.
Sources
- Karpenter documentation: NodePools (
karpenter.sh/v1schema,nodeClassRef,consolidationPolicyvalues) - Karpenter documentation: Disruption (consolidation, interruption handling, PDB behavior)
- Karpenter documentation: Getting Started (Helm install,
settings.interruptionQueue) - Kubernetes documentation: Specifying a Disruption Budget
- Amazon EC2 Spot Instances (Spot pricing, up to 90% below On-Demand)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why use Karpenter instead of Cluster Autoscaler?
Cluster Autoscaler scales fixed node groups, so you pay for whatever instance types those groups define. Karpenter provisions nodes directly from pending pod requirements and can choose from many instance types, which packs pods more tightly and makes Spot capacity easier to use.
Are Spot Instances safe for production Node.js services?
Yes, for stateless services that run several replicas. Spot capacity can be reclaimed with a two-minute warning, so spread replicas across instance types and zones, and keep a share of On-Demand capacity for critical workloads.
How should a Node.js service handle a Spot interruption?
Handle SIGTERM: stop accepting new requests, let in-flight requests finish, close database connections, and exit before the grace period ends. Kubernetes and the load balancer then move traffic to other pods without errors.
What do Pod Disruption Budgets protect against?
They stop voluntary disruptions, such as node consolidation or draining, from taking down too many replicas of a service at once. Combine them with topology spread constraints so replicas are not all placed on the same node or zone.
