Autoscaling Loki queriers with KEDA

Scale Loki queriers with daytime demand using KEDA and the query-scheduler's in-flight request metric, with the prerequisites checked first and scale-down guarded against long queries.

On this page

When Loki queriers need to autoscale with KEDA

KEDA can scale Loki queriers on the query-scheduler's loki_query_scheduler_inflight_requests metric, which tracks the queries waiting and running at any moment. A platform team whose log query load climbs during business hours and drops overnight is the typical case for this approach, because queriers can grow with demand and shrink again instead of sitting at peak size all day. Loki's autoscaling documentation recommends this path for Kubernetes microservices deployments, where the query-scheduler is in use. The metric is the sum of queued and running queries, so it reflects both the backlog a user is waiting on and the work already in progress.

The fit is narrow. The approach only works when queriers run as their own workload behind a query-scheduler, since the metric comes from the scheduler and the scaling target is the querier deployment. In a monolithic or simple scalable layout, or in a microservices layout that still embeds the queue in the query-frontend, there is no scheduler metric to scale on, and the team needs a different signal or a fixed querier count. Before committing, confirm which deployment mode you run, that the scheduler is enabled, and that KEDA can reach the Prometheus endpoint that stores the metric. Those three checks decide whether this section applies to your cluster at all.

Once the prerequisites are met, the decisions that matter are the target value per querier, the minimum and maximum replica counts, and how long KEDA waits before scaling down. Set the scale-down window with care, because a querier removed while it holds a long-running query can fail that query and force users to rerun it. Plan for a test that runs a heavy query during a scale-down event and confirms the query completes. Confirm the exact KEDA trigger fields and any Loki-specific settings against the current autoscaling documentation for your Loki version before you write the manifests.

How query demand reaches the KEDA scaler

The path starts in Grafana, where a user runs a LogQL query that goes to the query-frontend, which hands work to the query-scheduler. The scheduler queues requests and the queriers pull them, so the queued plus running total is what Prometheus records as loki_query_scheduler_inflight_requests. KEDA reads that metric through Prometheus and adjusts the querier deployment. Check that Prometheus scrapes the scheduler and that KEDA's query matches the metric name your Loki version exposes.

Query path from Grafana to queriers, with KEDA scaling on the scheduler metric.

Prerequisites before KEDA can scale queriers

KEDA can only scale queriers sensibly when Loki is deployed as separate microservices and the query-scheduler sits between the query-frontend and the queriers. Before installing anything, confirm that your cluster runs Loki in a Kubernetes microservices deployment, with distinct query-frontend, query-scheduler and querier workloads. Loki's documented deployment modes are monolithic (a single binary, suited to smaller volumes), simple scalable (separate read, write and backend targets) and microservices (for very large clusters). The simple scalable mode is being deprecated and will be removed with the Loki 4.0 release, so it is a poor base for a scaling design you intend to keep. If your current cluster runs monolithic or simple scalable, plan the move to microservices first, because the scaling signal described in this topic does not exist in those modes.

The scheduler must be a separate workload, not the query-frontend's built-in queue. Running a separate query-scheduler lets several frontends share one queue and gives KEDA a single place to read queue depth from. Confirm that the frontends and queriers point at the scheduler's address in the Loki configuration, and that the scheduler pods are healthy and exposing their metrics endpoint. Second, Prometheus must scrape the scheduler and store the loki_query_scheduler_inflight_requests series, since KEDA's Prometheus scaler reads it through a query. Check the series in Prometheus directly before writing any ScaledObject, and make sure the scrape job labels let you select the scheduler's pods by namespace and workload name.

Third, install KEDA in the cluster and confirm its operator and metrics API components are running, because the autoscaler cannot act until they are. Your cluster must also run a Kubernetes version that KEDA and your Loki chart support. Check the version against the current supported minor releases on kubernetes.io/releases, since the project maintains only the three most recent minor versions and patch support ends on fixed dates. Confirm the exact support end dates for your chosen version with that page rather than relying on this summary, and schedule any cluster upgrade before the autoscaling work starts so you do not tune scaling on a control plane that is about to change.

Scaler settings and when each fits

This table compares the four KEDA settings that shape querier autoscaling: the trigger metric, the target per querier, replica bounds, and polling and cooldown timing. Read each row for its effect on query latency and cost, and the signal that tells you to change it. The main takeaway is that bounds and cooldown protect running queries as much as they control spend.

SettingEffect on latency and costSignal to change it
In-flight requests trigger (loki_query_scheduler_inflight_requests)Counts queued and running queries, so scaling reacts to demand rather than CPU. A narrow trigger scales too late for bursts; a broad one scales on quiet background load.Queries wait in the queue while querier CPU stays low, or scaling reacts to load that never reaches users
Target value per querierA lower target adds queriers sooner, which lowers queue wait and raises cost. A higher target packs more queries per querier, which saves cost and can lengthen p99 latency.Queue wait rises at peak hours while queriers are fully busy, or replicas sit idle most of the day
Minimum replica countSets the warm capacity that answers the first queries after a quiet period. A low floor cuts idle cost but adds cold-start latency at the start of working hours.Morning dashboards are slow before scaling catches up, or the floor is paying for capacity nobody uses overnight
Maximum replica countCaps spend and the load placed on the object store and the query-frontend. A cap that is too low turns extra demand into queue time.Queue depth stays high at the cap, or object store errors and throttling appear during the busiest windows
Polling intervalA shorter interval reacts faster to bursts but queries the metric more often. A longer interval delays scale-out by up to one polling cycle.Bursts finish before replicas arrive, or metric queries add noticeable load to the monitoring stack
Cooldown periodA longer cooldown keeps replicas alive after a spike, protecting long queries from being cut off during scale-down. A shorter one returns cost savings sooner but risks interrupting in-flight work.Queriers are removed while long queries are still running, or replicas stay up for long stretches after demand has dropped
Scale-down behavior during long queriesScale-down removes pods that may still hold running queries. Confirm with your Loki version how in-flight queries drain before pod termination, and set cooldown and termination grace to match your longest expected query.Timeouts or partial results appear for long range queries that coincide with the end of a scale-down event

How to set up querier autoscaling step by step

This sequence takes a Kubernetes Loki cluster from a fixed querier count to a KEDA-driven setup that adds and removes queriers based on the query-scheduler's in-flight request count, with a check at each stage.

  1. Confirm the query-scheduler and frontend split

    Confirm that the cluster runs the query-frontend and query-scheduler as separate components, with queriers connecting to the scheduler rather than the frontend holding the queue. Your platform engineer checks the Loki configuration and the Kubernetes workloads, and the check passes when the scheduler pods are running, the frontend points at the scheduler, and queriers register with it. If the queue still lives in the frontend, KEDA has no scheduler metric to read, so resolve this before going further. Confirm the exact configuration keys against the Loki autoscaling documentation for your Loki version.

  2. Enable the Prometheus scrape for the scheduler

    Add a scrape target so Prometheus collects metrics from the query-scheduler's HTTP endpoint, typically through a ServiceMonitor if you run the Prometheus Operator or a static scrape job otherwise. Your monitoring team makes the change and confirms the scrape target shows as up in the Prometheus targets view. Then run a query for loki_query_scheduler_inflight_requests in Prometheus and confirm a series is returned for each scheduler replica. KEDA reads this metric through Prometheus, so an empty result here will stop scaling later.

  3. Install KEDA in the cluster

    Install KEDA into its own namespace using the method your organization uses for cluster add-ons, such as Helm or a GitOps application. Your platform team owns this step, and the check is that the KEDA operator and metrics components are running and their custom resource definitions, including ScaledObject, are present. Confirm the KEDA version and its supported Kubernetes versions against the KEDA release notes before installing, since the cluster version must fall within the range that KEDA supports.

  4. Create the ScaledObject for the querier deployment

    Write a ScaledObject that targets the querier Deployment or StatefulSet in the Loki namespace and uses a Prometheus trigger with the query loki_query_scheduler_inflight_requests. The query should sum the metric across scheduler replicas so the value reflects total queued and running queries. Apply it through your normal change process and check that KEDA creates the associated HorizontalPodAutoscaler, visible with kubectl get hpa, and that the ScaledObject reports Ready. A ready status with no reported metric value means the Prometheus address or query needs correcting.

  5. Set replica bounds and a scale-down policy

    Set minReplicaCount and maxReplicaCount on the ScaledObject to limit the range KEDA can use, and set the target threshold on the trigger so scaling reacts to queue depth. Also configure the HPA behavior for scale-down, including a stabilization window, so queriers are not removed while long queries are still running. Choose the bounds from your own capacity testing and cost limits, since the right values depend on your data volume and node pool. Confirm the bounds in the HPA status, where the minimum and maximum should match what you set.

  6. Verify scaling with test query load

    Generate a controlled burst of LogQL queries against the query-frontend, using a load tool or a scripted set of representative queries, and watch the querier replica count with kubectl get hpa and kubectl get pods. The check passes when replicas rise while in-flight requests stay above the threshold and fall back toward the minimum after the load stops, without removing queriers while queries are still running. Record the observed timings and compare them with your own service expectations. For broader test design, the Loki load testing topic covers what to measure in more depth.

  7. Confirm scale-down does not interrupt long queries

    Run a deliberately long query, such as a wide time range over a large stream selector, and observe whether any querier is terminated while it is still serving that request. Your platform engineer checks the scale-down behavior, the termination grace period on the querier pods, and the stabilization window in the HPA. The check passes when the long query completes and no querier is removed mid-request in the logs or events. If it fails, lengthen the stabilization window or grace period and repeat the test before relying on the setup in production.

Stopping scale-down from cutting off long queries

The main failure mode is simple: KEDA scales the querier Deployment down when the in-flight request metric falls, and Kubernetes then terminates a querier pod that may still be running a long query. The query fails or returns partial results, and the user sees an error that looks like a cluster problem. The fix is not one setting but a set of guardrails that work together: a cooldown period on the ScaledObject, a minReplicaCount high enough that a quiet period does not drop the cluster to a size that cannot absorb the next burst, and a terminationGracePeriodSeconds on the querier pod long enough for in-flight work to finish before the kubelet sends a hard kill.

The query timeout settings on the Loki side set the upper bound on how long any one query can run, so they define how long a graceful termination window needs to be. Compare the longest query you allow against the grace period you configure, and check that the timeout you choose in Loki is not longer than what the pod is given to drain. Confirm each of these against the Loki autoscaling and configuration documentation linked from this page, because option names and default behavior can change between Loki releases. Also confirm how your Kubernetes version handles pod termination and the grace period in your ScaledObject and Deployment, using the release documentation for the cluster version you run.

Before you go live, run a controlled test: start a query that runs close to your timeout, then trigger a scale-down and confirm the query completes and the pod stays up until it finishes. Record the values you chose for the cooldown, minimum replicas, grace period and query timeout in your runbook, and review them after each Loki or Kubernetes upgrade. If a quote or scope is being prepared, ask the implementer to show the test result for this case, since it is the one most likely to fail silently.

Security and operational considerations for the scaler

A KEDA scaler sits between your metrics, your Kubernetes API and your query path, so it inherits permissions and exposure from all three. The cards below cover the access it needs, the endpoints it reads from, what its logs can reveal and how to notice when it stops working.

Scoped RBAC for the KEDA operator

The KEDA operator needs permission to read the ScaledObject and TriggerAuthentication resources and to update the scale subresource of the queriers Deployment or StatefulSet, and nothing broader. Grant those verbs in a Role limited to the Loki namespace rather than a cluster-wide ClusterRole. Confirm the exact resources and verbs against the KEDA release you deploy, then review the bindings with your RBAC audit tooling after each upgrade.

Loki autoscaling docs

Authenticated access to Prometheus

The scaler reads loki_query_scheduler_inflight_requests from Prometheus on every polling cycle, so anyone who can reach that query endpoint can read Loki operational data. Place Prometheus on a private network path, require authentication in front of it and give KEDA a dedicated read-only credential. Prometheus does not ship its own authentication layer, so confirm how your deployment handles this against the Prometheus security model before go-live.

Prometheus security model

Tenant data in query logs

Scaling is driven by an aggregate count, but the query-frontend, query-scheduler and querier logs record LogQL text, which can include label values, search strings and tenant identifiers from the X-Scope-OrgID header. Decide who can read those logs, how long they are kept and whether they flow into shared log stores. Treat them as tenant data when a multi-tenant cluster serves separate customers or business units.

Pod Security Standards for the KEDA namespace

Run the KEDA namespace under a Pod Security Standards level set by a namespace label, starting with the restricted profile and relaxing only where the KEDA release you deploy requires it. Confirm the securityContext settings the operator and metrics server need before enforcing, and test in a staging namespace first. Document any exception so auditors can see why it exists and when it was reviewed.

Pod Security Standards

Monitoring the scaler itself

When KEDA cannot read its metric, the queriers keep their last replica count, so a broken scaler fails quietly during a traffic peak. Alert on ScaledObject conditions that report the trigger as inactive or erroring, on errors from the KEDA operator and on Prometheus query failures from the scaler. Confirm the metric names exposed by your KEDA version, then add a Loki-side alert on queue depth so a stalled scaler still shows up in on-call tooling.

Questions teams ask before autoscaling Loki queriers

What does autoscaling Loki queriers with KEDA cost, and what drives the effort?

The cost is mostly people time: someone has to configure the query-scheduler, install KEDA, write the scaling rule, and test it against real query load. Costs split into one-time work (design, installation, scaler tuning, load testing) and recurring work (upgrades of Loki, KEDA and Kubernetes, and tuning when query patterns change). Effort rises with the number of Loki components you already run, how many tenants share the cluster, and how much of the autoscaling behavior you must prove before go-live. DeployOpen does not publish prices. Ask any partner for a quote that lists the work items, the Kubernetes and Loki versions in scope, who performs load testing, and which upgrades and retesting are included after go-live.

How long does a first KEDA setup for Loki queriers take?

No duration is fixed by the Loki documentation, so treat any number you see as a planning assumption to confirm. The timeline depends on whether the query-frontend and query-scheduler already run in microservices mode, whether Prometheus already scrapes the Loki query-scheduler, how many clusters and environments are involved, and whether a staged load test is required before production. Teams that already run Kubernetes, Prometheus and a microservices Loki deployment usually spend less time on prerequisites than teams starting from a simple scalable or monolithic install. Ask for a written schedule that separates prerequisite checks, scaler configuration, load testing and the handover.

What must our team provide before the work starts?

Prepare access and information before the first working session:

  • Kubernetes access to the cluster that runs Loki, with rights to install KEDA and change the Loki deployment
  • A running Loki deployment in microservices mode with the query-scheduler enabled, since Loki's autoscaling guidance uses that component
  • Prometheus that scrapes Loki, so the scaling metric loki_query_scheduler_inflight_requests is available to KEDA
  • Loki and Kubernetes version details, plus your upgrade calendar and change process
  • Sample query workloads and dashboards that show current querier usage

Ask the partner to confirm which of these they need and which they will provide.

Can our internal platform team set up Loki querier autoscaling alone?

Often yes, if the team already runs Kubernetes, operates Prometheus and understands how Loki's read path is split into query-frontend, query-scheduler and queriers. The harder parts are the scale-down behavior during long queries, correct metric labels, and load testing that reflects your real query mix. A partner adds value when those skills are missing internally, when you need a formal validation record, or when the team cannot spare time during a rollout. Whichever path you choose, agree on who owns scaler changes after go-live, since a poorly tuned scaler causes slow queries or unnecessary cost.

What breaks when KEDA scales queriers down during long queries?

Scaling in a pod that still runs a long query can drop results and force users to retry. The safe pattern is to scale on the in-flight metric, which counts queued and running queries, so that scale-down waits until demand falls. Engineers should also check the termination grace period on querier pods and the cooldown settings in the KEDA ScaledObject, so queriers have time to finish work before shutdown. Test this with queries that run for longer than your normal scale-down window, not only with short dashboard queries.

How do we validate querier autoscaling under load?

Validate against a written test plan with a baseline, a ramp-up, a sustained peak and a ramp-down. Measure querier replica counts, query latency, queue depth from the query-scheduler, error rates and whether any query fails during scale-down. Include a few long-running queries to confirm the drain behavior. Run the same test after each Loki, KEDA or Kubernetes upgrade. The Loki documentation on autoscaling queriers and your own dashboards are the reference points, and load-testing tools such as k6 with xk6-loki can generate the traffic. Ask any partner to deliver the test scripts, results and the thresholds they used.

Does autoscaling queriers apply to every Loki deployment?

No. Loki's guidance for KEDA-based querier autoscaling applies to a Kubernetes microservices deployment that uses the query-scheduler. Monolithic installs run a single binary, and the simple scalable mode is being deprecated and will be removed with Loki 4.0, so it is a poor base for new autoscaling work. If you run a single-server or non-Kubernetes install, the scaling approach is different and this design does not apply. Confirm your deployment mode against the Loki deployment modes documentation before scoping the work.

How DeployOpen scopes and delivers querier autoscaling

DeployOpen starts every querier autoscaling engagement with a written scope that names the Kubernetes clusters, Loki namespaces, Helm chart version and Grafana users involved, and that states what is excluded. Before any scaler is written, the team confirms that Loki runs in the microservices deployment mode with a query-scheduler in front of the queriers, because the scaling signal depends on it. The scope also records who owns each decision: the client's platform team typically owns the cluster, the KEDA installation and the approval of any change to query concurrency, while DeployOpen owns the design, the build and the test evidence. Most engagements of this kind are fixed-scope, so the deliverables, the acceptance tests and the timeline are agreed in writing before work starts, and the quote follows from that document.

Prerequisites are checked inside the client's own cluster, not assumed from a reference design. The team reviews the KEDA version and its installation method, confirms that Prometheus or another metrics backend scrapes loki_query_scheduler_inflight_requests, and checks that the scrape interval and retention are adequate for the scaling window. It also reviews node capacity, pod disruption budgets, the querier terminationGracePeriodSeconds setting and the admission policies that govern KEDA objects. Each check produces a recorded result, so the client can see which prerequisites were met, which needed a change and who made it. Any gap found here is priced into the written scope rather than discovered after go-live.

The scaler is then implemented as code in the client's Git repository and tested against a staging copy of the cluster before it touches production. Testing covers scale-up under a simulated query burst, scale-down after the queue drains, and the behavior when a long-running query is still in flight, which is the case the scale-down settings must protect. After go-live, DeployOpen can continue under a retainer covering Loki and KEDA upgrades, repeat load tests after capacity changes and periodic review of the scaling thresholds. Clients should ask any provider for the same documents: the scope, the prerequisite report, the test results and the rollback steps.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.