Skip to content

Support updating SDK key at runtime - ideally using Microsoft.Extensions.Options primitives #182

Open

Description

@flakey-bit

Is your feature request related to a problem? Please describe.
We share our SDK key for a LD project among many components that are deployed.

We would like to be able to easily rotate the SDK key without having to recycle all of those components (across many teams in our organisation!)

Describe the solution you'd like
We're aware that the Launch Darkly SDK goes to some lengths to ensure low latency when calling code evaluates flags.

So ideally, we'd like to stick with a single LD client registered in the IoC container (singleton, as recommended by LD).

However, we would like the client to automatically notice when the SDK key has been updated and seamlessly start using the new key.

The Microsoft.Extensions.Options primitives - in particular IOptionsMonitor would be a good/natural fit for this.

Describe alternatives you've considered
Trying to coordinate recycling of components across multiple teams. We're aware that when a key is rotated, the old key can be kept functional for up to 30 days.

Additional context
N/A

Activity

  1. kinyoklion commented on Nov 12, 2025

    @kinyoklion
    Member

    Hello @flakey-bit,

    Thank you for the report. We will consider the request and look into options.

    The SDK currently isn't designed to allow for runtime changes of any configuration, and changing configuration will likely be similar in performance to initializing a new client instance. Likely equal to a wrapper around the client that detects changing and then initializes a new internal client for the singleton to use.

    Thank you,
    Ryan

    Filed internally as SDK-1571

  2. flakey-bit commented on Feb 1, 2026

    @flakey-bit
    Author

    I've done a proof-of-concept (complete hack job) for this.

    At a high-level, it involved a couple of things:

    • In the LaunchDarkly.EventSource repository, inside EventSourceService::ConnectToEventSourceApi we set (replace) the authorization header by reading from the SDK key current-value from the OptionsMonitor
    request.Headers.Remove("Authorization");
    request.Headers.Add("Authorization", _configuration.Monitor.CurrentValue.SdkKey);
    • In StreamingDataSource, register a callback for OptionsMonitor::OnChange that calls IEventSource::Restart(true) - this is the event source created in the StreamingDataSource constructor
    context.Monitor.OnChange(((settings, s) =>
    {
        _es.Restart(true);
    }));

    With these changes in place and a test harness program, I can swich between two LD projects at runtime - which is a neat party trick 🥳

    // Test harness program to demonstrate switching SDK keys at runtime
    
    using LaunchDarkly.Sdk;
    using LaunchDarkly.Sdk.Server;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Options;
    using Serilog;
    
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .WriteTo.Console()
        .CreateLogger();
    
    Log.Information("Application starting up...");
    
    const string project1SdkKey = "sdk-9271xxx";
    const string project2SdkKey = "sdk-73fexxxx";
    
    var configData = new Dictionary<string, string?> {
        {"LdSettings:SdkKey", project1SdkKey}
    };
    
    var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
        .AddInMemoryCollection(configData)
        .Build();
    
    var optionsFactory = new OptionsFactory<LdSettings>(
        new[] { new ConfigureFromConfigurationOptions<LdSettings>(config.GetSection("LdSettings")) },
        Enumerable.Empty<IPostConfigureOptions<LdSettings>>()
    );
    
    var cache = new OptionsCache<LdSettings>();
    var changeSource = new ConfigurationChangeTokenSource<LdSettings>(config.GetSection("LdSettings"));
    
    var monitor = new OptionsMonitor<LdSettings>(
        optionsFactory,
        new[] { changeSource },
        cache
    );
    
    var ldConfigBuilder = Configuration.Builder("SDK key from constructor not used any more!");
        var ldConfig = ldConfigBuilder.Build();
        ldConfig.SettingsMonitor = monitor; // Quick hack job to plumb the settings monitor in to the LD SDK
    
    var client = new LdClient(ldConfig);
    client.FlagTracker.FlagChanged += (sender, args) =>
    {
        var updatedFlagValue = client.BoolVariation(args.Key, Context.FromUser(User.WithKey("eddie")));
        Log.Information("SDK Event: Flag '{FlagName}' changed to {newValue}", args.Key, updatedFlagValue);
    };
    
    var quitEvent = new TaskCompletionSource<bool>();
    
    Log.Information("Starting main application loop");
    
    _ = Task.Run(() =>
    {
        Log.Information("Listening for 't' key or 'q' to quit...");
        while (true)
        {
            var key = Console.ReadKey(intercept: true);
            if (key.KeyChar == 't')
            {
                if (config["LdSettings:SdkKey"] == project1SdkKey)
                {
                    Log.Information("Switching to project 2");
                    config["LdSettings:SdkKey"] = project2SdkKey;
                }
                else
                {
                    Log.Information("Switching to project 1");
                    config["LdSettings:SdkKey"] = project1SdkKey;
                }
    
                // Notify the monitor that the source has changed
                config.Reload();
            }
            else if (key.KeyChar == 'q')
            {
                quitEvent.SetResult(true);
                break;
            }
        }
    });
    
    // Wait until 'q' is pressed
    await quitEvent.Task;
    Log.Information("Shutting down...");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions