Skip to main content

Performance

Current position versus Loki​

Latest weekly A/B, measured 2026-11-08 at commit e4a743f675 against Loki v3.7.9. This is the measured baseline, not a claim about a later build. Every figure below comes from the generated performance evidence, the weekly A/B trend or the generated README section, which the weekly run rewrites; the tables further down this page are older, dated measurements.

How to read the comparison: both sides run on the same fresh stack with the same seeded data (the e2e stack pins Loki v3.7.9). Loki ignores Cache-Control: no-cache on query_range and volume_range, so its first run can still hit caches warmed by earlier requests and understates a truly cold Loki. Warm timings on both sides come largely from results caches. Rows Loki's own cache counters show as cache-answered are left out of the slower-than-Loki counts. A pair counts as slower only beyond noise: 25% and 50 ms.

Summary​

Two views of the same data, each stated with its scope:

  • The weekly run of 2026-11-08 (loki-defaults profile, 39 shape sets, 1h to 24h), generated into the README with the distribution in both Loki profiles (🟒 below Loki, 🟑 close, 🟠 1–2Γ—, πŸ”΄ above 2Γ—) and the medians by workload: 560 comparable first requests, 352 faster, 202 on par, 6 slower; 713 of 779 answers the same as Loki.
  • The latest saved run of every shape and range (performance summary, generated by conformance/scripts/perf_evidence.py): it adds older dedicated runs (2026-09-30 to 2026-10-17, including 7d ranges) to the daily sets, so it covers more pairs: 878 measured, 586 comparable, 369 faster, 205 on par, 12 slower; 745 answers the same, 67 different, 66 not compared.
Timing (latest saved runs)FasterOn parSlowerPairs compared
Cold first request36920512586
  • By workload in the latest saved runs, cold faster / on par / slower: Drilldown and Explore pages 90 / 33 / 1 (median 0.06 s against Loki's 0.23 s), log queries 28 / 50 / 0 (0.01 s against 0.06 s), metric queries 248 / 120 / 7 (0.05 s against 0.17 s), metadata and label browser 3 / 2 / 4 of the 9 pairs Loki's cache did not answer.
  • Warm repeat and refresh are compared only for runs that give each set its own windows. None of the saved runs does, so the report makes no flagged warm or refresh comparison; the README's repeat medians are the recorded p50s of the weekly run, a reference rather than a judged comparison.
  • Metadata calls: most first requests are answered by Loki's results cache, so the report and the README list them separately with the cache-answered count.
  • Workload grouping is explicit in the script: an endpoint call is metadata, the Drilldown and Explore sets and shape names are one group, then log queries, then all other metric shapes.

First request​

The weekly run of 2026-11-08 measured 6 shape and range pairs slower than Loki beyond noise on a cold request:

shaperangeproxy coldLoki coldproxy warmLoki warm
DP1 patterns of a plain-text service1h0.21 s0.02 s0.01 s0.02 s
DP2 patterns of an environment1h0.97 s0.43 s0.09 s0.20 s
DP2 patterns of an environment24h0.24 s0.15 s0.20 s0.15 s
LS8 json count by level_extracted, collision6h0.30 s0.12 s0.03 s0.01 s
A5 drilldown exclude, volume by detected_level24h0.16 s0.10 s0.01 s0.01 s
E2 json duration_ms p95 by service24h0.95 s0.69 s0.01 s0.02 s

Above 2Γ— Loki (the list kept by the weekly run): 3 rows, all LS8 json count by level_extracted, collision on a first request (1h and 6h in loki-defaults, 6h in aligned). The other 6 slower pairs of the latest saved runs come from dedicated runs the weekly run does not repeat (listed under Not re-measured by the weekly run in the report). The performance evidence lists the registry items that cover each row and the rows the weekly run does not re-measure. Two-day ranges are measured separately; see Two-day ranges (48h).

Two-day ranges (48h)​

Ranges above 24h behave differently on both sides: Grafana's Loki datasource splits a metric range into 24h chunks and merges the frames, Loki reads older data from its store instead of the ingesters, and $__auto steps grow. The weekly run stops at 24h, so a separate pass measured every shape set that runs a 24h range at 48h (step 120 s, Grafana's $__auto step for two days), on 2026-11-04 at commit 69d07019b3, against Loki v3.7.9 with VictoriaLogs v1.53.0. 7d is not measured: Loki does not answer the heavier 7d shapes on the bench stack, so a 7d comparison would show Loki failing rather than the proxy's speed. The 7d rows listed above (E1, E3, E8) are superseded by this pass.

Method: bench/ab/daily.py --max-range 48h --runs 7 --long-runs 1 --profiles auto, with a 48h range ([172800, 120]) in place of 24h for those sets, and a 48.4h seed (4.60 M lines; Loki and VictoriaLogs agreed on the line count in every one of 290 slices). 26 sets, both Loki profiles, 7 runs per shape, 50 passes; every pass was valid, with VictoriaLogs restarts 0 before and after each. The first pass ran on a loaded host and inflated the cold times of the json-heavy sets (for example X1 39.7 s), so the 7 sets that showed a row above 2x were measured again on a fresh stack; the tables use the second measurement for those sets. Bands are those of bench/ab/over2x.py, as in the daily report; rows whose first request Loki's results cache answered are not compared.

Range-dependent rows (instant queries excluded):

Loki profileRequestRows comparedFaster than LokiClose to Loki1–2x LokiAbove 2x LokiLoki cache-served first request (not compared)
loki-defaultsfirst143116 (81.1%)23 (16.1%)2 (1.4%)2 (1.4%)31
loki-defaultsrepeat17474 (42.5%)100 (57.5%)00β€”
alignedfirst12099 (82.5%)18 (15.0%)3 (2.5%)08
alignedrepeat1284 (3.1%)121 (94.5%)2 (1.6%)1 (0.8%)β€”

On the 7 sets measured twice no row is above 2x Loki; the largest ratio is 1.39x. The three rows above 2x in the table (DB4 json field breakdown and one other first-request row in loki-defaults, and a logfmt logs-volume repeat in aligned) come from sets measured once, on the loaded first pass, and are waiting for a confirming run.

Shapes that changed since the previous 48h measurement (commit 7eaf79ce, VictoriaLogs v1.52.0, so part of each change is the VictoriaLogs version):

ShapeLoki profileThen: proxy / LokiNow: proxy / Loki
DLV3 plain json, detected_level (#1057)loki-defaults, first request6.43 s / 0.65 s0.34 s / 0.53 s
X1 json filter level_extracted, by level (#1058)loki-defaults, first request8.61 s / 2.21 s3.99 s / 3.61 s
X1 json filter level_extracted, by level (#1058)aligned, first request8.72 s / 1.95 s3.63 s / 2.83 s
DB1 label breakdown podloki-defaults, first request0.60 s / 7.94 s0.91 s / 26.77 s
E2 json duration_ms p95 by serviceloki-defaults, first request0.35 s / 0.43 s0.38 s / 0.49 s
  • Log queries (the logs shapes of the control, level-filter, or-filter, pattern-filter and stage-field sets) are at or below Loki's time on every compared row; plain log queries take 0.02 s against Loki's 0.10–0.14 s.
  • DB1, DB4, E2 and U9, which answered 502 on older 7d runs, answer 200 at 48h.
  • Open: answers larger than the buffered-response limit. B2 (sum by over a ratio of two per-stream metrics) answers 500 at 48h in both profiles, where Loki answers 200 (a first request in 41–167 s); at 24h it answers 200. The set series-level-fine-step (four sum/count/avg by shapes at a 20 s step over 48h, finer than Grafana's step for two days) answers 500 on all four shapes for the same reason. Loki never answers these with 500, so this is an open defect.

Backend safety at long ranges: 12 workers for 180 s sent 222 distinct 24h and 48h queries built from 146 bench shapes, with /labels and label-value probes every second. Every one of the 249 probes answered 200 (p95 105 ms, max 228 ms). VictoriaLogs and Loki restarted 0 times and neither was OOM-killed. Of the queries, 211 answered 200, 6 answered Loki's own 400 with Loki's text, 2 answered 429 too many outstanding requests, and 3 answered 500, all three at the buffered-response limit above.

Grafana range matrix on the same build (5m, 15m, 1h, 6h and 24h, 30 calls through Grafana's datasources, proxy against Loki direct, log generator on): no call answered other than 200 where Loki answered 200. Plain, json and logfmt log queries, logs volume, rate/count_over_time/bytes_over_time grouped and ungrouped, and the Logs Drilldown volume and field breakdown queries match Loki's status, series, grid and totals at every range. The known differences that remain: topk(5) returns 5 series where Loki returns 8, detected_fields lists 12 fields against Loki's 15 (Loki's _extracted fields), index/stats totals differ, and index/volume_range answers up to 6h (Loki answers it at 5m only) and answers 500 at 24h at the same buffered-response limit.

Visual comparison on the same code (all 139 pages, 287 captures at 15m, 1h, 6h, 24h and live): against Loki, 214 captures were compared; 12 are identical, 50 differ only in documented ways, 145 differ only in Loki's index/stats chunk accounting, and 7 captures on 5 pages show other differences (10 captures on 7 pages before). No new visual difference from Loki appeared.

Repeated and refreshed windows​

Before #862 the proxy cached only exact windows. A Grafana refresh moves the window forward a minute and a re-run moves it back, so each recomputed the whole range in VictoriaLogs while Loki answered from the extents of its results cache. A 6h A/B on main had the proxy 10 to 200 times slower than Loki on those repeated and refreshed metric windows.

Metric query_range now keeps the VictoriaLogs stats buckets it has read (-query-range-extent-cache, on by default) and asks only for the buckets a moved or widened window lacks. Answers are byte-for-byte those of the uncached path. Finished buckets older than -query-range-freshness (10m, Loki's max_cache_freshness) are kept per tenant, query, step and offset for -query-range-extent-cache-ttl (1h, Loki's default validity), in memory, on disk and on the peer fleet when those tiers are configured.

Stats extents use S2-encoded buffers sized to the compressed payload before cache ownership. This releases the codec's excess output capacity from RAM entries and pending disk/peer writes. Encoded bytes, keys, expiry and placement stay unchanged. Compaction costs an allocation and compressed-length copy when excess capacity exists; warm reads do not encode. Logical cache charges still count payload/key length, not process RSS, allocator size classes or transient encoding scratch. This change does not establish a hard process memory bound. The dated memory and parity proof retains main/PR heap measurements, copy costs, byte-identity checks and the three-proxy RF1/RF2 regression results.

A/B at 6h, p50 of the runs after the first, measured on ff3b9337 during #862 review (released in 2.35.0):

shapemodemainwith #862Loki
X1 json filter level_extracted, by levelshifted window0.387 s0.007 s0.006 s
X3 json rate, level_extracted equalityshifted window2.240 s0.006 s0.075 s
X5 logfmt filter level_extracted, by levelrefresh0.960 s0.009 s0.007 s
logfmt count by level, filter, droprefresh0.705 s0.003 s0.005 s
J4 json no-error count by service_nameshifted window0.389 s0.019 s0.007 s
DL1 drilldown field breakdown json-exprshifted window0.768 s0.023 s0.010 s

That run: 22 faster, 187 same, 0 new differences against Loki, VictoriaLogs restarts 0 to 0. Only 6h was measured directly. The weekly run of 2026-10-27 includes the change and shows the same effect at other ranges, for example X1 at 24h warm p50 2.59 s to 0.10 s (Loki 0.04 s), the control set's JSON volume at 24h 1.43 s to 5 ms and its logfmt count by level at 24h 2.58 s to 17 ms (#874). The repeat is not yet at Loki's speed everywhere: see the next section.

Not covered by the reuse, so they keep their earlier repeat times: subquery-based shapes (including Drilldown's over-limit ranked breakdowns and volume_range), queries with _time: or time_add, unwrap metrics with the conversion check, and the grids behind topk and bottomk. Instant queries, /hits, log queries and raw-row evaluation are unchanged. Because finished buckets are reused, a line that arrives late in a bucket older than the freshness horizon is not seen until the kept bucket expires (at most the TTL).

Rows above 2x Loki​

Any shape, range and mode where the proxy takes more than twice Loki's time, and more than 50 ms longer, is a defect (#876). On a first request Loki's results cache must not have answered. The list is bench/ab/history/over-2x-loki.json, shown in the performance report as "Above 2x Loki (must fix)". The weekly run keeps it: it adds a row after two consecutive runs above 2x and removes one after two consecutive runs within 2x (a row above 2x on one run only is a warning), and perf-smoke fails a pull request that adds a row or worsens one; rows already on the list are debt and do not fail it.

On 2026-11-02 it holds 67 rows, all in the loki-defaults profile (the profile the weekly run measures): 45 on the first request, 22 on a repeat, 0 on a refresh. The 165 rows listed before the profiles existed were measured with a proxy that did not align queries with the step; the aligned profile has not run since 2026-10-28 because no build supports -align-queries-with-step, so nothing judged them. They moved to loki-defaults, the daily history was replayed through the daily rule, and 118 rows left (two consecutive runs within 2x). A row joins and leaves only after two consecutive runs, so the list need not equal the 50 first-request and 17 repeat rows above 2x in the latest daily distribution. The worst repeats include the detected_level volume shapes over | json (DLV2 at 6h: 8.20 s against 0.04 s) and DLV1 at 24h (7.61 s against 0.02 s).

Label lists near now​

A /labels or /label/{name}/values request ending near now waits at most -metadata-edge-refresh-budget (100ms) for the exact edge read; otherwise it gets the last answer this replica read for the same tenant, auth scope and window, at most -metadata-max-staleness (10s) old (#877). This is a documented difference from Loki (quality/metadata-bounded-staleness, owner-kept). In its measurement, 32 heavy clients looping 6h range-metric shapes for 180 s per target with a /labels probe every second, on a busy shared host (VictoriaLogs and Loki restarts 0 to 0):

/labels under loadmainwith #877Loki
p95, run 1 / run 2279.5 / 210.5 ms103.6 / 142.5 ms6242.5 ms
max, run 1 / run 2484.3 / 598.6 ms106.7 / 187.1 ms6242.5 ms
answers served stale, run 1 / run 2 (of 136 and 132 near-now answers)n/a12 / 21 (4 waited in run 1, 7 in run 2)n/a

Every stale answer was between 5 and 10 s old. The first probe after a fresh start is not helped (1.8 to 3.2 s), because no answer exists yet. /series is not covered. Heavy-query throughput was unchanged.

First request with Loki's results caches off​

#862 also measured a true cold run on a quiet host (measured during its review; it merged on 2026-10-26): both proxies flushed before each shape's first run, Loki started with its results caches off.

  • 0 of 221 shape and range pairs are slower than on main, and no new difference from Loki's answers appeared.
  • 22 pairs are still slower than uncached Loki. They are the same on main: level_extracted shapes at 6h (3.1 to 3.3 s against 0.6 to 0.8 s), E7 (1.34 s against 0.16 s), explore volume with two filters and drop (1.36 s against 0.57 s), field breakdowns (1.37 to 1.43 s against 0.72 to 0.82 s), and label browser and label values after a flush (0.14 to 0.17 s against 0.02 to 0.06 s).

Load and backend safety​

#862 load test on an isolated stack: 7h of seeded data, 32 concurrent clients for 180 s, 80 range metric shapes at 6h with random step-aligned windows. This compares the build before and after the change; it is not a comparison with Loki.

mainwith #862
requests1,0281,314
200 / 400 / 502 / 429812 / 203 / 13 / 01,040 / 258 / 16 / 0
p50 / p955.6 s / 14.5 s2.9 s / 14.8 s
proxy RSS peak1.47 GB1.63 GB (the cache filling its -cache-max-bytes budget)
/labels probe91/91 200, max 3.1 s92/92 200, max 2.1 s
Loki / VictoriaLogs restarts0 to 00 to 0

The 400s are shapes rejected identically on both builds. The 502s are a detected-level | json shape that fails under load on both builds at the same rate.

Daily regression guard​

The weekly A/B (bench/ab/daily.py, run from main against the last release and Loki) keeps a ratchet of the shape and range rows that are as good as Loki; a run that loses one fails. The current guard state, the rows above 2Γ— Loki and the trend are generated in the performance evidence and the weekly trend.

Answers that differ​

Speed is only meaningful where the answer matches. The performance report marks each registry item as same or differs against Loki; nested vector aggregations keep every level's grouping on instant queries and tumbling windows, like Loki (#746); the open differences are ranked in ranked differences and the intended ones are in Known Issues.

Architecture Optimizations​

Lock-Free Hot Paths​

At high concurrency (100+ concurrent requests), mutex contention becomes the dominant source of latency. The proxy eliminates locks from the request hot path in several subsystems:

ComponentBeforeAfterImpact
Circuit breakersync.Mutex on every Allow()/RecordSuccess()Atomic state machine; mutex only on state transitionsZero contention in closed (healthy) state
Metrics histogramssync.RWMutex on observe() and scrapeAtomic CAS loops for all countersScrape no longer blocks request recording
Rate limiterSingle global sync.Mutex + mapsync.Map + per-bucket sync.MutexEliminates convoy effect across tenants
Query fingerprintingcrypto/sha256hash/maphash~30x faster hashing
Structured loggingslog.JSONHandler internal mutex (52% of contention at c=100)Async buffered handler with 8192-slot channelWriter goroutine decouples logs from request path

Connection Pool Tuning​

The proxy's HTTP transport is tuned for high-concurrency single-backend proxying:

SettingValueWhy
MaxIdleConns256Total idle connection pool size
MaxIdleConnsPerHost256All slots for VL (single backend)
MaxConnsPerHost0 (unlimited)No artificial cap on concurrent VL connections
IdleConnTimeout90sReuse warm connections
ResponseHeaderTimeout120sAllow slow VL queries to complete
DisableCompressionfalseAllow negotiated upstream compression

Go's default MaxIdleConnsPerHost=2 causes ephemeral port exhaustion at >50 concurrent requests. Our tuning handles 200+ concurrent with 0 errors.

Compression Path​

The proxy now uses compression on multiple read-path hops:

HopCurrent behavior
Client -> proxy responseFrontend stays on gzip/identity; the chart pins -response-compression=gzip with -response-compression-min-bytes=1024 for broad Loki/Grafana compatibility
Proxy -> peer-cache owner/_cache/get prefers zstd, then gzip, then identity for payloads >=1KiB
Proxy -> VictoriaLogs-backend-compression=auto advertises zstd, gzip; the proxy decodes either safely before translation or passthrough
Disk cacheVersioned S2 (default), zstd, gzip or raw records; incompressible values stored raw; see Disk cache
OTLP pushnone, gzip, or zstd

The cache storage verification measures L2 costs separately from API latency, with fixed committed work, allocation profiles, raw samples and restart/peer correctness evidence.

Important: current VictoriaLogs docs clearly describe HTTP response compression, but not a guaranteed zstd query-response contract on the normal select path. The proxy can accept zstd from upstream when the backend provides it, but stock VictoriaLogs deployments may still return gzip or identity today.

Verification note: against Grafana 12.4.2, the datasource proxy path advertised Accept-Encoding: deflate, gzip, not zstd, in local verification. That means the safe deployment default is frontend gzip, and -response-compression=auto now keeps that same gzip path enabled for legacy configs instead of maintaining a separate client-facing zstd mode.

The Tier0 compatibility cache now stores the canonical identity body and lazily adds compressed variants on hot hits. That removes repeated gzip/zstd work from the hot cached read path without forcing every cached response to occupy multiple encodings up front.

klauspost/compress (v1.27.0): The proxy uses the klauspost/compress library instead of the standard compress/gzip, providing 2.5–3Γ— faster gzip decode throughput. This matters for responses from remote VL backends where gzip decompression is on the critical path.

Window cache zstd (v1.27.0): Split-window query results are compressed with zstd before storing in the in-memory cache, achieving 5–15Γ— size reduction compared to raw NDJSON. This allows the window cache to hold significantly more windows within the same memory budget.

Loopback backend optimization: When VL runs on the same host (localhost/127.0.0.1/::1), the proxy detects this and requests uncompressed responses (identity encoding). This eliminates 25–35% of decompress CPU overhead for co-located deployments.

NDJSON Parsing Optimization​

VL returns log results as newline-delimited JSON. The proxy converts this to Loki's streams format. Key optimizations:

TechniqueEffect
Byte scanning (not strings.Split)Avoids copying entire body to string
sync.Pool for JSON entry mapsReuses maps across NDJSON lines, reducing GC pressure
Pre-allocated slice capacityEstimates line count from body size
Nanosecond timestamp via strconv.FormatIntAvoids fmt.Sprintf allocation

Result: 49% memory reduction and 9.6% faster parsing vs original implementation.

Request Coalescing​

When multiple clients send identical queries simultaneously, only 1 request reaches VL. Others wait for the shared result, on every cached read route and for failures as well as successes; a failed answer is held for a second or a few (-error-cache-transient-ttl, -error-cache-data-ttl) so refreshing dashboards do not ask a failing VL on every refresh. Keys include tenant ID to prevent cross-tenant data sharing.

Cache Topology​

The proxy now has two cache layers in front of the backend execution path:

LayerScopePrimary goal
Tier0 compatibility-edge cacheFinal Loki-shaped GET responses on safe read endpointsBypass translation and backend work for hot repeated reads
L1/L2/L3 cache stackLocal memory, optional disk, optional peer fleet reuseReduce backend load and share results across replicas

Metric query_range also keeps the VictoriaLogs stats buckets it has read, in the same cache tiers (see Current position versus Loki).

Tier0 is intentionally small and bounded as a percentage of the primary L1 memory budget. The deeper L1/L2/L3 stack still handles broader reuse, peer sharing, and persistent cache warming.

What This Means For Operators​

The simplest way to understand the cache stack is by operational outcome:

LayerPlain-English roleWhat it buys you
Tier0Fast answer cache at the Loki-compatible frontendRepeated Grafana reads can return before most proxy logic runs
L1 memoryHot cache inside the local processBest-case latency for repeated dashboards and Explore refreshes
L2 diskPersistent local cacheUseful cache survives beyond RAM pressure and supports larger working sets
L3 peer cacheFleet-wide cache reuse between replicasOne warm pod can make the rest of the fleet faster and cheaper; peer-first startup warmup means only 1 instance per label window hits VL on rolling restart regardless of fleet size

This is the difference between β€œit speaks Loki” and β€œit feels like Loki at runtime.” The project is designed to preserve Loki-compatible UX while reducing repeated backend work aggressively.

Drilldown Metadata Performance​

Grafana Logs Drilldown and the label browser make multiple metadata calls per page load. The proxy optimises these calls to eliminate the two main sources of latency: slow backend endpoints and cache key drift.

Current metadata behavior​

Label inventories cover the requested time window. The proxy can reuse settled buckets, but recent edges, expired entries and buckets due for revalidation still read VictoriaLogs. Native stream metadata preserves stream-label semantics; field metadata and bounded scan fallbacks depend on the endpoint and query. There is no fixed-latency guarantee for a wide range or high-cardinality field. See metadata configuration and the API reference for freshness, browse limits and stale responses.

Metadata keys bucket time bounds at 5 minutes, 1 hour or 6 hours according to the requested range. This reduces refresh drift; it does not prove all moved windows avoid backend reads. Current measurements belong to the linked A/B reports and retain their source revisions.

Historical metadata measurements​

The following table is from the earlier #421 implementation and dataset. It is not a statement of current endpoint selection, cache-key granularity or latency.

Measured improvement (e2e-compat, ~8M log entries, 1h window; recorded 2026-06-05 in #421, historical):

PathBeforeAfter (cold)After (warm)
service_name/values~5,028ms (4 Γ— stream_field_names)235ms12ms
Speedupβ€”21Γ—~420Γ—

That earlier experiment avoided its 5–10s background calls. It does not establish a current latency ceiling for other ranges, datasets or backend versions.

VictoriaLogs Native Stats Offloading​

The proxy routes as much metric aggregation as possible to VL's native /select/logsql/stats_query_range endpoint, which returns a Prometheus-compatible matrix directly. This eliminates the most expensive proxy path: fetching all raw log lines and aggregating them in-process.

VL Native Stats API β€” Feature Timeline​

FeatureAdded in VLRelease dateNotes
/select/logsql/stats_queryv0.29.02024-09-08Instant stats, Prometheus vector format
/select/logsql/stats_query_rangev0.29.02024-09-08Range stats, Prometheus matrix format β€” used by Grafana
count, sum, avg, min, max, quantile, stddevv0.29.02024-09-08In stats pipe
rate() and rate_sum()v1.2.02024-12-06Native per-second rate β€” no proxy aggregation needed
rate_sum(prefix*) prefix wildcardv1.25.02025-07-07

The proxy's minimum tracked capability profile is vl-v1.30-plus. All features above are available on every backend the proxy supports β€” no version gating required for stats offloading.

LogQL β†’ VL Native Stats Mapping​

LogQL metricVL LogsQL (stats_query_range)Condition
count_over_time({...}[r]) by (l){...} | stats by (l) count()always
rate({...}[r]) by (l){...} | stats by (l) rate()range == step
bytes_over_time({...}[r]) by (l){...} | stats by (l) sum_len(_msg)always
sum_over_time({...}|unwrap f [r]) by (l){...} | <parser> | stats by (l) sum(f)always
avg_over_time({...}|unwrap f [r]) by (l){...} | <parser> | stats by (l) avg(f)always
quantile_over_time(q, {...}|unwrap f [r]) by (l){...} | <parser> | stats by (l) quantile(q, f)always
max_over_time({...}|unwrap f [r]) by (l){...} | <parser> | stats by (l) max(f)always
min_over_time({...}|unwrap f [r]) by (l){...} | <parser> | stats by (l) min(f)always
stddev_over_time({...}|unwrap f [r]) by (l){...} | <parser> | stats by (l) stddev(f)range ≀ step; a longer range reads avg(f), count() and stddev(f) per bucket and the proxy merges the buckets of each window exactly (stdvar_over_time squares the result)
first_over_time({...}|unwrap f [r]), last_over_time{...} | <parser> | stats by (<series>) row_min(_time, f) (row_max), its value unpackedrange ≀ step; a longer range reads the earliest (latest) row per series in each bucket and the proxy takes the window's earliest (latest) bucket
bytes_rate({...}[r]){...} | stats by (l) sum_len(_msg) as __lvp_inner | math __lvp_inner/r_s as __lvp_raterange == step
rate_counter({...}|unwrap f [r])β€”manual path (monotonic counter reset detection required)

rate() / bytes_rate() condition β€” range == step: VL's stats pipe uses tumbling windows. LogQL's rate() and bytes_rate() compute over a sliding r window. These are semantically identical when r == step, which is Grafana's default with $__interval. The proxy shifts the query start back by r and trims the pre-start bucket to match Loki's first evaluation point. Fixed ranges that differ from the step keep the proxy sliding-window path.

Parser stage (| json / | logfmt) + range metric: Even when range == step, if the translated VL query contains an unpack_json or unpack_logfmt stage, the fast stats path is disabled. VL's unpack pipes do not model Loki's __error__ filtering (Loki excludes lines that fail to parse; VL may include them). These queries fall back to the manual log-fetch path.

Query Routing Decision​

The proxy chooses between native VL stats and the manual log-fetch path based on:

LogQL metric query
β”‚
β”œβ”€ has parser stage (| json, | logfmt, etc.)?
β”‚ β”œβ”€ NO β†’ native VL stats (translator emits | stats …)
β”‚ └─ YES + no post-parser filter + function = rate/count/bytes + range == step
β”‚ BUT translated query has unpack_json/unpack_logfmt β†’ manual path
β”‚ (VL unpack semantics differ from Loki __error__ filtering)
β”‚ function = rate_counter β†’ always manual
β”‚
└─ outer aggregation (sum/avg/topk)?
β”œβ”€ topk/bottomk/sort β†’ native VL stats + post-filter in proxy
└─ sum/avg/min/max by (labels) β†’ folded into | stats by (labels) …

Why this matters: the manual path fetches every matching log line from VL (/select/logsql/query), buffers them in proxy RAM, and computes rates/sums per step window. A 30-second query_range at step=60s with 1 M logs/min fetches 30 M lines; the same query via stats_query_range returns 30 aggregated data points. The performance ratio scales with log volume.

Query-Range Tuning (Long-Range Efficiency)​

Default tuning pattern:

  • split long query_range requests into fixed windows (commonly 1h)
  • avoid caching near-now windows (or keep TTL very short)
  • keep historical window cache TTL longer for reuse
  • use adaptive bounded parallel fetch to improve range latency under healthy backend conditions

Recommended operator workflow:

  1. Start with conservative adaptive bounds (for example min 2, max 8).
  2. Observe backend latency/error EWMA and window cache hit ratio.
  3. Increase max parallel only when backend latency/error stays stable.
  4. Increase history TTL together with disk cache budget, not independently.

Key tuning signals:

  • loki_vl_proxy_window_cache_hit_total
  • loki_vl_proxy_window_cache_miss_total
  • loki_vl_proxy_window_fetch_seconds
  • loki_vl_proxy_window_merge_seconds
  • loki_vl_proxy_window_prefilter_attempt_total
  • loki_vl_proxy_window_prefilter_error_total
  • loki_vl_proxy_window_prefilter_kept_total
  • loki_vl_proxy_window_prefilter_skipped_total
  • loki_vl_proxy_window_prefilter_duration_seconds
  • loki_vl_proxy_window_adaptive_parallel_current
  • loki_vl_proxy_window_adaptive_latency_ewma_seconds
  • loki_vl_proxy_window_adaptive_error_ewma

Capacity approximation for history window caching:

required_disk_bytes ~= unique_windows_per_day * avg_window_bytes * ttl_days

Always cap disk cache explicitly with -disk-cache-max-bytes for predictable retention and node usage.

Benchmark Results​

Measured on Apple M3 Max (14 cores), Go 1.26.2, -benchmem.

Long-Range Phase Program Benchmarks (1h split windows)​

Command:

go test ./internal/proxy -run '^$' -bench 'BenchmarkQueryRangeWindowing_(NoPrefilter|WithPrefilter|StreamAwareBatching_Off|StreamAwareBatching_On)$' -benchmem -benchtime=10x
Benchmarkns/ophits_calls/opquery_calls/opmax_inflightallocs/opKey result
NoPrefilter39,525,225049n/a11,582baseline full fanout
WithPrefilter11,672,412489n/a10,346~81.6% fewer backend query calls
StreamAwareBatching_Off17,048,771n/an/a49,490higher concurrency under load
StreamAwareBatching_On62,808,025n/an/a19,656lower concurrency spikes, more stable backend pressure

Notes:

  • Prefiltering is the largest direct backend-load reduction lever for sparse long ranges.
  • Stream-aware batching intentionally trades raw synthetic throughput for lower backend saturation risk and fewer breaker cascades on real 2d/7d traffic.

Per-Request Latency​

OperationLatencyAllocsBytes/op
Labels (cache hit)2.0 us256.6 KB
QueryRange (cache hit)118 us600142 KB
wrapAsLokiResponse2.8 us582.6 KB
VL NDJSON to Loki streams (100 lines)170 us311870 KB
LogQL translation~5 us~20~2 KB

Cache Story In One Table​

These are the numbers that matter most when you want to judge the value of the cache stack rather than the implementation details:

PathSlow pathFast pathWhat it means
query_range4.58 ms cold miss with delayed backend0.64-0.67 us warm cache hitRepeated dashboards stop behaving like backend-bound requests
detected_field_values2.76 ms without Tier00.71 us with Tier0Drilldown metadata becomes effectively instant after warm-up
L1 memory cachefull handler/backend path45 ns hitLocal hot cache is essentially free
L2 disk cachebackend refill0.45 us uncompressed read, 3.9 us compressed readPersistent cache is still cheap enough for hot-path reuse
L3 peer cachebackend or owner re-fetch52 ns warm shadow-copy hitA warm 3-node fleet can reuse results instead of refetching them

Tier0 is most valuable on metadata-style and Drilldown-style endpoints where the proxy still has meaningful compatibility work to skip. On query_range, the deeper primary cache is already so effective that Tier0 mostly preserves that win rather than multiplying it.

Throughput​

ScenarioConcurrencyThroughputAvg LatencyErrors
Cache hit (labels)100175,726 req/s6 us0
No cache, 10 concurrent109,823 req/s102 us0
No cache, 50 concurrent5017,791 req/s56 us0
No cache, 200 concurrent20033,659 req/s30 us0
Cache miss (1ms backend)5012,976 req/s80 us0

Resource Usage at Scale​

Load (req/s)CPU (est.)MemoryNotes
100<1%~10 MBIdle, mostly cache hits
1,000~8%~20 MBMixed cache hit/miss
10,000~30%~50 MBBackend-bound
30,000+~100%~100 MBCPU-bound, scale horizontally

Memory Stability​

Under sustained load (10K requests, no cache):

  • Total allocation: ~70 KB/request (GC reclaims between requests)
  • Live heap growth: <1 MB (no leak)
  • GC handles ~200 cycles per 10K requests

1000-line NDJSON body (700 bytes/line, 700 KB input): 1.2 MB allocated total.

Test Coverage​

TestWhat it verifies
TestOptimization_VLLogsToLokiStreams_* (7 tests)Correctness of byte-scanned NDJSON parser
BenchmarkProxy_Series_CompatCacheHit / BenchmarkProxy_Series_NoCompatCacheTier0 hit-path cost versus the uncached route-execution path
TestPeerCache_ThreePeers_ShadowCopiesAvoidRepeatedOwnerFetches3-node fleet reuses one owner fetch per non-owner after warm-up
BenchmarkPeerCache_ThreePeers_ShadowCopyHitWarm non-owner reads stay local after the first peer shadow copy
TestOptimization_SyncPool_NoStateLeakPool doesn't leak labels between invocations
TestOptimization_SyncPool_ConcurrentSafety50 goroutines x 100 iterations, correct results
TestOptimization_ConnectionPool_HighConcurrency200 concurrent, 0 errors (port exhaustion regression)
TestOptimization_FormatVLStepVL step format conversion (8 cases)
TestOptimization_VLLogsToLokiStreams_ValidJSON100-line output produces valid parseable JSON
TestOptimization_NoMemoryLeak_SustainedLoad<200 KB/req allocation after 10K requests
TestOptimization_LargeBody_GCPressure1000-line body within allocation budget
TestLoad_NoCache_ScalingProfile3 concurrency tiers, 0 errors
TestLoad_WithCache_ScalingProfileSame tiers with cache enabled

Running Benchmarks​

# All proxy benchmarks
go test ./internal/proxy/ -bench . -benchmem -run "^$" -count=3

# Focus on the new Tier0 path
go test ./internal/proxy/ -bench 'BenchmarkProxy_Series_(CompatCacheHit|NoCompatCache)$' -benchmem -run "^$" -count=3

# Focus on fleet cache warm shadow-copy behavior
go test ./internal/cache/ -bench 'BenchmarkPeerCache_ThreePeers_ShadowCopyHit$' -benchmem -run "^$" -count=3

# Load tests
go test ./internal/proxy/ -run "TestLoad" -v -timeout=120s

# Optimization regression tests
go test ./internal/proxy/ -run "TestOptimization" -v

# CPU profile
go test ./internal/proxy/ -bench BenchmarkVLLogsToLokiStreams -cpuprofile=cpu.prof
go tool pprof cpu.prof

# Memory profile
go test ./internal/proxy/ -bench BenchmarkVLLogsToLokiStreams -memprofile=mem.prof
go tool pprof mem.prof

Go Runtime Tuning​

GOMEMLIMIT​

The Helm chart now injects GOMEMLIMIT at runtime. Resolution order:

  1. goMemLimit when explicitly set
  2. otherwise goMemLimitPercent of resources.limits.memory

In percentage mode, the chart computes bytes and exports that numeric value as GOMEMLIMIT.

# Default: 85% of memory limit
goMemLimitPercent: 85 # 256Mi * 85% => GOMEMLIMIT=228589772 (bytes)

# Override with explicit value
goMemLimit: "500MiB" # ignores goMemLimitPercent

Supported memory-limit units for percentage mode are integer quantities with Ki|Mi|Gi|Ti|Pi|Ei|K|M|G|T|P|E. If resources.limits.memory is missing or unsupported, the chart does not inject a computed GOMEMLIMIT.

GOGC​

GOGC=200 is the proxy default (set via -go-gc-percent=200), halving GC frequency at the cost of higher peak RSS versus Go's default of 100. Set -go-gc-percent=100 to restore Go's default, or lower it for tighter memory control.

Go Runtime Metrics Exposed​

The /metrics endpoint exposes Go runtime and GC statistics:

go_memstats_alloc_bytes # current heap allocation
go_memstats_sys_bytes # total OS memory
go_memstats_heap_inuse_bytes # heap in use
go_memstats_heap_idle_bytes # heap idle
go_goroutines # active goroutines
go_gc_cycles_total # completed GC cycles

CI Integration​

The bench job in .github/workflows/ci.yaml runs all benchmarks and load tests on every push. It:

  1. Runs benchmarks 3x for stability
  2. Runs load tests at all concurrency tiers
  3. Fails the build if load tests produce errors (regression gate)
  4. Uploads results as CI artifacts for historical tracking

The next CI step is to add compose-backed e2e cache/fleet smoke runs for pull requests and post-merge main builds, so Tier0 behavior and 3-node peer-cache gains are validated against the full Grafana + proxy + VictoriaLogs stack rather than only unit/load environments.

For TestLoad_HighConcurrency_MemoryStability, the throughput expectation is >10k req/s in local environments and >5k req/s on shared CI runners (CI=true) to reduce race-mode noise while still catching major regressions.