Superposition Documentation

repository·main·Indexed 19 days ago

https://github.com/juspay/superposition

An open-source context-aware configuration management platform for managing application configuration and experimentation. It supports defining defaults and multi-dimensional overrides based on context such as environment, tenant, or region. The platform provides clients for Go (CAC and Experimentation clients), Java (OpenFeature provider), and JavaScript (OpenFeature provider, SDK, and native Node.js bindings).

Tokens
281.1K
Snippets
807
Records
1.1K
Agent score
61%

What's inside Superposition

  1. What is SuperTOML?

    main

    SuperTOML is an extension of the TOML configuration format designed for managing complex configurations at scale. It introduces two primary features to standard TOML:

    1. Type Safety via JSON Schema: Every configuration value is validated against an associated JSON Schema, allowing for early error detection.
    2. Cascading Configuration: A CSS-inspired model that allows you to define default values and override them based on specific application contexts (e.g., environment, tenant, region, or user segment).

    SuperTOML files are fully compatible with standard TOML parsers, but the advanced type-safety and cascading features require Superposition libraries.

  2. How Overrides and Contexts work in CAC

    main

    In Context-Aware Configuration (CAC), Overrides allow you to define a subset of configurations that differ from the Default Config.

    Overrides are always associated with a Context. A context is a logical expression built using dimensions as variables. An override is applied only when its associated context evaluates to true. This allows you to specialize configuration values based on the current environment or state (e.g., different rates for different vehicle types or cities).

    [[overrides]]
    _context_ = { vehicle_type = "bike" }
    per_km_rate = 15.0
  3. Audit trail for Variable operations

    main

    Superposition maintains an automatic audit log for all variable lifecycle events (create, update, and delete).

    Key requirements and metadata:

    • change_reason: This field is mandatory when performing operations to ensure changes are tracked.
    • Automatic Metadata: The system automatically maintains created_at, last_modified_at, created_by, and last_modified_by for every variable.
  4. Reuse schemas with $ref and Type Templates

    main

    To avoid duplication, you can reuse schemas in two ways:

    1. Local Schema References ($ref and definitions)

    Define a set of definitions within the same configuration block and reference them using "$ref" = "#/definitions/name".

    2. Workspace-level Type Templates

    Superposition supports reusable type templates defined at the workspace level. You can reference these templates across multiple configurations using "$ref" = "TemplateName".

    Built-in Type Templates:

    • Number: { "type": "integer" }
    • Decimal: { "type": "number" }
    • Boolean: { "type": "boolean" }
    • String: { "type": "string" }
    # Using a local definition
    address = {
        value = { street = "123 Main St", zip = "560001" },
        schema = {
            type = "object",
            properties = {
                street = { type = "string" },
                zip = { "$ref" = "#/definitions/zipCode" }
            },
            definitions = {
                zipCode = { type = "string", pattern = "^[0-9]{6}$" }
            }
        }
    }
    
    # Using a workspace-level template
    user_email = {
        value = "user@example.com",
        schema = { "$ref" = "Email" }
    }
  5. Configure Refresh Strategies

    main

    The RefreshStrategy interface defines how the provider updates its local configuration. There are two primary implementations:

    • RefreshStrategy.Polling: Performs periodic background refreshes at a specified interval.
    • RefreshStrategy.OnDemand: Fetches configuration on access and caches it with a specified Time-To-Live (TTL).

    Both strategies allow you to specify a timeout in milliseconds for the refresh operation.

    // Polling — periodic background refresh
    RefreshStrategy.Polling.of(
        10000,  // interval in milliseconds
        5000    // timeout in milliseconds
    )
    
    // OnDemand — fetch on access, cache with TTL
    RefreshStrategy.OnDemand.of(
        300000, // TTL in milliseconds
        5000    // timeout in milliseconds
    )
  6. Use Cohort Dimensions to group values

    main

    Cohort dimensions allow you to derive a new dimension from an existing one by grouping raw values into meaningful segments. This prevents you from having to write individual contexts for every possible value of a dimension.

    Key Rules for Cohorts:

    • A cohort must be based on exactly one existing dimension (the parent).
    • The parent dimension cannot be a Local Cohort.
    • The cohort's position must be $\le$ (on create) or $<$ (on update) the parent's position.
    • You cannot delete a dimension if other cohort dimensions depend on it; you must delete the cohorts first.
  7. Understand Dimensions in Superposition

    main

    Dimensions are attributes of your domain that define segmentation criteria used to create different contexts for configuration overrides. They represent the parameters (like city, vehicle_type, or hour_of_day) that can govern which configuration values are applied to a specific request or user.

    Dimensions can be defined in TOML using a [dimensions] table, where each dimension specifies a schema (JSON Schema) to validate its values.

    [dimensions]
    city = { schema = { "type" = "string", "enum" = ["Bangalore", "Delhi"] } }
    vehicle_type = { schema = { "type" = "string", "enum" = ["auto", "cab", "bike"] } }
    hour_of_day = { schema = { "type" = "integer", "minimum" = 0, "maximum" = 23 }}
  8. What are Type Templates

    main

    Type Templates are reusable JSON Schema definitions used as standardized data type specifications for configuration values. They allow you to define and enforce consistent data types and validation rules across the entire Superposition configuration management system.

    Key Benefits:

    • Reusability: Define complex types once and use them across multiple configurations.
    • Consistency: Standardize type definitions across an organization.
    • Validation: Uses built-in JSON Schema validation to prevent invalid data entry.
    • UI Generation: Enables automatic form generation based on the type definitions.
    • Maintainability: Centralizes schema updates.

    Type templates can be used in Default Configurations (to specify rules for keys), Dimension Schemas (to define allowed values for attributes), and Override Validation (to ensure overrides conform to expected types).

  9. Understand Mayday Webhook Event Types

    main

    Mayday responds to three specific Superposition webhook events to manage the rollout lifecycle:

    1. ExperimentStarted

    Trigger: A new experiment begins. Actions: Creates a new Kubernetes Deployment, Service, and Ingress (using NGINX canary annotations) for the experimental variant.

    2. ExperimentInprogress

    Trigger: The traffic percentage for the experiment is updated. Actions: Updates existing Ingress resources with new nginx.ingress.kubernetes.io/canary-weight values to adjust traffic distribution.

    3. ExperimentConcluded

    Trigger: The experiment ends and a winning variant is chosen. Actions:

    • Updates the main Service to point to the winning variant's Deployment.
    • Removes experimental Ingress resources.
    • Cleans up unused Services and Deployments.
  10. Understand the OpenTelemetry Golden-Signals Middleware Architecture

    main

    The OpenTelemetry Golden-Signals Middleware is designed to emit Google SRE golden signals (latency, traffic, errors, and saturation) for every HTTP route in the Superposition API. It is implemented within the service_utils::observability module.

    Core Components

    • Observability::init(): Initializes an OpenTelemetry SdkMeterProvider configured with a Prometheus exporter and an optional OTLP HTTP push exporter. It also includes an SDK View to filter out unnecessary data (like body-size histograms).
    • Request Metrics Middleware: A factory function build_request_metrics_middleware() that wraps the opentelemetry-instrumentation-actix-web RequestMetrics middleware. It uses custom RouteFormatter and metric_attrs_from_req hooks to handle project-specific requirements like route normalization and label injection (e.g., sp.org_id, sp.workspace_id).
    • Saturation Collectors: Callback-driven collectors that monitor resource saturation for:
      • r2d2 DB pool
      • fred Redis pool
      • Tokio runtime (using Handle::metrics() to track worker busy time).
    • Metrics Endpoint: A dedicated HttpServer running on the port specified by the SUPERPOSITION_METRICS_PORT environment variable, exposing a /metrics endpoint for Prometheus scraping.