Skip to content

Metric

Records and reads measurements from Effect programs.

A Metric<Input, State> accepts typed update values and stores an aggregated state that can be read directly or included in a snapshot. Metrics are used for counters, gauges, frequencies, histograms, summaries, and timers. This module includes metric constructors, update and read helpers, attributes, histogram boundaries, registry snapshots, text dumps, and controls for enabling runtime metrics.

43 exports Added in v2.0.0 Source

Annotations

mapInput

Added in v2.0.0 Source

Returns a new metric that is powered by this one, but which accepts updates of the specified new type, which must be transformable to the input type of this metric.

Signature

declare const mapInput: {
  <Input, Input2>(
    f: (input: Input2, context: Context<never>) => Input,
  ): <State>(self: Metric<Input, State>) => Metric<Input2, State>;
  <Input, State, Input2>(
    self: Metric<Input, State>,
    f: (input: Input2, context: Context<never>) => Input,
  ): Metric<Input2, State>;
};

Constants

Service key for the current metric attributes context.

Signature

declare const CurrentMetricAttributesKey: "effect/Metric/CurrentMetricAttributes";

Service key for the fiber runtime metrics service.

Signature

declare const FiberRuntimeMetricsKey: "effect/observability/Metric/FiberRuntimeMetricsKey";

Constructors

Creates histogram bucket boundaries from an iterable set of values.

Details

Processes any iterable of numbers by removing duplicates, filtering out non-positive values, and automatically appending positive infinity as the final boundary.

Signature

declare function boundariesFromIterable(iterable: Iterable<number>): readonly Array<number>

counter

Added in v2.0.0 Source

Represents a Counter metric that tracks cumulative numerical values over time. Counters can be incremented and decremented and provide a running total of changes.

Details

The optional description describes the counter, and attributes attach dimensions to it. Set bigint to create a counter that accepts bigint inputs. Set incremental to true to create a counter that can only ever be incremented.

Signature

declare const counter: {
  (
    name: string,
    options?: {
      readonly attributes?: Metric.Attributes;
      readonly bigint?: false;
      readonly description?: string;
      readonly incremental?: boolean;
    },
  ): Counter<number>;
  (
    name: string,
    options: {
      readonly attributes?: Metric.Attributes;
      readonly bigint: true;
      readonly description?: string;
      readonly incremental?: boolean;
    },
  ): Counter<bigint>;
};

Creates histogram bucket boundaries with exponentially increasing values.

Details

Creates boundaries that grow exponentially, useful for metrics that span multiple orders of magnitude. Each boundary is calculated as start * factor^i.

Signature

declare function exponentialBoundaries(options: {
  readonly count: number;
  readonly factor: number;
  readonly start: number;
}): readonly Array<number>

frequency

Added in v2.0.0 Source

Creates a Frequency metric which can be used to count the number of occurrences of a string.

When to use

Use when you need a metric for counting how often a specific event or incident occurs.

Details

The optional description describes the frequency, and attributes attach dimensions to it. Use preregisteredWords to initialize occurrence counts for known string values before updates arrive.

Signature

declare function frequency(name: string, options?: {
  readonly attributes?: Attributes;
  readonly description?: string;
  readonly preregisteredWords?: readonly Array<string>;
}): Frequency

gauge

Added in v2.0.0 Source

Represents a Gauge metric that tracks and reports a single numerical value at a specific moment.

When to use

Use when you need a metric for instantaneous values, such as memory usage or CPU load.

Details

The optional description describes the gauge, and attributes attach dimensions to it. Set bigint to create a gauge that accepts bigint inputs.

Signature

declare const gauge: {
  (
    name: string,
    options?: {
      readonly attributes?: Metric.Attributes;
      readonly bigint?: false;
      readonly description?: string;
    },
  ): Gauge<number>;
  (
    name: string,
    options: {
      readonly attributes?: Metric.Attributes;
      readonly bigint: true;
      readonly description?: string;
    },
  ): Gauge<bigint>;
};

histogram

Added in v2.0.0 Source

Represents a Histogram metric that records observations into buckets.

When to use

Use when you need a metric for measuring the distribution of values within a range.

Details

The optional description describes the histogram, and attributes attach dimensions to it. The required boundaries option defines the histogram bucket boundaries.

Signature

declare function histogram(name: string, options: {
  readonly attributes?: Attributes;
  readonly boundaries: readonly Array<number>;
  readonly description?: string;
}): Histogram<number>

Creates histogram bucket boundaries from a linear sequence and appends positive infinity.

Details

Generates count - 1 candidate boundaries using start + index * width for each zero-based index, then applies the same normalization as boundariesFromIterable: non-positive values are removed, duplicates are collapsed, and Infinity is appended.

Signature

declare function linearBoundaries(options: {
  readonly count: number;
  readonly start: number;
  readonly width: number;
}): readonly Array<number>

summary

Added in v2.0.0 Source

Creates a Summary metric that records observations and calculates quantiles which takes a value as input and uses the current time.

When to use

Use when you need a metric that records statistical information about a set of values, including quantiles.

Details

The optional description describes the summary, and attributes attach dimensions to it. maxAge controls how long observations are retained, maxSize controls how many observations are kept, and quantiles lists the quantiles to calculate, such as [0.5, 0.9].

Signature

declare function summary(name: string, options: {
  readonly attributes?: Attributes;
  readonly description?: string;
  readonly maxAge: Input;
  readonly maxSize: number;
  readonly quantiles: readonly Array<number>;
}): Summary<number>

Creates a Summary metric that records observations with explicit timestamps and calculates quantiles.

When to use

Use when you need a metric that records statistical information about a set of values together with timestamps.

Details

Inputs to this metric are [value, timestamp] pairs; the current clock is used when reading quantiles against the configured maxAge.

The optional description describes the summary, and attributes attach dimensions to it. maxAge controls how long observations are retained, maxSize controls how many observations are kept, and quantiles lists the quantiles to calculate, such as [0.5, 0.9].

Signature

declare function summaryWithTimestamp(name: string, options: {
  readonly attributes?: Attributes;
  readonly description?: string;
  readonly maxAge: Input;
  readonly maxSize: number;
  readonly quantiles: readonly Array<number>;
}): Summary<[value: number, timestamp: number]>

timer

Added in v2.0.0 Source

Creates a timer metric, based on a Histogram, which keeps track of durations in milliseconds.

Details

The unit of time will automatically be added to the metric as a tag (i.e. "time_unit: milliseconds").

If options.boundaries is not provided, the boundaries will be computed using Metric.exponentialBoundaries({ start: 0.5, factor: 2, count: 35 }).

Signature

declare function timer(name: string, options?: {
  readonly attributes?: Attributes;
  readonly boundaries?: readonly Array<number>;
  readonly description?: string;
}): Histogram<Duration>

Formatting

dump

Added in v4.0.0 Source

Returns a human-readable string representation of all currently registered metrics in a tabular format.

Details

This debugging utility captures a snapshot of all metrics and formats them in an easy-to-read table showing names, descriptions, types, attributes, and current state values.

Signature

declare const dump: Effect<string>;

Getters

value

Added in v2.0.0 Source

Retrieves the current state of the specified Metric.

Details

The returned state depends on the metric type. Counters return CounterState<number | bigint> with count and incremental, gauges return GaugeState<number | bigint> with value, frequencies return FrequencyState with occurrences, histograms return HistogramState with buckets, count, min, max, and sum, and summaries return SummaryState with quantiles, count, min, max, and sum.

Signature

declare function value<Input, State>(self: Metric<Input, State>): Effect<State>;

Guards

isMetric

Added in v4.0.0 Source

Returns true if the specified value is a Metric, otherwise returns false.

When to use

Use when you need runtime type checking and ensuring that a value conforms to the Metric interface before performing metric operations.

Signature

declare function isMetric(u: unknown): u is Metric<never, unknown>;

Layers

Layer that disables automatic collection of fiber runtime metrics.

Signature

declare const disableRuntimeMetricsLayer: Layer<never, never, never>;

Layer that enables automatic collection of fiber runtime metrics across an entire Effect application.

When to use

Use when you need runtime metrics collection for all Effects in the application context rather than wrapping individual Effects.

Signature

declare const enableRuntimeMetricsLayer: Layer<never, never, never>;

Mapping

Returns a new metric that applies the specified attributes to all operations.

Details

Attributes are key-value pairs that provide additional context for metrics, enabling filtering, grouping, and more detailed analysis. Each combination of attribute values creates a separate metric series.

Signature

declare const withAttributes: {
  (attributes: Attributes): <Input, State>(self: Metric<Input, State>) => Metric<Input, State>;
  <Input, State>(self: Metric<Input, State>, attributes: Attributes): Metric<Input, State>;
};

Returns a new metric that is powered by this one, but which accepts updates of any type, and translates them to updates with the specified constant update value.

Signature

declare const withConstantInput: {
  <Input>(input: Input): <State>(self: Metric<Input, State>) => Metric<unknown, State>;
  <Input, State>(self: Metric<Input, State>, input: Input): Metric<unknown, State>;
};

Models

Counter interface

Added in v2.0.0 Source

A Counter metric that tracks cumulative values that typically only increase.

When to use

Use when counters are useful for tracking monotonically increasing values like request counts, bytes processed, errors encountered, or any value that accumulates over time.

Signature

interface Counter<in Input extends number | bigint> extends Metric<Input, CounterState<Input>> {}

CounterState interface

Added in v4.0.0 Source

State interface for Counter metrics containing the current count and increment mode.

Signature

interface CounterState<in Input extends number | bigint> {
  readonly count: Input extends bigint ? bigint : number;
  readonly incremental: boolean;
}

Frequency interface

Added in v2.0.0 Source

A Frequency metric interface that counts occurrences of discrete string values.

When to use

Use when frequency metrics are ideal for tracking categorical data where you want to count how many times specific string values occur, such as HTTP status codes, user actions, error types, or any discrete string-based events.

Signature

interface Frequency extends Metric<string, FrequencyState> {}

FrequencyState interface

Added in v4.0.0 Source

State interface for Frequency metrics containing occurrence counts for discrete string values.

Signature

interface FrequencyState {
  readonly occurrences: ReadonlyMap<string, number>;
}

Gauge interface

Added in v2.0.0 Source

A Gauge metric that tracks instantaneous values that can go up or down.

When to use

Use when gauges are useful for tracking current state values like memory usage, CPU load, active connections, queue sizes, or any value that represents a current level.

Signature

interface Gauge<in Input extends number | bigint> extends Metric<Input, GaugeState<Input>> {}

GaugeState interface

Added in v4.0.0 Source

State interface for Gauge metrics containing the current instantaneous value.

Signature

interface GaugeState<in Input extends number | bigint> {
  readonly value: Input extends bigint ? bigint : number;
}

Histogram interface

Added in v2.0.0 Source

A Histogram metric that records observations in configurable buckets to analyze value distributions.

When to use

Use when histograms are ideal for measuring request durations, response sizes, and other continuous values where you need to understand the distribution of values rather than just aggregates.

Signature

interface Histogram<Input> extends Metric<Input, HistogramState> {}

HistogramState interface

Added in v4.0.0 Source

State interface for Histogram metrics containing bucket distributions and aggregate statistics.

Signature

interface HistogramState {
  readonly buckets: readonly Array<[number, number]>;
  readonly count: number;
  readonly max: number;
  readonly min: number;
  readonly sum: number;
}

Metric interface

Added in v2.0.0 Source

A Metric<Input, State> represents a concurrent metric which accepts update values of type Input and are aggregated to a value of type State.

Details

For example, a counter metric would have type Metric<number, number>, representing the fact that the metric can be updated with numbers (the amount to increment or decrement the counter by), and the state of the counter is a number.

There are five primitive metric types supported by Effect:

- Counters - Frequencies - Gauges - Histograms - Summaries

Signature

interface Metric<in Input, out State> extends Pipeable {
  readonly "~effect/observability/Metric": "~effect/observability/Metric";
  readonly attributes: Readonly<Record<string, string>> | undefined;
  readonly description: string | undefined;
  readonly id: string;
  Input: Contravariant<Input>;
  readonly modifyUnsafe: (input: Input, context: Context<never>) => void;
  State: Covariant<State>;
  readonly type: Type;
  readonly updateUnsafe: (input: Input, context: Context<never>) => void;
  readonly valueUnsafe: (context: Context<never>) => State;
}

Summary interface

Added in v2.0.0 Source

A Summary metric that calculates quantiles over a sliding time window of observations.

When to use

Use when summaries provide statistical insights into value distributions by tracking specific quantiles (percentiles) such as median (50th), 95th percentile, 99th percentile, etc. They're ideal for understanding performance characteristics like response time distributions.

Signature

interface Summary<Input> extends Metric<Input, SummaryState> {}

SummaryState interface

Added in v4.0.0 Source

State interface for Summary metrics containing quantile calculations and aggregate statistics.

Signature

interface SummaryState {
  readonly count: number;
  readonly max: number;
  readonly min: number;
  readonly quantiles: readonly Array<readonly [number, number | undefined]>;
  readonly sum: number;
}

Mutations

modify

Added in v3.6.5 Source

Modifies the metric with the specified input.

Details

The behavior of modify depends on the metric type. Counters add the input value to the current count, gauges add the input value to the current gauge value, frequencies increment the occurrence count for the input string, histograms record the input value in the appropriate bucket, and summaries record the input observation.

Signature

declare const modify: {
  <Input>(input: Input): <State>(self: Metric<Input, State>) => Effect<void>;
  <Input, State>(self: Metric<Input, State>, input: Input): Effect<void>;
};

update

Added in v2.0.0 Source

Updates the metric with the specified input.

Details

The behavior of update depends on the metric type. Counters add the input value to the current count, gauges replace the current value with the input value, frequencies increment the occurrence count for the input string, histograms record the input value in the appropriate bucket, and summaries record the input value as a new observation.

Signature

declare const update: {
  <Input>(input: Input): <State>(self: Metric<Input, State>) => Effect<void>;
  <Input, State>(self: Metric<Input, State>, input: Input): Effect<void>;
};

Other

Metric

Added in v2.0.0 Source

The Metric namespace provides a comprehensive system for collecting, aggregating, and observing application metrics in Effect applications.

Providing Services

Disables automatic collection of fiber runtime metrics for the provided Effect.

When to use

Use when you need to disable runtime metrics for a specific effect while keeping them enabled elsewhere.

Signature

declare const disableRuntimeMetrics: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>;

Enables automatic collection of fiber runtime metrics for the provided Effect.

Details

When enabled, automatically tracks fiber lifecycle metrics including active fibers, started fibers, successful completions, and failures. These metrics provide valuable insights into the concurrency patterns and health of your Effect application.

Signature

declare const enableRuntimeMetrics: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>;

Services

Context reference for metric attributes applied from the current Effect context.

When to use

Use to provide default attributes that should be merged into metric updates and reads in a scoped part of a program.

Details

The default value is an empty attribute set. Metric reads and updates merge these contextual attributes with the metric's own attributes to select the metric series being accessed.

Signature

declare const CurrentMetricAttributes: Reference<Readonly<Record<string, string>>>;

Context reference for the optional service that records fiber runtime metrics.

When to use

Use to provide or inspect the service that receives fiber start and end notifications for automatic runtime metrics.

Details

When provided, the runtime can notify the service about child-fiber start and end events. When the reference is undefined, automatic fiber runtime metric collection is disabled.

Signature

declare const FiberRuntimeMetrics: Reference<FiberRuntimeMetricsService | undefined>;

Default implementation of the fiber runtime metrics service.

Signature

declare const FiberRuntimeMetricsImpl: FiberRuntimeMetricsService;

FiberRuntimeMetricsService interface

Added in v4.0.0 Source

Interface for the fiber runtime metrics service that tracks fiber lifecycle events.

Signature

interface FiberRuntimeMetricsService {
  readonly recordFiberEnd: (context: Context<never>, exit: Exit<unknown, unknown>) => void;
  readonly recordFiberStart: (context: Context<never>) => void;
}

Context reference for the metric registry in the current context.

When to use

Use when you need a custom metric registry for an isolated program or test instead of the default registry.

Details

By default, the reference creates an empty Map the first time it is resolved. Metrics register their metadata and hooks lazily in this map when they are read or updated.

Gotchas

Because Context.Reference caches default values, the default Map is shared by contexts that do not provide an override. Provide MetricRegistry with a fresh Map when isolation matters.

See

  • snapshot for reading all registered metrics from the current Effect context
  • snapshotUnsafe for reading all registered metrics from an explicit Context

Signature

declare const MetricRegistry: Reference<Map<string, Metadata<any, any>>>;

Snapshotting

snapshot

Added in v2.0.0 Source

Captures a snapshot of all registered metrics in the current context.

Details

Returns an array of metric snapshots, each containing the metric's metadata (name, description, type) and current state (values, counts, etc.).

Signature

declare const snapshot: Effect<ReadonlyArray<Metric.Snapshot>>;

Captures a snapshot of all registered metrics synchronously using the provided service context.

When to use

Use to read metric snapshots from an explicit Context in low-level integrations, exporters, or debugging tools that already have the context.

Details

This is the "unsafe" version that bypasses Effect's safety guarantees and requires manual handling of the services context. Use the safe snapshot function for normal application code.

Signature

declare function snapshotUnsafe(context: Context<never>): readonly Array<Snapshot>