Skip to main content

Architecture

Overview​

Loki-VL-proxy is a read-only Loki compatibility proxy that sits between Grafana (or any Loki API client) and VictoriaLogs. It exposes Loki-compatible HTTP and WebSocket routes on the frontend, translates LogQL into LogsQL where needed, shapes VictoriaLogs responses back into Loki-compatible structures, and optionally exposes rules and alerts reads from a separate backend such as vmalert.

Cache semantic layers and storage tiers​

The proxy keeps two logical cache layers separate:

Semantic layerCached meaningValidity contract
Loki-facingLoki API answers and LogQL-derived results or fragmentsLoki route/profile/parser semantics, tenant/auth, bounds, step phase, ordering, limits and completeness
VictoriaLogs-facingVL API results or backend-result fragmentsBackend identity, tenant/auth, endpoint/query parameters, response schema, coverage and completeness

Each layer has its own key namespace, payload interpretation, admission, freshness, expiry, coalescing identity and invalidation rules. A backend cache hit can supply an explicit evaluation/conversion step; it is not a cached Loki answer. Loki-shaped results must never be interpreted as VL results either. Existing cache families retain their own eligibility and placement rules.

Loki query and query_range response identities include the effective max_query_series: the global flag, tenant/default overrides and the minimum across federated tenants. Replicas with different limits cannot share a partial or unrestricted response under the wrong policy, including a response read from SSD after restart. Equal resolved limits keep the same identity. This response policy does not enter the VL bucket namespace or metadata keys, so changing it preserves reusable backend data and label/field inventories.

Complete eligible ordered JSON metric query_range replies use the existing Loki-facing local response cache when the compatibility cache is inactive and response streaming is disabled (-stream-response=false). Capture is bounded by the cache's entry limit; errors, cancelled evaluations and oversized captures are not admitted. The five-minute response TTL and near-now maximum-staleness check apply independently. Full responses keep their local-only placement; this does not add VL raw-row caching, SSD/peer replication or reuse across different time windows.

These semantic layers may reuse the same bounded RAM pool, SSD engine/files, codecs, allocation pools and peer transport. RAM, SSD and peers describe storage tiers, not result semantics. Shared storage must preserve namespace and payload isolation, separate accounting and aggregate resource bounds; it does not imply that every family is persisted or replicated.

Resource reporting must distinguish each layer's occupancy, read/write bytes and rates, lookup outcomes, admission/rejection and eviction counts. Logical RAM and encoded SSD accounting are different from process RSS, bbolt file high-water and physical device throughput/IOPS. Legacy tier-level metrics remain aggregate. The semantic-layer metrics attribute supported resident/index/queue charges, lookup outcomes and logical record traffic to audited Loki/VL families, retaining an unknown category. They do not establish total cache-owned RAM or a physical file share per layer; mixed counters cannot establish a per-layer saving.

Current limits apply to individual cache instances and working resources, not one semantic-layer budget broker. The compatibility cache is additional to primary L1, and translation/stream-field-name caches have their own limits. The primary limit therefore does not establish a total cache-memory or process RSS bound. L2's byte cap counts logical records and keys; deleting records can leave free pages in the bbolt file. It does not cap physical file size.

The current persistence path names one shared database. Runtime configuration and Helm do not yet expose separate Loki/VL directories, complete per-layer RAM and physical-disk caps, or automatic sharing within those caps. Do not infer these controls from existing primary-cache or persistence-volume settings.

A purge of one semantic layer does not establish invalidation of the other. Backend deletion or security revocation must explicitly cover all affected layers, replicas, pending writes and in-flight refills. This contract does not claim that durable distributed invalidation is already implemented.

Tests and measurements distinguish the proxy's Loki-facing and VL-facing caches from the reference Loki server's own caches. They must not attribute a hit, miss, byte saving or invalidation across these boundaries without evidence.

Runtime Paths​

Protection Layers​

LayerPurposeDefault Config
Tenant validationEnforce Loki-style tenant header policy and mapping rules before backend accessEnabled on tenant-scoped routes
Per-client rate limiterPrevent individual client abuse-rate-limit-per-second=50, -rate-limit-burst=100
Global concurrent limitCap in-flight requests and backend operations (including fanout, until response bodies are consumed)-max-concurrent=100 (Helm chart default 64)
Request coalescingIdentical read requests share one run; failed answers are held per classAutomatic (-coalescer-disabled, -error-cache-*)
Query normalizationImprove cache hit rateSort matchers, collapse whitespace
Tier0 response cacheShort-circuit repeated safe GET reads after tenant validationEnabled, 10% of L1 memory budget, safe GET read endpoints only
Tiered cacheReduce backend calls with local, disk, and peer reuseL1 memory, optional L2 disk, optional L3 peer cache
Query-length enforcementReject requests whose time range exceeds the configured maximum-default-max-query-length=721h (Loki's max_query_length default; 0 disables it); per-tenant override via limits config; tenant limit takes precedence
Stats series and concurrency capsBound stats responses and parallel stats_query_range calls-max-stats-query-series=0 (built-in 1000, above Loki's 500), -stats-query-range-concurrency=0 (built-in 4)
Metadata lookbackBound /labels, /label/{name}/values and /series when the client omits start/end-metadata-default-lookback=12h
Execution budgetsReject oversized raw metric scans, binary expressions and line_format output with explicit errors instead of partial results-manual-range-metric-row-limit=1000000 plus fixed budgets; see Security hardening migration
Circuit breakerProtect VL from cascading failure-cb-fail-threshold=5 failures within -cb-window-duration=30s, -cb-open-duration=10s
Backend error redactionStrip query-like content (selectors, long quoted literals, long hex ids) from VictoriaLogs error bodies and transport errors before logging or returning themEnabled; disabled only by -debug-log-raw-queries=true
Admin and peer exposureKeep admin/debug routes off the public listener and authenticate peer cache trafficAdmin routes on -admin-listen=127.0.0.1:3101 unless -server.admin-auth-token is set; /metrics requires -server.register-instrumentation=true; peer cache refuses to start without -peer-auth-token unless -peer-insecure-ip-allowlist=true
Tail origin allowlistReject browser websocket origins unless explicitly trustedDeny browser origins by default

How Coalescing Works​

When 50 Grafana dashboards send {app="nginx"} |= "error" simultaneously:

Only 1 request reaches VictoriaLogs. All clients get the same response. This holds on every cached read route, for a failure as well as a success: a failure is handed over byte for byte with Loki's status and text, and a failed answer is then held per replica for the time of its class (-error-cache-transient-ttl, -error-cache-data-ttl; never pushed to peers), so refreshes of a failing query ask VictoriaLogs about once per second. Coalescing and cache keys include a scope fingerprint derived from the resolved tenant routing, backend identity, field mappings and forwarded identity, so requests from different tenants or authorization scopes never share a backend response.

Metadata read keys include the effective POST form parameters, with body values taking precedence over URL values as they do in the handlers. Normalization uses a copy of the form; POST bypasses the URL-only key memo. Equivalent GET and POST requests can reuse metadata entries. The singular /loki/api/v1/label route uses the labels handler and metadata identity of /loki/api/v1/labels; the outer GET compatibility cache still distinguishes their paths.

The affected label, detected-metadata, index-stats and volume namespaces fence entries created before form parameters were included. Upgrading can therefore cause initial metadata misses across memory, disk and peers. Old records become unreachable and follow existing expiry and eviction policies. This namespace change is an upgrade fence, not a distributed deletion-invalidation protocol.

Query And Metadata Flow​

Tier0 Cache Guardrails​

  • Tier0 is a separate cache instance that reuses the same cache implementation, but not the same keyspace, as the deeper L1/L2/L3 caches.
  • It runs only after tenant validation, auth checks, request logging setup, and route classification.
  • It only serves cacheable GET read endpoints such as query, query_range, series, labels, volume, patterns, and Drilldown metadata.
  • It never covers /tail, write/delete/admin paths, websocket upgrades, or non-JSON responses.
  • Its separate memory budget is added to primary L1, sized from -cache-max-bytes through -compat-cache-max-percent (default 10%, maximum 50%); it does not subtract from primary L1.
  • Tenant-map and field-mapping reloads invalidate Tier0 immediately so label translation and metadata exposure changes cannot go stale.

Cold Storage Routing​

When -cold-enabled=true and -cold-backend is set, the proxy time-splits queries based on their time range:

Query rangeRoute
Entirely within hot boundaryHot backend (VictoriaLogs) only
Entirely beyond cold boundaryCold backend (Victoria Lakehouse) only
Spans the boundary (overlap zone)Both backends; results merged at proxy

The boundary is configured via -cold-boundary (default 168h = 7 days). The overlap window (-cold-overlap, default 1h) ensures no gaps around the boundary by querying both backends in that zone.

For backward-direction queries spanning both backends, the proxy keeps at most limit cold lines (up to 5,000) in a ring buffer to reverse them before merging. Hot and forward-cold responses are buffered up to 64 MiB each; overflow or a read failure returns an error instead of a partial result.

Tail Flow​

Rules And Alerts Read Flow​

Data Model Mapping​

Loki vs VictoriaLogs​

Loki ConceptVL Equivalent
Stream labels_stream fields (declared at ingestion)
Structured metadataRegular fields (all others)
Timestamp_time
Log line body_msg
Parsed labelsFields from `

VictoriaLogs treats all fields equally, while Loki 3.x distinguishes stream labels, structured metadata, and parsed labels. In practice, Grafana Explore handles both transparently.

Log query responses group entries into streams the way Loki does: by stream labels plus the labels extracted by | json / | logfmt. With the categorize-labels encoding (and -emit-structured-metadata), extracted labels stay out of the stream object and are returned in each entry's parsed metadata; a level field returned by VictoriaLogs still adds level and detected_level to the stream labels. Single-request, windowed (-query-range-windowing) and -stream-response log queries share this stream resolution.

Label Translation​

VictoriaLogs stores OTel attributes with native dotted names (service.name), while Loki uses underscores (service_name). The -label-style flag controls translation:

ModeResponse DirectionQuery Direction
passthroughNo translationNo translation
underscoresservice.name → service_name{service_name="x"} → VL "service.name":"x"

Built-in reverse mappings cover 50+ OTel semantic convention fields.

E2E Test Architecture​

Component Design​

LogQL Parser (internal/logql/)​

Typed recursive-descent parser for LogQL. Produces a fully-typed AST (Expr interface with concrete node types: *LogQuery, *RangeAggregation, *VectorAggregation, *BinOpExpr, *OpaqueMetricExpr, …) that drives three subsystems:

  • Validation — ValidateLogQL(query) returns Loki-compatible error strings for invalid queries before any work is done.
  • Routing — proxy.go type-switches on the parsed AST to dispatch binary metric expressions, range aggregations and stream queries to separate execution paths (more reliable than regex-based marker injection).
  • Drop/Keep extraction — stream_processing.go extracts | drop/| keep matchers from the AST for VL response post-processing.

The parser includes a semantic pass for structural constraints (missing | unwrap inside rate_counter, __error__ inside rate(), malformed ip() filters, quantile phi bounds, line-format template validity). All error messages are formatted to match Loki 3.x exactly so Grafana clients receive the expected error shape.

See LogQL Parser deep dive for grammar, data flow diagrams, and extension points.

Translator (internal/translator/)​

LogQL→LogsQL converter. Receives canonical LogQL (produced by Expr.String() after AST normalisation). Translation uses two tiers: stable string operations for well-understood paths (stream selectors, line filters, label format) and typed logsql builder calls for complex paths (stats aggregations, IP filters).

Typed errors in internal/translator/errors.go replace bare fmt.Errorf for two failure classes: ParseError (invalid LogQL input) and UnsupportedError (LogQL constructs with no LogsQL equivalent). Callers can type-assert to distinguish parse failures from unsupported constructs; the query handlers return both as HTTP 400 with errorType: bad_data.

internal/logql/translate.go adds a second, typed translation path alongside the string-based translator: Translate(expr Expr, opts TranslateOptions) (string, error). For *LogQuery nodes it performs a direct AST-to-AST mapping — stream selector → logsql.FilterExpr, pipeline stages → []logsql.Pipe — without a String() roundtrip. Metric nodes (*RangeAggregation, *VectorAggregation, *BinOpExpr, *OpaqueMetricExpr) return an errFallthrough sentinel that routes to the existing string translator unchanged. TranslateOptions carries LabelFn, StreamFields, and Caps; the Caps field gates VL version-specific features. The proxy's main translation path (translator.TranslateLogQLWithCapabilities) is unchanged — logql.Translate is wired but not yet called by handlers.

Translation Pipeline​

See LogQL parser — Translation for the stage-by-stage mapping table and edge case reference.

Proxy (internal/proxy/)​

HTTP handlers for Loki-compatible read endpoints, split into domain-focused modules.

The Proxy struct is decomposed into three explicit types (migration in progress):

  • Deps (deps.go) — external dependencies: backend URLs, HTTP clients, caches, logger, metrics, rate limiter, circuit breaker.
  • HandlerConfig (config.go) — immutable startup configuration (83 flag-derived fields); pointer-shared across goroutines.
  • State (state.go) — mutable runtime state: tenant maps, label indices, pattern snapshots, backend version, atomics; pointer-typed mutexes for safe sharing.
  • Handler{Deps, Cfg *HandlerConfig, State *State} (handler.go) — carries all three concerns; populated by New(); routeHandler method extracted from the former anonymous rl closure in RegisterRoutes.
ModuleResponsibility
handler.goHandler struct definition and routeHandler dispatch method
deps.goDeps struct: external dependency container
config.goHandlerConfig struct: immutable startup configuration
state.goState struct: mutable runtime state
proxy.goConstructor (New()), RegisterRoutes, and remaining Proxy wiring
middleware.goRequest middleware chain: security headers, tenant validation, rate limiting, WebSocket upgrade checks
middleware_security.goSecurity-specific middleware: auth forwarding, token redaction, request fingerprinting
query_translation.goLogQL→LogsQL translation per request, structured request logging
query_range_windowing.goTime-window splitting and stitching for long-range metric queries
stream_processing.goVL→Loki stream conversion, label shaping, log line proxying
postprocess.goPost-query response shaping: limit enforcement, deduplication, sorting
multitenant.goMulti-tenant fanout, per-tenant narrowing, and Loki-shaped response merging
label_handlers.go/labels, /label/{name}/values, /series, /detected_fields HTTP handlers
label_metadata.goVL metadata fetching: field discovery, OTel attribute detection
label_index.goIn-process label-values index for low-latency label cardinality queries
cache_keys.goCache key construction: query_range, labels, series, detected_fields, volume
patterns.goPattern query handling, autodetection from query history, pattern clustering
patterns_persistence.goPattern snapshot persistence: load, save, and rotation
metric_agg.goInstant-vector queries and post-aggregation metric math
metric_binary.goStats queries and binary metric expression evaluation
volume.go/loki/api/v1/index/volume and /index/volume_range handlers
drilldown.goLogs Drilldown plugin metadata endpoints
tail.goWebSocket /tail with native VL stream and synthetic polling fallback
alerting.goHealth/readiness probes, rules and alerts read-through handlers
backend.goBackend HTTP client construction, TLS config, compression negotiation
telemetry.goPer-route Prometheus instrumentation, OTLP push, request duration histograms
time_utils.goTimestamp parsing, range normalization, step alignment helpers
http_utils.goHTTP error helpers, response header forwarding, Accept-Encoding negotiation
metric_eval_limits.goEvaluation point/sample bounds and numeric helpers shared by proxy-side metric evaluation
range_metric_compat.goRange metric compatibility shims for Loki 2.x vs 3.x divergences
vector_matching.goVector matching logic for binary metric operations
unwrap_convert.gounwrap expression conversion between LogQL and LogsQL forms
redact.goToken and credential redaction from logs and error messages
safety.goQuery safety checks: cardinality limits, expression complexity guards

Middleware (internal/middleware/)​

  • Rate limiter: per-client token bucket + global semaphore (-rate-limit-per-second, -rate-limit-burst, -max-concurrent)
  • Coalescer: singleflight-based request deduplication
  • Circuit breaker: 3-state (closed/open/half-open) with a sliding failure window (-cb-fail-threshold, -cb-window-duration, -cb-open-duration)

Cache (internal/cache/)​

Three lookup tiers: bounded L1 in-memory, optional L2 on-disk (bbolt with LRU capacity and S2/zstd/gzip/raw codecs), and optional L3 peer cache (consistent hash ring, zstd/gzip on larger peer transfers). L0 is a bounded hot-key index beside L1 that drives peer hot read-ahead; it is reported as tier="l0" in cache metrics but is not a lookup tier. POST /admin/cache/flush clears L0, L1 and L2 locally; with ?peers=1 it also fans out to every peer's /_cache/purge. Disk encryption is delegated to cloud provider (EBS, PD, etc.).

Metrics (internal/metrics/)​

Prometheus text exposition at /metrics (served only with -server.register-instrumentation=true, optionally on a dedicated -metrics-listen address) plus OTLP push. Route-aware downstream and upstream request metrics, tenant/client breakdowns, cache and windowing metrics, peer-cache state, circuit-breaker state, and prefixed process/runtime health.