Skip to main content

Policy Engine & Rule Evaluation

The Olympus Cloud Policy Engine provides dynamic rule evaluation for feature gating, access control, and business logic enforcement.

Overview

The Policy Engine consists of three integrated components:

ComponentPurposeUse Case
Gating ServiceFeature flag evaluationGradual rollouts, A/B testing
Rule EvaluatorDynamic condition evaluationAccess control, targeting
Scheduling PoliciesLabor law complianceWorkforce scheduling

Architecture

┌─────────────────────────────────────────────────────────────────┐
│ POLICY ENGINE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Policy │───▶│ Rule │───▶│ Result │ │
│ │ Lookup │ │ Evaluator │ │ Cache │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ▲ │ │ │
│ │ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Spanner │ │ Override │ │ Redis │ │
│ │ Database │ │ Matching │ │ Cache │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘

Policy Model

Policy Structure

{
"id": "550e8400-e29b-41d4-a716-446655440000",
"key": "new_checkout_flow",
"name": "New Checkout Flow",
"description": "Redesigned checkout experience",
"policy_type": "feature_flag",
"enabled": true,
"rules": {
"allOf": [
{
"condition": {
"field": "tenant.tier",
"operator": "in",
"value": ["enterprise", "professional"]
}
},
{
"condition": {
"field": "user.role",
"operator": "not_equals",
"value": "guest"
}
}
]
},
"default_value": { "variant": "control" },
"metadata": {
"category": "checkout",
"owner": "product-team"
}
}

Policy Types

TypeDescriptionExample
feature_flagBoolean on/off toggleEnable new UI
gradual_rolloutPercentage-based activation25% of users
experimentA/B testing with variantsCheckout A vs B
access_controlPermission gatingAdmin-only features
business_ruleDynamic configurationPricing rules

Rule Evaluation

Evaluation Context

Every policy evaluation requires a context object:

{
"user_id": "user-abc123",
"user_role": "manager",
"user_roles": ["manager", "staff"],
"user_groups": ["premium-beta"],
"tenant_id": "tenant-xyz789",
"tenant_tier": "enterprise",
"app_version": "2.5.0",
"environment": "production",
"attributes": {
"location_id": "loc-001",
"device_type": "mobile",
"custom_field": "value"
}
}

Rule Operators

OperatorDescriptionExample
equalsExact matchrole == "admin"
not_equalsNot equalstatus != "disabled"
greater_thanNumeric greatercount > 10
less_thanNumeric lessprice < 100
greater_than_or_equal>= comparisonversion >= 2.0
less_than_or_equal<= comparisonage &lt;= 65
containsString containsemail contains "@company"
not_containsString doesn't containname not contains "test"
inValue in arraytier in ["pro", "enterprise"]
not_inValue not in arrayrole not in ["guest"]
matches_regexRegex pattern matchemail matches ".*@corp.com"

Logical Combinators

Combine conditions with logical operators:

{
"allOf": [
{ "condition": { "field": "user.role", "operator": "equals", "value": "admin" } },
{ "condition": { "field": "tenant.tier", "operator": "in", "value": ["enterprise"] } }
]
}
CombinatorDescriptionBehavior
allOfLogical ANDAll conditions must pass
anyOfLogical ORAt least one must pass
notLogical NOTNegates the condition

Nested Rules

Rules can be nested for complex logic:

{
"anyOf": [
{
"allOf": [
{ "condition": { "field": "user.role", "operator": "equals", "value": "admin" } }
]
},
{
"allOf": [
{ "condition": { "field": "tenant.tier", "operator": "equals", "value": "enterprise" } },
{ "condition": { "field": "user.groups", "operator": "contains", "value": "beta-testers" } }
]
}
]
}

Policy Overrides

Target specific segments with overrides:

Override Structure

{
"id": "override-001",
"policy_id": "policy-xyz",
"tenant_id": "tenant-specific",
"tenant_group_id": null,
"role_id": "manager",
"user_id": null,
"app_version": ">=2.5.0",
"environment": "production",
"enabled": true,
"value": { "variant": "experimental" },
"rules": null,
"rollout_percentage": 100,
"priority": 10
}

Override Matching Priority

Overrides are matched in priority order:

  1. User-specific (highest) - user_id matches
  2. Role-specific - role_id matches
  3. Tenant-specific - tenant_id matches
  4. Group-specific - tenant_group_id matches
  5. Version-specific - app_version matches
  6. Environment-specific - environment matches
  7. Default policy (lowest) - No override matches

API Reference

Evaluate Policy

POST /api/v1/platform/evaluate-policy
Authorization: Bearer {access_token}
Content-Type: application/json

Request:

{
"policy_key": "new_checkout_flow",
"context": {
"user_id": "user-123",
"user_role": "manager",
"tenant_id": "tenant-456",
"tenant_tier": "professional",
"app_version": "2.5.0",
"environment": "production"
}
}

Response:

{
"policy_key": "new_checkout_flow",
"enabled": true,
"value": { "variant": "variant_a" },
"matched_override": "override-001",
"evaluation_time_ms": 2
}

Batch Evaluate Policies

POST /api/v1/platform/batch-evaluate-policies
Authorization: Bearer {access_token}
Content-Type: application/json

Request:

{
"policy_keys": ["feature_a", "feature_b", "feature_c"],
"context": {
"user_id": "user-123",
"tenant_id": "tenant-456"
}
}

Response:

{
"results": {
"feature_a": { "enabled": true, "value": null },
"feature_b": { "enabled": false, "value": null },
"feature_c": { "enabled": true, "value": { "limit": 100 } }
},
"total_time_ms": 15
}

Create Policy

POST /api/v1/platform/policies
Authorization: Bearer {access_token}
Content-Type: application/json

Request:

{
"key": "new_feature",
"name": "New Feature",
"description": "A new feature being rolled out",
"policy_type": "feature_flag",
"enabled": true,
"rules": {
"condition": {
"field": "tenant.tier",
"operator": "equals",
"value": "enterprise"
}
},
"default_value": null
}

List Policies

GET /api/v1/platform/policies?status=active&category=checkout
Authorization: Bearer {access_token}

Create Override

POST /api/v1/platform/policies/{policy_key}/overrides
Authorization: Bearer {access_token}
Content-Type: application/json

Request:

{
"tenant_id": "tenant-beta",
"enabled": true,
"value": { "variant": "experimental" },
"rollout_percentage": 50,
"priority": 10
}

Canary Releases

Create Canary Release

POST /api/v1/platform/policies/{policy_key}/canary
Authorization: Bearer {access_token}
Content-Type: application/json

Request:

{
"target_percentage": 10,
"increment_percentage": 10,
"increment_interval_hours": 24,
"success_criteria": {
"error_rate_threshold": 0.01,
"latency_p99_threshold_ms": 500
}
}

Promote Canary

POST /api/v1/platform/policies/{policy_key}/canary/promote
Authorization: Bearer {access_token}

Rollback Canary

POST /api/v1/platform/policies/{policy_key}/canary/rollback
Authorization: Bearer {access_token}

Scheduling Policies

The Policy Engine includes specialized scheduling policies for labor law compliance.

Rule Categories

CategoryDescriptionExample
labor_lawState/federal labor lawsOvertime rules
minor_restrictionsMinor worker protectionsCurfew hours
overtime_rulesOvertime calculationsCA overtime
break_requirementsMandatory breaksMeal periods
company_policyCustom business rulesMax shifts/week
operationalOperational constraintsMin staffing

Constraint Types

// Maximum consecutive days worked
MaxConsecutiveDays { max_days: 6 }

// Minimum rest between shifts (clopening prevention)
MinRestBetweenShifts { min_hours: 8 }

// Weekly hour limits
MaxHoursPerWeek { max_hours: 40 }

// Daily hour limits
MaxHoursPerDay { max_hours: 10 }

// Minor curfew restrictions
MinorCurfew { start_hour: 22, end_hour: 6 }

// California overtime rules
CaliforniaOvertime { daily_threshold: 8, weekly_threshold: 40 }

// Required break periods
RequiredBreak { hours_worked: 6, break_duration_minutes: 30 }

// Predictive scheduling notice
PredictiveScheduling { notice_days: 14 }

State-Specific Configurations

StateMeal BreakPredictive SchedulingRest Period
California30 min after 5 hours14 days notice10 hours
New York30 min after 6 hours72 hours notice11 hours
Oregon30 min after 6 hours14 days notice10 hours
FederalNo requirementNo requirementNo requirement

Performance

SLA Targets

OperationTargetActual
Cache hit< 10ms< 1ms
Cache miss< 100ms~47ms
Batch (10 policies)< 200ms~150ms
Rule evaluation< 10ms~5ms P99

Caching Strategy

  • Redis cache with 300-second TTL
  • Cache hit ratio: ~85% after warmup
  • Pub/Sub invalidation on policy updates
  • Deterministic cache keys based on policy + context hash

Security

warning

The matches_regex operator is protected against ReDoS attacks with a 200-character pattern limit. Prefer simpler operators like contains or in whenever possible, as regex evaluation is significantly slower and more error-prone than exact match operators.

  • ReDoS protection: Pattern length limits (200 chars max)
  • Regex size limits: 1MB compiled, 1MB DFA
  • Execution timing: Monitored for anomalies
  • Access control: Requires platform_admin or policy_admin role

Best Practices

Policy Design

  1. Use descriptive keys: checkout_redesign_v2 not feature_1
  2. Add metadata: Include owner, category, and description
  3. Start disabled: Enable after configuration is complete
  4. Use overrides: Target specific segments before broad rollout

Rule Writing

  1. Keep rules simple: Prefer multiple policies over complex rules
  2. Use dot notation: user.role, tenant.tier, attributes.custom
  3. Test thoroughly: Verify rule logic with different contexts
  4. Avoid regex when possible: Use contains or in instead

Rollout Strategy

  1. Start small: Begin with 5-10% rollout
  2. Monitor metrics: Track error rates and latency
  3. Use canary releases: Automated gradual rollout
  4. Have a rollback plan: Quick disable if issues arise

Troubleshooting

Policy Not Evaluating

  1. Check policy is enabled: true
  2. Verify context fields match rule conditions
  3. Check for overrides that might disable the policy
  4. Review Redis cache (may have stale data)

Unexpected Results

  1. Enable evaluation logging
  2. Check override priority order
  3. Verify rule operator usage
  4. Test with simplified rules

Performance Issues

  1. Check Redis connectivity
  2. Review rule complexity
  3. Consider batch evaluation for multiple policies
  4. Monitor database query times