• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
No results for ""
EXPAND ALL

EDIT ON GITHUB

Getting started: Flag rules and targeting

Read time: 16 minutes
Last edited: Jul 29, 2022

Overview

This guide explains LaunchDarkly's flag Targeting features, including percentage rollouts, flag evaluations graphs, and segments. You can use these targeting features to create flags that serve different values to different users.

This guide covers:

  • Concepts and terms that LaunchDarkly uses for targeting
  • Adding user details to flag evaluation code
  • Protecting Personally Identifiable Information (PII) when you create flags
  • Examining users in the Users list
  • Rolling out flag variations to a percentage of users
  • Targeting specific users with flag rules
  • Understanding how flag evaluations change over time with flag insights
  • Targeting users by their attributes
  • Preventing specific user details from being sent to LaunchDarkly

Prerequisites

To complete this guide, you must have the following prerequisites:

  • An active LaunchDarkly account with the ability to create a flag.
  • Basic knowledge of the Python programming language. You use Python in the exercises in this guide.
  • Access to Glitch.
  • You must have completed the exercises in Getting started: Configuring an SDK and creating a flag. The exercises in this guide rely on apps and flags you create in that guide.
  • The SDK key for the environment you created in Getting started: Configuring an SDK and creating a flag.

Learn more: How to use Glitch

Concepts

In order to use this guide, you should understand the following concepts:

User context

The user context is everything LaunchDarkly knows about a targeted endpoint. LaunchDarkly refers to all objects targeted by a flag as users. Not all users are human beings. A user might be a server, an IP address, or any other object that can be addressed.

The user context is composed of different attributes. An attribute is any identifier applied to an endpoint or user context.

Targeting users by attribute is a Pro and Enterprise feature

Targeting users by attribute is available to customers on a Pro or Enterprise plan. To learn more, read about our pricing. To upgrade your plan, contact Sales.

Possible attributes include, but are not limited to:

  • User ID
  • Group membership
  • Number range
  • Location
  • Prerequisites
  • Version
  • IP address
  • Local browser time

There are also optional standard attributes that must conform to these requirements:

AttributeRequirements
emailMust be a string.
firstNameMust be a string.
lastNameMust be a string.
nameMust be a string.
avatarMust be an absolute URL to an avatar image for the user.
ipMust be an IP address.
countryMust be a string.
anonymousMust be a boolean. This attribute prevents the user's other attributes from being transmitted to the events endpoint, and prevents the user from showing up on the Users list.

With LaunchDarkly, you can create user objects with as many attributes as you need. The only required attribute is the key attribute, which holds the user identifier. If the LaunchDarkly rules engine encounters two user objects with the same key, it assumes they represent the same user.

When a user encounters a flag, their attributes are sent to LaunchDarkly. This makes the attributes available through the Users list. All the user attributes are sent, with the exception of those that have been marked private.

Flag variations

A flag variation is whatever action the flag enables that is not the flag's default behavior. Some flags are boolean, and only have true and false variations. Other flags have many more variations.

Rule evaluation

Rule evaluation occurs when a LaunchDarkly client determines whether or not to show a flag variation to a user. The rule is how the decision is described in a human-readable way. For example, “Turn on a new feature for 10% of users” is a rule that targets 10% of users.

LaunchDarkly uses rule evaluation when it checks the rule against the user context of a particular destination. For example, LaunchDarkly could determine yes or no in response to the rule “Is this user in the 10% who get the new feature variation?"

Flags can have multiple rules. If multiple rules exist, LaunchDarkly evaluates them top to bottom based on how the rules are configured in the flag's Targeting tab. You can drag and drop rules to change the evaluation order.

Most people write rules that have AND or ONLY IF statements, to refine the targeting.

For example:

  • IF user is in test_group,
  • AND user is using version 2.1 or above,
  • show the user flag variation 1.

In that case, even if a user is in the test_group, they won’t receive flag variation 1 unless their version has been updated recently. If someone is on a new version but is not in the test_group, they also won’t receive it. In this example, it doesn’t matter what order the rules are evaluated in.

Flag targeting

In feature management, targeting is the ability to make a flag's different variations appear to different users, "targeting" users with specific versions of the flag. Each flag can have targeting rules that specify which users should receive which variations.

In LaunchDarkly, none of the targeting rules need to live in application code. They're all configured using the flags list. Only the user needs to be implemented in your code. This prevents sensitive information from being transmitted with feature flag data.

Identifying users

LaunchDarkly uses the user object's key attribute as the identifier for the user. This identifier can be any string of characters. It doesn't need to be in a particular format.

Be thoughtful about how you construct user identifiers in your app. The most important considerations are:

  • Uniqueness: Each identifier should only be used for one user.
  • Consistency: Each user should always have the same identifier.
  • Opacity: Identifiers should not reveal any Personally Identifiable Information (PII) about the user, such as their name, location, or email address.
Protecting personally identifiable information (PII)

A person's email address is a common form of identifying information. It's a good identifier because it's unique to the individual, and consistent. Email addresses rarely change. However, malicious third parties can easily trace an email address back to the human being who owns it. This makes an email address sensitive information, because it could be abused by a bad actor. The same is true for a person's phone number or home address.

Many countries, states, and organizations have rules about handling PII. To ensure user privacy, don't store or use PII anywhere unless it's necessary.

If you must create user attributes that contain PII, mark the attribute as private so that it's not uploaded to LaunchDarkly. We'll discuss private attributes later in this guide.

Exercise preparation

You must have completed prerequisites to do these exercises

The exercises in this guide rely on the flags and SDK keys you created in the Getting started: Configuring an SDK and creating a flag guide.

If you have not completed that guide, do so now and return to this section.

These exercises use a Python-based web application that we provide which runs on Glitch, an online tool for creating web apps.

Remixing the targeting lab app

You must remix the Glitch project embedded below to create an editable copy of the Python web app. Remixing is Glitch's term for cloning a project. This creates an editable copy of the Python web app we use for this exercise.

To remix the app, click this Glitch remix link, or follow the instructions below.



To remix the app:

  1. Click the fullscreen button in the bottom right-hand corner of the Glitch app embedded above. app. The app appears in a separate tab.
  2. In the new Glitch tab, click Remix to Edit.
  3. The name of your project appears in the top left corner. If you want to rename the app, click the arrow next to the name.

Learn more: How to use Glitch

Switching between the code and app views in Glitch


In the Glitch app, you have the option to view the live app in production, or the code for the app.

To switch between them:

  1. Navigate to the Glitch app you remixed.
  2. At the top of the Glitch page, click Show:
The "Show" menu in Glitch.
The "Show" menu in Glitch.
  1. Click In a New Window.
  2. Confirm that you can switch between the code and the app view.
Issues when running the app next to the code

Some learners encounter issues when running the Glitch editor and app in the same window. These issues happen primarily when trying to use the app's "Log in" form. If the form isn't working, run the app in its own browser tab or window.

Finding the LaunchDarkly SDK key in your project

During the exercises in the Getting started: Configuring an SDK and creating a flag guide, you created a LaunchDarkly project, and configured your app to use the SDK key from an environment in that project. This new app will use the same SDK key.

To retrieve the SDK key for your environment:

  1. Navigate to the Account settings page.
  2. Click the Projects tab.
  3. Click on the name of the project which you created for the Getting started: Configuring an SDK and creating a flag guide. The Environments tab appears.
  4. Click the "Production" environment's SDK key to copy it to your clipboard:
The Account settings page in LaunchDarkly with environment SDK keys called out.
The Account settings page in LaunchDarkly with environment SDK keys called out.

Configuring the LaunchDarkly SDK key in your app

  1. Click the .env file in the Glitch sidebar.
  2. Assign the SDK key you copied above to an environment variable called LD_SDK_KEY:
LD_SDK_KEY=<PASTE-YOUR-SDK-KEY-HERE>
The .env file in Glitch.
The .env file in Glitch.

Exercise: Targeting a flag

When you completed the exercises in Getting started: Configuring an SDK and creating a flag, you created a flag named Pricing Tier 3.

This exercise references Pricing Tier 3's Targeting tab throughout the guide. Keep the Targeting tab open to access it quickly.

To open the Targeting tab:

  1. Navigate to your LaunchDarkly project.
  2. Find the "Pricing Tier" 3 flag in your feature flags list.
  3. Click the flag name. The flag's Targeting tab appears. Keep this page open to access it quickly.

Finding the user object

In Getting started: Configuring an SDK and creating a flag, you learned about the variation() method, which application code uses to evaluate flags.

variation() takes three arguments:

  • The flag name
  • The user object
  • The default value

The user object in the example app code has two attributes: key and anonymous. Because the variation() call is always made with the same user key, LaunchDarkly assumes that there's only one user of this app, who never changes.

In the code for the Starlight Travel app, the user object is in the file named server.py, inside the pricing() function.

In the example below, the anonymous attribute is set to True. When this happens, LaunchDarkly won't record any of this user's other attributes or list this user on the Users list.

Here is an example:

# This page doesn't require a logged-in user,
# so tell LaunchDarkly that this is an anonymous user.
# The key is arbitrary and can be anything.
# To clarify that this is an anonymous
# user, it's named "anon".
user = {
"key": "anon",
"anonymous": True
}

To learn more, read Anonymous users.

Logging in to the Glitch app

We'll create a user in LaunchDarkly to reference for this exercise. To do this, log in to the Starlight Travel app with an email address.

To log in:

  1. Navigate to the app view of your Glitch app.
  2. Click the "Log in" link in the top right of the app's front page:
The "Log in" link at the top right of the Starlight Travel app's front page.
The "Log in" link at the top right of the Starlight Travel app's front page.
  1. Enter an email address in the email address field. Any email address works. You are redirected to the main page.
  2. Click the user avatar in the top right-hand corner. The log in menu appears.
The user avatar, with a menu expanded.
The user avatar, with a menu expanded.
  1. Click Log out.

The email address you just logged in with was registered as a user in LaunchDarkly.

Creating a user key with a hashed email address

The Starlight Travel app uses email addresses as user IDs. Providing the user's email address as the key in our user object means that LaunchDarkly stores that email address. We do not recommend this approach for production environments.

For purposes of this guide exercise, there is no other unique, consistent identifier for users, because this exercise collects very limited user data.

To protect the email addresses, you can use the common programming technique known as hashing. When you hash something, you apply an algorithm to obscure its true value by translating letters and numbers in it into other characters. This process is almost impossible to reverse, so email addresses you store using this method are protected.

Python includes several popular hashing algorithms in its standard library. Use the SHA256 algorithm to convert the user's email address into a meaningless but unique hash which can be used as the user key.

To hash the email address:

  1. Add Python's hashing module, hashlib, to the list of included modules right at the top of server.py:
import hashlib
import os
from flask import Flask, render_template, session, request, flash, redirect, url_for
  1. Add the user_object_from_email() function under the pricing() function. The code that generates a hash has its own function, user_object_from_email(), which takes an email address and returns a user object as a Python dict:
def user_object_from_email(email):
## Hash the email address using the SHA256 algorithm
email_hash = hashlib.sha256(email.encode())
## Output the hash as hexadecimal and truncate to 10 characters long
email_hash_hex = email_hash.hexdigest()[:10]
## Identify user by their hashed email address
return {
"key": email_hash_hex
}
  1. Navigate to pricing() and find the user object:
# Because this page doesn't require a logged-in user,
# tell LaunchDarkly that this is an anonymous user for now.
# The key is arbitrary and can be anything you want.
# Here, we wanted to be clear that this was an anonymous
# user, so the key is set to "anon".
user = {
"key": "anon",
"anonymous": True
}
  1. When the user is logged in, you should send a new user object from the user_object_from_email() function, instead of the old user object.

    Replace the lines above with this code, which chooses which user object to use by checking if there's a logged-in user session with an email address:

if (email):
user = user_object_from_email(email)
else:
## Because the user isn't logged in,
## let's tell LD that this is an anonymous user.
user = {
"key": "anon",
"anonymous": True
}
  1. Modify this version of the app to reveal the hash that's been generated from the email address. To do this, add an extra key parameter to the render_template() call at the end of pricing():
return render_template(
'pricing.html',
is_tier_3_enabled=is_tier_3_enabled,
email=email,
key=user['key']
)

The whole pricing() function should now be formatted like this:

@app.route('/')
def pricing():
"""Displays the pricing page."""
## Fetch the user's email address. If they aren't logged in,
## the stored value will be None.
email = session.get("email")
if (email):
user = user_object_from_email(email)
else:
## Because the user isn't logged in,
## let's tell LD that this is an anonymous user.
user = {
"key": "anon",
"anonymous": True
}
is_tier_3_enabled = ld_client.variation('pricing-tier-3', user, False)
return render_template(
'pricing.html',
is_tier_3_enabled=is_tier_3_enabled,
email=email,
key=user['key']
)

To verify everything is working correctly, use this procedure to check your work:

  1. Navigate to Glitch's left sidebar and click into the views folder.
  2. Open avatar.html. This is the template for the clickable avatar and its drop-down menu.
  3. Find the two lines that show the user's email in the menu:
<span class="dropdown-item disabled">{{ email }}</span>
<div class="dropdown-divider"></div>
  1. Copy those two lines and add them immediately below the previous two, then change email to key:
<span class="dropdown-item disabled">{{ email }}</span>
<div class="dropdown-divider"></div>
<span class="dropdown-item disabled">{{ key }}</span>
<div class="dropdown-divider"></div>
  1. Navigate to your Glitch app and log in.
  2. Click on the avatar in the top right corner. If everything is working correctly, the menu should display both the email and the hash:
The avatar menu now includes the user key, which is the shortened hash of the user's email address.
The avatar menu now includes the user key, which is the shortened hash of the user's email address.

Adding more users to LaunchDarkly

After you verify you've configured a user correctly, log in to the Glitch app a few times using different email addresses.

You can use random values for the email address, such as test1@email.com. When you log in, refresh the page to view the front page of the app.

Each time you view the front page as a logged-in user, LaunchDarkly records that user ID.

After you've logged in using four or five different email addresses, look at the users that have been collected by LaunchDarkly in the Users list.

Accessing the Users list

The Users list displays all users who have been included in user objects so far. Access the Users list in the sidenav of your LaunchDarkly project.

To learn more, read The Users list.

The Users list lists all the users for whom flags have been evaluated in this particular environment and project.

Here is an image of the Users list:

The "Users" list.
The "Users" list.

Click on a user's key attribute to look at an individual user page. The left side displays all the attributes which have been uploaded to LaunchDarkly so far. The right side displays how each flag in the project will evaluate for that particular user.

You might notice that there are not many users yet. As you continue this guide, you'll add more users to test with.

Configuring a percentage rollout

A percentage rollout is when you choose a percentage of users to receive each variation of your flag. You can increase or decrease these percentages over time.

To learn more, read Targeting users.

To turn on a percentage rollout for the Pricing Tier 3 flag:

  1. Navigate to the Feature flags list in LaunchDarkly.
  2. In the "Feature flags" list, click Pricing Tier 3. The flag's Targeting tab appears.
  3. Find the "Default rule", which is the flag variation or rollout that appears when targeting is enabled. In this example, it is set to true:
The flag's Default rule selector.
The flag's Default rule selector.
  1. Click the Serve menu.
  2. Choose "a percentage rollout":
A percentage rollout with percentage values for each variation.
A percentage rollout with percentage values for each variation.
  1. Set the true variation to 30%.
  2. Confirm that the flag's targeting toggle is set to On.
  3. Click Review and save.
  4. Log in to the Starlight Travel app as a few different users. Keep track of which email addresses you use as you log in and log out.
  5. When the third pricing tier appears, you know the user you logged in as is part of the 30% of users targeted by the "Pricing Tier 3" flag.
  6. Log out and log back in again as that same user. The third pricing tier appears every time that user logs in, because LaunchDarkly can now identify individual users. That user will always receive the third tier until the flag's targeting changes.
  7. When you find a user who doesn't receive the third tier, save their email address.

Now you've experienced flag targeting in action. Let's move on to verifying that the flag is working as you intended.

Verifying flag behavior with flag insights

You can confirm that the "Pricing Tier 3" flag is appearing for 30% of users. LaunchDarkly offers analytics tools to help you confirm that your flags are behaving the way you want them to.

  1. Navigate to the "Pricing Tier 3" flag and click the Insights tab:
The "Insights" tab of the "Pricing Tier 3" flag.
The "Insights" tab of the "Pricing Tier 3" flag.
  1. Choose Last 60 minutes from the menu to zoom in on recent activity.

    This flag evaluations graph shows all the times this flag has been evaluated in the last hour. It also shows the variations that were shown to users.

    As you've changed how the flag is targeted, the data changes with it. Because you changed the flag's targeting to a percentage rollout, you should notice that roughly a third of flag evaluations have been true, while the rest have been false.

Waiting for insights data

It can take a couple of minutes for the flag evaluations graph to process and display the latest data. If you reload the page, be sure to check that the time range button still reads Last 60 minutes.

If it shows an absolute time range instead, such as "10:35 AM - 11:35 AM", change it back to Last 60 minutes.

Percentage rollouts give you broad control over the flag variation different users receive. You can exercise much finer control too.

Targeting individual users

You can override the percentage rollout for any particular user, forcing them to receive or not receive a flag regardless of other targeting rules. You can do this by targeting them with rules individually.

In Configuring a percentage rollout, you saved the email address of a user who did not receive the new pricing option in your Glitch app. You need that email address for this exercise, so find it now.

To target an individual user through the Users list:

  1. Log in to your Glitch app with the email address of the user who did not receive the "Pricing Tier 3" flag.
  2. Click on the avatar icon in the top-right of the page. The 10-character hashed user key is displayed. Copy this key and save it.
  3. Navigate to the LaunchDarkly Users list.
  4. Find the user key you saved in the list of users and click their name. The user's menu appears.
  5. Change the flag setting for the "Pricing Tier 3" flag from false to true.
  6. A targeting circle appears next to the selector. This indicates that you are adding an explicit targeting rule for this user.
  7. Click Save changes:
The flag settings for the user, after choosing the flag variation.
The flag settings for the user, after choosing the flag variation.
  1. From the flags list, click the name of the "Pricing Tier 3" flag to return to its Targeting tab. The "Individual targeting" section is expanded. This section specifies the individual users who should always receive a particular flag variation. In the true section, you can view the key for the user whose setting you just changed:
The "Individual targeting" section of the flag's "Targeting" tab.
The "Individual targeting" section of the flag's "Targeting" tab.
  1. Log back into the Starlight Travel app as that user and refresh the page. The third pricing tier should now be visible.

Targeting users by attribute

Targeting individual users can take a long time if you wish to add entire groups to a flag. If you do not want to target one user at a time, you can configure LaunchDarkly to show a flag to every user with a certain attribute.

Let's pretend that you only want to show the option for tier 3 pricing to users whose email addresses begin with the letter A. The "Pricing Tier 3" flag should evaluate to true only for those users.

To evaluate flags based on specific user criteria, you must create a targeting rule. You can create a rule about any user attribute.

However, in our current example, we can't use a rule to look at the first letter of the user's email address. Only the hashed version of the email is stored, which looks nothing like the real email address.

There are several ways around this problem. You can use a custom attribute or a private attribute to configure the targeting behavior how you want.

Configuring custom attributes

You can create and add your own attributes to user objects. These are known as custom attributes. The values of these attributes can be numbers, strings, or even lists. Place these attributes within a sub-dictionary of your user object named custom.

At this point, the user object only has one attribute: key. Add another attribute to hold the first letter of the user's email address.

To add this attribute:

  1. Navigate to your Glitch app.
  2. Open server.py.
  3. Modify the dict returned at the end of the user_object_from_email function:
return {
"key": email_hash_hex, ## don't forget the comma
"custom": {
"firstLetter": email[0].lower() ## normalize your string case
}
}
  1. Log in to the Starlight Travel app a couple more times, so that you send examples of this new attribute to LaunchDarkly.
  2. Navigate to the flags list in LaunchDarkly and find the "Pricing Tier 3" flag.
  3. Click on the "Pricing Tier 3" flag name. The Targeting tab appears.
  4. Find the section titled "Target users who match these rules":
The rules section of the "Targeting" tab.
The rules section of the "Targeting" tab.
  1. Click + Add rules. A form for adding a rule appears:
The form for adding a new targeting rule.
The form for adding a new targeting rule.
  1. (Optional) Name the rule in the first field.

  2. In the Select an attribute menu, choose "firstLetter."

  3. In the Select an operator menu, choose "is one of." For the targeting rule to succeed, the value of firstLetter must match one of the two options you just entered.

  4. In the Enter some values field, enter both the upper and lower case letter A as values. Here's how:

    • Click the field to focus it.
    • Type a lower-case a. A suggestion appears: Create option "a".
    • Press Enter. The letter a becomes an attribute.
    • Type an upper-case A and press Enter. Each of the two letters should be in its own option box, like this:
    The rule form, configured for the rule we specified.
    The rule form, configured for the rule we specified.

    If you don't want to include both the lowercase and capitalized values, normalizing the attribute's string case can help simplify your targeting rules.

  5. In the last menu, choose the true variation. Now when the rule matches a user object, the true variation appears.

  6. In the "Default rule" section, choose false under the Serve menu . This ensures that only users who match our rules receive a true evaluation:

Set the default rule to `false`.
Set the default rule to `false`.
  1. Click Review and save.

You can test your new targeting rule by logging in to your Glitch app with email addresses starting with the letter a, and addresses that start with other letters.

Alternatively, you can also use a private attribute to target groups of users.

Configuring private attributes


You can use private attributes to target users without sending PII to LaunchDarkly.

Instead of creating the firstLetter custom attribute, we can put the whole email address in the email attribute and use it in a targeting rule. To ensure that this attribute isn't uploaded, we will designate it as private.

There are three different ways to mark attributes private:

  • You can mark all attributes private globally in the LDClient configuration object. This indicator does not apply to the user's key, because LaunchDarkly needs the key to determine flag targeting.
  • You can mark specific attributes private by name globally in the LDClient configuration object.
  • You can mark specific attributes private by name for individual users when you construct user objects.

In this guide we won't mark all attributes private, because we may want to use non-private attributes later.

This leaves two options to create a private attribute:

  • when ldclient is configured, or
  • when the user object is created.

To ensure that the email attribute is never accidentally uploaded, change the ldclient configuration to mark that attribute as private.

To mark the email attribute as private:

  1. Navigate to your Glitch app.
  2. Open server.py.
  3. Find the line near the top of server.py which starts with ldclient.set_sdk_key and add this ldclient.set_config command before it:
ldclient.set_config(ldclient.Config(private_attribute_names=['email']))
ldclient.set_sdk_key(os.getenv('LD_SDK_KEY')) ## Set your SDK key in .env
  1. In the user_object_from_email() function, delete the custom attributes section from the user object.
  2. In its place, add a single email attribute:
return {
"key": email_hash_hex,
"email": email
}

Now change the existing targeting rule:

  1. Navigate to LaunchDarkly.
  2. Find Pricing Tier 3 and click into its Targeting tab.
  3. Find the section titled Target users who match these rules:
  4. Change the value in the first field from firstLetter to email.
  5. Change the operator selector from is one of to starts with. You don't need to change the third field, because we're still looking for an A or a.
  6. Click Review and save.

At the end, the rule should look like this:

The finished `email` rule.
The finished `email` rule.

You can test your new targeting rule by logging in to your Glitch app with email addresses starting with the letter a, and addresses that start with other letters. It should only show the third pricing tier to users whose email address begins with the letter A.

You can verify that none of the users' email addresses have been sent to LaunchDarkly. Return to the Users list, and look at the Email column. The whole column should be blank.

Conclusion

In this tutorial, you have learned to:

  • target a rule to individuals or by attribute
  • mark attributes as private
  • execute a percentage-based rollout
  • use the Users list to understand rule evaluation and how it changes over time.

We hope that this has helped you understand how precisely you can target flag delivery and how you can configure targeting to return only the information you want.

Want to know more? Start a trial.

Your 14-day trial begins as soon as you sign up. Learn to use LaunchDarkly with the app's built-in tutorial. You'll discover how easy it is to manage the whole feature lifecycle from concept to launch to control.

Want to try it out? Start a trial.