Overview
Routing Rules provide dynamic, expression-based control over request routing. They execute before governance provider selection and can override it, allowing you to make sophisticated routing decisions based on request context, headers, parameters, capacity metrics, and organizational hierarchy. Unlike governance routing (which uses static provider weights), routing rules use CEL expressions (Common Expression Language) to evaluate conditions at runtime and make routing decisions dynamically.How It Works
Request Flow
Scope Hierarchy & Precedence
Routing rules are organized by scope with first-match-wins evaluation:- When a request arrives with a Virtual Key, Bifrost builds a scope chain
- Rules are evaluated in scope order (highest to lowest)
- The first matching rule wins - no further rules are evaluated
- Within each scope, rules are sorted by priority (ascending: 0 evaluates before 10)
- If no rule matches, the incoming provider/model is used unchanged
CEL Expression Guide
Available Variables
Routing rules evaluate CEL expressions with these available variables:Request Context
Headers & Parameters
Organization Context
Capacity Metrics (as percentages: 0-100)
CEL Operators & Functions
Comparison Operators
Logical Operators
String Functions
Collections
Expression Examples
Simple Conditions
Complex Conditions (Multiple Criteria)
Pattern Matching
Validation & Error Handling
- Invalid CEL syntax → Rule logs warning, skipped, evaluation continues
- Missing header/parameter → Expression returns false (graceful no-match)
- Type mismatches → Logged as warning, rule skipped
- Empty expression → Rule always matches (use
true/falsefor explicit behavior)
Configuration
- Web UI
- API
- config.json
Access routing rules from the dashboard:Routing Rules Dashboard
Features:
Fields:

- List all rules with scope, priority, and enabled status
- Filter by scope or scope_id
- Create/Edit/Delete rules
- View rule expressions and targets
- Enable/disable rules without deletion
- Drag to reorder priority

- Name (required): Unique rule identifier
- Description (optional): Internal notes
- Enabled: Toggle rule on/off
- CEL Expression: Visual or manual expression builder
- Provider (required): Target provider if matched
- Model (optional): Target model if matched (empty = use original)
- Fallbacks (optional): Array of fallback providers
- Scope: Where rule applies (global, customer, team, virtual_key)
- Scope ID: Required if scope is not global
- Priority: Lower = evaluated first (default: 0)
Visual CEL Builder
The dashboard includes a visual query builder for CEL expressions:- Condition Builder: Select field, operator, value
- Logical Operators: Combine conditions with AND/OR
- Manual Mode: Switch to edit CEL directly
- Validation: Real-time syntax validation
- Conversion: Auto-converts visual rules to CEL
Real-World Use Cases
When to use Routing Rules:- Dynamic routing based on request headers or parameters
- Capacity-based routing (route to fallback when budget/rate limit is high)
- Organization-based routing (different rules for different teams/customers)
- A/B testing or canary deployments
- Conditional provider override based on complex logic
Use Case 1: Tier-Based Routing
Route requests based on customer tier using headers:Use Case 2: Capacity-Based Failover
Route to cheaper provider when budget is exhausted:Use Case 3: Team-Specific Routing
Route team-specific requests to their preferred provider:Use Case 4: Complex Multi-Condition Routing
Combine multiple criteria for sophisticated routing:Use Case 5: A/B Testing
Route percentage of traffic using request patterns:Use Case 6: Regional Routing
Route based on region headers:Integration with Governance & Load Balancing
Interaction with Governance Routing
Routing Rules run BEFORE governance provider selection and can override it: If a routing rule matches:- Governance configures: 70% Azure, 30% OpenAI
- Routing rule exists:
budget_used > 85 → groq - Request arrives with budget_used = 90%
- Result: Groq selected by routing rule, governance provider_configs ignored
Interaction with Load Balancing
Routing rules determine provider BEFORE adaptive load balancing runs:Fallback Chain
Routing rules can define fallbacks that flow into load balancing:- Level 2 load balancing evaluates Azure keys
- If all Azure keys fail, tries Groq
Execution & Performance
CEL Compilation
- First evaluation: CEL expression is compiled into a bytecode program
- Subsequent evaluations: Program is cached and reused
- Performance: Cached program evaluation is very fast (microseconds)
- Memory: Compiled programs cached in memory until Bifrost restart
Priority & Ordering
Rules within the same scope are evaluated in ascending priority order:Optimization Tips
- Order rules by likelihood: Put frequently matching rules first
- Use specific scopes: Avoid global scope when possible (narrower = faster)
- Avoid expensive string operations: Prefer
==over.matches()with regex - Keep expressions simple: Complex conditions increase evaluation time
- Use reasonable priorities: Gaps in priorities (0, 10, 20) make reordering easy
Best Practices
Rule Naming
Rule Naming
✅ Good names:
- “Premium Tier Fast Track”
- “Budget Exhaustion Fallback”
- “ML Team Anthropic Route”
- “Production High Priority Route”
- “Rule 1”
- “Fix”
- “Temp”
- “TODO”
CEL Expression Safety
CEL Expression Safety
✅ Safe patterns:❌ Risky patterns:
Scope Management
Scope Management
✅ Good scope design:
- Global rules for organization-wide policies
- Customer scope for compliance (EU, data residency)
- Team scope for team preferences
- Virtual Key scope for specific integrations
- Too many virtual key-level rules (maintenance nightmare)
- Conflicting rules across scopes
- Rules that duplicate governance routing
Testing & Validation
Testing & Validation
✅ Validate before deployment:
- Test CEL expression with expected headers
- Verify provider/model exist in your setup
- Check fallbacks are valid providers
- Confirm scope_id matches actual entity
- Test with
from_memory=trueto verify in-memory state
- Deploy rules without testing
- Use nonexistent providers
- Create circular fallback chains
Monitoring
Monitoring
✅ Track rule usage:
- Log which rules match (logged in Bifrost logs as
[RoutingEngine]) - Monitor routing decisions by scope
- Alert on unexpected provider selection patterns
- Review priority order occasionally
- Disabling unused rules (instead of deleting)
- Updating documentation when rules change
- Testing failover chains
Troubleshooting
Rule Not Matching
Symptom: Rule expression is correct but doesn’t match Diagnosis:- Check if rule is enabled (
enabled: true) - Verify scope matches (check VirtualKey’s team/customer hierarchy)
- Check rule priority vs other rules in scope (lower priority evaluates first)
- Verify variable values: Use
from_memory=trueto debug
Expression Compilation Error
Symptom: “Failed to compile rule: invalid CEL syntax” Common causes:- Unclosed quotes:
headers["x-tier(missing closing quote) - Invalid operators:
headers["x"] ??(not standard CEL) - String escaping:
headers["x-\type"](incorrect escape)
- Use the visual CEL builder to avoid syntax errors
- Test expressions incrementally
- Check CEL operator documentation above
- Wrap complex expressions in parentheses:
(A && B) || (C && D)
Wrong Provider Selected
Symptom: Request routed to unexpected provider Diagnosis:- Multiple rules matching? (first-match-wins means earlier rules take precedence)
- Governance routing already determined provider? (check scope hierarchy)
- Load balancing changed key? (rule sets provider, LB sets key)
- Lower priority of matching rules
- Verify scope precedence (VirtualKey > Team > Customer > Global)
- Check if another rule has lower priority and matches first
- Review logs:
[RoutingEngine] Rule matched! Decision: provider=...
Header/Parameter Not Found
Symptom: “no such key” error in CEL evaluation This is normal! Bifrost treats missing headers as non-matches:Debugging with Logs
Enable debug logging to see routing rule evaluation:API Reference
Request/Response Examples
Create Capacity-Based Rule
Create Header-Based Rule
List Rules by Team Scope
Get In-Memory Rules (Debug)
Additional Resources
Provider Routing
Understand how routing rules fit into the complete routing pipeline
Virtual Keys
Configure Virtual Keys that scope routing rules
Governance
Learn about the governance layer (applied after routing rules determine provider selection when no rule matches)
CEL Language Spec
Complete CEL expression language documentation

