Introducing a new way to review your PRs.

Read the announcement

thomaspoignant / go-feature-flag

GO Feature Flag is a simple, complete and lightweight self-hosted cloud native feature flag solution 100% Open Source — built on OpenFeature 🎛️

View on GitHub

18 documents · Updated Nov 23, 2026

docs / feature-flag-sdk

Feature flag SDK lifecycle

The Go SDK gives an application one path to load flag definitions, evaluate them for a subject, and send evaluation or business events to an export target. The application supplies configuration and an evaluation context. The SDK keeps the current flag state in memory so normal evaluations do not depend on a live read from the source.

Application-facing lifecycle

An application uses the SDK in four stages:

  1. Configure a flag source, refresh policy, optional fallbacks, and event targets.
  2. Initialize the SDK and wait for the first flag state to become available.
  3. Build an evaluation context and request a typed flag value or a detailed result.
  4. Close the SDK during application shutdown so refresh work and queued events finish cleanly.

The package offers both a default process-wide client and GoFeatureFlag methods for applications that need more than one SDK instance. The default client is initialized once through Init; New creates an explicit instance. References: feature_flag.go• L17-83, feature_flag.go• L159-175

Configuration and initialization

Public configuration

home/…/config.go defines Config, the application contract for the SDK. It joins the source of flag definitions with policies for refresh, logging, notifications, event export, offline operation, and shared evaluation data.

The most important choices are:

ConcernApplication decision
Flag sourceSelect one or more retrievers. When several sources define the same key, their order controls the result.
RefreshSet a polling interval or use the default interval. Optional jitter spreads reads from many application instances.
Startup fallbackDecide whether startup must fail when the source is unavailable. A persistent local configuration can provide a possibly old fallback.
Evaluation dataSet an environment and common attributes that the SDK adds to each evaluation. Request data takes precedence for the same key.
EventsConfigure separate targets for flag evaluation events and explicit tracking events.
Offline modePrevent flag reads, notifications, and event export. Evaluations use the SDK default value.

Config.Initialize supplies safe defaults before the SDK starts. Retriever and Retrievers are combined into one ordered source list. The same compatibility pattern applies to DataExporter and DataExporters. The built-in Redis and MongoDB sources present their data as JSON flag definitions to the SDK. See SDK configuration and retrieval for the source and configuration contract. References: config.go• L16-115, config.go• L125-187, config_exporter.go• L16-36, retriever/…/retriever.go• L74-111, retriever/…/retriever.go• L60-110

Initialization and readiness

Initialization first prepares the configuration and then builds the retriever manager and event managers. The retriever manager initializes supported sources, loads the first flag set into the in-memory cache, and starts background polling when the interval is enabled. Cache changes can also notify configured notifiers.

Each remote source must be ready before it can provide flags. The Redis source checks its connection during initialization and returns to a not-ready state after shutdown. The MongoDB source establishes its database connection during initialization and reads flag documents from its configured collection. Both sources report JSON output to the manager, which lets the SDK parse their results consistently. References: feature_flag.go• L56-119, retriever/manager.go• L56-73, retriever/manager.go• L189-235, retriever/…/retriever.go• L29-71, retriever/…/retriever.go• L29-57

Startup normally returns an error when no usable flag state can be loaded. With StartWithRetrieverError, the SDK can start and return SDK defaults until a later refresh succeeds. With a persistent flag configuration, it can instead start from the last stored state, which may be out of date. The SDK does not need a cache for offline initialization. References: feature_flag.go• L56-119, retriever/manager.go• L56-73, retriever/manager.go• L189-235

Flag evaluation

Evaluation requests

The SDK exposes typed variation calls for Boolean, integer, floating-point, string, array, and object values. Each call takes a flag key, an evaluation context, and an application default. The application normally uses the typed value methods. Detail methods are useful when the application must inspect why a value was selected.

The request reads the current flag from the cache and passes the flag, context, SDK configuration, and expected type to the evaluation engine. The SDK adds configured common attributes and the configured environment to that evaluation input. It then returns the selected value without requiring the application to know which source supplied the flag. References: variation.go• L18-57, variation.go• L60-100, variation.go• L102-187, variation.go• L190-291, variation.go• L294-302

Evaluation results

Each detailed result separates the returned value from the state of the evaluation. It can report the selected variation, reason, error code, flag version, metadata, and whether the flag requests event tracking. A typed call returns only the value and error, so callers that need operational detail should use its matching detail call.

The application default is the safety value for a missing flag, an unavailable provider, or a type mismatch. An uninitialized SDK reports a provider-not-ready error. Offline mode returns the application default without treating the result as an evaluation failure. See flag evaluation and targeting for targeting rules and resolution semantics. References: variation.go• L347-402, modules/…/evaluation.go• L16-66

Evaluation contexts

Context identity and attributes

An evaluation context identifies the subject of a flag decision. Its required key should stay stable for that subject. Its custom attributes give targeting rules the data they need. The same context also supplies identity and user data for event records.

Applications can create a context directly or use the builder. Anonymous status is represented by the anonymous attribute. Context data is passed into evaluation and is copied into explicit tracking events. See evaluation contexts for the context contract and attribute rules. References: ffcontext/context.go• L13-33, modules/…/context.go• L28-57, modules/…/context.go• L71-125, modules/…/context_builder.go• L7-53

Shared evaluation data

Configuration-level enrichment adds attributes that apply to every evaluation. This lets an application attach data such as a server version without adding it to each request. A value in the request context overrides an enrichment value with the same name, while the configured environment is also available to flag rules.

The SDK keeps these shared values separate from the application-created context. This makes the context reusable while still giving every evaluation the same service-level data. References: config.go• L97-103, variation.go• L395-402, variation_all_flags.go• L44-51

Event tracking

Evaluation events

An evaluation event records a flag decision for downstream analysis. The SDK creates one only when the evaluated flag enables event tracking. The event carries the flag key, returned value, selected variation, default-use status, version, source, context kind, and metadata.

The SDK adds the event to the configured feature-event manager in a separate goroutine. A bulk target flushes on its interval or when its queue reaches its limit. A live target sends the event without waiting for a batch. See event export pipeline for delivery behavior. References: variation.go• L320-345, exporter/feature_event.go• L15-41, exporter/manager.go• L46-64, exporter/data_exporter.go• L74-123

Explicit tracking events

Track lets an application record a business event that is not itself a flag evaluation. It uses the context identity and attributes together with an event name and application-provided details. These events use the tracking-event pipeline rather than the feature-event pipeline.

Offline mode does not export tracking data. When no tracking target is configured, the call has no downstream effect. References: tracking.go• L10-41, exporter/tracking_event.go• L10-37, feature_flag.go• L122-156

Runtime refresh and shutdown

Flag refresh

After the first load, the SDK refreshes the flag cache at the configured interval. A refresh reads the configured sources, combines their flag definitions, and replaces the current cache state. An application can call ForceRefresh when it knows that a source changed and can inspect the last successful cache refresh time.

Setting the SDK offline stops its background polling and makes later evaluations use SDK defaults. The default process-wide helper can start polling again when it is put back online, but the current updater is not recreated after it has been stopped. Treat offline changes as a lifecycle decision rather than a temporary network switch. References: retriever/manager.go• L75-107, retriever/manager.go• L283-293, feature_flag.go• L190-217, feature_flag.go• L219-261

The following diagram shows how source data becomes the state used by an application evaluation.

flowchart LR
    A[Configured retrievers] --> B[Initial or scheduled read]
    B --> C[Flag cache]
    C --> D[Evaluation context]
    D --> E[Typed value or detailed result]
    B --> F[Notifiers]

Shutdown sequence

Close stops retriever polling before it shuts down retrievers and closes the cache. It then waits for in-flight evaluation event submission and stops both event managers. Stopping the managers flushes pending events, so application shutdown should call Close rather than abandoning the client.

The sequence protects two shared resources: no refresh should write the cache after shutdown, and no evaluation event should be lost because its submission goroutine still runs. Source shutdown is also safe when a Redis source has not completed initialization or has already been closed. References: feature_flag.go• L159-175, retriever/manager.go• L97-107, retriever/manager.go• L164-186, retriever/…/retriever.go• L52-71, exporter/data_exporter.go• L93-117

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the default-client helpers and GoFeatureFlag methods aligned when a public lifecycle operation changes.
  • Preserve the ordering contract between Retriever and Retrievers, since source order changes which flag definition wins.
  • Keep each retriever's output format aligned with the manager parser. Redis and MongoDB sources must continue to return JSON flag data.
  • Keep FeatureEvent and TrackingEvent routed to their matching exporter managers. A target configured for one event type must not silently receive the other.
  • Recheck startup fallback behavior when changing retriever readiness, persistent configuration, or cache update rules.
  • Recheck shutdown ordering when changing polling or exporter queues. Refresh and event submission must finish before their shared resources close.
  • Keep every typed variation entry point aligned with its detail call so it uses the same expected value type and records the same evaluation event.
  • Preserve the evaluation contract that offline mode returns the SDK default without exporting an evaluation event.

Important failure modes

TriggerConsequenceGuard
No retriever is configuredInitialization cannot load flags and returns an error.Configure Retriever or at least one entry in Retrievers.
Initial source read fails with the default startup policyThe SDK does not start.Use a reachable source or explicitly choose StartWithRetrieverError or a persistent configuration fallback.
Redis or MongoDB retrieval runs before source initializationThe source returns an initialization error and the SDK cannot refresh from it.Let SDK initialization complete before serving evaluations or forcing a refresh.
A Redis value is not valid JSONThe Redis refresh fails instead of producing a partial flag state.Store valid JSON for every key selected by the configured prefix.
A MongoDB document has no string flag keyThe document is ignored, so that flag is absent from the retrieved state.Store each flag definition with a string flag field.
Evaluation runs before initialization or against a missing flagThe SDK default is returned with a failure result and an error.Initialize before serving requests and treat the application default as the safe path.
Flag value does not match the typed variation callThe SDK default is returned with a type-mismatch error.Match the variation method to the flag value type.
Offline mode is enabledNo source refresh, notification, or event export occurs.Use offline mode only when this behavior is intended.
A detail method uses the wrong expected typeA valid flag can be treated as a type mismatch and return the application default.Keep each public typed variation method paired with its correct evaluation type.
Event manager is not closedQueued events or exporter workers can remain active at process exit.Call Close during application shutdown.

Key files

FileWhy to read it
feature_flag.goDefines the SDK instance, default client, initialization, refresh controls, and shutdown lifecycle.
config.goDefines the application-facing configuration and its source and exporter composition rules.
variation.goDefines typed evaluation entry points, safe defaults, detailed results, and evaluation-event submission.
variation_all_flags.goDefines all-flag evaluation and direct cache access for integrations that need a complete flag state.
ffcontext/context.goDefines the public context types exposed to applications.
retriever/manager.goShows how sources become cached flag state and how polling and fallback behavior are controlled.
retriever/…/retriever.goIllustrates a Redis-backed source with prefix-based flag selection and JSON output.
retriever/…/retriever.goIllustrates a MongoDB-backed source that turns collection documents into JSON flag data.
exporter/manager.goShows how feature and tracking events move from the SDK into configured targets.
tracking.goDefines the explicit business-event entry point.