In one published benchmark of six deep RL algorithms, a properly calibrated rule-based autoscaler won on cost across every workload tested. In a benchmark of six deep RL algorithms on replica control, a calibrated rule-based controller had the lowest cost on all six workloads and zero constraint violations on steady traffic. It trailed the best RL agents on bursty and flash patterns. Reinforcement learning in Python earns its engineering cost on unpredictable traffic, where a violation costs more than the resources, and in combinatorial, multi-resource decisions. This tutorial covers how to frame that control problem, deploy it with a fallback, and test whether it actually helped.
When does reinforcement learning beat a tuned autoscaler for inference control?
A reproducible benchmark for this question is RLScaleBench. It ran PPO, DQN, A2C (advantage actor-critic), SAC, TD3 and DDPG on Kubernetes-style replica control with matched [256,256] MLP networks, matched 50K-step training budgets and matched rewards. The baseline was a Horizontal Pod Autoscaler tuned to a 70% utilisation target, built to be a strong comparator rather than a strawman. On bursty traffic, PPO cut SLO violations by 54% compared with that baseline (13.7 against 30.0), but it cost 24% more. The authors put the practical consequence plainly: RL pays off where a constraint violation costs much more than the resources, and in cost-dominated settings the rule-based controller wins.
They give three reasons the tuned rule is hard to beat. In most production workloads, CPU utilisation is a strong, low-latency proxy for load. The 70% target leaves a built-in safety margin. And a rule trained on no distribution pays no “transfer tax” when the workload shifts. The rule’s cost advantage also has a mechanical explanation: HPA kept 2.0 to 3.0 replicas on average, against 2.7 to 3.8 for the RL agents.
Batch-size control tells a similar story. A 2026 study of policy-gradient batching found that a well-tuned static batching policy on a single GPU is already near-optimal under Poisson-like arrivals, with RL adding only +0.1% to +1.0%. In heterogeneous multi-GPU routing, the same agent learned to keep fast and slow requests apart, which removed head-of-line blocking. That gave a 48% improvement over the strongest heuristic (shortest-queue), with 60% higher throughput and 25% lower latency. The authors conclude that RL’s advantage is concentrated in multi-resource decisions, not single-resource temporal scheduling.
Results that show RL far ahead deserve a look at the baseline before anyone celebrates. An attention-LSTM PPO autoscaler (arXiv, 2026) held average latency within a 50 ms hard SLO for 98.8% of the run, against 43.5% for HPA. That HPA, though, used a static 50% CPU target and upstream defaults. Against KEDA, the gain was reliability rather than speed: similar latency with 75% fewer replica-steps and 59% less churn. In that study, RL’s lead was large against the default-configured HPA and narrowed to reliability against KEDA.
Decision table: rule-based controller or RL policy
| Situation | Start with | Why |
|---|---|---|
| Steady or gradually changing traffic, cost dominates | Calibrated rule (HPA at a sensible target, Ray Serve target_ongoing_requests) |
Lowest cost, no violations on steady traffic, no transfer tax |
| Bursty or flash traffic, a violation costs more than a replica | RL policy behind a fallback | Proactive scaling cut bursty violations by 54%, at 24% higher cost |
| Single-GPU dynamic batching, Poisson-like arrivals | Tuned static batching or AIMD | RL adds 0.1% to 1.0% |
| Routing across heterogeneous GPUs | RL candidate | 48% over the best heuristic in simulation |
| Many tenants on a serverless FaaS platform, each with its own controller | Multi-agent formulation | In one multi-tenant FaaS study, the state-of-the-art single-agent algorithm showed up to 4.6x worse tail-latency degradation and failed to converge |
| Traffic where one observation cannot tell jitter from a real shift | Add history or a recurrent policy | Single-step agents suffer “temporal blindness” |
Before training anything, we would ask whether the latency or cost problem sits in the serving path at all. Batching, routing and serving configuration are tuned below the model layer, and they often move cost and latency without replacing the model. An RL controller is one more lever at that layer. Profiling decides whether it is the right one.
Framing replica or batch control as state, action and reward
An inference controller is a Markov decision process: at each control step the agent observes a state, chooses an action from its policy and receives a reward. The design work is choosing those three things so the agent can learn something the rule cannot already do.
State. For replica control, candidate observations include the request rate, the current replica count, recent tail latency and queue depth. FIRM (OSDI 2020) went further and fed its agent resource utilisation, per-service and end-to-end latency distributions, and workload characteristics such as arrival rate and request mix. History matters because most real systems have delays in the state, the actuators or the reward. Hester and Stone put recent history into the state so the agent could learn the delay effects itself. In our minimal example below, that means including the previous step’s request rate, and in production, a short window.
Action. Keep the actions discrete when the actuator is discrete. RLScaleBench found discrete-action algorithms (PPO, DQN, A2C) beat continuous ones (SAC, TD3, DDPG) by one to two orders of magnitude on constraint violations. The cause is action-space mismatch: integer replica counts force continuous outputs into bins. Inside a bin, the reward gradient is near zero. At a bin edge, it jumps. Batch sizes are discrete too. BCEdge’s scheduler chose a pair (batch size, number of concurrent model instances) from a discrete action space.
The fixed-rule baseline for batching is worth knowing, because RL has to beat it. Clipper (NSDI 2017) defines the optimal batch size as the one that maximises throughput while batch latency stays under the SLO, and finds it with additive-increase, multiplicative-decrease (AIMD). It also caps batch size so the first queries in a batch are not delayed too long.
Designing a reward that trades tail latency against cost without hiding SLO breaches
The reward needs at least three terms: resource cost, an SLO penalty measured on the percentile the SLO is written in, and a stability penalty against flapping.
A policy that minimises cost without SLO awareness fails. In RLScaleBench, DDPG settled on a degenerate single-replica policy and scored the worst possible composite on every non-constant workload, which shows that cost minimisation without SLO awareness is not a viable strategy. Measure the SLO on the right statistic. Google’s SRE guidance gives percentile SLOs as examples, such as “99.9% of Get RPC calls will complete in less than 100 ms”. A reward built on mean latency can therefore look healthy while the tail breaches the target. Penalise breaches of p95 or p99 per step, as a separate term, so a breach cannot be averaged away.
Set the penalty threshold below the contractual SLO. The SRE book argues for a tighter internal SLO than the one advertised, so there is room to respond before users notice. A reward threshold works the same way.
A stability term guards against flapping. The attention-LSTM autoscaler combined a stability penalty with PPO’s smoothed updates. Its agent learned to size each response correctly and to hold capacity through a burst rather than retreat during short dips, which avoided the flapping typical of reactive control. The rule-based equivalent is the Kubernetes HPA stabilisation window, which restricts replica flapping when metrics fluctuate, plus a default 0.1 tolerance band inside which no scaling happens.
The ratio between the SLO penalty and the cost term is the business decision from the first section, written as code. A heavy breach penalty asks for the RL behaviour that pays off on bursty traffic. A light one hands the advantage back to the rule. Whatever weights you pick, report each reward component separately during evaluation. Real-world RL rewards are usually a balance of sub-goals, and a single scalar hides the trade-offs the policy is making.
Gymnasium, Stable-Baselines3 or RLlib: which Python RL framework fits?
The three are layers, not competitors: Gymnasium defines the environment API, and Stable-Baselines3 or RLlib trains against it.
| Library | Role | Fits when |
|---|---|---|
| Gymnasium | Maintained fork of OpenAI Gym; the standard API (reset, step) plus reference environments |
Always: your simulator or production wrapper implements this interface |
| Stable-Baselines3 | RL algorithm implementations; custom environments only need to follow the Gymnasium interface | One controller, a simulator on one machine, fast iteration |
| RLlib (Ray) | Production-level, scalable, fault-tolerant RL; each training iteration collects samples in parallel across EnvRunner actors | Multi-agent setups or external, TCP-connected environments |
Two further RLlib features bear on inference control. It supports multi-agent learning natively, with independent, shared-policy and adversarial modes, and its independent mode matches the multi-agent PPO design in the multi-tenant study. It can also connect to external, TCP-connected environments that run their own action inference, for example through ONNX. For a first single-controller prototype, SB3 is the shorter path. PPO in SB3 is meant to run mainly on the CPU when no CNN is involved. Policies that must run on the device itself face different constraints, which our guide to RL frameworks for on-device inference policies covers.
A reinforcement learning Python example: replica control with Gymnasium and SB3 PPO
This worked example trains PPO to add, hold or remove replicas against a latency target. The simulator uses the latency and cost model RLScaleBench calibrated against a real Kubernetes cluster: p95 = 50 + (QPS/replicas)^1.5 × 0.08 ms, an SLO of p95 < 500 ms, and a cost of $0.01 per replica per 15-second decision step. Our simplifications are assumptions, not findings: a sinusoidal base load with random bursts, no overload blow-up, and no cold-start delay.
import numpy as np
import gymnasium as gym
from gymnasium import spaces
from stable_baselines3 import PPO
from stable_baselines3.common.env_checker import check_env
class ReplicaEnv(gym.Env):
"""Replica controller over a calibrated p95 latency model (toy simulator)."""
def __init__(self, max_replicas=12, slo_ms=500.0, episode_len=240,
breach_weight=1.0, churn_weight=0.02):
super().__init__()
self.max_replicas = max_replicas
self.slo_ms = slo_ms
self.episode_len = episode_len
self.breach_weight = breach_weight
self.churn_weight = churn_weight
# 0 = remove a replica, 1 = hold, 2 = add a replica (discrete on purpose)
self.action_space = spaces.Discrete(3)
# [qps_now/1000, qps_prev/1000, replicas/max, p95/slo (clipped)]
self.observation_space = spaces.Box(low=0.0, high=np.inf,
shape=(4,), dtype=np.float32)
def _qps(self):
base = 900.0 + 500.0 * np.sin(2 * np.pi * self.t / 120)
if self.np_random.random() < 0.05: # occasional burst
base *= 2.5
return float(max(base, 1.0))
def _p95(self):
load = self.qps / self.replicas
return 50.0 + load ** 1.5 * 0.08
def _obs(self, p95):
return np.array([self.qps / 1000, self.prev_qps / 1000,
self.replicas / self.max_replicas,
min(p95 / self.slo_ms, 10.0)], dtype=np.float32)
def reset(self, seed=None, options=None):
super().reset(seed=seed) # seeds self.np_random
self.t = 0
self.replicas = 3
self.qps = self.prev_qps = self._qps()
return self._obs(self._p95()), {}
def step(self, action):
old = self.replicas
self.replicas = int(np.clip(old + int(action) - 1, 1, self.max_replicas))
self.t += 1
self.prev_qps, self.qps = self.qps, self._qps()
p95 = self._p95()
breach = p95 > self.slo_ms
cost = 0.01 * self.replicas
reward = -(cost + self.breach_weight * float(breach)
+ self.churn_weight * abs(self.replicas - old))
truncated = self.t >= self.episode_len
info = {"p95_ms": p95, "breach": bool(breach), "cost": cost,
"replicas": self.replicas}
return self._obs(p95), float(reward), False, truncated, info
env = ReplicaEnv()
check_env(env)
model = PPO("MlpPolicy", env, n_steps=2048, seed=0, verbose=0)
model.learn(total_timesteps=50_000)
model.save("ppo_replica_controller")
A few choices in this code are deliberate. The environment inherits from gymnasium.Env and declares its observation and action spaces, as Gymnasium requires. reset() calls super().reset(seed=seed) first so the random generator behind the bursts is seeded properly. The 50,000-step budget matches RLScaleBench’s training budget; the network is SB3’s default rather than the benchmark’s [256,256] MLP. PPO’s clipped update keeps each new policy close to the old one. The reward sums cost, a per-step breach penalty and a churn term; info returns cost and breach separately so evaluation can report them apart. In this code, raising breach_weight makes each violation cost the agent more reward.
Gymnasium’s own guide warns that a poorly designed environment makes learning difficult or impossible, however good the algorithm. If you want to add a time limit or reshape the reward later, Gymnasium wrappers do that without touching the core class.
The simulator is the weakest link
The latency formula above was calibrated against a real cluster with Prometheus monitoring. Swap in your own: measure p95 against per-replica load on your model and hardware, fit the curve, and include cold-start delay. Reactive scaling suffers precisely from the gap between a surge starting and new replicas becoming ready. The sources disagree on how well policies transfer. AWARE notes that a simulator-trained policy faces a problem when moved to production. The batching study saw its policy generalise to unseen bursty and real-world traces despite training only on synthetic Poisson arrivals.
Deploying a trained RL policy into the serving loop with a fallback
Never let an RL policy be the only thing between your traffic and your SLO. Put it behind a safety condition and a known-safe fallback controller. The “training wheels” design extends the standard RL setting with three components. A safety condition over the state decides whether the system is safe. A guaranteed-safe fallback policy takes over when it is not. And activating the fallback adds a penalty to the reward. With this structure, the RL model never performs worse than the safe fallback, yet it can still learn workload-specific policies that improve on it.
The paper calls the penalty term necessary, not decoration. Without it, the agent learns to break the safety condition on purpose, because triggering the fallback earns better rewards than an early random policy. In that paper’s load-balancer case, the safety condition was a maximum server queue below 100, and the fallback sent requests to the shortest queue until all queues drained. For replica control, the natural fallback is the calibrated rule you already have.
SLO_MS = 500.0
FALLBACK_P95_MS = 0.8 * SLO_MS # tighter internal threshold
def control_step(obs, metrics, policy, rule_controller):
"""Return (action, used_fallback). Training adds a penalty when used_fallback."""
unsafe = metrics["p95_ms"] > FALLBACK_P95_MS or metrics["queue_len"] > metrics["queue_limit"]
if unsafe:
return rule_controller(metrics), True
action, _ = policy.predict(obs, deterministic=True)
return int(action), False
AWARE adds two production patterns on top of this. It bootstraps the agent offline, using a heuristic controller (HPA or VPA) to drive exploration, and moves to online training only after the RL reward matches the heuristic’s. In offline mode, the heuristic serves the traffic while the RL policy learns from the logged data. It also monitors episode rewards continuously, comparing their mean and variance against thresholds that switch retraining on or off. The bootstrapping exists because suboptimal early-training actions are unacceptable for production workloads. In AWARE’s measurements, RL agents caused 56.1x more SLO violations than the rule-based approach in the first 100 training episodes. If you want the basic mechanism behind that early behaviour, see how agents learn through trial and error. The monitoring side, catching a policy that drifts as traffic changes, is the subject of our piece on RL loops in production and drift telemetry.
The attention-LSTM agent measured 0.70 ms on CPU and 0.80 ms on GPU per control step, about 0.001% of its 60-second control interval. Policy inference must run in real time at the system’s control frequency; at replica-control intervals that is negligible. A batching or routing policy in the request path needs a latency budget of its own.
Testing whether the RL controller actually improved latency and cost
A controller that won one run has not yet shown that it is better. Henderson et al. (2017) showed that non-determinism in environments, combined with the variance built into deep RL methods, makes reported improvements hard to interpret without significance testing. Distribution shift adds a second risk. In RLScaleBench, algorithm rankings moved by up to four positions between steady and bursty traffic.
Diagnostic checklist before shipping
- Strong baseline. Compare against a calibrated rule, not defaults. RLScaleBench’s tuned HPA beat every RL agent on cost.
- Multiple seeds. RLScaleBench used five random seeds. The attention-LSTM study used five seeds on each of two clusters.
- Paired statistics. Report a paired test across matched runs, as the attention-LSTM study did with a paired t-test and a Wilcoxon signed-rank test.
- Shifted workloads. Evaluate on traffic patterns the agent did not train on, including bursts.
- Tail metrics. Report P90, P95 and P99 plus the fraction of time inside the SLO.
- Per-constraint violation counts. Track each safety constraint’s violations separately, during training and in deployment.
- Cost and churn. Report replica-steps and scaling churn. Activity alone is not a valid stability criterion.
- Reward components apart. Show cost, breach and churn terms separately so the trade-off is visible.
- Fallback activation rate. A policy that leans on the fallback has not learned the job.
Run this checklist on the simulator first, then in shadow mode against live metrics with the rule still in control, and only then hand over control behind the fallback.
What has to be settled before anyone writes the environment
The hardest number in the whole project is not a hyperparameter. It is how much one SLO breach costs relative to one replica-hour. That ratio sets the reward weights, decides whether the bursty-traffic advantage in the RLScaleBench data is worth paying 24% more for, and tells you whether a well-tuned HPA or Ray Serve autoscaler is already the right answer. Ray Serve makes the rule-based version a tuning job: lower target_ongoing_requests for longer requests or tighter latency objectives. If nobody on the team can put a number on that ratio, tune the rule and measure it first. RL needs a clear objective, and right now it doesn’t have one.