Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Precalculated attributes

This recipe explains how to target contexts based on calculated values that LaunchDarkly’s built-in operators cannot express directly.

Use case

You want to target users based on relative time periods or calculated metrics. For example:

  • Users who logged in more than 90 days ago
  • Users whose subscription expires within 7 days
  • Users with an account balance below a threshold percentage

LaunchDarkly provides before and after operators for date comparisons. These operators require absolute dates as arguments. There are no operators for relative date comparisons or mathematical calculations.

Solution

Precalculate the derived value in your application and pass it to LaunchDarkly as a context attribute. Your application code performs the calculation before the SDK evaluates any flags.

The pattern follows these steps:

  1. Calculate the value in your application code when building the context.
  2. Add the calculated value as a custom attribute on the context.
  3. Create targeting rules using standard numeric operators.

Example: days since last login

Your application calculates the number of days between the current date and the user’s last login date. Store this value as daysSinceLastLogin on the context.

In LaunchDarkly, create a targeting rule that checks if daysSinceLastLogin is greater than 90. The flag serves users who have not logged in for more than 90 days.

The following screenshot shows a targeting rule using the precalculated daysSinceLastLogin attribute:

A targeting rule checking if daysSinceLastLogin is greater than 90.

Other examples

This pattern applies to many scenarios:

  • daysUntilExpiration - target users whose subscriptions expire soon
  • storageUsedPercent - target users approaching storage limits
  • lifetimeSpend - target high-value customers for loyalty programs
  • distanceToNearestStore - target users far from physical locations
  • featuresUsedCount - target users who might benefit from plan upgrades
  • riskScore - target based on fraud or churn risk calculated from multiple signals

When to use this pattern

This pattern applies when your targeting logic requires:

  • Relative date comparisons instead of absolute dates
  • Mathematical operations like subtraction, addition, or percentage calculations
  • Derived values that combine multiple source fields
  • Complex business logic that cannot map to built-in operators

Considerations

Calculate the attribute value at the appropriate point in your application. For server-side applications, calculate the value when constructing the context before flag evaluation. For client-side applications, calculate the value before initializing the SDK.

Keep attribute names descriptive. Names like daysSinceLastLogin communicate the attribute’s purpose clearly.

Resources