SDKs
Java
Server-side decisions for the JVM (Java 11+, Spring, Kotlin), with no dependencies and live updates.
com.liftcanary:liftcanary decides on your JVM servers: Spring Boot, Quarkus, Micronaut, Jakarta EE and plain main() jobs, from Java or Kotlin. One thread-safe client serves every request, keeps the datafile up to date in the background and sends events in batches. Decisions take microseconds and never wait for the network, and a user gets the same variation as on the website, in the apps and in every other SDK.
Install#
<dependency>
<groupId>com.liftcanary</groupId>
<artifactId>liftcanary</artifactId>
<version>0.1.0</version>
</dependency>implementation("com.liftcanary:liftcanary:0.1.0")Java 11 or newer. No dependencies: it uses java.net.http and a small built-in JSON codec.
Usage#
@Configuration
class LiftCanaryConfig {
@Bean // Spring calls close() at shutdown, which sends the remaining events
LiftCanaryClient liftcanary(@Value("${LIFTCANARY_SDK_KEY}") String sdkKey) {
LiftCanaryClient client = LiftCanaryClient.builder(sdkKey)
.shutdownHook(false) // Spring closes it, so the JVM hook isn't needed
.build();
client.ready(Duration.ofSeconds(3)); // at startup; until then every flag is off
return client;
}
}@PostMapping("/checkout")
Order checkout(@AuthenticationPrincipal Account account, @RequestBody Cart cart,
@RequestHeader(name = "CF-IPCountry", required = false) String country) {
UserContext user = liftcanary.createUser(User.builder(account.getId())
.attribute("plan", account.getPlan())
.attribute("country", country)
.build());
String flow = user.getString("new_checkout", "flow", "classic");
Order order = orders.place(cart, flow);
user.track("purchase", order.getTotal().doubleValue());
return order;
}Without a framework, create the client once and close it when the job ends. It is AutoCloseable:
try (LiftCanaryClient liftcanary = LiftCanaryClient.builder(System.getenv("LIFTCANARY_SDK_KEY")).build()) {
liftcanary.ready(Duration.ofSeconds(3));
for (Account account : accounts) {
UserContext user = liftcanary.createUser(account.getId());
if (user.isEnabled("weekly_digest")) sendDigest(account);
}
} // close() sends the remaining eventsThe user#
| Method | Returns |
|---|---|
isEnabled(flagKey) | Whether the feature is on for this user. |
getString / getBoolean / getInt / getLong / getDouble / getJson(flag, name, fallback) | The variable, or the fallback when the flag or variable is missing or has another type. |
getVariable(flag, name, fallback) | The same, typed by the fallback: String, Boolean, any Number, Map, List. |
decide(flagKey) | A Decision: isEnabled(), getVariationKey(), getRuleKey(), isInExperiment(), getReason(), getVariables(), getRevision(). |
decideAll() | Decisions for every flag, by key. |
track(key) / track(key, value) / track(key, TrackOptions) | Records a goal event. value is summed or averaged by goals (revenue, latency); TrackOptions.builder().value(…).property(…) adds properties. |
User.builder(id) takes attribute, bucketingId, page, activeLocations and anonymousId, the same fields as the other SDKs; createUser(id) and createUser(id, attributes) are shortcuts. A UserContext is cheap: create one per request. Attribute values are strings, numbers, booleans or null, and are sent with events; page (the full request URL, for location conditions) and activeLocations never are. Experiment exposures are logged automatically, once per user, flag, rule and variation; decide(flagKey, false) skips it, and user.logExposure(decision) logs it later.
At sign-in, pass the browser's anonymous id (the liftcanary_anon cookie, also LiftCanaryClient.ANONYMOUS_ID_COOKIE) 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.
@PostMapping("/welcome")
void welcome(@AuthenticationPrincipal Account account,
@CookieValue(name = LiftCanaryClient.ANONYMOUS_ID_COOKIE, required = false) String anonymousId) {
UserContext user = liftcanary.createUser(User.builder(account.getId()).anonymousId(anonymousId).build());
user.track("signed_in");
}Options#
Methods of LiftCanaryClient.builder(sdkKey), called before build():
datafileMap or String | A datafile to start from (bootstrap, offline, tests), so the first decisions need no download. |
cdnUrlString | Where datafiles come from. Default https://cdn.liftcanary.com; use your own domain or the API when self-hosting. |
eventsUrlString | The collector. Default https://events.liftcanary.com. |
streamingtrue | Live updates: a published change arrives in about a second. false turns them off and leaves polling. |
streamUrlString | Where live updates connect: {streamUrl}/stream/{sdkKey}. Default: the CDN URL. |
pollingInterval30 s | Time between datafile checks, in case the live connection drops (ETag, so unchanged datafiles cost almost nothing). Zero turns polling off. |
eventFlushInterval2 s | How often queued events are sent. |
eventBatchSize200 | Events per request; a full batch is sent at once. |
eventMaxQueueSize20000 | Events held in memory before the oldest are dropped (counted in getDroppedEventCount()). |
modelPrice(model, input, output) | Price per 1M tokens for a model, for AI configs. |
transportJdkTransport | The HTTP layer. new JdkTransport(myHttpClient) for a proxy or SSL context; a custom Transport without openStream only polls. |
httpTimeout10 s | Per request. |
loggercom.liftcanary | A java.util.logging.Logger. SLF4J users can route it with jul-to-slf4j. |
autoStarttrue | Starts the background work in build(); otherwise call start() or ready(). |
shutdownHooktrue | Sends the remaining events when the JVM exits. Turn it off when your framework calls close(). |
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 a Subscription:
Subscription sub = liftcanary.subscribe(() -> log.info("datafile revision " + liftcanary.getRevision()));Threads and shutdown#
- Exit: background work runs in daemon threads, so it never keeps the JVM alive, and a shutdown hook sends the remaining events.
close()does it explicitly (at most 5 s, orclose(Duration)). - Short jobs and serverless (AWS Lambda, Cloud Functions, batch jobs): call
liftcanary.flush()before returning. It returnsfalsewhen events are left. - Errors never throw into your code: failed downloads are logged and the last datafile keeps deciding. 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.
LiftCanaryClient liftcanary = LiftCanaryClient.builder(sdkKey).modelPrice("my-small-model", 0.25, 1.25).build();
AIConfig cfg = LiftCanaryAI.aiConfig(user, "support_bot", "my-small-model", "You are a helpful assistant. Answer in {{language}}.");
Reply reply = LiftCanaryAI.measureLLM(user, cfg,
() -> llm.chat(cfg.getModel(), LiftCanaryAI.renderPrompt(cfg.getPrompt(), Map.of("language", "Turkish")), cfg.getParams()),
r -> LLMUsage.tokens(r.inputTokens(), r.outputTokens()));
// When the user rates the answer:
LiftCanaryAI.trackFeedback(user, cfg, true);measureLLM rethrows the call's exception after recording it (aborted for an interrupted thread or a cancelled future, error otherwise). measureLLMAsync does the same for a CompletionStage. For streamed answers, measureLLMStream passes the chunks through and also records the time to first token; use it in try-with-resources, and a stream left early is recorded as aborted. trackLLM(user, cfg, LLMUsage) records a call you measured yourself. Prompts and answers are never sent; see AI configs and LLM experiments.