We are designing a cross-language feature flag DSL compiler. The goal is to have a domain-specific language (DSL) for defining feature flags that can be used across multiple programming languages (like Java, JavaScript, Python, etc.). We'll consider:
AST design: What the abstract syntax tree looks like for our DSL.
Interpreter vs transpiler trade-offs: Whether we interpret the DSL at runtime or transpile it to the host language.
Static validation: How we validate the DSL for errors before deployment.
Rollout strategy: How we roll out the feature flags to different environments and users.
Let's break it down.
1. AST Design
The DSL should be simple and expressive. We can think of a feature flag as a condition that evaluates to true or false. Conditions can be based on:
User attributes (e.g., userId, email, country)
Environment (e.g., staging, production)
Random allocations (e.g., percentage rollout)
Time (e.g., after a certain date)
And combinations of these (using logical operators).
We can design the AST to have nodes for:
FeatureFlag: the root node, containing a name and a condition.
Condition: can be a simple condition or a compound condition (and, or, not).
PercentageCondition: percentage (0-100) and an optional seed (for consistent bucketing).
TimeCondition: before/after a timestamp.
BooleanFlag: a simple on/off flag (no condition).
Operators: for user attributes, we can have ==, !=, >, <, >=, <=, in, not in, etc.
Example DSL:
code
feature flag "new_checkout" {
condition: (user.country == "US" and user.account_age > 30) or (percentage(50) and environment == "staging")
}
We can design the AST classes (in a hypothetical host language, say Java for the compiler) as:
java
abstract class Node {}
class FeatureFlag extends Node {
String name;
Condition condition;
}
interface Condition extends Node {}
class AndCondition implements Condition {
List<Condition> conditions;
}
class OrCondition implements Condition {
List<Condition> conditions;
}
class NotCondition implements Condition {
Condition condition;
}
class UserAttributeCondition implements Condition {
String attribute;
String operator;
Object value; // could be string, number, etc.
}
class EnvironmentCondition implements Condition {
String environment;
}
class PercentageCondition implements Condition {
double percentage;
String seed; // optional, for consistent bucketing per user
}
class TimeCondition implements Condition {
String operator; // "before" or "after"
LocalDateTime time;
}
class BooleanFlag implements Condition {
boolean value;
}
But note: we might want to have a more generic condition node that can represent all these, but for clarity and type safety, separate classes are better.
Alternatively, we can have a Condition node with a type and a map of properties, but that would be less structured.
2. Interpreter vs Transpiler Trade-offs
Interpreter: We parse the DSL into an AST and then evaluate the AST at runtime by traversing it and checking conditions against the current context (user, environment, etc.). This is flexible and allows for dynamic changes (if the DSL is loaded from a remote source) but has runtime overhead and requires the DSL to be shipped and parsed in the production environment.
Pros:
Dynamic: can change flags without redeploying.
Simple to implement: just write an evaluator for the AST.
Cons:
Runtime performance: every flag check involves traversing the AST and evaluating conditions.
Requires the DSL to be available at runtime (might be a security concern if user-provided? but usually not).
Harder to debug: if there's an error in the DSL, it might only be caught at runtime.
Transpiler: We convert the DSL into code in the host language (e.g., Java, JavaScript) and then compile that code as part of the application. The generated code is a function that takes a context and returns a boolean.
Pros:
Performance: the generated code is native and can be optimized by the host language compiler.
Static analysis: we can validate the DSL at build time and catch errors early.
Security: no need to parse DSL at runtime.
Integration: can use host language features (like logging, metrics) easily in the generated code.
Cons:
Less dynamic: changing the flag requires rebuilding and redeploying the application.
More complex: need to generate code for each target language and maintain the transpiler.
Hybrid: We can also have a configuration-driven approach where the conditions are stored in a database or config file and the application uses a library that evaluates them. This is similar to the interpreter approach but the conditions are stored in a structured format (like JSON) and we have a generic evaluator. This is common in feature flag services (like LaunchDarkly). However, that's not a DSL but a structured data format.
Given we are designing a DSL compiler, we are likely leaning towards transpilation for performance and static validation. But we might also support an interpreter for dynamic use cases? We can design the system to support both:
The transpiler generates code for the host language.
Alternatively, we can have a runtime interpreter that loads the DSL from a file and evaluates it (maybe with a cache of parsed ASTs).
But note: the requirement is for a cross-language DSL, so we want the same DSL to be used in multiple languages. Transpilation would require a transpiler for each target language. Alternatively, we can transpile to an intermediate representation (like a set of nested conditionals) and then have a small runtime in each language that interprets that intermediate form. That's a middle ground.
Proposed approach: Transpile to a simple intermediate representation (IR) that is a tree of conditions in a language-agnostic format (maybe JSON). Then, in each host language, we have a small runtime that evaluates that IR. This way, we get:
Static validation: we can validate the DSL and generate the IR at build time (or even at deployment time).
Runtime: we load the IR (which is just data) and evaluate it with a generic evaluator. This is similar to the interpreter but with a simpler IR and without parsing the DSL at runtime.
But then we lose the performance of native code? Not necessarily: the IR can be a set of nested if-else conditions that are evaluated by a simple interpreter. The performance might be acceptable if the conditions are not too complex and we cache the results per user.
Alternatively, we can generate native code for each language. That would be more work but better performance.
Given the trade-offs, I would recommend:
For high-performance, low-latency use cases (like per-request feature flag checks), generate native code (transpile to the host language).
For flexibility and ease of cross-language support, generate an IR and have a small runtime in each language.
But note: the requirement says "cross-language", so we want to write the DSL once and use it in multiple languages. Transpiling to each language would require maintaining multiple code generators. Alternatively, we can have a single transpiler that outputs the IR (in JSON, for example) and then each language has a runtime that evaluates that IR.
Let's decide on:
AST -> Transpile to IR (JSON) -> Runtime in each language evaluates IR.
Then we can also have an option to transpile to native code for performance-critical applications? But that would be a separate code generator.
Given the complexity, let's stick with the IR approach for cross-language support.
3. Static Validation
We can validate the DSL at the time of transpilation (or even before, with a linter). Validation includes:
Syntax: the DSL must be syntactically correct (handled by the parser).
Semantic:
The feature flag name must be unique (if we have a global registry).
The attributes used in conditions must be known (we can have a schema of available user attributes, environment variables, etc.). For example, if we have a condition user.age > 18, we must know that age is a numeric attribute.
The operators must be applicable to the attribute type (e.g., in for string or list, > for numbers).
The percentage must be between 0 and 100.
The time condition must have a valid date.
The environment must be one of the allowed environments.
We can define a schema for the context (user, environment) that the flag evaluator will have. This schema can be provided by the application (or by a central registry). Then, during transpilation, we check that all conditions are compatible with the schema.
Also, we can check for unreachable conditions? That might be hard in general but we can do some simple checks (like true and false is always false, but that's more of an optimizer).
4. Rollout Strategy
The rollout strategy is about how we deploy the feature flags and how we gradually enable them for users.
In the context of our DSL, the rollout strategy is defined by the condition. For example:
percentage(10): roll out to 10% of users.
user.country in ["US", "CA"]: roll out to users in US and Canada.
time(after: "2024-01-01"): roll out after New Year.
But we might also want more sophisticated strategies:
Gradual rollout: start with 10% and then increase to 50%, then 100%. We can change the condition over time. But note: our DSL condition is static. So we might need to have multiple flags or change the DSL to support time-based percentage changes? Alternatively, we can have the percentage condition take a function of time? That complicates the DSL.
Alternatively, we can store the condition in a database and update it without redeploying. That's the dynamic approach. But if we are transpiling, we are back to static conditions.
So, if we want dynamic rollout, we need to have the condition stored externally (like in a feature flag management system) and then our runtime evaluates that condition. In that case, the DSL is used to define the condition and then we store the condition in the system. Then, when we want to change the rollout, we update the condition in the system (without deploying code). This is the typical feature flag service model.
But if we are transpiling, the condition is fixed at build time. So we have two modes:
Static flags: defined in DSL, transpiled and deployed with the app. Rollout strategy must be changed by deploying a new version.
Dynamic flags: defined in DSL, but the condition is stored in a remote system and the app fetches the condition (as IR) at runtime. Then we can change the condition without deploying.
We can design our system to support both:
The transpiler can generate code that either uses a static condition (hard-coded) or fetches the condition from a remote source (by feature flag name). Then, the condition is evaluated using the runtime.
But that's getting complex.
Given the requirement of a DSL compiler, I think we are focusing on the static case. However, we can design the AST and IR to be serializable so that they can be stored and retrieved.
Summary of Proposed Design
AST: as above.
Transpilation: Parse DSL -> AST -> Validate -> Transpile to IR (JSON). The IR will be a JSON representation of the condition tree, plus metadata (feature flag name).
Example IR for user.country == "US" and percentage(50):
Runtime in each language: We have a library that loads the IR (from a file or from a remote source) and evaluates it given a context (user attributes, environment, current time, etc.). The context must match the schema we validated against.
Static validation: During transpilation, we validate the AST against a provided context schema (which lists available attributes, their types, and allowed values for enums, etc.). We also validate the syntax and basic constraints (percentage in [0,100], etc.).
Rollout strategy: Since the condition is static (unless we fetch it from a remote source), the rollout strategy is fixed in the DSL. To change the rollout, we change the DSL and redeploy (or update the IR in the remote system). We can design the DSL to support time-based conditions for scheduled rollouts.
Extensibility: We might want to add new condition types (like experiment for A/B testing). We can design the AST and IR to be extensible by having a type field and a properties map for unknown types? But then static validation would need to know about the new types. Alternatively, we can have a plugin system for condition types.
Given the complexity, let's stick to a fixed set of condition types for now.
Implementation Steps
Define the grammar for the DSL (using ANTLR or a similar parser generator).
Build the parser that produces the AST.
Implement the static validator that checks the AST against a schema.
Implement the transpiler that converts the AST to IR (JSON).
Implement the runtime in each target language (at least one for prototype) that evaluates the IR.
This is a very simplified grammar. We might want to support parentheses for grouping and have a more complete expression grammar.
Alternatively, we can use a more standard expression grammar and then have the condition be an expression that returns boolean.
But let's keep it simple for now.
Conclusion
We have outlined an AST for feature flag conditions, proposed transpilation to an IR (JSON) for cross-language support, discussed static validation against a context schema, and considered rollout strategies (static vs dynamic). The IR approach allows us to have a single transpiler and multiple runtimes, and we can also support dynamic updates by fetching the IR from a remote source.
Next steps: implement a prototype in one language (say, Java for the compiler and JavaScript for the runtime) to validate the design.
I'll design a cross-language feature flag DSL compiler with production-grade considerations.
1. AST Design
Core Node Hierarchy
python
# Pseudocode for AST nodes
class FeatureFlag:
name: str
description: Optional[str]
conditions: Condition # Root condition
metadata: Dict[str, Any] # tags, owner, created_at, etc.
class Condition(ABC):
pass
class BinaryOp(Condition):
op: str # AND, OR
left: Condition
right: Condition
class UnaryOp(Condition):
op: str # NOT
operand: Condition
class UserAttributeCondition(Condition):
attribute: str
operator: str # ==, !=, >, <, in, etc.
value: Any
class PercentageRollout(Condition):
percentage: float # 0.0-1.0
seed: Optional[str] # For consistent bucketing
namespace: Optional[str] # For experiment groups
class EnvironmentCondition(Condition):
environments: List[str]
class TimeCondition(Condition):
operator: str # before, after, between
timestamps: List[datetime]
class SegmentCondition(Condition):
segment_id: str
operator: str # in, not_in
class CustomCondition(Condition):
function_name: str
arguments: Dict[str, Any]
Example DSL: flags.dsl
python
flag "new_checkout" {
description: "Enable new checkout flow"
tags: ["checkout", "revenue"]
condition:
(user.country in ["US", "CA"] and
user.account_age_days > 30) or
(percentage(0.1, seed="checkout_exp") and
environment in ["staging", "canary"])
}
AST Properties:
Immutable: AST nodes are immutable after parsing
Serializable: Can be serialized to JSON/Protocol Buffers for distribution
Extensible: Support custom condition types via plugin system
Annotated: Each node has source position for error reporting
2. Interpreter vs Transpiler Trade-offs
Interpreter Approach
python
# Runtime evaluation
class Interpreter:
def evaluate(self, flag: FeatureFlag, context: EvaluationContext) -> bool:
# Recursive AST traversal
# Access context.user, context.environment, etc.
# Pros:
# + Dynamic flag updates without deployment
# + Easier debugging (AST dump)
# + Single runtime for all languages (via FFI)
# + Supports user-defined functions
# Cons:
# - Runtime overhead (AST traversal per evaluation)
# - Security surface (DSL injection risk)
# - Harder to optimize
# - Language-specific context adapters needed
Transpiler Approach
python
# Generate native code
transpile_to_java(flag) -> """
public boolean evaluate(User user, String env) {
return (Arrays.asList("US","CA").contains(user.country())
&& user.accountAgeDays() > 30)
|| (consistentHash(user.id(), "checkout_exp") < 0.1
&& Arrays.asList("staging","canary").contains(env));
}
"""""
# Pros:
# + Zero runtime overhead (native code)
# + Full IDE support (type checking, autocomplete)
# + Compiler optimizations apply
# + Better security (no runtime parsing)
# Cons:
# - Requires rebuild for flag changes
# - Multiple transpiler targets to maintain
# - Harder to support user-defined functions
Hybrid Recommendation:
Default: Transpiler for performance-critical paths
Optional: Interpreter for dynamic flags (managed via config service)
Implementation: Generate IR (intermediate representation) first, then:
JIT compile to native code (hot paths)
Interpret (cold paths/dynamic flags)
3. Static Validation
Validation Pipeline:
code
DSL Text → Lexer → Parser → AST → Type Checker → Validator → IR/Code
Validation Rules:
python
class Validator:
def validate(self, ast: FeatureFlag, schema: ContextSchema):
# 1. Syntax errors (parser's job)
# 2. Type checking
# - user.account_age must be numeric if using >
# - percentage(1.5) invalid
# 3. Schema conformance
# - user.country must exist in UserAttributeSchema
# - environment must be in ALLOWED_ENVIRONMENTS
# 4. Logical contradictions
# - "percentage(0) and percentage(100)" always false
# 5. Performance anti-patterns
# - Deeply nested OR conditions (warning)
# - Unbounded IN lists (>100 items)
# 6. Security checks
# - No unbounded recursion in custom functions
# - No external calls in conditions
This design balances performance (transpilation), safety (static validation), flexibility (rollout strategies), and cross-language support (via IR). The hybrid interpreter/transpiler approach lets you choose per-flag whether it's static or dynamic based on risk profile.