Superposition Documentation
repository·main·Indexed 19 days ago
https://github.com/juspay/superpositionAn 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).
What's inside Superposition
- Superposition provides OpenFeature-compatible provider implementations that enable feature flag management, context-aware configuration, and experimentation. These providers allow you to manage boolean, string, integer, float, and object flags dynamically based on user context and dimensions.
Use Superposition Native JavaScript Bindings
mainThis package provides native JavaScript (Node.js) bindings for the Superposition core library. It allows you to interact with Superposition functionality directly within a Node.js environment.
Note: It is highly recommended to use the superposition-provider instead of using these native bindings directly for most use cases.
What is SuperTOML?
mainSuperTOML is an extension of the TOML configuration format designed for managing complex configurations at scale. It introduces two primary features to standard TOML:
- Type Safety via JSON Schema: Every configuration value is validated against an associated JSON Schema, allowing for early error detection.
- 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.
How Overrides and Contexts work in CAC
mainIn 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.0Audit trail for Variable operations
mainSuperposition 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, andlast_modified_byfor every variable.
Reuse schemas with $ref and Type Templates
mainTo avoid duplication, you can reuse schemas in two ways:
1. Local Schema References (
$refanddefinitions)Define a set of
definitionswithin 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" } }Configure Refresh Strategies
mainThe
RefreshStrategyinterface 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 )Use Cohort Dimensions to group values
mainCohort 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.
Understand Dimensions in Superposition
mainDimensions 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, orhour_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 aschema(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 }}What are Type Templates
mainType 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).
Understand Mayday Webhook Event Types
mainMayday responds to three specific Superposition webhook events to manage the rollout lifecycle:
1.
ExperimentStartedTrigger: A new experiment begins. Actions: Creates a new Kubernetes Deployment, Service, and Ingress (using NGINX canary annotations) for the experimental variant.
2.
ExperimentInprogressTrigger: The traffic percentage for the experiment is updated. Actions: Updates existing Ingress resources with new
nginx.ingress.kubernetes.io/canary-weightvalues to adjust traffic distribution.3.
ExperimentConcludedTrigger: 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.
Understand the OpenTelemetry Golden-Signals Middleware Architecture
mainThe 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::observabilitymodule.Core Components
Observability::init(): Initializes an OpenTelemetrySdkMeterProviderconfigured 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 theopentelemetry-instrumentation-actix-webRequestMetricsmiddleware. It uses customRouteFormatterandmetric_attrs_from_reqhooks 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
HttpServerrunning on the port specified by theSUPERPOSITION_METRICS_PORTenvironment variable, exposing a/metricsendpoint for Prometheus scraping.