Your auto-scaler is wired to “add a node when CPU > 75% for 5 minutes.” A flash sale starts. CPU climbs to 70% — not over the threshold. Queue depth in your job worker grows from 200 to 9,800 in eight minutes. P95 latency on the checkout endpoint goes from 380 ms to 4.2 s. The auto-scaler does nothing, because by its definition nothing is wrong. The CEO emails you a screenshot of the checkout page at 6:14 PM. The metric you scaled on was not the metric that mattered.
What’s happening
CPU% is the easiest auto-scaling signal to wire up — every PaaS exposes it, every monitoring stack graphs it — and it’s almost always the wrong one for application-tier scaling decisions. The reasons stack:
- CPU% is a lagging indicator. By the time a Node.js process is at 85% CPU, the event loop is already starved and queueing has started. The latency users feel started ramping ten seconds before CPU caught up.
- CPU% averages over the wrong thing. On a four-cloudlet container, two pegged threads can look like 50% CPU. The system is half-saturated by the dashboard and fully saturated for the workload.
- CPU% is decoupled from the unit of work. A request that hits a cache returns in 4 ms with 0.1% CPU. A request that does an AI inference takes 12 s with 100% CPU. Averaging them across a five-minute window produces a number that means nothing to anyone.
The metrics that map to business reality are domain-specific. For a request/response app: P95 (or P99) latency on the customer-facing endpoint. For a queue-driven worker: queue depth and oldest message age. For batch processing: lag from now to last processed timestamp. These are what you want the auto-scaler reading.
Jelastic doesn’t ship custom-metric auto-scaling out of the box, but it exposes a JSON-RPC API that lets you implement it cleanly: a small scaler process reads Prometheus, decides, and calls the Jelastic API to add or remove nodes.
How to verify
Confirm the metric you want to scale on is being scraped and is responsive:
# Queue depth (RabbitMQ example)
curl -s -u admin:pass http://rabbit:15672/api/queues/%2f/orders \
| jq '.messages_ready'
# Oldest message age (seconds)
curl -s http://prom:9090/api/v1/query \
--data-urlencode 'query=time() - min(rabbitmq_queue_head_message_timestamp{queue="orders"})' \
| jq '.data.result[0].value[1]'
# P95 latency from a histogram exporter
curl -s http://prom:9090/api/v1/query \
--data-urlencode 'query=histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{route="/checkout"}[2m])))' \
| jq '.data.result[0].value[1]'
If any of these don’t return a usable number, the auto-scaler has nothing to act on. Fix the metric pipeline before you wire the scaler.
The fix
A complete autoscaler that reads Prometheus, evaluates a rule, and drives the Jelastic API. Save as /opt/sh-autoscale/scaler.py and run it under systemd on a tiny utility node — or on the application node itself, as long as it has API credentials.
#!/usr/bin/env python3
"""
Custom-metric autoscaler for Jelastic PaaS.
Reads Prometheus, decides scale up / hold / scale down,
calls Jelastic JSON-RPC API.
"""
import os, sys, time, json, urllib.request, urllib.parse, logging
from datetime import datetime, timezone
# === Config (env-driven) ===
PROM_URL = os.environ["PROM_URL"] # http://prom:9090
JEL_API = os.environ["JEL_API"] # https://app.paas.example.com
JEL_TOKEN = os.environ["JEL_TOKEN"] # personal access token
ENV_NAME = os.environ["ENV_NAME"] # env shortdomain
NODE_GROUP = os.environ.get("NODE_GROUP", "cp") # cp = compute / app
MIN_NODES = int(os.environ.get("MIN_NODES", "2"))
MAX_NODES = int(os.environ.get("MAX_NODES", "8"))
COOLDOWN_UP = int(os.environ.get("COOLDOWN_UP", "60")) # seconds
COOLDOWN_DOWN = int(os.environ.get("COOLDOWN_DOWN", "300")) # seconds — longer
INTERVAL = int(os.environ.get("INTERVAL", "20"))
# === Rules ===
# A rule is (name, query, scale_up_if, scale_down_if).
# We OR scale-up across rules; we AND scale-down across rules.
RULES = [
{
"name": "p95_checkout",
"query": 'histogram_quantile(0.95, sum by (le) '
'(rate(http_request_duration_seconds_bucket{route="/checkout"}[2m])))',
"scale_up_if": lambda v: v > 1.0, # P95 > 1 s
"scale_down_if": lambda v: v < 0.3, # P95 < 300 ms
},
{
"name": "orders_queue_depth",
"query": 'rabbitmq_queue_messages_ready{queue="orders"}',
"scale_up_if": lambda v: v > 500,
"scale_down_if": lambda v: v < 50,
},
{
"name": "orders_oldest_msg_age",
"query": 'time() - min(rabbitmq_queue_head_message_timestamp{queue="orders"})',
"scale_up_if": lambda v: v > 30, # oldest msg older than 30 s
"scale_down_if": lambda v: v < 5,
},
]
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("scaler")
_last_up = 0.0
_last_down = 0.0
def prom_query(q):
"""Return a single scalar from a Prometheus instant query, or None."""
url = f"{PROM_URL}/api/v1/query?{urllib.parse.urlencode({'query': q})}"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=5) as r:
data = json.load(r)
if data.get("status") != "success":
return None
result = data["data"]["result"]
if not result:
return None
try:
return float(result[0]["value"][1])
except (KeyError, IndexError, ValueError):
return None
def jel_call(method, params):
"""Call the Jelastic JSON-RPC API."""
payload = {"session": JEL_TOKEN, **params}
url = f"{JEL_API}/1.0/environment/control/rest/{method}"
body = urllib.parse.urlencode(payload).encode()
req = urllib.request.Request(url, data=body, method="POST")
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r)
def current_node_count():
res = jel_call("getenvinfo", {"envName": ENV_NAME})
nodes = res.get("nodes", [])
return sum(1 for n in nodes if n.get("nodeGroup") == NODE_GROUP)
def add_node():
log.info("scaling UP: adding 1 node in group %s", NODE_GROUP)
return jel_call("addnode",
{"envName": ENV_NAME, "nodeGroup": NODE_GROUP, "count": 1})
def remove_node():
log.info("scaling DOWN: removing 1 node in group %s", NODE_GROUP)
res = jel_call("getenvinfo", {"envName": ENV_NAME})
nodes = [n for n in res.get("nodes", []) if n.get("nodeGroup") == NODE_GROUP]
if len(nodes) <= MIN_NODES:
log.warning("at MIN_NODES, refusing scale-down")
return None
# remove the highest-numbered node (newest)
victim = sorted(nodes, key=lambda n: -n.get("id", 0))[0]
return jel_call("removenode",
{"envName": ENV_NAME, "nodeid": victim["id"]})
def decide():
"""Return 'up', 'down', or 'hold' based on current metrics."""
up_votes = []
down_votes = []
for rule in RULES:
v = prom_query(rule["query"])
if v is None:
log.warning("rule %s has no data; ignoring", rule["name"])
continue
log.info("rule %s = %.3f", rule["name"], v)
if rule["scale_up_if"](v):
up_votes.append(rule["name"])
elif rule["scale_down_if"](v):
down_votes.append(rule["name"])
if up_votes:
return "up", up_votes
# only scale down if EVERY rule with data votes down
rules_with_data = [r["name"] for r in RULES if prom_query(r["query"]) is not None]
if rules_with_data and set(rules_with_data) == set(down_votes):
return "down", down_votes
return "hold", []
def main():
global _last_up, _last_down
log.info("autoscaler starting: env=%s group=%s min=%d max=%d",
ENV_NAME, NODE_GROUP, MIN_NODES, MAX_NODES)
while True:
try:
decision, why = decide()
now = time.time()
count = current_node_count()
if decision == "up" and count < MAX_NODES \
and (now - _last_up) > COOLDOWN_UP \
and (now - _last_down) > COOLDOWN_UP:
add_node()
_last_up = now
elif decision == "down" and count > MIN_NODES \
and (now - _last_down) > COOLDOWN_DOWN \
and (now - _last_up) > COOLDOWN_DOWN:
remove_node()
_last_down = now
else:
log.info("decision=%s votes=%s nodes=%d (hold)",
decision, why, count)
except Exception as e:
log.exception("scaler iteration failed: %s", e)
time.sleep(INTERVAL)
if __name__ == "__main__":
main()
Systemd unit at /etc/systemd/system/sh-autoscale.service:
[Unit]
Description=Stack Harbor custom-metric autoscaler
After=network.target
[Service]
Type=simple
EnvironmentFile=/etc/sh-autoscale.env
ExecStart=/usr/bin/python3 /opt/sh-autoscale/scaler.py
Restart=on-failure
RestartSec=5s
User=scaler
Group=scaler
[Install]
WantedBy=multi-user.target
The environment file /etc/sh-autoscale.env holds the secrets and the rule parameters — never commit it:
PROM_URL=http://prom.internal:9090
JEL_API=https://app.paas.example.com
JEL_TOKEN=<personal access token>
ENV_NAME=acmeprod
NODE_GROUP=cp
MIN_NODES=2
MAX_NODES=8
COOLDOWN_UP=60
COOLDOWN_DOWN=300
INTERVAL=20
Three design rules baked in:
- Multiple rules, asymmetric voting. Any rule can trigger scale-up; scale-down requires every rule with data to agree. Errs on the side of being a node up rather than a node short.
- Asymmetric cooldowns. Scale-up cooldown is short (60 s) because lateness costs revenue. Scale-down cooldown is long (300 s) because flapping costs warmup latency on every new node. We cover the math in detail in the scale-down hysteresis article.
- Floor and ceiling are non-negotiable.
MIN_NODES=2for production, always — single-node availability is not negotiable even if the metrics say “you could remove one.”MAX_NODESis the cost ceiling: better to alert a human than to scale to twenty nodes at 3 AM.
Wire your dashboards to plot “rule values vs decision over time” so you can audit why the scaler did what it did when you do the post-mortem next week.
For an auto-scaling pipeline that’s reading your domain metrics and not just CPU, our Cloud PaaS team builds the scaler against your stack and runs it under environment management. If you’d rather hand us the post-mortems too, start a scoping call.