Codebase analysis · CoreStory V3

Prometheus

An open-source monitoring system and time series database, written in Go. It scrapes metrics, stores them, evaluates alerting and recording rules, and answers PromQL queries. Maintained by the Prometheus project.

Maintained by
the Prometheus project
License
Apache-2.0
Commit analyzed
49c815a0ea46c7a6a6b723e4b634c4bf36f7022c
Rules extracted
2026-11-15
Extracted by CoreStory V3
13450
accepted rules, each with a cited source quote
27
capabilities
1952
features
01 · Rules

Business rules, traced to source lines.

These 12 rules are a sample of the 13,450 CoreStory V3 extracted from Prometheus. Each one links to the exact lines on GitHub at commit 49c815a. The statement is CoreStory V3’s wording; the code excerpt is the source it cites.

limit
web/api/v1/api.go

For range queries and range cost queries, the number of returned points per timeseries is limited; if (end - start) / step exceeds 11000, the request is rejected as bad data with an error mentioning the maximum resolution of 11,000 points per timeseries.

  • 11000 — maximum points per timeseries
// For safety, limit the number of returned points per timeseries. // This is sufficient for 60s resolution for a week or 1h resolution for a year. if end.Sub(start)/step > 11000 { err := errors.New("exceeded maximum resolution of 11,000 points per timeseries. Try decreasing the query resolution (?step=XX)") return apiFuncResult{nil, &apiError{errorBadData, err}, nil, nil} }

Also cited: L1100–L1105

validation
promql/engine.go

Per-query overrides for max_series, max_samples_read, and max_query_duration may only lower the operator-set ceiling, never raise it; zero means no override. An override above the ceiling is rejected with ErrLimitAboveCeiling rather than silently clamped.

  • max_series — client-facing limit name for series
var err error if qry.maxSeries, err = resolveUintLimit("max_series", reqSeries, ceilSeries); err != nil { return nil, nil, err } if qry.maxSamplesRead, err = resolveUintLimit("max_samples_read", reqSamplesRead, ceilSamplesRead); err != nil { return nil, nil, err }
calculation
rules/alerting.go

When sending an alert, its ValidUntil is set to ts plus 4 times the maximum of interval and resendDelay, allowing for two Eval or Alertmanager send failures.

  • 4 — multiplier for delta when computing ValidUntil
delta := max(interval, resendDelay) alert.ValidUntil = ts.Add(4 * delta)
limit
rules/recording.go

When the limit is greater than 0 and the number of series produced by the recording rule evaluation exceeds the limit, evaluation fails with an error reporting the limit and the actual number of series.

  • 0 — threshold above which the limit is enforced (limit must be greater than 0)
numSeries := len(vector) if limit > 0 && numSeries > limit { return nil, fmt.Errorf("exceeded limit of %d with %d series", limit, numSeries) }
validation
rules/alerting.go

If two alerts produced by evaluation yield the same labelset after applying alert labels, the evaluation fails with ErrDuplicateAlertLabelSet ("vector contains metrics with the same labelset after applying alert labels").

  • vector contains metrics with the same labelset after applying alert labels — error message for duplicate labelsets
if _, ok := alerts[h]; ok { return nil, ErrDuplicateAlertLabelSet }

Also cited: L54

calculation
cmd/prometheus/main.go

In non-agent mode, when storage.tsdb.max-block-duration is 0, it defaults to 31d; if the retention duration is non-zero and retention/10 is less than that default, the max block duration is set to retention/10.

  • 0 — flag value that triggers the default max block duration
  • 31d — default maximum block duration
  • 10 — divisor applied to the retention duration
// Max block size settings. if cfg.tsdb.MaxBlockDuration == 0 { maxBlockDuration, err := model.ParseDuration("31d") if err != nil { panic(err) } // When the time retention is set and not too big use to define the max block duration. if cfg.tsdb.RetentionDuration != 0 && cfg.tsdb.RetentionDuration/10 < maxBlockDuration { maxBlockDuration = cfg.tsdb.RetentionDuration / 10 } cfg.tsdb.MaxBlockDuration = maxBlockDuration }
validation
cmd/prometheus/main.go

In non-agent mode, when storage.tsdb.retention.percentage is greater than 0, storage.tsdb.retention.size is ignored (with a warning), and if the total capacity of the metric storage path cannot be detected the process prints an error with the path and percentage and exits with status 2.

  • 0 — threshold above which the percentage retention path applies
if cfg.tsdb.MaxPercentage > 0 { if cfg.tsdb.MaxBytes > 0 { logger.Warn("storage.tsdb.retention.size is ignored, because storage.tsdb.retention.percentage is specified") } if storagePathFsSize(localStoragePath) == 0 { fmt.Fprintln(os.Stderr, fmt.Errorf("unable to detect total capacity of metric storage at %s, please disable retention percentage (%g%%)", localStoragePath, cfg.tsdb.MaxPercentage)) os.Exit(2) } }
validation
model/rulefmt/rulefmt.go

For alerting rules only, templates used in labels and annotations must parse successfully; label templates that fail produce "label %q: %w" and annotation templates that fail produce "annotation %q: %w" errors.

  • label %q: %w — error prefix for failing label template
  • annotation %q: %w — error prefix for failing annotation template
// Parsing Labels. for k, val := range rl.Labels { err := parseTest(val) if err != nil { errs = append(errs, fmt.Errorf("label %q: %w", k, err)) } } // Parsing Annotations. for k, val := range rl.Annotations { err := parseTest(val) if err != nil { errs = append(errs, fmt.Errorf("annotation %q: %w", k, err)) } }
limit
scrape/target.go

limitAppenderV2.Append increments the counter and returns errSampleLimit when the counter exceeds the limit, except when writing a staleness marker for a known series (ref non-zero and non-stale value).

  • sample limit exceeded — error message returned when limit exceeded
if ref == 0 || !value.IsStaleNaN(v) { app.i++ if app.i > app.limit { return 0, errSampleLimit } }

Also cited: L373

validation
config/config.go

A remote_write config with a non-empty name that duplicates a previously seen non-empty remote_write name fails loading with 'found multiple remote write configs with job name'; empty names are skipped and filled with a config hash elsewhere.

// Skip empty names, we fill their name with their config hash in remote write code. if _, ok := rwNames[rwcfg.Name]; ok && rwcfg.Name != "" { return fmt.Errorf("found multiple remote write configs with job name %q", rwcfg.Name) }

Also cited: L455, L467

validation
tsdb/agent/db_append_v2.go

When appending a sample, if the sample timestamp t is less than or equal to the minimum valid time computed from the series' last timestamp, the out-of-order samples metric is incremented and the append returns series ref 0 with storage.ErrOutOfOrderSample.

  • 0 — series reference returned on out-of-order sample
if t <= a.minValidTime(lastTS) { a.metrics.totalOutOfOrderSamples.Inc() return 0, storage.ErrOutOfOrderSample }

Also cited: L67–L69

policy
config/config.go

In agent mode, loading a config file that lists any rule_files fails with 'field rule_files is not allowed in agent mode'.

if len(cfg.RuleFiles) > 0 { return nil, errors.New("field rule_files is not allowed in agent mode") }

Also cited: L142

02 · Capabilities

What the application does

27 capabilities identified, grouping 157 of the 1,910 distinct features extracted. Most extracted features are not grouped under a capability, so this list is a partial view of the application. These are descriptions, not the cited rules above.

Time-Series Storage (TSDB)

Persistent local storage of time-series samples in head and blocks with compaction and retention.

  • Background Block Compaction: Automatically compacts in-order and out-of-order head data and existing blocks, and schedules compactions with delay.
  • Block Compaction: Compacting storage blocks with options for delayed, overlapping, and stale-series-aware compaction.
  • Block Creation: Creating persisted storage blocks from head data, including optionally from out-of-order head samples.
  • Chunk Encoding: Encode data into chunks using an encoding scheme.
  • Data Retention and Truncation: Enforce time-based retention by garbage collecting and truncating old data and WAL segments.
  • Head Block Compaction: Compacting the head into persistent blocks, including with deletion, ST storage, and checkpoint creation.
  • Head Compaction: Compacts recent in-memory/head blocks including out-of-order data into persistent blocks.
  • Series Lifecycle Management: Handles series reset, dropping of old time-series, and timestamp-based obsolescence across the queue.
  • Time Series Storage: Persists and retrieves time-series samples, gauges, and histograms with support for counter reset metadata.
  • XOR2 Chunk Encoding: Encoding and decoding sample values using XOR2 delta compression.

Alerting and Notification

Evaluation of alerting rules and delivery of fired alerts to Alertmanager and other notifiers.

  • Alert Delivery: Sends alerts to the discovered Alertmanager instances with batching and retry handling.
  • Alert Generation: Produce alert instances with labels, annotations, timing, and source URLs for downstream notification.
  • Alert Grouping: Groups related alerts together for consolidated handling and notification.
  • Alert Notification Dispatch: Sends and queues alerts to alertmanagers, distributing them across destinations and per-AM remapping.
  • Alert Rule Evaluation: Evaluates PromQL expressions within alerting rule groups and fires alerts when conditions are met, such as instances being down.
  • Alert State Series Querying: Exposing alert rule state (pending/firing) as queryable time series with template-derived labels.
  • Alert Template Expansion: Expands alert message templates with query-derived data to render the final notification text.
  • Alerting: Evaluates alerting rules against collected metrics and dispatches notifications to configured Alertmanager endpoints.
  • Alertmanager Discovery: Discovers and tracks the set of Alertmanager targets, reporting active and dropped instances.

Metrics Ingestion Pipelines

Ingesting metrics via Prometheus, OpenMetrics, OTLP, and remote-write protocols.

  • OTLP Ingestion: Accepts OpenTelemetry OTLP metrics data over HTTP for ingestion.
  • OTLP Metrics Ingestion: Ingesting metrics over OTLP with label sanitization, resource attribute sanitization, scope metadata promotion, UTF-8 handling, and histogram conversion.
  • OpenMetrics Parsing: Parse OpenMetrics exposition text into structured metric samples, including support for bare identifiers, UTF-8 names, and error handling for malformed input.
  • OpenMetrics Text Parsing: Parses OpenMetrics exposition text into a sequence of metric series, tokens, and metadata.
  • Prometheus Protobuf Parsing: Parses Prometheus remote-write protobuf payloads into series and histograms.
  • Prometheus Remote Write Ingestion: Accepts Prometheus remote-write payloads and converts gauge and sum samples into ingested data points.
  • Prometheus Text Format Parsing: Parse Prometheus/OpenMetrics exposition text into typed metric samples with labels, timestamps, and values.
  • Remote Write Receiver: Provides an HTTP endpoint that accepts Prometheus remote-write requests, letting external systems push metrics into the receiver.
  • StatsD Parsing: Parse StatsD-format metric input with failure handling for invalid syntax.

Service Discovery

Dynamic discovery of scrape targets from cloud providers, registries, and files.

  • AWS EC2 Service Discovery: Discovers AWS EC2 instances as Prometheus scrape targets using region, filters, and job naming configuration.
  • Azure Service Discovery: Discovers and registers Azure compute targets by authenticating with Azure using client credentials and subscription configuration.
  • Consul Service Discovery: Discovers and tracks Consul services as scrape targets, watching the catalog and exposing resulting service addresses for monitoring.
  • DNS Service Discovery: Discovers services via DNS-SD lookups and tracks lookup activity through metrics.
  • Discovery Configuration: Configure ECS discovery through YAML and directory-based settings including credentials, region, ports, and endpoints.
  • Discovery Configuration Load: Loads and parses discovery service configuration including IP lists and application credentials.
  • File-Based Service Discovery: Discovers scrape targets by reading and refreshing target definitions from configured files on disk.
  • Kubernetes Service Discovery: Discovers scrape targets dynamically from Kubernetes via service discovery roles such as pod.
  • Service Discovery: Discovers scrape targets dynamically from cloud providers and service registries via pluggable SD configurations.

PromQL Query Engine

Parsing, evaluating, and formatting PromQL expressions including aggregations, functions, and vector matching.

  • Aggregation Over Time: Aggregates samples within a range vector over time, including sum, average, min/max, quantile, standard deviation/variance, and count aggregations.
  • PromQL Aggregation: Groups series by labels and applies aggregation operators (including count_values and topk/bottomk) to produce aggregated results.
  • PromQL Function Library: A broad library of user-invocable PromQL functions covering math, trigonometric, date/time, sorting, clamping, and scalar operations, including _over_time aggregations and absent/clamp helpers, plus the safety classification data that governs their invocation.
  • PromQL Query Evaluation: Evaluate PromQL query expressions across engine options, lookback deltas, subqueries, shutdown, and cancellation for user-facing query results.
  • PromQL Query Parsing: Parse PromQL query strings into an abstract syntax tree of expressions and statements.
  • PromQL Vector Matching: Configure how binary operations match series across vectors via cardinality and fill values.
  • Rate and Counter Reset Correction: Computes per-second rates over range vectors while correcting for counter resets, including irate, increase, delta, idelta, deriv, resets, and start-timestamp reset detection.
  • Trend and Prediction: Performs linear regression over range vectors and predicts future values with prediction and double-exponential-smoothing functions.

Query Execution and API

HTTP and programmatic execution of instant and range queries over stored time series.

  • Federated Queries: A user can issue PromQL queries that are evaluated across multiple federated Prometheus instances and merged into a single result.
  • Instant Query: Execute a Prometheus-style instant query at a single point in time and return the results.
  • Instant Query Evaluation: Evaluates a PromQL expression at a single point in time and returns the resulting vector.
  • Instant and Range Query API: Prometheus HTTP API endpoints that execute instant and range PromQL queries against the attached storage, with timeout handling.
  • Prometheus HTTP API: Exposes an HTTP API for querying and inspecting Prometheus state such as targets, rules, and alertmanagers.
  • Query Execution: Query stored time-series data, including chunk-based queries and exemplar retrieval.
  • Range Query: Execute a query over a time range with start and end times and return the resulting series.
  • Range Query Evaluation: Evaluates a PromQL expression over a time range and returns matrix results.

Scrape Management

Configuration, scheduling, and execution of metric scrapes against targets.

  • Prometheus Scrape Configuration: Defines scrape jobs and their target endpoints via a scraping configuration container.
  • Scrape Configuration: Loading, validating, and applying scrape job configuration including intervals, protocols, headers, compression, name escaping/validation, external labels, and Kubernetes service discovery.
  • Scrape Job Configuration: Define and retrieve scrape job targets, target addresses, and static target checks for metric collection.
  • Scrape Loop: Runs the periodic scrape-and-append loop that collects metrics from targets and reports results.
  • Scrape Pool Lifecycle Management: Manages a pool of scrape loops, including reload, restart, stop, and target limits.
  • Scrape Pool Management: Create, configure, and reload scrape pools through a manager lifecycle (start, reload, stop).
  • Scrape Target Health Reporting: Exposes the health status, last scrape time, duration, and error of each scrape target so users can observe target liveness.
  • Scrape Target Lifecycle Management: Handles registration, description, active state exposure, and unregistration of scrape targets.

Authentication and Credentials

Cloud and endpoint authentication via OAuth, basic auth, bearer tokens, and workload identity.

  • API Key Authentication: Supports API key-based authentication for accessing server resources.
  • Azure AD Authentication: Obtains and manages Azure Active Directory access tokens for authenticating requests, including support for custom scopes, workload identity token files, and token expiry handling.
  • Basic Authentication: Allows users to authenticate using a configured set of username/password credentials.
  • Bearer Token Authentication: Supports authenticating scrape targets using a bearer token.
  • Client TLS Authentication: Clients can configure TLS credentials via certificate, key, and password to authenticate and establish secure connections.
  • OAuth Authentication: Enables users to authenticate with an external provider using client credentials and cloud configuration.
  • Workload Identity Federation: Authenticate a workload to a cloud provider by presenting an external identity (client id, tenant id, token file) to obtain federated cloud credentials.

Label and Series Indexing

Indexing and querying label names, values, postings, and series lookups.

  • Index Persistence: Create, open, and persist index data structures to durable storage with end-to-end round-tripping.
  • Label Index Lookup: Lets users discover label names, label values, and postings from the index to build queries.
  • Label Names and Values Query: Exposes the set of label names and the values associated with a given label name for time-series metadata discovery.
  • Postings Iteration: Iterating and seeking through merged postings with index heap support.
  • Postings Listing: Enumerate postings for label matchers, all label values, or sharded subsets to drive index-level series selection.
  • Postings Set Operations: Iterating, intersecting, merging, and expanding posting lists to combine query results.
  • Series Lookup: Resolve and return series by their references, including selection and sorting of matching series.

Native Histograms

Encoding, conversion, validation, and query support for native and custom-bucket histograms.

  • Classic Histogram to NHCB Conversion: Converts classic Prometheus histograms to native histograms with custom buckets.
  • Float Histogram Arithmetic: Adds, subtracts, multiplies, and divides float histograms, including compensated (Kahan) summation to preserve precision.
  • Histogram Encoding: Serialize and deserialize histogram data including exponential bucket spans and custom buckets into a compact wire format.
  • Histogram Metrics Support: Representation and ingestion of histogram metric samples including buckets, positive/negative counts and deltas, and reset hints.
  • Histogram Support: Provide histogram and custom-bucket histogram data handling used alongside checkpoint storage.
  • Histogram Validation: Enables checking histograms for mismatched counts, spans, and bucket inconsistencies.
  • Native Histogram Query Support: Query and compute over native histograms including classic conversion, counter-reset hints, bucket layout validation, rate, and copy semantics.

Recording and Rule Management

Management, evaluation, and lifecycle of recording and alerting rule groups and their files.

  • Recording Rule Evaluation: Executes recording rules to produce result vectors while tracking the evaluation timestamp.
  • Rule File Parsing: Parses rule files into rule definitions, with support for aliases and template expressions.
  • Rule Group Evaluation: Evaluation of rule groups over intervals, producing and appending samples with metadata and handling offsets and concurrency.
  • Rule Group Management: Lifecycle management of rule groups, including starting, stopping, and restoring evaluation state.
  • Rule Health Monitoring: Tracking and updating the health status of rules for observability.
  • Rule Import: Imports Prometheus alerting/recording rules into a rule store.
  • Rule State Restoration: Restoration of rule group state from persisted samples, including hold durations and appending samples to the for-state.

Tombstones and Data Deletion

Deleting series and samples while tracking tombstones and cleaning them from blocks.

  • Admin Delete Series: Delete selected time series from the TSDB.
  • Data Deletion and Cleanup: Deleting series data and cleaning up tombstones in the storage backend.
  • Retention Enforcement and Block Deletion: Deletes blocks beyond configured time or size retention and removes tombstones from disk.
  • Series Deletion: Delete series matching given selectors.
  • Tombstone Management: Record and remove deleted time ranges and compact them out of blocks.
  • Tombstone Resource Management: Lifecycle management of the tombstones store, including closure and test-time construction.
  • Tombstone-Aware Series Iteration: Iterates series and chunks while applying deletion tombstones so deleted data is excluded from results.

HTTP API and OpenAPI Specification

Exposing HTTP endpoints and generating/serving the OpenAPI specification.

  • API Endpoint Handling: Handles incoming requests to defined API endpoints on the mock server.
  • CORS Handling: Provides cross-origin resource sharing support so browser clients from other origins can call the service.
  • HTTP API Endpoints: Exposes HTTP endpoints that clients call, including route-prefixed paths and graph redirection.
  • OpenAPI Spec Serving: Serves the OpenAPI specification document over HTTP so clients can retrieve the API schema.
  • OpenAPI Specification Generation: Builds an OpenAPI document (info, paths, servers, tags) from the configured options and serves it to clients.
  • OpenAPI Specification Serving: Exposes the generated OpenAPI document over HTTP via a handler wrapper for external consumers.

Relabeling and Target Labeling

Rewriting, filtering, and enriching discovered target and metric label sets.

  • Alert Relabeling: Rewrite alert label sets according to relabeling rules before they are emitted.
  • Label Set Management: A collection of key/value labels that can be added to, removed from, queried, iterated, validated, and persisted via JSON/YAML and string serialization.
  • Metric Relabeling: Rewrites discovered targets and scraped samples via relabeling rules before ingestion and remote write.
  • Target Label Application: Attaches standardized PuppetDB labels (certname, environment, resource type/title, tags, etc.) to discovered targets for use in relabeling and alerting.
  • Target Labeling: Annotation and labeling of monitored targets and groups for identification and selection.
  • Target Relabeling: Rewrites and filters discovered Prometheus scrape targets using source-label, regex, replacement, and target-label configuration.

Remote Write and Remote Read

Shipping samples to and querying samples from remote storage endpoints.

  • Remote Read: Query a remote endpoint for stored time-series data and return the sampled results to the caller.
  • Remote Read Configuration: Configure remote read endpoints with URL, timeouts, required matchers, and chunked read limits.
  • Remote Read Query: A remote read request accepts matchers, hints, and a response type, returning query results and timeseries back to the caller.
  • Remote Write: Sends data to a remote endpoint specified by a URL.
  • Remote Write Configuration: Configure remote write endpoints, queueing, timeouts, HTTP client settings, and compression for shipping metrics.
  • Remote Write Ingestion: Accepts Prometheus remote write requests and appends incoming samples, histograms, exemplars, and metadata to storage, including v1 and v2 message formats.

Web UI and Visualization

React-based web interface with charts, dashboards, and rule/target views.

  • Chart Rendering: Renders the interactive uPlot chart canvas that displays the underlying data.
  • Frontend Web Application Runtime: A React-based single-page application runtime providing UI rendering and client-side routing for end users.
  • Graphite Metric Publishing: Create a Graphite client and publish metrics to a Graphite endpoint over a configurable transport, address, and prefix.
  • Rules View: List configured alerting and recording rule groups with their state.
  • Targets View: List scrape targets with their health, labels, and last scrape details.
  • UI Component Library: A Bootstrap-based React component library delivering buttons, forms, modals and other interactive UI widgets to the user.

Write-Ahead Log and Recovery

Durability, checkpointing, and crash recovery of the write-ahead and write-behind logs.

  • WAL Checkpointing: Writing checkpoints from the WAL including in-memory series and metadata records.
  • WAL Replay and Recovery: Recover persisted state by loading and replaying the write-ahead log and series metadata after opening.
  • WAL Truncation: Full and partial truncation of the write-ahead log to reclaim disk space while preserving recoverability.
  • WAL Write-Ahead Log: A write-ahead log that persists appended samples and can be truncated, replayed, and recovered after write errors.
  • WAL and WBL Corruption Repair: Detect and repair corrupted write-ahead log or write-behind log segments during recovery.
  • WBL Replay and Recovery: Replaying the write-behind log to recover samples that were not yet flushed before shutdown.

Build and Continuous Integration

Building artifacts and running automated tests, linting, and dependency management.

  • Application Build and Bundling: Compiles and bundles application source into deployable assets through the build toolchain.
  • Continuous Integration Pipeline: Runs automated testing and quality checks across multiple Go versions, platforms, and UI components for every change.
  • Go Dependency Management: Updates Go module dependencies across the repository and its submodules.
  • Go Lint Check: A CI capability that runs golangci-lint to check Go code quality.
  • Release Artifact Packaging: Produces distributable release artifacts as tarballs and Docker images.

CLI and Promtool Tooling

Command-line tooling for config checking, TSDB inspection, and query execution.

  • Command-Line Invocation: Runs the tool as a command-line entry point driving the generation workflow.
  • Promtool CLI: Bundled promtool command-line utility for validating and inspecting Prometheus configuration and rules.
  • Promtool Config Checking: Validate Prometheus configuration files and rule definitions for syntax and semantic correctness.
  • Promtool Query Execution: Run instant and range PromQL queries against a Prometheus server and retrieve results.
  • TSDB Block Dump: Dump a TSDB block's samples to a human-readable text format from the command line.

Configuration Loading and Reload

Loading, validating, and hot-reloading YAML configuration at runtime.

  • Configuration Auto-Reload: Automatically reloads and applies configuration changes at runtime, with verification of reload outcomes and metrics.
  • Configuration Loading: Loading the global configuration file with validation, secret elision, rule file paths, runtime log level, and query cost limits.
  • Configuration Reload: Applies updated configuration at runtime, recreating and updating target sets on config changes.
  • Runtime Configuration of Storage: Applies runtime options such as exemplar storage, out-of-order window, chunk encoding, stripe size, and feature registry settings.
  • YAML Configuration Parsing: Parsing and round-tripping YAML configuration while rejecting the deprecated AM API format.

Exemplars

Appending, storing, and querying exemplars linked to samples for trace correlation.

  • Exemplar Ingestion: Append exemplars alongside samples through the fanout appender path.
  • Exemplar Parsing: Reads exemplar samples attached to metric series.
  • Exemplar Querying: Query exemplars associated with series in the head block.
  • Exemplar Storage: Store exemplars alongside samples with duplicate exemplars being ignored.
  • Exemplar Validation: Validate attached exemplars before they are accepted into the storage.

Feature Flags and Build Info

Runtime feature flag management and reporting of build/runtime information.

  • Feature Flag Management: Runtime control over experimental or optional capabilities by looking up, toggling, and registering named features.
  • Feature Flags Discovery: Exposes the set of enabled runtime feature flags to clients.
  • Feature Flags Introspection: List the enabled feature flags of the running server.
  • Runtime and Build Information: Report server build metadata, runtime statistics, and enabled feature flags.
  • Server Features View: Report which optional server features are enabled.

Out-of-Order Data Ingestion

Accepting, storing, compacting, and querying samples that arrive outside normal time order.

  • Out-of-Order Chunk Insertion: Inserting and storing chunks that arrive out of order, including handling duplicates.
  • Out-of-Order Compaction: Compacting out-of-order head data, including safely releasing locks during compaction.
  • Out-of-Order Data Ingestion: Ability to append out-of-order (OOO) samples and histograms and query them back, including across restarts and with OOO enabled/disabled settings.
  • Out-of-Order Query: Querying time series data through the out-of-order head, including across chunk ID wraparound, and returning consistent results while the head is expanding.
  • Out-of-Order Sample Handling: Handles out-of-order samples, histograms, and exemplars in remote write messages across v1 and v2 formats.

Query Cost Estimation and Limits

Estimating query cost and enforcing resource limits on query execution.

  • Query Cost Estimation: Estimates the cost of a query by sampling series and reading chunks, with fallback behavior when sampling or density data is unavailable.
  • Query Cost Estimation and Limiting: Endpoint and gating logic that estimates query cost, enforces configured ceilings, and rejects or times out over-budget queries.
  • Query Duration Limit Configuration: Provides a configurable maximum query duration setting that users or calling systems can read and apply to bound query execution time.
  • Query Resource Limits Enforcement: Enforces limits on query execution such as max series, max samples, and query duration.
  • Query Statistics Collection: Captures and exposes per-query execution statistics such as timings, samples read, series touched, and total samples for users and downstream systems to observe query performance.

Snapshots and Backup

Creating consistent snapshots of head, blocks, and chunk data for backup and recovery.

  • Admin Snapshot: Trigger creation of a TSDB snapshot for backup.
  • Block Snapshotting: Create a hardlinked snapshot copy of a block in the data directory.
  • Chunk Snapshotting: Takes snapshots of head chunk data, handling incomplete snapshots and WAL-ahead errors.
  • Head Snapshot: Create and restore point-in-time snapshots of head state with chunk encoding fallback.
  • Snapshot Creation: Create a snapshot of the TSDB data.

Tracing and Self-Observability

Internal self-metrics, profiling, and distributed tracing export.

  • Debug and Metrics Endpoint: Serves an HTTP debug/console and metrics surface exposing runtime information and instrumentation.
  • Internal Self-Metrics: Provides instrumentation metrics about the Prometheus instance itself.
  • Metrics Exposition: Serves operational metrics over HTTP for monitoring systems to scrape.
  • Profiling Debugging: Provides pprof profiler inspection endpoints.
  • Tracing and OTLP Export: Exports telemetry via OpenTelemetry tracing and OTLP receivers.

Health and Readiness Probes

Reporting service readiness and clean handling of shutdown signalling.

  • Graceful Shutdown: Running managers terminate cleanly and complete a final scrape when shutdown is requested.
  • Health and Readiness Probes: Provides readiness and health check endpoints so orchestrators can observe service availability.
  • Readiness Status Reporting: Exposes whether the service is ready or not-ready for orchestrators and callers to observe.
03 · Size

What was analyzed

  • Go · 765 files · 324,192 lines
  • YAML · 384 files · 74,453 lines
  • TypeScript · 249 files · 42,098 lines
  • JSON · 55 files · 27,656 lines
  • Markdown · 70 files · 16,108 lines
  • Text · 15 files · 9,962 lines
  • JavaScript · 21 files · 4,388 lines
  • Python · 4 files · 2,413 lines
  • yacc · 1 file · 1,205 lines
  • Bourne Shell · 18 files · 921 lines
  • CSS · 22 files · 618 lines
  • Other (10 languages) · 32 files · 1,580 lines

Whole repository: 1,773 files. cloc 2.06 counts 505,594 lines of code in 1,636 of them (606,049 lines with comments and blanks).

04 · Source

Where this came from

Extracted by CoreStory V3 (build 4470 with two small engine fixes) using DeepSeek-V4.1-Flash from the public repository at commit 49c815a on 2026-11-15. Capability descriptions are from the same run.

Code excerpts are from the upstream repository and remain under its Apache-2.0 license. CoreStory is not affiliated with or endorsed by the Prometheus project.

Want this for your own codebase?

Talk to us about mapping the business rules in your repositories.

Talk to an expert