Prometheus (remote write, remote read and the query API): implementation reference
How the Prometheus listener is built: HTTP handling, authentication, remote write and remote read framing, the PromQL engine and HTTP query API, in-memory and durable storage, errors, limits and tests. For the scores, how to turn the wire on and how to re-run the compliance harness, see the operator page Prometheus. Authentication policy across all wires is in Security. A separate Prometheus-format /metrics endpoint for SynergyDB's own metrics lives on the HTTP API port and is described in HTTP API.
1. Source layout
| File | Role |
|---|---|
src/protocol/prometheus/mod.rs |
PrometheusHandler: listener, HTTP/1.1 parsing, authentication, route table, query API handlers, JSON formatting, legacy table migration |
src/protocol/prometheus/remote.rs |
Snappy framing and a hand-written protobuf reader and writer for prompb.WriteRequest and ReadRequest/ReadResponse, including native histograms |
src/protocol/prometheus/storage.rs |
TimeSeriesStorage: in-memory series, label index, head window, eviction, retention |
src/protocol/prometheus/persist.rs |
PromStore: durable samples and metadata in the shared key-value engine; the cold store for evicted samples |
src/protocol/prometheus/types.rs |
Labels, matchers, samples, metadata, API response types |
src/protocol/prometheus/promql/ |
PromQL lexer, parser, type checker, evaluator, functions, native histogram arithmetic, Go-compatible float formatting |
The listener is a hand-written HTTP/1.1 server on Tokio; it does not use hyper. Third-party crates used here: snap (raw and framed snappy), serde_json, regex (label matchers), chrono, base64, bytes. Protobuf messages are encoded and decoded by hand in remote.rs, not with prost. (source: src/protocol/prometheus/remote.rs, ProtobufReader, ProtobufWriter, snappy_decode; src/protocol/prometheus/mod.rs, use lines)
2. Transport
- Port:
[server] prometheus_port, default 9091 inServerConfig::default. The Docker image's default config does not set it;docker/synergydb.allwires.tomldoes. (source:src/config.rs,ServerConfig::default;docker/synergydb.allwires.toml; Prometheus) - When TLS is configured, every connection is wrapped with
TlsListener::acceptbefore any HTTP byte (implicit TLS): a plaintext client cannot use the port. This differs from Kafka and Schema Registry, which detect TLS by the first byte. (source:src/protocol/prometheus/mod.rs,start,with_tls) Not verified: no test covers Prometheus over TLS. - Requests are read with a
BufReader: request line, headers (names lowercased), thenContent-Lengthbytes of body.Transfer-Encoding: chunkedis not read. A declared length abovemax_body_size(100 MiB) is not refused; only the first 100 MiB is read, and the rest is left on the socket. (source:src/protocol/prometheus/mod.rs,parse_request,PrometheusConfig::default) - A new
BufReaderis created for every request, so bytes it read past the end of one request are discarded. Not verified: from the code, pipelined requests on one connection can be lost; no test sends pipelined requests. - The connection is kept open after each response until the client closes it or a request fails to parse. There is no read or idle timeout. (source:
src/protocol/prometheus/mod.rs,handle_connection) - The body is read before authentication. (source:
src/protocol/prometheus/mod.rs,handle_connection,route_request; Security)
3. Authentication
Every request except GET/HEAD /-/healthy and /-/ready is authenticated before routing:
-
Authorization: Basic base64(user:pass)with a non-empty user or password is checked byverify_wire_credential("prometheus", ...): a catalog role and password, and the role must be a superuser or a member ofsynergy_wire_prometheusorsynergy_wire_all(unlessSYNERGYDB_WIRE_ACCESSisopen,offorany). A wrong credential is 401 even in dev mode. - With no credential, the request is served only when
SYNERGYDB_DEV_INSECURE_AUTHis1ortrue; otherwise 401.
Bearer tokens are not accepted. The 401 body is {"status":"error","errorType":"unauthorized","error":"..."}. (source: src/protocol/prometheus/mod.rs, authenticate, extract_basic_credentials, is_health_endpoint, HttpResponse::unauthorized; src/auth/wire_auth.rs, verify_wire_credential) Tested by test_is_health_endpoint and test_extract_basic_credentials in src/protocol/prometheus/mod.rs. Not verified: no test sends a request through route_request without credentials and checks the 401.
Once authenticated, a principal can write and read every series; there is no tenant or per-metric authorization. (source: src/protocol/prometheus/mod.rs, route_request)
Audit: when the audit log is on, every /api/... request is recorded with wire prometheus, <METHOD> <path> as the action, the HTTP status and the query or match[] text (truncated to 4,096 characters). Paths ending in /write or containing /admin/ are writes; the rest are reads. 401 and 403 are recorded as denied. (source: src/protocol/prometheus/mod.rs, handle_connection) Not verified: no test of the audit records was found.
4. Endpoints
The complete route table from route_request. Anything else answers 404 {"status":"error","errorType":"not_found","error":"Endpoint not found: <METHOD> <path>"}.
| Method | Path | Behaviour |
|---|---|---|
| GET, HEAD | /-/healthy |
200 Healthy. (no auth) |
| GET, HEAD | /-/ready |
200 Ready. (no auth) |
| POST | /api/v1/write |
Remote write (section 5); 204 |
| POST | /api/v1/read |
Remote read (section 6); snappy protobuf |
| GET, POST | /api/v1/query |
Instant query: query, time
|
| GET, POST | /api/v1/query_range |
Range query: query, start, end, step (all required) |
| GET, POST | /api/v1/series |
Series matching match[], with start, end, limit
|
| GET, POST | /api/v1/labels |
Label names, optionally filtered by match[], with start, end, limit
|
| any | /api/v1/label/{name}/values |
Values of one label, optionally filtered; UTF-8 label names in the escaped U__ form are unescaped |
| GET | /api/v1/metadata |
Metric metadata from remote write; metric, limit, limit_per_metric
|
| GET, POST | /api/v1/query_exemplars |
Parses query, then always returns [] (exemplars are not stored) |
| GET | /api/v1/targets |
Stub: empty activeTargets and droppedTargets
|
| GET | /api/v1/rules |
Stub: no groups |
| GET | /api/v1/alerts |
Stub: no alerts |
| GET | /api/v1/status/config |
Stub: empty YAML |
| GET | /api/v1/status/flags |
Stub: {}
|
| GET | /api/v1/status/runtimeinfo |
Fixed values; startTime is the request time; storageRetention is 15d
|
| GET | /api/v1/status/buildinfo |
version 3.13.5 (the API level clients such as Grafana read), revision synergydb-<crate version>
|
| GET | /api/v1/status/tsdb |
headStats.numSeries from storage; the other figures are zero or empty |
(source: src/protocol/prometheus/mod.rs, route_request, handle_healthy, handle_ready, handle_series, handle_labels, handle_label_values, handle_metadata, handle_targets, handle_rules, handle_alerts, handle_status_*, unescape_label_name)
Parameters come from the query string and, for a body with Content-Type: application/x-www-form-urlencoded, from the form body (the query string wins on a clash). match[] may repeat. Timestamps (time, start, end) are a number or RFC 3339; a number above 10^12 is read as milliseconds, anything else as seconds, where Prometheus always reads seconds. step is a float number of seconds or a Prometheus duration. (source: src/protocol/prometheus/mod.rs, get_params, match_values, parse_timestamp, parse_step)
Not implemented: the admin APIs (/api/v1/admin/tsdb/delete_series, clean_tombstones, snapshot), /api/v1/format_query, /api/v1/parse_query, /api/v1/notifications, /api/v1/targets/metadata, /api/v1/alertmanagers, /federate, /metrics, /-/reload, /-/quit, the OTLP receiver and the web UI all answer 404. Scraping is not implemented: data arrives only by remote write. (source: src/protocol/prometheus/mod.rs, route_request) PromStore::delete_series exists but no route calls it.
Tested by metadata_endpoints_follow_prometheus, test_instant_query and test_parse_query_string in src/protocol/prometheus/mod.rs.
5. Remote write
(source: src/protocol/prometheus/mod.rs, handle_remote_write, in_order_samples; src/protocol/prometheus/persist.rs, PromStore::write; src/protocol/prometheus/remote.rs, parse_write_request, RemoteStorageHandler::ingest)
-
Framing. The body is snappy-compressed protobuf.
snappy_decodetries raw snappy first (what Prometheus sends) and falls back to the snappy framing format. A raw body that declares a decompressed length over 64 MiB (MAX_DECOMPRESSED_BODY) is refused before allocating.Content-Type,Content-EncodingandX-Prometheus-Remote-Write-Versionare not inspected. (source:src/protocol/prometheus/remote.rs,snappy_decode,MAX_DECOMPRESSED_BODY) Tested bysnappy_length_bomb_is_rejected_before_allocating,normal_bodies_still_decodeandtest_snappy_roundtripinremote.rs. -
Message.
prompb.WriteRequest(remote write 1.0): field 1timeseries(labels, float samples, exemplars skipped, native histograms with spans, deltas or absolute counts), field 3metadata(type, metric family name, help, unit). Unknown fields are skipped; truncated or overlong fields and overflowing varints are protocol errors. Remote write 2.0 (io.prometheus.write.v2.Request, with a symbol table) is not parsed. (source:src/protocol/prometheus/remote.rs,parse_write_request_proto,parse_timeseries_full,parse_histogram,parse_metadata) Tested bytruncated_unknown_fixed_fields_return_protocol_error,oversized_unknown_length_returns_protocol_errorandoverflowed_varint_returns_protocol_error. -
Ordering. Per series, float samples older than the newest stored timestamp are dropped silently before the commit; a sample at exactly the newest timestamp is kept (a retry). The response is still 204. Prometheus itself refuses out-of-order samples with an error. Native histogram samples are not filtered this way. (source:
src/protocol/prometheus/mod.rs,in_order_samples) -
Durability. The samples are committed to the key-value engine (
write_batch, chunks of at most 50,000 entries) on a blocking thread before the reply. A failed commit is 500internal, which Prometheus retries. Only then are the samples applied to memory. (source:src/protocol/prometheus/mod.rs,handle_remote_write;src/protocol/prometheus/persist.rs,PromStore::commit,MAX_BATCH) Tested byremote_write_survives_restart_and_legacy_rows_migrateinmod.rsandeverything_survives_reopeninpersist.rs. -
Errors after commit. If ingesting into memory fails after the commit, for example when a new series would pass the 1,000,000-series limit, the reply is 400
bad_dataalthough the samples are already stored. (source:src/protocol/prometheus/mod.rs,handle_remote_write;src/protocol/prometheus/storage.rs,get_or_create_series) Not verified: no test covers this path. -
Duplicates. In memory, a float sample whose timestamp is not after the series' last timestamp and within 1 s of it is not added again (
dedup_window_ms). (source:src/protocol/prometheus/storage.rs,Series::add_sample,TsStorageConfig::default) Tested bytest_deduplicationinstorage.rs.
6. Remote read
POST /api/v1/read takes a snappy ReadRequest (queries with start, end, label matchers and hints). For each query it selects the matching series over the time range, with Prometheus matcher semantics (a missing label equals the empty string), and writes a ReadResponse with one QueryResult per query, each series carrying float samples (field 2) and native histograms (field 4). The response is raw snappy with Content-Type: application/x-protobuf and Content-Encoding: snappy. (source: src/protocol/prometheus/remote.rs, parse_read_request, parse_read_query, RemoteStorageHandler::handle_read; src/protocol/prometheus/mod.rs, HttpResponse::protobuf) Tested by remote_read_returns_floats_and_native_histograms in remote.rs.
Only the SAMPLES response type is produced. accepted_response_types is not read, so a client asking for STREAMED_XOR_CHUNKS gets a samples response. Read hints are parsed and not used. (source: src/protocol/prometheus/remote.rs, handle_read, parse_read_hints) The operator page reports remote read 40/40 in the Grafana harness.
7. PromQL and the query API
The engine follows Prometheus 3.x semantics, per the module comment: left-open lookback and range windows, staleness markers, extrapolated rate, increase and delta, subqueries, offset, @, start(), end() and bool modifiers, full vector matching (on, ignoring, group_left, group_right) with many-to-many and duplicate-labelset errors, Kahan-compensated aggregations, classic and native histogram functions. The parser applies Prometheus's static checks (argument types and arity, set operators only between vectors, comparisons between scalars need bool, selectors that match the empty string everywhere are refused). (source: src/protocol/prometheus/promql/mod.rs, module comment; src/protocol/prometheus/promql/parser.rs; docs/status/2026-11-24-promql-engine.md)
Aggregation operators (AggOp::from_name): sum, avg, count, min, max, group, stddev, stdvar, topk, bottomk, count_values, quantile, limitk, limit_ratio. The last two are experimental in Prometheus and accepted here without a feature flag. (source: src/protocol/prometheus/promql/ast.rs, AggOp::from_name; docs/status/2026-11-24-promql-engine.md)
Functions, the complete FUNCS table:
| Group | Functions |
|---|---|
| Counters and gauges over ranges |
rate, irate, increase, delta, idelta, deriv, predict_linear, resets, changes, double_exponential_smoothing
|
*_over_time |
avg_over_time, sum_over_time, count_over_time, min_over_time, max_over_time, stddev_over_time, stdvar_over_time, quantile_over_time, mad_over_time, last_over_time, first_over_time, present_over_time, absent_over_time
|
| Histograms |
histogram_quantile, histogram_fraction, histogram_count, histogram_sum, histogram_avg, histogram_stddev, histogram_stdvar
|
| Math |
abs, ceil, floor, round, sqrt, exp, ln, log2, log10, sgn, clamp, clamp_min, clamp_max, pi, deg, rad
|
| Trigonometry |
sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh
|
| Time |
time, timestamp, year, month, day_of_month, day_of_week, day_of_year, days_in_month, hour, minute
|
| Labels and types |
label_replace, label_join, vector, scalar, absent
|
| Sorting |
sort, sort_desc, sort_by_label, sort_by_label_desc
|
(source: src/protocol/prometheus/promql/functions.rs, FUNCS, call) Any other name is a parse error. info() and the Prometheus 3.5+ ts_of_*_over_time functions are not in the table.
Query API behaviour:
| Rule | Value |
|---|---|
| Lookback for instant selectors | 5 minutes (DEFAULT_LOOKBACK_MS) |
| Default subquery step | 1 minute |
| Points per series in a range query | at most 11,000 (exceeded maximum resolution of 11,000 points per timeseries...) |
| Subquery steps | at most 1,000,000 |
| Timestamps | within ±2^60 ms |
| Parse and type errors | 400, errorType bad_data
|
| Evaluation errors | 422, errorType execution
|
| Float output | Go's formatting (NaN, +Inf, -Inf, 2.02e-07) |
(source: src/protocol/prometheus/promql/eval.rs, DEFAULT_LOOKBACK_MS, DEFAULT_SUBQUERY_STEP_MS, MAX_POINTS_PER_SERIES, MAX_SUBQUERY_STEPS; src/protocol/prometheus/promql/mod.rs, MAX_ABS_TS, format_value; src/protocol/prometheus/mod.rs, promql_error)
The timeout, lookback_delta, limit (on queries) and stats query parameters are not read. Not wired: PrometheusConfig has lookback_delta_ms and query_timeout_ms fields with defaults of 5 minutes and 2 minutes, but no code reads them, so a query has no time limit. enable_remote_write and enable_remote_read are read (403 when false), but the server always builds the handler with the defaults (both true) and there is no config key for them. (source: src/protocol/prometheus/mod.rs, PrometheusConfig, with_synergy_storage, handle_remote_write, handle_remote_read)
Tested by 10 tests in src/protocol/prometheus/promql/tests.rs (parses_full_grammar, rejects_invalid_queries, scalar_arithmetic_and_precedence, lookback_and_offset, staleness_marker_ends_series, rate_handles_reset_and_extrapolation, vector_matching_and_aggregation, subquery_and_range_query, bad_ranges_and_timestamps_error, classic_histogram_quantile) and by the official compliance suite (section 10).
8. Storage
8.1 In memory
TimeSeriesStorage keeps one Series per label set (fingerprinted), each with a BTreeMap of float samples and one of native histograms, plus an inverted label index (label name to value to series ids, and metric name to series ids). (source: src/protocol/prometheus/storage.rs, Series, LabelIndex)
| Setting | Default | Effect |
|---|---|---|
Head window, SYNERGYDB_PROMETHEUS_HEAD_HOURS
|
3 hours | With the durable store attached, samples older than this leave memory and are read back from the store on query; 0 keeps everything in memory |
Eviction interval, SYNERGYDB_PROMETHEUS_EVICT_SECS
|
60 s | How often samples past the head window are dropped from memory (checked on write and query) |
Retention (TsStorageConfig::retention_ms) |
15 days | Applied hourly in memory and, on writes, to the store; no config key or variable changes it |
Maximum series (max_series) |
1,000,000 | A new series beyond it is an error |
Dedup window (dedup_window_ms) |
1 s | Section 5 |
(source: src/protocol/prometheus/storage.rs, TsStorageConfig::default, head_window_from_env, maybe_run_maintenance, run_maintenance, evict_cold; src/protocol/prometheus/mod.rs, maybe_purge; docs/status/2026-11-30-prometheus-head-window.md) Tested by evicted_samples_read_back_from_store in persist.rs, which compares answers with eviction against all-in-memory answers before and after a restart.
max_samples_per_series (100,000) is in the config struct but nothing reads it. (source: src/protocol/prometheus/storage.rs, TsStorageConfig) Samples are never downsampled. (source: src/protocol/prometheus/storage.rs, run_maintenance doc comment)
8.2 On disk
| Key | Value |
|---|---|
__prom__:d: + u32 BE length + series key + timestamp (i64 with the sign bit flipped, big-endian) |
0 + f64 bits (little-endian) for a float sample, or 1 + an encoded FloatHistogram
|
__prom__:m: + metric name + NUL + JSON (type, help, unit)
|
JSON MetricMetadata, one key per distinct entry |
__prom__:legacy_migrated |
Marker that the old SQL table was migrated |
The series key is the JSON array of [name, value] pairs, so it decodes back to the label set, and the keys of one series sort by time, so retention deletes a contiguous range. Float samples are stored bit for bit, so staleness markers (a NaN payload) survive a restart. (source: src/protocol/prometheus/persist.rs, module comment, series_key, data_key, encode_histogram) Tested by keys_sort_by_time_and_split_back and histogram_roundtrip in persist.rs.
At startup, with_synergy_storage first moves rows from the SQL table _prometheus_samples that older builds wrote into the key-value layout and empties the table, then loads the head window into memory and registers series whose samples are all older with no samples, so they are still found. (source: src/protocol/prometheus/mod.rs, with_synergy_storage, migrate_legacy_table; src/protocol/prometheus/persist.rs, load_with_head) Tested by remote_write_survives_restart_and_legacy_rows_migrate.
There is no cluster replica listener in this module: in a multi-node deployment, samples written on one node's Prometheus port are not loaded into another node's memory until it restarts. (source: src/protocol/prometheus/mod.rs, with_synergy_storage) Not verified: no test covers Prometheus in a cluster.
9. Errors and limits
Error responses follow the Prometheus API shape {"status":"error","errorType":...,"error":...}.
| Status | errorType |
When |
|---|---|---|
| 400 | bad_data |
Missing body or parameter, bad timestamp or step, PromQL parse or type error, bad match[], remote write or read decode error, memory ingest error after commit |
| 401 | unauthorized |
Missing or wrong credentials |
| 403 | forbidden |
Remote write or read disabled (not reachable with the server's defaults) |
| 404 | not_found |
Unknown endpoint |
| 422 | execution |
PromQL evaluation error |
| 500 | internal |
Storage commit failed on remote write |
(source: src/protocol/prometheus/mod.rs, HttpResponse::error, promql_error, handlers)
| Setting | Default | Effect |
|---|---|---|
[server] prometheus_port |
9091 (unset in the Docker image's default config) | Listener port |
| TLS settings | off | Implicit TLS on the port |
SYNERGYDB_DEV_INSECURE_AUTH |
unset | Serve requests with no credentials |
SYNERGYDB_WIRE_ACCESS |
enforced |
open/off/any drops the synergy_wire_prometheus check |
SYNERGYDB_PROMETHEUS_HEAD_HOURS |
3 | Head window |
SYNERGYDB_PROMETHEUS_EVICT_SECS |
60 | Eviction interval |
max_body_size (constant default) |
100 MiB | Body read limit (truncates, does not refuse) |
MAX_DECOMPRESSED_BODY (constant) |
64 MiB | Snappy decompressed size limit |
(source: src/config.rs; src/protocol/prometheus/mod.rs, PrometheusConfig::default; src/protocol/prometheus/remote.rs; src/protocol/prometheus/storage.rs)
10. Tests and proof evidence
| Where | What |
|---|---|
tests/protocol_prometheus.rs (63 tests) |
TimeSeriesStorage and the evaluator called directly, not over HTTP: writes, overwrite at the same timestamp, range and instant selection, label names and values, the four matcher operators, series metadata, eval_instant/eval_range with arithmetic and the basic aggregations, label cardinality, series deletion |
| Unit tests |
mod.rs 8, remote.rs 12, storage.rs 4, persist.rs 4, types.rs 5, promql/tests.rs 10, promql/gomath.rs 1 |
docs/proof/2026-11-30/proof-pack-a3232c9/promql-compliance-run.txt.gz |
Official prometheus/compliance PromQL suite against Prometheus 3.13.5: 661 test cases pass, none fail |
docs/status/2026-11-30-prometheus-head-window.md |
Compliance 661/661 again with a 1.8 s head window and 1 s eviction, so nearly every query reads from disk |
The Grafana Node Exporter Full check (302/302 panel queries), remote read 40/40 and the kill -9 restart 27/27 quoted on the operator page come from test-scripts/prometheus-grafana/, which is not in the reviewed snapshot, and no log of those runs is in the proof pack. The proof pack's report.md describes Prometheus as covered by a "9-probe check; no diff suite yet", which is older wording than the compliance run in the same pack. The Prometheus wire is not part of make prove. (source: docs/proof/2026-11-30/proof-pack-a3232c9/report.md; Prometheus)
Not verified: no Rust test drives the HTTP listener over a socket (the handler tests call route_request or internal functions directly), and none covers TLS, authentication refusal, pipelining, the 100 MiB body truncation or the out-of-order drop.