Custom Metrics Autoscaling With KEDA in Event-Driven Workloads
KEDA feeds queue and event demand to the HPA, including scale-to-zero.

Custom metrics autoscaling with KEDA aligns Kubernetes capacity with pending work. Its central value is not replacing the Horizontal Pod Autoscaler, but feeding it the demand signals that event-driven workloads actually need. Scale-to-zero extends that model to idle periods, provided cold starts, authentication, and scaling behavior are treated as production design decisions.
Why CPU and memory are the wrong signals for event-driven workloads
CPU and memory describe resource consumption. A Kafka consumer can remain at low CPU while thousands of messages accumulate behind it, leaving a resource-based Horizontal Pod Autoscaler watching a flat signal during a demand spike. Consumer group lag shows more directly how much work is waiting. Without that signal, teams either over-provision for bursts or maintain custom metrics pipelines just to give the HPA a useful number.
What KEDA is and how it fits into the Kubernetes autoscaling stack

KEDA, Kubernetes Event-Driven Autoscaling, translates external demand into metrics the HPA can use. The HPA still decides how many replicas to run. KEDA runs through three components, namely the Operator, keda-operator, the Metrics API Server, keda-metrics-apiserver, and the Admission Webhooks server, keda-admission-webhooks. A ScaledObject connects a workload to its triggers, while a ScaledJob describes event-driven batch Jobs.
When a ScaledObject is applied, KEDA creates and manages an HPA named keda-hpa-<name>. Its metrics server supplies external metrics through the Kubernetes API. The operator separately handles transitions to and from zero. This division preserves the Kubernetes autoscaling control loop, but introduces an installation constraint. KEDA registers as the cluster’s external.metrics.k8s.io provider, so it conflicts with a Prometheus Adapter already serving that API.
The scale-to-zero mechanism and why it changes the economics of idle workloads
Native HPA needs the alpha HPAScaleToZero feature gate to scale below one replica. KEDA handles that boundary outside the HPA. With minReplicaCount set to zero, KEDA can write a zero replica count after all triggers become inactive and cooldownPeriod expires. It continues checking the external source while no workload pods exist. When demand returns, KEDA activates the workload on a polling cycle, after which the HPA manages further scale-out.
The savings depend on times when there is no work to do. Choreo, from WSO2, turned on scale-to-zero for mediation application pods in lower environments and saw clusters scale down by approximately seven nodes, which made the clusters much more efficient. It chose to leave critical production environments out because cold starts would affect API response times. Keeping minReplicaCount at one retains a warm pod when response latency outweighs idle savings.
The cold-start latency floor and other trade-offs teams get wrong
Scale-from-zero latency includes demand detection and pod startup, with the HPA sync period also governing subsequent scale-out. Faster polling cannot eliminate the startup portion. GPU inference makes this particularly visible because a first request may wait for model loading as well as pod readiness. For latency-sensitive workloads, the engineering question is whether that delay is acceptable.
Other settings impose costs of their own. If a cooldown ends before batch processing finishes, the workload can shut down and restart over and over. Polling too often when there are many pods can add to HPA API rate-limiting, so faster responses must be weighed against the load on the control plane. Metrics failures require a separate decision. KEDA’s default error behavior suppresses the metric, and production consumers should have explicit fallback replica counts.
Stateful workloads introduce a different constraint from latency. Scale-to-zero destroys Pod identity and is unsuitable where hard memory persistence is required. A steady service that rarely needs to scale also gains less from this setup. These constraints shape the configuration before any trigger threshold is chosen.
Installing KEDA and the ScaledObject structure every configuration builds on
For implementation, the starting point is a Helm installation targeting the keda namespace with --create-namespace. The command kubectl get pods -n keda should show the operator, metrics server, and admission webhooks running. Provider registration is visible through kubectl get apiservice v1beta1.external.metrics.k8s.io. Ownership must remain unambiguous after installation. A workload managed by a ScaledObject should not also receive a manually created HPA, because both would target the same Deployment.
The shared ScaledObject structure centers on scaleTargetRef.name, which identifies the Deployment, and triggers, which defines the demand sources. pollingInterval controls trigger checks, while cooldownPeriod governs the wait before zero. minReplicaCount and maxReplicaCount bound the replica range. Each scaler fills in the trigger metadata within that structure. The basic sizing relationship is total metric value divided by the per-replica threshold, subject to the configured bounds and scaler-specific constraints.
Configuring scalers for the most common event-driven patterns
Kafka scaling uses bootstrapServers, consumerGroup, and topic to identify the backlog. lagThreshold sets the target lag per replica, while activationLagThreshold controls activation from zero. offsetResetPolicy is another explicit configuration choice. By default, the partition count limits how many consumers can work in parallel because any extra consumers would sit idle.
RabbitMQ uses queueName, mode set to QueueLength, and value for the messages-per-replica target. A target of five describes work allocated per replica. With minReplicaCount set to zero, an empty queue permits shutdown after cooldown, while growing depth increases capacity up to maxReplicaCount. Credentials for a ScaledObject belong in TriggerAuthentication. AWS SQS follows the same demand model through queueURL, queueLength, and awsRegion, with authentication configured separately.
Prometheus provides the route for application-defined demand signals. Its trigger specifies serverAddress, a PromQL query, a per-replica threshold, and an activationThreshold for waking from zero. Custom demand need not require a large pipeline. Needl.ai uses a small Python metrics server that exposes a count of waiting tasks per service, allowing more than two dozen background services to scale from zero to a configured maximum. That implementation uses a custom HTTP source as an alternative to Prometheus.
Cron triggers address predictable demand before a backlog forms. Their fields include timezone, start, end, and desiredReplicas, with the schedule boundaries expressed in cron syntax. Using cron and queue triggers together lets the schedule set a floor for capacity while the queue handles bursts that were not expected. KEDA uses the highest computed replica count across triggers. As a result, scheduled capacity can remain running even when the queue is empty.
The HTTP Add-On installs with helm install http-add-on kedacore/keda-add-ons-http --namespace keda and uses HTTPScaledObject rather than ScaledObject, with hosts and scaleTargetRef identifying the route and workload. Its reverse proxy intercepts and buffers requests while pods start. That makes HTTP activation possible, but adds a proxy and a latency trade-off that queue-based consumers do not need.
Using ScaledJob for batch workloads that need one job per event
ScaledJob creates Kubernetes Jobs as an alternative to adjusting a long-running Deployment. Each Job completes its work and exits. This fits image processing, report generation, and other tasks that each need to run on their own. A persistent consumer belongs under ScaledObject, while one-task-per-event processing belongs under ScaledJob.
The jobTargetRef contains the Job pod template. pollingInterval controls source checks, and maxReplicaCount limits concurrent Jobs. successfulJobsHistoryLimit and failedJobsHistoryLimit govern retained Job history. A per-message queue target expresses the one-Job-per-message pattern.
Key ScaledObject settings that govern production behavior
When tuning for production, account for the cost of each check by raising pollingInterval when scaling more than a few dozen pods if frequent polling puts pressure on API rate limits, and set cooldownPeriod to give current work time to finish without keeping idle capacity forever. Activation thresholds serve a different purpose from scaling targets. activationThreshold or activationLagThreshold filters low-level demand before a zero-replica workload wakes.
Scaling behavior then controls how quickly capacity changes. A typical production pattern uses a scale-up stabilizationWindowSeconds of zero and conservative scale-down, such as one pod per minute with a 300-second stabilization window. This avoids shedding capacity during a brief lull. Fallback configuration should specify a replica count for production ScaledObjects handling live traffic. It handles failures in the metrics source, while cooldown and stabilization handle normal changes in the demand being measured.
Securing scaler credentials with TriggerAuthentication
TriggerAuthentication separates credential management from scaling configuration at namespace scope. ClusterTriggerAuthentication provides the cluster-wide counterpart for shared infrastructure such as a central Kafka cluster. The trigger connects to the authentication resource through authenticationRef.name. Credentials remain outside the ScaledObject manifest itself. That separation allows scaling configuration and authentication resources to be versioned and controlled through role-based access controls independently.
For AWS, pod identity through IRSA or EKS Pod Identity is preferable to static access keys. TriggerAuthentication sets podIdentity.provider to aws, and the IAM role should receive only the scaler’s required permissions, such as sqs:GetQueueAttributes. Credential-based sources instead use secretTargetRef to map Secret keys to scaler parameters. Static AWS keys remain a fallback option. In that case, the mappings use awsAccessKeyID and awsSecretAccessKey.
Observing KEDA: how to know whether it is working and why it is doing what it does
Observability closes the loop between demand and capacity. kubectl get scaledobjects exposes resource state, while kubectl describe scaledobject <name> provides events and metric information. kubectl get hpa shows the managed HPA and its scaling targets. The raw external metrics API can be inspected with kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1" | jq..
The operator exposes Prometheus metrics on port 8080. The signals include keda_scaler_active, keda_scaler_metrics_value, and keda_scaled_object_errors_total, and alerts on the error counter show when metric collection fails. Operator logs are the next diagnostic step through kubectl logs -n keda deploy/keda-operator. These signals belong in the deployment’s operational feedback loop from the start. OneUptime supports Kubernetes observability workflows that complement monitoring and alerting on KEDA scaling behavior.
Beyond queues: Prometheus-backed custom metrics and the LLM inference pattern
Prometheus extends scaling beyond sources with dedicated queue scalers. HTTP request rate, database queue depth, error rate, and business-level throughput can all become triggers through PromQL. The metric must still represent useful demand. KEDA translates the number into capacity decisions, but the application’s workload model determines what that number should mean.
LLM inference demonstrates the scope of this approach. Relevant signals include vllm:num_requests_running, num_requests_waiting, and gpu_cache_usage_perc, which describe pressures that CPU utilization alone does not capture. Google Cloud demonstrated a GKE scenario using KEDA to scale an Ollama workload to zero when no inference requests were pending, avoiding idle GPU usage. That example establishes the deployment pattern without establishing a universal latency or savings result.
Forecasting can supply a different kind of demand signal. A separate forecasting service can expose expected future load through Prometheus, allowing KEDA to act on that metric. A cron trigger can cover known daily patterns without requiring a perfect forecast. The adapter model stays the same even when the signal changes from observed work to expected work.
When KEDA is and is not the right tool
KEDA is a strong default for asynchronous, event-driven, and batch workloads whose demand is external to CPU or memory. Discrete events that need isolated execution strengthen the case for ScaledJob. Native HPA is still simpler for steady CPU-bound services that can run without external signals or scaling to zero replicas. Stateful requirements can also rule out the shutdown behavior that makes KEDA attractive.
Replica count is only one dimension of efficiency. Inflated resource requests still produce oversized pods, even when KEDA selects the right number of them, so full savings also require VPA or deliberate request tuning.


