Aller au contenu

LaunchDarkly Cheat Sheet

Overview

LaunchDarkly is the leading enterprise feature flag management platform that decouples code deployments from feature releases. It enables teams to wrap new features in flags and control their visibility through a centralized dashboard, allowing progressive rollouts, instant kill switches, targeted user segments, and A/B testing without redeploying code. LaunchDarkly supports over 25 SDKs spanning server-side, client-side, mobile, and edge environments.

The platform goes beyond simple boolean toggles to support multivariate flags, percentage-based rollouts, user targeting with complex rules, and experimentation with statistical analysis. LaunchDarkly’s architecture uses a streaming connection model for near-instant flag updates (typically under 200ms globally), with local evaluation that keeps latency minimal and provides resilience even when the LaunchDarkly service is unavailable.

Installation

Server-Side SDKs

# Node.js
npm install @launchdarkly/node-server-sdk

# Python
pip install launchdarkly-server-sdk

# Go
go get github.com/launchdarkly/go-server-sdk/v7

# Java (Maven)
# Add to pom.xml:
# <dependency>
#   <groupId>com.launchdarkly</groupId>
#   <artifactId>launchdarkly-java-server-sdk</artifactId>
#   <version>7.0.0</version>
# </dependency>

# Ruby
gem install launchdarkly-server-sdk

# .NET
dotnet add package LaunchDarkly.ServerSdk

Client-Side SDKs

# React
npm install launchdarkly-react-client-sdk

# JavaScript
npm install launchdarkly-js-client-sdk

# iOS (Swift Package Manager)
# Add: https://github.com/launchdarkly/ios-client-sdk.git

# Android (Gradle)
# implementation 'com.launchdarkly:launchdarkly-android-client-sdk:5.0.0'

# Flutter
flutter pub add launchdarkly_flutter_client_sdk

CLI (ldcli)

# Install LaunchDarkly CLI
brew install launchdarkly/tap/ldcli

# Or via npm
npm install -g @launchdarkly/ldcli

# Configure
ldcli config --set access-token YOUR_API_TOKEN

# Verify
ldcli members list --output json | jq '.[0].email'

Core Commands — Flag Management

Creating and Managing Flags (API)

# Set API credentials
export LD_API_TOKEN="api-key-here"
export LD_PROJECT="default"
export LD_ENV="production"
LD_API="https://app.launchdarkly.com/api/v2"

# Create a boolean feature flag
curl -X POST "$LD_API/flags/$LD_PROJECT" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "new-checkout-flow",
    "name": "New Checkout Flow",
    "description": "Redesigned checkout experience",
    "tags": ["frontend", "checkout", "q2-2026"],
    "variations": [
      {"value": true, "name": "Enabled", "description": "Show new checkout"},
      {"value": false, "name": "Disabled", "description": "Show legacy checkout"}
    ],
    "defaults": {
      "onVariation": 0,
      "offVariation": 1
    },
    "temporary": true
  }'

# Create a multivariate flag
curl -X POST "$LD_API/flags/$LD_PROJECT" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "pricing-algorithm",
    "name": "Pricing Algorithm",
    "kind": "multivariate",
    "variations": [
      {"value": "v1-standard", "name": "Standard"},
      {"value": "v2-dynamic", "name": "Dynamic"},
      {"value": "v3-ml-based", "name": "ML-Based"}
    ],
    "defaults": {"onVariation": 0, "offVariation": 0}
  }'

# Toggle flag on/off
curl -X PATCH "$LD_API/flags/$LD_PROJECT/new-checkout-flow" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "environmentKey": "production",
    "instructions": [{"kind": "turnFlagOn"}]
  }'

# List all flags
curl -s "$LD_API/flags/$LD_PROJECT?env=$LD_ENV&summary=true" \
  -H "Authorization: $LD_API_TOKEN" | jq '.items[] | {key, name, on: .environments.production.on}'

SDK Usage — Node.js

// Initialize the LaunchDarkly client
const LaunchDarkly = require('@launchdarkly/node-server-sdk');

const client = LaunchDarkly.init('sdk-key-here');

await client.waitForInitialization();

// Evaluate a boolean flag
const context = {
  kind: 'user',
  key: 'user-123',
  email: 'user@example.com',
  custom: {
    plan: 'enterprise',
    region: 'us-east'
  }
};

const showNewCheckout = await client.variation('new-checkout-flow', context, false);

if (showNewCheckout) {
  // Render new checkout
} else {
  // Render legacy checkout
}

// Evaluate with detail (includes reason)
const detail = await client.variationDetail('new-checkout-flow', context, false);
console.log(`Value: ${detail.value}, Reason: ${JSON.stringify(detail.reason)}`);

// Track custom event for experimentation
client.track('checkout-completed', context, { revenue: 49.99 });

// Flush and close
await client.flush();
client.close();

SDK Usage — Python

import ldclient
from ldclient.config import Config
from ldclient import Context

# Initialize
ldclient.set_config(Config("sdk-key-here"))
client = ldclient.get()

# Create context
context = Context.builder("user-123") \
    .kind("user") \
    .set("email", "user@example.com") \
    .set("plan", "enterprise") \
    .build()

# Evaluate flag
show_feature = client.variation("new-checkout-flow", context, False)

# Evaluate with detail
detail = client.variation_detail("new-checkout-flow", context, False)
print(f"Value: {detail.value}, Reason: {detail.reason}")

# Track metric
client.track("purchase-completed", context, metric_value=49.99)

# Cleanup
client.close()

Configuration

Targeting Rules via API

# Add user targeting (specific users get the flag)
curl -X PATCH "$LD_API/flags/$LD_PROJECT/new-checkout-flow" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "environmentKey": "production",
    "instructions": [
      {
        "kind": "addUserTargets",
        "variationId": "variation-id-for-true",
        "values": ["user-123", "user-456"]
      }
    ]
  }'

# Add percentage rollout
curl -X PATCH "$LD_API/flags/$LD_PROJECT/new-checkout-flow" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "environmentKey": "production",
    "instructions": [
      {
        "kind": "updateFallthroughVariationOrRollout",
        "rolloutWeights": {
          "variation-true-id": 20000,
          "variation-false-id": 80000
        },
        "rolloutBucketBy": "key"
      }
    ]
  }'

# Add a targeting rule (enterprise users get new feature)
curl -X PATCH "$LD_API/flags/$LD_PROJECT/new-checkout-flow" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "environmentKey": "production",
    "instructions": [
      {
        "kind": "addRule",
        "clauses": [
          {
            "contextKind": "user",
            "attribute": "plan",
            "op": "in",
            "values": ["enterprise", "business"]
          }
        ],
        "variationId": "variation-true-id",
        "description": "Enterprise and business users"
      }
    ]
  }'

Terraform Provider

terraform {
  required_providers {
    launchdarkly = {
      source  = "launchdarkly/launchdarkly"
      version = "~> 2.0"
    }
  }
}

provider "launchdarkly" {
  access_token = var.launchdarkly_access_token
}

resource "launchdarkly_feature_flag" "new_checkout" {
  project_key = "default"
  key         = "new-checkout-flow"
  name        = "New Checkout Flow"
  description = "Redesigned checkout experience"

  variation_type = "boolean"

  variations {
    value = true
    name  = "Enabled"
  }

  variations {
    value = false
    name  = "Disabled"
  }

  defaults {
    on_variation  = 0
    off_variation = 1
  }

  tags = ["frontend", "checkout"]
}

resource "launchdarkly_feature_flag_environment" "new_checkout_prod" {
  flag_id = launchdarkly_feature_flag.new_checkout.id
  env_key = "production"
  on      = true

  fallthrough {
    rollout_weights = [20000, 80000]
  }

  rules {
    clauses {
      attribute  = "plan"
      op         = "in"
      values     = ["enterprise"]
      context_kind = "user"
    }
    variation = 0
  }
}

Advanced Usage

Experimentation

# Create an experiment
curl -X POST "$LD_API/projects/$LD_PROJECT/environments/$LD_ENV/experiments" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Checkout Flow A/B Test",
    "key": "checkout-ab-test",
    "maintainerId": "member-id",
    "iteration": {
      "hypothesis": "New checkout flow increases conversion rate",
      "canReshuffleTraffic": true,
      "metrics": [
        {
          "key": "checkout-completed",
          "isGroup": false
        }
      ],
      "primarySingleMetricKey": "checkout-completed",
      "treatments": [
        {"name": "Control", "baseline": true, "allocationPercent": "50", "flagKey": "new-checkout-flow", "variationId": "false-variation-id"},
        {"name": "Treatment", "baseline": false, "allocationPercent": "50", "flagKey": "new-checkout-flow", "variationId": "true-variation-id"}
      ],
      "flags": {
        "new-checkout-flow": {"ruleId": "fallthrough", "flagConfigVersion": 1}
      }
    }
  }'

# Get experiment results
curl -s "$LD_API/projects/$LD_PROJECT/environments/$LD_ENV/experiments/checkout-ab-test/results" \
  -H "Authorization: $LD_API_TOKEN" | jq '.treatmentResults'

Segments (Reusable User Groups)

# Create a segment
curl -X POST "$LD_API/segments/$LD_PROJECT/$LD_ENV" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "beta-testers",
    "name": "Beta Testers",
    "description": "Users opted into beta features",
    "tags": ["beta"]
  }'

# Add users to segment
curl -X PATCH "$LD_API/segments/$LD_PROJECT/$LD_ENV/beta-testers" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "instructions": [
      {"kind": "addIncludedUsers", "values": ["user-789", "user-012"]}
    ]
  }'

Flag Lifecycle Management

# Find stale flags (not evaluated recently)
curl -s "$LD_API/flags/$LD_PROJECT?env=$LD_ENV&filter=state:live+maintainerMissing:true" \
  -H "Authorization: $LD_API_TOKEN" | jq '.items[] | {key, name}'

# Archive a flag
curl -X PATCH "$LD_API/flags/$LD_PROJECT/old-feature-flag" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '[{"op": "replace", "path": "/archived", "value": true}]'

# List flag dependencies
curl -s "$LD_API/flags/$LD_PROJECT/new-checkout-flow/dependent-flags?env=$LD_ENV" \
  -H "Authorization: $LD_API_TOKEN"

Troubleshooting

IssueCauseSolution
Flag returning default valueSDK key wrong or client not initializedVerify SDK key matches environment; await initialization
Flag changes not propagatingStreaming connection droppedCheck network/firewall allows SSE connections to LaunchDarkly
High evaluation latencyUsing polling instead of streamingSwitch to streaming mode (default) for sub-200ms updates
Context not matching rulesAttribute names case-sensitiveVerify context attribute names match targeting rules exactly
Percentage rollout inconsistentBucket by attribute missingEnsure rolloutBucketBy matches a unique user attribute
Experiment not collecting dataTrack events not sentVerify client.track() calls with correct metric keys
Terraform drift detectedManual changes in dashboardUse terraform import or enforce IaC-only changes
SDK offline mode not workingLocal flag data file missingConfigure fileDataSource with valid flag data JSON
# Debug: check SDK connection status (Node.js)
# client.on('ready', () => console.log('Connected'));
# client.on('failed', (err) => console.error('Failed:', err));
# client.on('error', (err) => console.error('Error:', err));

# Verify flag configuration via API
curl -s "$LD_API/flags/$LD_PROJECT/new-checkout-flow?env=$LD_ENV" \
  -H "Authorization: $LD_API_TOKEN" | jq '.environments.production | {on, rules, fallthrough}'

# Check flag evaluation count
curl -s "$LD_API/flags/$LD_PROJECT/new-checkout-flow?env=$LD_ENV" \
  -H "Authorization: $LD_API_TOKEN" | jq '.environments.production._summary'