Skip to content

Provider lifecycle race condition in multi-threaded SDKs #365

Closed

Description

@dd-oleksii

I've been digging provider lifecycle in Go and Swift SDKs, and I believe there's a couple of things in OF spec that make it hard to implement it correctly in the presence of true multi-threading.

The main one is that there's no clear ownership of the provider state and provider events — it's split between the provider and the API, and both provider and the API are allowed to emit events. This is an issue because neither the provider nor the API are equipped to ensure the consistent ordering of events

The API is required to emit "provider ready" event and update the state after initialization is complete. However, once the provider returns from the init function, there's a brief window before the API updates the state and emits the event. This is not an issue in single-threaded languages like js or python. However, with multi-threading, the provider is allowed to do work in the background and emit an error event within that window — and now the order of provider ready and error events is undefined.

Current state across multi-threaded SDKs:

  • Go: race condition
  • Swift: 🐛 implements eventing but does not update state on provider events
  • Java: race condition
  • Kotlin: race condition
  • Dotnet: race condition
  • Rust: eventing not implemented

This would be trivial to fix if only one of API or provider were allowed to emit events (or update the state), so they could use locks/queues to order the events/updates properly.

If both are allowed to emit, the only way to prevent a race is for the API to guard eventing with a lock and to hold this lock throughout the provider initialization. This way, no provider events would come through until API processes its own ready event first.

The main issue with this approach is that it locks up the API/provider and serializes all calls to init/shutdown/on context change. This more or less completely destroys concurrency and prevents the provider from reacting to context change / shutdown if initialization is taking a while. This also easily leads to deadlocks if provider tries to emit events from/during lifecycle handlers.

Both race condition and total locking sound bad, so I would really suggest moving state management responsibility back to providers — they are the only party who knows their own state at all times, and they are equipped to resolve any races.

I see that the spec is trying to lift the burden from provider authors but imo SDK trying to manage providers' state is not helping. Anecdotally, I can add that as a provider author, the eventing and state management has been the most confusing part of the OF spec/SDKs, and I've spent quite a bit of time trying to make SDK set the state I want.


PoCs by @toddbaert here:

Go: open-feature/go-sdk#487
Java: open-feature/java-sdk#1892
JS: open-feature/js-sdk#1362

Activity

  1. self-assigned this
    on Feb 19, 2026
  2. toddbaert commented on Feb 19, 2026

    @toddbaert
    Member

    Very insightfull summary @dd-oleksii .

    The API is required to emit "provider ready" event and update the state after initialization is complete. However, once the provider returns from the init function, there's a brief window before the API updates the state and emits the event. This is not an issue in single-threaded languages like js or python. However, with multi-threading, the provider is allowed to do work in the background and emit an error event within that window — and now the order of provider ready and error events is undefined.

    This is the key point.

    It's tough, because having the state in the provider was a foot gun. It would certainly would solve this race, but it forces an stateful abstraction onto providers, which are currently an interface that can be assumed to be stateless. I would love to find a way to solve this without moving state back into the providers.

    cc @kinyoklion @lukas-reining

  3. added
    bug
    on Feb 19, 2026
  4. kinyoklion commented on Feb 19, 2026

    @kinyoklion
    Member

    It would certainly would solve this race, but it forces an stateful abstraction onto providers, which are currently an interface that can be assumed to be stateless.

    I do feel like that may be a mismatch in what providers do, and the abstraction we are using. As almost all providers do have relevant state, some of them very simple and some of them very complex. It is reasonably easy to translate the state upon request, but potentially more complex to derive the state through observation. The exceptions would be in-memory (or hard-coded) providers that are ready for use upon construction. Or providers that block the thread doing their construction until they have finished their initialization (which do have state, but largely bypass this problem, and is the default behavior for most of the LaunchDarkly providers which would be affected by this issue).

    I think we could infer the state based on events from providers, but inferring the state from a combination of data sources, makes this harder to keep safe. Currently the combination basically being a function call completing + events. It does still depend on the provider emitting its events in a way that is deterministic regardless of which threads get priority.

  5. toddbaert commented on Feb 23, 2026

    @toddbaert
    Member

    I believe this is one of those situations where it's worth calling a technical committee meeting (anyone else interested can also attend). I suggest we spend some time this week thinking about solutions, and I will create a meeting poll and we can come to a decision. As I see it, we have 2 options:

    • investigate what can be done to address this race in multi-threaded SDKs, with locks or some kind of queue
    • move the state back to the providers
      • if this is the best choice, we need to understand the migration/compatibility strategy
  6. dd-oleksii commented on Feb 26, 2026

    @dd-oleksii
    ContributorAuthor

    UPD: One technical way to solve the race I discovered in open-feature/swift-sdk#108 is asking providers to execute a callback on initialize and on context change instead of returning their result from the function. This makes it possible for providers to avoid the race by synchronizing callbacks with event emission (so they don't happen concurrently). This requires that OF SDK reacts to event emission synchronously — this is true in swift but may not be true in languages that implement events via a channel. This API is also clumsy: providers might forget to execute the callback, and it's not obvious that callbacks and events must be synchronized.

  7. toddbaert commented on Mar 3, 2026

    @toddbaert
    Member

    UPD: One technical way to solve the race I discovered in open-feature/swift-sdk#108 is asking providers to execute a callback on initialize and on context change instead of returning their result from the function. This makes it possible for providers to avoid the race by synchronizing callbacks with event emission (so they don't happen concurrently). This requires that OF SDK reacts to event emission synchronously — this is true in swift but may not be true in languages that implement events via a channel. This API is also clumsy: providers might forget to execute the callback, and it's not obvious that callbacks and events must be synchronized.

    That's one of the options I considered as well - beyond a callback it could be some kind of atomic object reference that represents a lock... but I agree this is very clumsy.

  8. toddbaert commented on Mar 9, 2026

    @toddbaert
    Member

    Meeting on 2026/03/04

    Overview

    The meeting focused on addressing a concurrency issue in multi-threaded SDKs related to provider initialization and event handling. The team discussed two potential solutions: implementing event queuing/locking mechanisms or moving the provider state management back to the providers themselves. After thorough discussion, the group agreed that moving the state back to providers was the preferred approach, despite requiring significant changes to the SDK. Ryan and André confirmed this would be feasible for .NET implementations, while Oleksii and others agreed to investigate the feasibility for other languages including Java, JavaScript, and Python. The team also identified a related issue regarding evaluation methods for providers in fatal/non-ready states that would need to be addressed alongside the main state management change.

    Details

    Multi-threaded SDK Timing Issues:

    The team discussed an issue with multi-threaded SDKs where there is a timing gap between initialization and event admission, which could lead to undefined behavior. They explored two potential solutions: moving state back into the provider (which would require undoing a recent SDK change) or implementing complex queuing and locking mechanisms. Ryan explained that in his case, implementing queuing would involve two layers of buffering, which would be complex. Oleksii pointed out that even with queuing, race conditions could still occur between concurrent events. The team seemed to lean towards the provider-state solution, though concerns were raised about migration paths and the need for a deprecation period.

    State Management Migration Discussion:

    The team discussed moving state management from SDKs to providers, with Ryan and Vaughan focusing on mature SDKs like Java and .NET. Ryan confirmed this could be done non-breakingly in .NET and Java, though Vaughan noted they should check for potential conflicts. The team agreed to investigate this approach for 1.0 languages, with Vaughan offering to review Java and JavaScript, while asking others to comment on their findings for other languages.

    Status Reporting Approach Implementation:

    The team discussed implementing a new approach for status reporting in providers, with Ryan proposing to use a binding object in an abstract class. They agreed this would not be a breaking change for .NET providers, though André noted that providers might be hesitant to bump their version numbers. Ryan requested further investigation into potential issues in Python, Java, and JavaScript, while also planning to update documentation and create a more robust checklist for authoring providers. The team decided to move forward with this approach despite the non-trivial amount of work involved.

    Decision Timeline and SDK Review:

    The team discussed the timeline for making a decision about a significant change, with Vaughan aiming for a decision within one to two weeks. André offered to help with the .NET aspect, though he mentioned being overloaded with work. Oleksii raised a concern about concurrency issues in the spec, specifically regarding the handling of provider states and the potential for time-of-check/time-of-use problems. The team agreed to keep comments related to the SDK review on the spec issue to maintain synchronization.

    SDK and Provider State Issues:

    The team discussed issues with SDKs and providers, particularly regarding how to handle non-recoverable states. Ryan explained that SDKs should continue evaluations even when providers are in a fatal state, as this affects analytics. Oleksii pointed out that moving status back to providers could create problems with controlling it. The team agreed to consider these issues together and potentially make changes to the specification. Vaughan will summarize the meeting and post it in the thread.

    Next Steps

    • @toddbaert : Investigate the feasibility of moving provider state management back into providers for Java and JavaScript SDKs, and comment findings on the spec issue.
    • @kinyoklion : Review the feasibility of moving provider state management back into providers for .NET SDK, and comment findings on the spec issue.
    • @toddbaert @dd-oleksii @kinyoklion @erka (volunteer basis): Scout the feasibility of moving provider state management back into providers for other SDKs (e.g., Python, Rust, Ruby), and comment findings on the spec issue.
    • @toddbaert @dd-oleksii @kinyoklion @erka: Comment on the spec issue with any concerns or issues found during the above investigations, especially regarding breaking changes or migration challenges.
    • @toddbaert: Summarize the meeting and post the summary (and recording link if available) in the relevant spec issue thread.
    • @toddbaert: Update provider authoring documentation to include new requirements and migration guidance as part of this effort.
    • @toddbaert: Make a comment in the spec issue regarding the related concurrency issue raised by Oleksii (time-of-check/time-of-use and fatal state handling), and consider opening a separate issue for this if needed.
    • @toddbaert: Ensure external provider maintainers (e.g., LaunchDarkly, other vendors) are notified about upcoming changes and deprecation period.
    • @toddbaert @dd-oleksii @kinyoklion @erka: Aim to complete the above investigations and provide feedback within approximately one to two weeks, ahead of the next community meeting if possible.
  9. fabriziodemaria commented on Mar 10, 2026

    @fabriziodemaria
    Contributor

    I am curious if this re-work would affect the current application-facing APIs?
    I hope we can keep the state/eventing complexity away from the OpenFeature adopters, by still offering idiomatic "awaitable" lifecycle methods (e.g. await api.setProvider(provider)). I guess the implementation of these methods (inside the SDKs) would rely on the Provider's events to return correctly.

    Great to see this initiative taking shape!

  10. dd-oleksii commented on Mar 10, 2026

    @dd-oleksii
    ContributorAuthor

    I am curious if this re-work would affect the current application-facing APIs?

    I don't think we need to change application-facing API.

    For awaitable lifecycle methods, I find it hard to resolve lifecycle methods reliably based on events (you can show me an implementation and I will likely find a race condition), so I would expect provider's lifecycle methods to still be awaitable (so SDK only needs to await on it before returning to application).

  11. dd-oleksii commented on Mar 10, 2026

    @dd-oleksii
    ContributorAuthor

    btw, adding to the list of affected SDKs:

    • Ruby is affected because it also has threads and CRuby (and other) are allowed to switch the thread on any functions call / garbage collection, which may happen (almost) anytime
    • JS is likely also affected because returning from an async function is not immediate but schedules a new microtask. Some other code may run before the handler microtask and emit an event (event handler run synchronously), and the initialize handler microtask will then overwrite the status which was set by emitted event 🫠
  12. dd-oleksii commented on Mar 11, 2026

    @dd-oleksii
    ContributorAuthor

    General note: base implementation

    I think we can simplify the job for providers by implementing BaseFeatureProvider or SimpleFeatureProvider class/wrapper/adapter that simplifies the tedious work of managing the status and emitting events. I also argue that it should serialize all calls to lifecycle methods and event emission, so they don't happen concurrently — this allows the base implementation to avoid race conditions and is least surprising for naïve providers. (It's important that event emission is synchronized with lifecycle, so either no extra events can be emitted during lifecycle method execution, or they are called from the method itself — e.g., via recursive mutex)

    Advanced providers should be able to opt-out of the base class and implement the provider interface directly, benefitting from concurrency, cancelation, etc if they are ready to handle the added complexity.

    General note: splitting provider interface package

    Moving status handling back to providers is a breaking for providers but it shouldn't change the API for application authors. Ecosystems with dependency unification (the ones that make sure that only a single version of each dependency package is present) may benefit from splitting provider interface package from the rest of SDK. This way the main openfeature package may stay at its current major version, while the provider interface may get bumped. If providers specify version constraints correctly, I guess package managers should be able to resolve the constraints and select OF SDK version that is compatible with the provider (and vice versa).

    Not 100% sure about this idea but it's worth exploring for Python, Ruby, Swift, Go, Java, Kotlin, .NET. (JS and Rust don't always unify dependencies. Though it still may be helpful to split off provider interface package for other reasons.)

    (Tangentially, this also helps feature providers to implement OF provider natively. Some teams I worked with were unwilling to pull in the whole OF SDK package as a dependency just to implement the provider interface, so we had to implement adapter packages. Splitting provider interface from the rest of SDK makes the dependency significantly smaller, so there's less concern for pulling it in as a dependency.)

    Rust

    No changes needed. Provider is already expected to manage its own status. Eventing is not implemented yet. The SDK is pre-1.0.

    Swift

    This one is feasible. I have a wip changes locally that implement the change. It is a breaking change for providers but is non-breaking for application authors. Although the SDK is pre-1.0, so that should be fine.

    I have implemented ProviderStatusTracker that implements EventSender, EventPublisher. It accepts provider events, updates provider status according to the rules, and handles the subtleties of ordering and concurrency for downstream providers. It should be a good building block for all providers.

    Swift also has implementation inheritance, so we can implement BaseFeatureProvider that can be extended by simple providers. The safe behavior is to serialize all lifecycle methods, so they cannot happen concurrently (similar to what's currently forced on all providers) — this allows us to avoid race conditions and is least surprising for naïve providers. Advanced providers that want to opt-in to concurrency may implement FeatureProvider interface directly (using the ProviderStatusTracker helper).

    Go

    ❗ Go SDK is post 1.0

    Feasible. With Go's dynamic interface probing, I think this can be implemented as a minor version bump:

    • Declare a new interface for providers to implement, requiring them to implement EventHandler interface and Status() method
    • Providers that don't implement the new interface we can automatically wrap into "simpleFeatureProvider" adapter that serializes all lifecycle methods and manages status updates and events.

    Python

    Python SDK is pre 1.0. The change will probably be a breaking one for providers. The good news is that python already has AbstractProvider (which I expect most providers to rely on), so we can implement helpers here. e.g. it already implements functions for event emission, so we can augment it to track provider status.

    The tricky part would be to augment initialize to always emit the final event, given that the provider may override it. This could be done with wrapping like this. For advanced providers, we may allow them to opt-out from this wrapping by passing a new named parameter to constructor.

    Ruby

    Ruby is pre 1.0 as well, though I think we can make it non-breaking:

    We may implement a mixin similar to EventEmitter that also tracks provider status. The reason why it's better to have a new mixin (rather than extending EventEmitter) is that providers should opt-in to new requirements (requirement to emit event at the end of initialize). This allows us to add a grace period: check if provider responds to "get status" — if not, wrap it into adapter that emits event at the end of initialize and serializes it with other provider-emitted events. Ideally, this new mixin is prepended, so it can wrap provider's initialize with recursive lock (monitor). Providers who want to opt-out from this wrapping/locking may include the mixin instead.

    Alternatively, if this is too convoluted, we can bite the bullet and make it a breaking change.

  13. typotter commented on Mar 12, 2026

    @typotter

    Kotlin

    We can use a similar approach to Go and do interface checking (is keyword) to determine if the set provider implements some ProviderStateHandler interface and wrap with a default implementation otherwise. This makes it easy on vendors, though we could break providers as Kotlin is pre 1.0

    Recommend we

    • split the Provider and EventEmitter interface(s) and required datatypes into their own module separate from the rest of the SDK
    • Implement an event-emitting, lifecycle-serializing default provider wrapper that developers can extend
    • Use is to determine if a provider is an event emitter and wrap it in the default if not

    I think this provides the best devX. works out of the box with existing providers, but exposes all the knobs and levers for advanced use.

    What is not immediately clear to me is how we raise provider-initiated states such STALE or differentiate between ERROR and FATAL.
    The rest of the states: NotReady, Ready, Reconciling, and onContextChanged all follow from lifecycle events which the wrapper would control

  14. erka commented on Mar 12, 2026

    @erka
    Member

    Just for the record, the Go SDK in v1.13.1 had StateHandler.Status. It was removed in v1.14.0.

  15. toddbaert commented on Mar 12, 2026

    @toddbaert
    Member

    I did some reasearch:

    Survey and PoC

    Spec Issue: #365
    Date: 2026-03-11

    1. Spec Changes

    New requirements (Section 2, Providers)

    The provider MUST define a status accessor with possible values NOT_READY, READY, STALE, ERROR, FATAL, or (in static-context paradigm) RECONCILING.

    The provider's status MUST return NOT_READY before initialize is called and after shutdown terminates.

    The provider's status accessor MUST be safe for concurrent access.

    Status changes and associated event emissions MUST be atomic from the perspective of external observers.

    Modified requirements

    Requirement Current Change
    1.7.1 Client MUST define a provider status accessor Still exists, delegates to provider.status
    1.7.3 Client status MUST indicate READY if init terminates normally Provider status MUST indicate READY if init terminates normally
    1.7.4 Client status MUST indicate ERROR if init terminates abnormally Provider status MUST indicate ERROR if init terminates abnormally
    1.7.5 Client status MUST indicate FATAL if init terminates with PROVIDER_FATAL Provider status MUST indicate FATAL if init terminates with PROVIDER_FATAL
    1.7.9 Client status MUST indicate NOT_READY after shutdown Provider status MUST indicate NOT_READY after shutdown
    5.3.5 SDK MUST update client status on provider event Remove — client reads provider status directly
    5.1.1 Providers MAY emit READY/ERROR/STALE/CONFIG_CHANGED. Cannot emit RECONCILING/CONTEXT_CHANGED State-managing providers CAN also emit RECONCILING and CONTEXT_CHANGED
    5.3.4.1–3 SDK manages RECONCILING/READY/ERROR during context changes Provider manages these transitions; SDK reads provider status

    Unchanged

    For completeness, these are related but I think they will remain unchanged.

    1.1.2.2 (SDK calls init), 1.1.2.3 (SDK calls shutdown), 1.1.2.4 (setProviderAndWait), 1.7.6–1.7.7 (default during NOT_READY/FATAL), 2.4.1/2.5.1/2.6.1 (provider MAY define lifecycle methods), 5.2.1–5.2.7 (handler registration), 5.3.3 (late-attached handlers).


    2. SDK Migration

    SDKs provide a base class or wrapper that manages status on behalf of legacy providers (same behavior as today). New providers implement status natively. Legacy behavior is deprecated, removed in next major version.

    flowchart TD
        A[Provider registered with SDK] --> B{Implements<br/>StateManagingProvider?}
    
        B -- Yes --> C[SDK wrapper delegates<br/>status to provider]
        C --> C1[initialize / shutdown / onContextChange:<br/>SDK skips state writes AND event emissions]
        C --> C2[Provider events:<br/>SDK skips state writes]
        C --> C3[getState / status:<br/>reads from provider directly]
    
        B -- No --> D[SDK wrapper manages<br/>state internally<br/>**legacy, deprecated**]
        D --> D1[initialize / shutdown / onContextChange:<br/>SDK sets state AND emits events after return]
        D --> D2[Provider events:<br/>SDK updates state on emit]
        D --> D3[getState / status:<br/>reads from SDK wrapper]
    
        C1 & C2 & C3 --> E[Provider-emitted events<br/>still propagate<br/>to registered handlers]
        D1 & D2 & D3 --> E
    
    Loading
    Language Notes PoCs
    .NET Confirmed non-breaking (abstract class)
    Java PoC. New StateManagingProvider interface. FeatureProviderStateManager delegates getState() and skips SDK-side state writes when delegate implements it. ProviderRepository.initializeProvider() skips SDK-side READY/ERROR event emissions. Legacy providers unchanged. All tests pass. PR #1892
    Go Interface-based; needs adapter
    JS PoC. New StateManagingProvider interface + isStateManagingProvider type guard (discriminant: managesState: true). ProviderWrapper delegates status getter and no-ops setter. setAwaitableProvider() skips SDK-side READY/ERROR event emissions. runProviderContextChangeHandler() (web only) skips SDK-side RECONCILING/CONTEXT_CHANGED/ERROR emissions and status writes. Legacy providers unchanged. All 583+33 tests pass. PR #1362
    Python, Swift, Kotlin, Ruby, Rust Under investigation

    3. Context Change / Reconciliation

    The same race condition from initialize() also applies to onContextChange() (static-context paradigm only):

    1. SDK calls provider.onContextChange()
    2. Provider returns (async)
    3. Window: provider can emit ERROR here, changing its own state
    4. SDK emits CONTEXT_CHANGED + sets status to READY => wrong state, wrong event order

    Decision: State-managing providers own all context change transitions too: RECONCILING, READY (via CONTEXT_CHANGED), and ERROR. The SDK skips all status writes and event emissions in this path.

    Spec impact: Current spec (5.1.1) says providers cannot emit PROVIDER_RECONCILING or PROVIDER_CONTEXT_CHANGED. This must change for state-managing providers. They MUST be able to emit these events atomically with their state transitions.

    Per-paradigm impact:

    Paradigm Context change handling Impact
    Static context (client-side / web) onContextChange() Full guard needed. Done in JS web SDK.
    Dynamic context (server-side) N/A No context change handler. No impact.
  16. typotter commented on Mar 12, 2026

    @typotter

    Kotlin

    Forgot to mention. Kotlin has ambiguous observation vectors via statusFlow and observe

    statusFlow is a filtered subset of events emitted from the provider (subscribed via provider.observe()) plus lifecycle events example

    observe is just a straight patch into the provider's observe method, so the lifecycle events normally emitted around setProvider and setContext are not in this stream.

    It would be good to fix this up as part of the Eventing refactor.

  17. added a commit that references this issue on Jul 8, 2026
    79285dc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions