LiftCanary

SDKs

.NET

Server-side decisions for ASP.NET Core and workers (.NET 8+), with live updates and AI config helpers.

The LiftCanary package decides on your .NET servers: ASP.NET Core, worker services, Azure Functions and console jobs. One thread-safe client serves every request, refreshes the datafile in the background and sends events in batches. Decisions make no network call, and a user gets the same variation as on the website, in the apps and in every other SDK.

Install#

Terminal
dotnet add package LiftCanary

.NET 8 or newer. No dependencies beyond .NET itself (System.Text.Json, HttpClient).

Usage#

Register one client for the whole app as a singleton, wait for the datafile at startup, and create a user per request.

Program.cs
using LiftCanary;

var builder = WebApplication.CreateBuilder(args);
// Created by the container, so it is disposed at shutdown, which sends the remaining events.
builder.Services.AddSingleton(_ => new LiftCanaryClient(builder.Configuration["LiftCanary:SdkKey"]!));

var app = builder.Build();
// Waits up to 3 s for the first datafile; until then every flag is off.
await app.Services.GetRequiredService<LiftCanaryClient>().ReadyAsync();

app.MapPost("/checkout", async (HttpContext http, Cart cart, LiftCanaryClient liftcanary, OrderService orders) =>
{
    var user = liftcanary.CreateUser(
        http.User.FindFirst("sub")!.Value,
        new Dictionary<string, object?>
        {
            ["plan"] = http.User.FindFirst("plan")?.Value,
            ["country"] = (string?)http.Request.Headers["CF-IPCountry"],
        });

    var flow = user.GetString("new_checkout", "flow", "classic");
    var order = await orders.PlaceAsync(cart, flow);
    user.Track("purchase", (double)order.Total);
    return Results.Ok(order);
});

app.Run();

The user#

MethodReturns
IsEnabled(flagKey)Whether the feature is on for this user.
GetString / GetBool / GetInt / GetDouble(flagKey, name, fallback)The variable, or the fallback when the flag or variable is missing, null or of another kind.
GetVariable<T>(flagKey, name, fallback)The variable as T: strings, booleans, numeric types, enums (from a string), JsonElement, JsonNode types and your own classes.
GetJson(flagKey, name)A JSON variable as a JsonElement?.
Decide(flagKey, sendExposure: true)A Decision: Enabled, VariationKey, RuleKey, InExperiment, Reason, Variables, Revision.
DecideAll()Decisions for every flag, by key.
Track(eventKey, value, properties)Records a goal event. value is summed or averaged by goals (revenue, latency).

JSON variables can be read into your own classes, with ASP.NET Core's camelCase rules. A number that doesn't fit the type gives the fallback.

C#
record Layout(int Columns, string Highlight);
var layout = user.GetVariable("pricing_page", "layout", new Layout(3, "pro"));

CreateUser(id, attributes, bucketingId, page, activeLocations, anonymousId) takes the same fields as the other SDKs, as optional named arguments. Attributes can be strings, booleans, any numeric type (10, 10L, 10.0 and 10m are the same number), null or JsonElement values, and are sent with events; page (the full request URL, for location conditions) and activeLocations never are. Targeting is type-strict like JavaScript's ===: "10" never equals 10. Experiment exposures are logged automatically, once per user, flag, rule and variation; pass sendExposure: false to Decide to skip it.

At sign-in, pass the browser's anonymous id (the liftcanary_anon cookie, also LiftCanaryClient.AnonymousIdCookie) as anonymousId, so results count the landing-page visit and the signed-in user as one person. bucketingId is optional: pass the same value only if the server should decide the flag the way the landing page did. See From landing page to app.

C#
var anon = http.Request.Cookies[LiftCanaryClient.AnonymousIdCookie];
var user = liftcanary.CreateUser(userId, anonymousId: anon);

Options#

C#
new LiftCanaryClient(sdkKey, new LiftCanaryOptions { PollingInterval = TimeSpan.FromSeconds(60) });
Datafile
Datafile
Datafile.Parse(json): a datafile to start from (bootstrap, offline), so the first decisions need no download.
CdnUrl
string
Where datafiles come from. Default https://cdn.liftcanary.com; use your own domain or the API when self-hosting.
EventsUrl
string
The collector. Default https://events.liftcanary.com.
Streaming
true
Live updates: a published change arrives in about a second. false turns them off and leaves polling.
StreamUrl
string
Where live updates connect. Default: CdnUrl.
PollingInterval
30 s
Time between datafile checks, in case the live connection drops (ETag, so unchanged datafiles cost almost nothing). TimeSpan.Zero turns polling off.
EventFlushInterval
2 s
How often queued events are sent.
EventBatchSize
200
Events per request.
EventMaxQueueSize
20000
Events held in memory before the oldest are dropped (counted in client.DroppedEvents).
ModelPrices
IDictionary<string, ModelPrice>
Price per 1M tokens per model, for AI configs.
HttpClient
HttpClient
Replaces the SDK's own HTTP client: for example factory.CreateClient("liftcanary") from IHttpClientFactory, for proxies or Polly handlers. The SDK never disposes it.
HttpMessageHandler
HttpMessageHandler
A handler for the SDK's own client (proxies, tests). Ignored when HttpClient is set.
HttpTimeout
10 s
Per datafile download and event request.
Logger
Action<LiftCanaryLogLevel, string>
Receives the SDK's logs, for example to forward them to an ILogger. Without one, nothing is logged.
AutoStart
true
Starts the background work in the constructor; otherwise call Start() or ReadyAsync().

Live updates#

The client keeps a server-sent events connection open, so a change you publish reaches your decisions in about a second. Polling goes on underneath, so a dropped connection only means waiting for the next poll. The connection reconnects with backoff, and a 404 turns live updates off for the life of the client. Only a newer revision is ever applied. Subscribe runs after each one and returns an IDisposable that stops it:

C#
var subscription = liftcanary.Subscribe(() => logger.LogInformation("Datafile revision {Revision}", liftcanary.Revision));

Shutdown and short jobs#

  • ASP.NET Core and worker services: the container disposes the singleton at shutdown, which sends the remaining events. It only disposes what it created, so register the client with a factory as above.
  • Console apps: await using var liftcanary = new LiftCanaryClient(...), or await liftcanary.CloseAsync() at the end (it waits at most 5 s by default).
  • Short jobs and Azure Functions: call await liftcanary.FlushAsync() before returning. It returns false when events are left.
  • Errors never throw into your app: a failed download keeps the last datafile, and failed event batches are retried with backoff on 5xx, 429 and network errors (other 4xx batches are dropped).

AI configs#

Test models, prompts and parameters on real users, measured on latency, tokens, cost, errors and feedback. Your code still calls the provider.

C#
var liftcanary = new LiftCanaryClient(sdkKey, new LiftCanaryOptions
{
    ModelPrices = new Dictionary<string, ModelPrice> { ["my-small-model"] = new(Input: 0.25, Output: 1.25) },
});

var cfg = user.AiConfig("support_bot", model: "my-small-model", prompt: "You are a helpful assistant. Answer in {{language}}.");
var system = LiftCanaryAi.RenderPrompt(cfg.Prompt, new Dictionary<string, object?> { ["language"] = "Turkish" });
var reply = await user.MeasureLlmAsync(cfg,
    () => llm.ChatAsync(cfg.Model, system, cfg.Params, http.RequestAborted),
    r => new LlmUsage(r.Usage.InputTokens, r.Usage.OutputTokens));

// When the user rates the answer:
user.TrackFeedback(cfg, positive: true);

A cancelled call (an OperationCanceledException, such as HttpContext.RequestAborted) is recorded as aborted; timeouts count as errors. MeasureLlm does the same for synchronous calls, and MeasureLlmStreamAsync wraps an IAsyncEnumerable of chunks, adding the time to first token; a stream left early is recorded as aborted. TrackLlm records a call you measured yourself. Prompts and answers are never sent; see AI configs and LLM experiments.