惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works
The Practica · 2023-09-15 · via The Practical Developer

The team’s API has an HPA configured to scale at 80% CPU. Traffic doubles. Pods do not scale up. Latency goes up, customers complain. The reason: the workload is I/O-bound, CPU never crosses 50%, but the request rate has doubled, and CPU was a poor proxy for “we need more pods.”

The default-CPU HPA is a relic. Most modern workloads (Node.js APIs, Python web apps, queue consumers) are not CPU-bound. They are I/O-bound, queue-bound, or memory-bound. Scaling on CPU misses the actual signal. Custom metrics (request rate, queue depth, p95 latency) are what should drive scaling.

This post is the working setup for a custom-metric HPA, the formula HPA uses internally (so you can predict what it does), and the four mistakes that cause autoscaler flap.

The HPA formula

For any metric m, HPA computes:

desiredReplicas = ceil(currentReplicas * (currentMetric / targetMetric))

CPU example: 4 pods, current avg CPU 80%, target 50%:

desiredReplicas = ceil(4 * (80/50)) = ceil(6.4) = 7

The formula is identical for any metric. Pick a metric that linearly correlates with load and a target that represents “we want each pod to be at this utilization.” Then HPA does the math.

The right metric for the workload

A few common workloads and the right scaling metric:

HTTP API, light per-request work. Scale on requests per second per pod. Each pod handles roughly the same RPS at saturation; doubling RPS means double the pods. CPU is a poor proxy because Node’s event loop is happy at low CPU.

Queue consumer. Scale on queue depth. Backlog = need more workers. CPU is irrelevant.

Memory-heavy app (Java, Python with large in-memory state). Scale on memory utilization or GC pause time.

WebSocket / long-lived connection server. Scale on active connections per pod.

Latency-sensitive API. Scale on p95 latency. When latency rises, add capacity. (Be careful; this can mask underlying problems.)

For most teams, the right combination is “RPS per pod” plus a memory ceiling.

Wiring up custom metrics

Out of the box, HPA can use CPU and memory. For anything else, you need a metrics adapter. The standard combo: Prometheus for collection, Prometheus Adapter for exposure to the metrics API, HPA reading from the metrics API.

# prometheus-adapter ConfigMap (excerpt)
rules:
- seriesQuery: 'http_requests_total{namespace!="", pod!=""}'
  resources:
    overrides:
      namespace: { resource: "namespace" }
      pod:       { resource: "pod" }
  name:
    matches: "^(.*)_total$"
    as: "${1}_per_second"
  metricsQuery: |
    sum(rate(<<.Series>>{<<.LabelMatchers>>}[1m])) by (<<.GroupBy>>)

This exposes http_requests_per_second as a per-pod metric the HPA can read. Then:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 3
  maxReplicas: 50
  metrics:
  - type: Pods
    pods:
      metric: { name: http_requests_per_second }
      target:
        type: AverageValue
        averageValue: "100"           # target 100 RPS per pod
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300  # don't scale down for 5min after a peak
      policies:
      - type: Percent
        value: 25
        periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
      - type: Percent
        value: 100
        periodSeconds: 30                # double quickly if needed
      - type: Pods
        value: 5
        periodSeconds: 30
      selectPolicy: Max

The two metrics: scale up on RPS-per-pod (primary signal), scale up also on memory utilization (safety net). The behavior block tunes how aggressively each direction reacts.

The four mistakes that cause flap

1. Target too tight. Setting averageValue: 50 when the steady-state is 60 means HPA tries to scale up by 20% constantly. Pick a target that represents peak healthy utilization, with headroom, typically 70-80% of the saturation point.

2. No stabilization window. Default scaleDownStabilizationWindow is 300s for a reason. Without it, a brief traffic dip causes scale-down, and the next spike causes a scramble. Keep it ≥5 minutes for scale-down. Scale-up can be 0.

3. Scaling on a noisy metric. A 1-minute average of latency is noisy at low traffic. Use a longer window or scale on a steadier metric (RPS).

4. Scaling on a metric the application controls. Scaling on cpu while the app is yielding to event loop is a circular dependency. The metric is high because the pod is busy, but adding pods doesn’t reduce per-pod CPU if the bottleneck is elsewhere (database, downstream API). Pick metrics that represent demand, not internal state.

The KEDA alternative

KEDA is a CRD that wraps HPA with a richer set of scalers: Kafka, RabbitMQ, AWS SQS, Redis, Prometheus, cron, even Postgres. For queue-based workloads it is much simpler than wiring up Prometheus Adapter.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: queue-worker
spec:
  scaleTargetRef:
    name: queue-worker
  minReplicaCount: 1
  maxReplicaCount: 30
  triggers:
  - type: aws-sqs-queue
    metadata:
      queueURL: https://sqs.us-east-1.amazonaws.com/.../my-queue
      queueLength: "10"     # target 10 messages per replica

For “scale workers based on queue depth,” KEDA in 10 lines, vs Prometheus Adapter and custom metrics setup. Strong default for queue-driven systems.

Vertical Pod Autoscaler: the other dimension

HPA scales horizontally (more pods). VPA scales vertically (resize pods). They are not interchangeable; VPA evicts and restarts pods to resize them, which is disruptive.

VPA is most useful in recommendation mode: it watches usage, suggests right-sized requests/limits, but you apply them at deploy time. This is dramatically better than guessing.

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: api
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  updatePolicy:
    updateMode: "Off"   # recommendations only

kubectl describe vpa api after a few days shows recommended CPU and memory. Apply, redeploy. Free right-sizing.

Cluster autoscaler: the layer above

HPA decides how many pods. The cluster autoscaler decides how many nodes. For full elasticity, both need to be on. Make sure your cluster has scaling configured (managed Kubernetes services typically handle this).

Watch for: pods stuck pending because no node has room. That is a cluster-autoscaler issue, not an HPA issue.

Monitoring the autoscaler itself

Three signals to watch:

  • kube_horizontalpodautoscaler_status_current_replicas: how many pods HPA actually has.
  • kube_horizontalpodautoscaler_status_desired_replicas: how many it wants.
  • kube_horizontalpodautoscaler_status_condition{condition="ScalingLimited"}: HPA is at min or max and cannot adjust.

If desired > current for more than a minute, HPA is asking for more capacity than the cluster can give, usually a node-pool issue.

Common-sense limits

Always set:

  • minReplicas ≥ 2 for production. Single-pod services cannot survive any disruption.
  • maxReplicas sane (10× minReplicas is a reasonable starting point). Without it, a runaway metric can spawn 1000 pods and burn money.
  • PodDisruptionBudget alongside HPA so voluntary disruptions (node drains) respect minimums. (See: PDB post once published.)

The takeaway

Default-CPU HPA is the wrong choice for most modern workloads. Pick metrics that represent demand: RPS, queue depth, active connections. Use KEDA for queue-driven systems. Tune the behavior block to prevent flap. Set min/max sanely. Test in staging by simulating load.

The next time the team is debugging “why didn’t the HPA scale,” the question is “what metric is it scaling on?” Nine times out of ten, the answer is “CPU, and that is not the right signal.”


A note from Yojji

The kind of platform-engineering judgment that picks the right autoscaling metric, and prevents the “we have 50 pods but the dashboard says we still need more” flap, is the kind of detail Yojji’s DevOps and platform engineers build into the Kubernetes deployments they ship for clients.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. They specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and Kubernetes operations, including the autoscaling and capacity-planning work that decides whether a service stays up under load.