Skip to main content

Feature Flag Service High-Level Design

Comprehensive backend architecture for a scalable feature flag service with real-time updates and A/B testing capabilities

A feature flag service enables safe, controlled feature deployments by allowing dynamic configuration of application behavior without code changes, supporting gradual rollouts, A/B testing, and emergency toggles for production systems.

1. Executive Summary

Clarifying questions

  1. What is the expected read/write ratio for feature flag evaluations?

    • This impacts caching strategy, database throughput requirements, and API gateway design.
  2. What consistency guarantees are required for feature flag evaluations?

    • Are real-time updates critical (e.g., A/B testing) or eventual consistency acceptable?
  3. Is the system expected to be global or regional?

    • Influences multi-region deployment strategy, latency targets, and data replication.
  4. How sensitive is the system to latency?

    • Is sub-100ms response time critical for user-facing feature flags?
  5. What is the expected growth in feature flags and users?

    • Helps size storage, compute, and caching needs.
  6. Are there any external integrations or dependencies (e.g., CI/CD, analytics)?

    • Influences event streaming, API gateway, and audit logging requirements.
  7. What is the expected data ownership model (e.g., teams managing their own flags)?

    • Affects service boundaries, RBAC, and data partitioning strategy.

Problem being solved

The Feature Flag Service enables teams to safely release new features, A/B test variants, and gradually roll out changes without deploying new code. It provides centralized control over feature visibility, allowing for dynamic configuration of features based on user attributes, environment, or time-based conditions.

Back-of-envelope calculations

Assuming:

  • 10 million daily active users (DAU)
  • Average 50 feature flag evaluations per user per day
  • Peak-to-average ratio of 10:1 (86,400 seconds in a day)
  • Average feature flag evaluation payload size: 500 bytes

QPS Calculation:

  • DAU → Peak QPS = (10M * 50) / 86400 ≈ 5,787 QPS (average)
  • Peak QPS = 5,787 * 10 ≈ 57,870 QPS

Storage Calculation:

  • Per user per day = 50 flags * 500 bytes = 25KB
  • Per user per year = 25KB * 365 ≈ 9.1 MB
  • Total storage for 10M users = 91 GB/year (assuming no versioning or history)

Bandwidth Calculation:

  • Read throughput = 57,870 QPS * 500 bytes ≈ 28.9 MB/s (read)
  • Write throughput = Assuming 100 feature flag updates/day per user → ~578 MB/s (write)

Cache Hit Rate & DB QPS:

  • Assuming 90% cache hit rate (common in feature flag systems)
  • DB QPS = 57,870 * (1 - 0.9) ≈ 5,787 QPS

Server Count Estimation:

  • Assuming 10,000 QPS per server (typical for a high-throughput backend)
  • Servers needed = 5,787 / 10,000 ≈ 1 server (but with redundancy and peak handling, likely 3–5 servers)

SLA targets

  • Availability: 99.9% (3.6 minutes of downtime/month)
  • Latency:
    • p50: <100ms
    • p95: <200ms
    • p99: <500ms
  • Throughput: 50,000 QPS (peak) with 100% availability

Key architectural decisions summary

  • Service Architecture: Microservices with a centralized feature flag service and minimal state
  • Data Storage: Relational DB (PostgreSQL) for flag definitions, Redis for caching
  • Caching Strategy: Multi-tiered (L1 in-memory, L2 Redis) with TTL and cache warming
  • Scalability: Horizontal scaling with sharding by feature flag key or user ID
  • Reliability: Circuit breaker, retry logic, and multi-AZ deployment for high availability
  • Security: mTLS between services, RBAC for flag management, audit logging
  • Observability: Distributed tracing, metrics, and structured logging with alerting
  • Deployment: Canary rollouts, feature flags for progressive delivery, GitOps-based deployment

2. System Goals & Non-Functional Requirements

Latency Targets

  • p50: 20ms for flag evaluation requests
  • p95: 50ms for flag evaluation requests
  • p99: 100ms for flag evaluation requests
  • API response time: < 150ms end-to-end including network overhead

Throughput Requirements

  • Average QPS: 10,000 flag evaluation requests/sec
  • Peak QPS: 100,000 flag evaluation requests/sec (10x average)
  • Feature flag updates: 1,000 updates/sec (create/update/delete operations)
  • API requests: 50,000 total requests/sec (evaluations + management)

Availability Target

  • 99.9% (3 9s) availability for flag evaluation service
  • 99.99% (4 9s) availability for management APIs
  • Justification: Feature flags are critical to release control and can impact user experience and business operations. Downtime can cause feature rollbacks or force manual deployments.

Durability and Consistency Requirements

  • Consistency Model: Eventual consistency for flag updates with strong consistency guarantees for read operations within 100ms
  • Durability: All flag changes must be persisted to at least 3 availability zones with 2 copies per zone (3x replication)
  • CAP Trade-off: Prioritizes availability and partition tolerance over strong consistency (CP trade-off acceptable for feature flags)
  • Write Consistency: All writes to flag state must be acknowledged before considering operation complete

Data Retention and Compliance Requirements

  • Retention: 2 years of historical flag state and change logs
  • Compliance: GDPR compliance for user-level targeting data, HIPAA compliance for healthcare-specific flags
  • Audit Trail: Full audit logs of all flag modifications with timestamps and user identifiers
  • Data Deletion: Support for data retention policies and complete deletion on user request

Security and Regulatory Requirements

  • Authentication: JWT-based authentication for all API endpoints with support for OAuth2/OIDC
  • Authorization: RBAC model with team-based permissions (admin, developer, viewer roles)
  • Data Encryption: AES-256 encryption at rest and TLS 1.3 for all in-transit data
  • SOC2 Type II: Compliance with SOC2 Type II standards for security and availability
  • HIPAA: For healthcare use cases, ensure all data handling meets HIPAA requirements with proper business associate agreements
  • Audit Logging: All API access and flag modifications must be logged with detailed metadata for compliance audits

3. High-Level Architecture Diagram

C4Context
    title Feature Flag Service - System Context

    Person(user, "End User")
    Person(developer, "Developer/Operator")
    
    System_Boundary(b1, "Feature Flag Service") {
        System(flag_service, "Feature Flag Service", "Core service managing feature flags")
        System(config_service, "Configuration Service", "Manages flag configurations and rollout strategies")
        System(rollout_service, "Rollout Service", "Handles flag evaluation and targeting logic")
        System(event_service, "Event Service", "Tracks flag usage and analytics")
        System(auth_service, "Auth Service", "Handles authentication and authorization")
    }
    
    System_Ext(db, "Database", "PostgreSQL for configuration storage")
    System_Ext(cache, "Cache", "Redis for caching flag evaluations")
    System_Ext(event_store, "Event Store", "Kafka for event streaming")
    System_Ext(monitoring, "Monitoring", "Prometheus + Grafana for observability")
    System_Ext(logs, "Logging", "Loki + Tempo for logs and traces")
    
    Rel(user, flag_service, "Uses feature flags via SDK")
    Rel(developer, flag_service, "Manages flags via UI/CLI")
    Rel(flag_service, config_service, "Requests configuration")
    Rel(flag_service, rollout_service, "Evaluates flag state")
    Rel(flag_service, event_service, "Reports flag usage")
    Rel(flag_service, auth_service, "Authenticates requests")
    Rel(flag_service, db, "Reads/Writes configuration")
    Rel(flag_service, cache, "Caches flag evaluations")
    Rel(flag_service, event_store, "Streams events")
    Rel(flag_service, monitoring, "Exports metrics")
    Rel(flag_service, logs, "Logs events")
C4Container
    title Feature Flag Service - Container Diagram

    Container_Boundary(c1, "Feature Flag Service") {
        Container(flag_service, "Feature Flag Service", "Go/Java", "Core service handling flag evaluation and management")
        Container(config_service, "Configuration Service", "Go/Java", "Manages flag configurations and rollout strategies")
        Container(rollout_service, "Rollout Service", "Go/Java", "Handles flag evaluation and targeting logic")
        Container(event_service, "Event Service", "Go/Java", "Tracks flag usage and analytics")
        Container(auth_service, "Auth Service", "Go/Java", "Handles authentication and authorization")
    }
    
    Container_Boundary(c2, "External Systems") {
        Container(db, "Database", "PostgreSQL", "Stores flag configurations and metadata")
        Container(cache, "Cache", "Redis", "Caches flag evaluations for performance")
        Container(event_store, "Event Store", "Kafka", "Streams usage events and analytics")
        Container(monitoring, "Monitoring", "Prometheus + Grafana", "Metrics and dashboard")
        Container(logs, "Logging", "Loki + Tempo", "Structured logs and traces")
    }
    
    Rel(flag_service, config_service, "Requests configuration")
    Rel(flag_service, rollout_service, "Evaluates flag state")
    Rel(flag_service, event_service, "Reports flag usage")
    Rel(flag_service, auth_service, "Authenticates requests")
    Rel(flag_service, db, "Reads/Writes configuration")
    Rel(flag_service, cache, "Caches flag evaluations")
    Rel(flag_service, event_store, "Streams events")
    Rel(flag_service, monitoring, "Exports metrics")
    Rel(flag_service, logs, "Logs events")
    
    UpdateRelStyle(flag_service, config_service, $offsetX="-20", $offsetY="0")
    UpdateRelStyle(flag_service, rollout_service, $offsetX="-20", $offsetY="20")
    UpdateRelStyle(flag_service, event_service, $offsetX="-20", $offsetY="40")
    UpdateRelStyle(flag_service, auth_service, $offsetX="-20", $offsetY="60")
    UpdateRelStyle(flag_service, db, $offsetX="-20", $offsetY="80")
    UpdateRelStyle(flag_service, cache, $offsetX="-20", $offsetY="100")
    UpdateRelStyle(flag_service, event_store, $offsetX="-20", $offsetY="120")
    UpdateRelStyle(flag_service, monitoring, $offsetX="-20", $offsetY="140")
    UpdateRelStyle(flag_service, logs, $offsetX="-20", $offsetY="160")

Major Components, Services, Data Stores, and External Integrations

Core Services:

  • Feature Flag Service: Main service that evaluates flags for end users and provides APIs for management
  • Configuration Service: Manages flag configurations, targeting rules, and rollout strategies
  • Rollout Service: Handles complex flag evaluation logic including percentage-based rollouts, targeting by user attributes
  • Event Service: Tracks and reports flag usage analytics and events for monitoring and compliance

Data Stores:

  • Database: PostgreSQL instance storing flag configurations, targeting rules, and metadata
  • Cache: Redis cluster for caching flag evaluations to reduce database load and improve latency
  • Event Store: Kafka cluster for streaming usage events and analytics data

External Integrations:

  • Monitoring System: Prometheus + Grafana for metrics and dashboarding
  • Logging System: Loki + Tempo for structured logging and distributed tracing
  • Authentication Service: Handles authentication and authorization for management APIs

Traffic Flow and Data Flow Annotation

  1. User Traffic: End users make requests to the Feature Flag Service via SDKs, which returns flag states for feature evaluation
  2. Management Traffic: Developers use the Feature Flag Service APIs to create, update, and manage flags through UI or CLI
  3. Internal Service Communication: Feature Flag Service coordinates with Configuration, Rollout, and Event services for full functionality
  4. Data Flow: Flag configurations are stored in PostgreSQL, cached in Redis, and usage events are streamed to Kafka for analytics
  5. Observability Flow: Metrics are exported to Prometheus, logs to Loki, and traces to Tempo for system monitoring

4. Service Architecture

Microservices vs. Monolith vs. Modular Monolith Decision

For a Feature Flag Service, I recommend a modular monolith approach as the initial architecture. This decision balances the need for rapid development, clear service boundaries, and operational simplicity while maintaining flexibility to evolve into microservices later.

Justification:

  • Feature flags are a cross-cutting concern that benefits from tight integration with application code
  • Early-stage feature flag systems typically have low complexity and high coupling requirements
  • Modular monolith allows for clean separation of concerns while avoiding the operational overhead of microservices
  • Easier to implement and test feature flag logic in a single codebase before scaling

Service Decomposition Strategy

The Feature Flag Service will be decomposed into the following domains:

  1. Flag Management Service - Core CRUD operations for feature flags, targeting, and configurations
  2. Flag Evaluation Service - Real-time flag evaluation engine with client-side SDK integration
  3. Analytics Service - Usage tracking, A/B testing, and reporting capabilities
  4. Configuration Service - System-wide configuration, environment management, and rollout strategies
  5. Audit & Compliance Service - Change tracking, version control, and compliance reporting

Service Boundaries and Contracts

Each service will maintain clear boundaries with well-defined contracts:

Flag Management Service:

  • REST API for flag creation, updates, and deletions
  • GraphQL endpoint for complex targeting queries
  • Event-driven notifications for flag changes

Flag Evaluation Service:

  • SDK-compatible endpoints (HTTP/GRPC)
  • Client-side caching and refresh mechanisms
  • Real-time flag change propagation

Analytics Service:

  • Metrics aggregation endpoints
  • Historical reporting APIs
  • Real-time dashboard integration

Configuration Service:

  • Environment and context configuration endpoints
  • Rollout strategy management (gradual rollouts, percentage-based)
  • Feature flag lifecycle management

Audit & Compliance Service:

  • Change history and diff APIs
  • Compliance report generation endpoints
  • Audit trail storage and retrieval

Inter-Service Communication Pattern

Synchronous Communication:

  • Flag Management → Flag Evaluation (for flag state updates)
  • Configuration → Flag Evaluation (for rollout strategies)
  • Analytics → Flag Management (for usage metrics)

Asynchronous Communication:

  • All services communicate via event streams for state changes and notifications
  • Flag changes propagate through a centralized event bus (Kafka)
  • Audit events are published to a dedicated audit topic

Service Mesh Consideration

I recommend not using service mesh for the initial architecture due to:

  • Low complexity and small number of services (5-6)
  • Simpler debugging and monitoring without additional abstraction layers
  • Reduced operational overhead during early development phases
  • Service mesh adds latency and complexity that isn't justified for this use case

Service Registry and Discovery Strategy

Service Registry:

  • Use Consul or Eureka for service discovery
  • Services register with health checks every 30 seconds
  • Health status monitoring and automatic failover

Service Discovery:

  • Client-side discovery for better control over routing decisions
  • Support for multiple service instances with load balancing
  • Graceful degradation when services are unavailable

Cross-Service Data Ownership

No shared databases rule enforced through:

  • Each service owns its data store completely
  • Services communicate only through well-defined APIs and events
  • Data synchronization handled via event-driven architecture
  • Audit trail maintained in each service's own database

CQRS Pattern Application

CQRS Implementation:

  • Flag Management Service: Implements CQRS pattern with separate write and read models
    • Write model handles flag creation, updates, and versioning
    • Read model optimized for fast flag evaluation queries
  • Analytics Service: Uses CQRS to separate real-time metrics collection from historical reporting
  • Audit Service: Read model optimized for compliance and audit query patterns

Event Sourcing Consideration

Event Sourcing Not Applied Due to:

  • Simpler use case with well-defined CRUD operations
  • Low complexity in flag state transitions
  • Better performance with direct database writes for feature flags
  • Easier debugging and system understanding without event replay complexity

Object Storage Design

Not Applicable: Feature Flag Service primarily handles configuration data rather than file/media storage.

Storage Tiering Strategy

Not Applicable: Feature Flag Service uses primarily in-memory and relational storage with no significant file storage requirements.

Backup and Restore Strategy

Not Applicable: Feature Flag Service has minimal data persistence needs that can be handled through database replication and backup strategies.

5. Data Architecture

Database Selection per Service

Feature Flag Service (Primary Service)

  • Database: PostgreSQL 15+ (primary relational store)
  • Justification:
    • Strong consistency requirements for flag evaluation
    • Complex querying patterns (flag rules, targeting, variants)
    • Need for ACID transactions during flag updates
    • Support for JSONB fields for flexible flag configurations
    • Mature ecosystem with excellent tooling and observability

Flag Evaluation Service (Secondary)

  • Database: Redis 7+ (in-memory cache)
  • Justification:
    • High read throughput requirements (millions of evaluations/sec)
    • Low latency SLA (sub-50ms p99)
    • Simple key-value operations for flag state retrieval
    • TTL support for automatic flag expiration
    • Built-in pub/sub for real-time flag updates

Audit & Analytics Service

  • Database: TimescaleDB (time-series)
  • Justification:
    • Historical flag evaluation data with time-based queries
    • Need for analytical queries over flag usage patterns
    • Efficient storage and querying of time-series data
    • Built-in compression for cost optimization

Data Partitioning Strategy

Primary Database (PostgreSQL)

  • Partitioning Method: Hash-based on project_id with 32 shards
  • Justification:
    • Even distribution of feature flags across shards
    • Predictable performance scaling with horizontal partitioning
    • Minimal cross-shard queries (95% of operations within shard)
    • Support for multi-tenant isolation with project-level boundaries

Cache Layer (Redis)

  • Partitioning Method: Key-based sharding with consistent hashing
  • Justification:
    • Distributes cache keys across multiple Redis instances
    • Maintains cache consistency during failover
    • Allows for easy scaling of cache capacity

Data Replication Strategy

Primary Database (PostgreSQL)

  • Replication: Primary-replica with read replicas
  • Configuration:
    • 1 primary instance (master) for writes
    • 3 read replicas (hot standby) for reads
  • Justification:
    • High availability with automatic failover (pgBouncer + Patroni)
    • Read scaling without impacting write performance
    • Backup and disaster recovery capabilities

Cache Layer (Redis)

  • Replication: Redis Sentinel + Cluster mode
  • Configuration:
    • 3 master nodes with 3 replicas each (6 total)
    • Automatic failover and client redirection
  • Justification:
    • High availability for cache layer (99.99% uptime)
    • Zero downtime during maintenance or failures
    • Support for cross-region replication

Cross-Service Data Ownership

No Shared Databases Rule

  • Enforcement Strategy:
    • Each service owns its database instance
    • Database access via service accounts with role-based permissions
    • API gateway enforces database access policies
    • Cross-service communication through events (Kafka) or gRPC

CQRS Pattern Application

Feature Flag Service

  • Read Model: PostgreSQL (primary)
  • Write Model: PostgreSQL + Redis cache
  • Justification:
    • Write-heavy workload with strict consistency requirements
    • Read-heavy evaluation queries (cache layer)
    • Separation of concerns between flag definition and evaluation

Audit & Analytics Service

  • Read Model: TimescaleDB (analytics)
  • Write Model: Kafka topic (audit events)
  • Justification:
    • Separation of operational and analytical workloads
    • Real-time audit logging with eventual consistency for analytics

Event Sourcing Consideration

Use Case: Audit trail and flag versioning

  • Implementation:
    • Events published to Kafka when flags are created/updated/deleted
    • Event store maintained in Kafka with retention policy (30 days)
  • Trade-offs:
    • Pros: Complete audit trail, replay capability, eventual consistency
    • Cons: Additional complexity, storage overhead, latency for real-time queries

Object Storage Design

Not Applicable: Feature flag service does not store large media or binary objects.

Storage Tiering Strategy

Primary Database (PostgreSQL)

  • Tier: Hot storage (SSD)
  • Justification: High read/write frequency, low latency requirements

Cache Layer (Redis)

  • Tier: Hot storage (SSD)
  • Justification: High read throughput, sub-millisecond latency

Audit Logs (TimescaleDB)

  • Tier: Warm storage (SSD with compression)
  • Justification: Frequent read patterns for recent data, infrequent access to older logs

Backup and Restore Strategy

Primary Database (PostgreSQL)

  • Backup: Continuous Archival with WAL (Write-Ahead Log) archiving
  • Restore: Point-in-time recovery (PITR) with 15-minute granularity
  • RTO: < 30 seconds (for failover)
  • RPO: < 5 minutes (with WAL archiving)

Cache Layer (Redis)

  • Backup: RDB snapshots every 15 minutes with AOF persistence
  • Restore: Full state recovery from last snapshot
  • RTO: < 1 minute (for failover)
  • RPO: < 15 minutes (with AOF)

Audit Logs (TimescaleDB)

  • Backup: Daily logical backups with compression
  • Restore: Full database restore within 2 hours (with compressed backups)
  • RTO: < 2 hours
  • RPO: < 24 hours

6. Caching Architecture

Cache Layers and Strategy

The caching strategy follows a multi-tier approach to optimize performance and reduce database load:

  1. Client-side Cache (L1): Mobile/web clients cache feature flags locally with TTLs
  2. CDN Layer (L2): Cloudflare or AWS CloudFront caches flags for global distribution
  3. API Gateway Cache (L3): API gateway caches recent flag evaluations with short TTLs
  4. Application Cache (L4): In-memory cache per service instance using Redis or similar
  5. Distributed Cache (L5): Shared Redis cluster for cross-service flag caching

Cache Implementation Details

In-Memory Cache (L4):

  • L1 cache per application instance using Redis or Memcached
  • TTL set to 30 seconds for frequently accessed flags
  • Cache warming strategy using background preloading of active flags
  • Cache invalidation via Redis Pub/Sub for real-time updates

Distributed Cache (L5):

  • Redis cluster with 3 master nodes for HA
  • Cache keys follow pattern: flag:{flagName}:{userId}
  • TTL set to 5 minutes for most flags, 1 hour for stable flags
  • Cache warming via periodic background jobs

Cache Sizing and Eviction Strategy

Cache Size Calculation:

  • Peak concurrent users: 100K
  • Average flags per user: 50
  • Cache size estimate: 100K * 50 * 1KB = 5MB per cache node
  • 3-node Redis cluster with 2GB RAM per node (10% overhead for metadata)
  • Eviction policy: LRU with maxmemory-policy allkeys-lru

Cache Consistency Strategy

Cache Invalidation:

  • Event-driven invalidation via Kafka topics when flags change
  • Cache warming on service startup and periodic refresh
  • Cache consistency maintained through cache-aside pattern with TTLs
  • Client-side cache invalidation via push notifications

Cross-Service Cache Coherency:

  • Shared Redis cluster with consistent key naming
  • Cache invalidation events published to centralized topic
  • Service instances subscribe to flag change notifications
  • Cache warming strategy for cold starts using bulk flag loading

Cache Warming Strategy

Cold Start Handling:

  • Background job preloads popular flags (top 1000) into cache
  • Service startup loads recent flag states from database
  • Cache warming uses bulk operations to reduce DB load
  • Warm-up strategy prioritizes flags with highest access frequency

Cache Hit Rate Target:

  • Target 95% cache hit rate for feature flag lookups
  • Cache hit rate monitoring via Prometheus metrics
  • Cache warming reduces initial cache miss rate by 70%
  • Client-side caching increases effective hit rate to 98%

7. Messaging & Event Streaming Architecture

Message Broker Selection

For a Feature Flag Service, we'll use Apache Kafka as the primary message broker due to:

  • High throughput requirements: Feature flag updates need to be propagated to all service instances with minimal latency
  • Durability guarantees: Flags must survive broker failures and be replayable for compliance
  • Partitioning capabilities: Enables horizontal scaling and consistent flag evaluation per user segment
  • Stream processing support: Future extensibility for flag analytics and A/B testing
  • Ecosystem maturity: Strong tooling for monitoring, management, and integration

Event Schema Registry and Versioning

We'll implement a Confluent Schema Registry for:

  • Schema evolution management: Version control of flag change events with backward/forward compatibility
  • Type safety: Prevents malformed flag updates from being published
  • Validation at publish time: Ensures all consumers can process new schema versions
  • Audit trail: Track flag event schema changes over time

Topic Partitioning and Consumer Group Design

FlagChangeEvents topic:

  • Partitions: 128 partitions (scalable to 1000+ consumers)
  • Partition key: flagKey (ensures all changes to same flag go to same partition)
  • Retention: 7 days (enough for replay and recovery scenarios)

Consumer groups:

  • FlagService consumer group: Handles flag evaluation logic
  • Analytics consumer group: Processes flag usage metrics and A/B test data
  • Audit consumer group: Logs all flag changes for compliance

Event Ordering Guarantees

Per-partition ordering:

  • Within a flag's partition, events are ordered by timestamp
  • This ensures consistent flag evaluation across service instances
  • Global ordering: Not required for feature flags, but can be achieved via Kafka's global ordering if needed

Exactly-once vs. At-least-once Processing Trade-offs

Decision: At-least-once processing with idempotent consumers

Justification:

  • Risk mitigation: Re-processing flag changes is safer than missing updates
  • Consumer resilience: Services can safely reprocess events during outages
  • Simpler implementation: Avoids complex state management for exactly-once semantics
  • Performance: Lower overhead compared to idempotent consumer complexity

Event Replay and Reprocessing Strategy

Replay capability:

  • Kafka's retention policy enables replay of flag changes for up to 7 days
  • Replay API: Expose endpoint to replay events for specific flags or time ranges
  • Historical evaluation: Support flag state reconstruction at any point in time

Reprocessing triggers:

  • Manual trigger: Admin UI to replay specific flag changes
  • Automated recovery: System detects and retries failed consumer processing

Dead Letter Queue and Poison Pill Handling

Dead Letter Queue (DLQ) design:

  • Primary DLQ topic: flag-change-dlq
  • Poison pill detection:
    • Max retries (5) before routing to DLQ
    • Failed event metadata (timestamp, flag key, error type) stored in DLQ headers
  • Monitoring: Alert on DLQ queue size and error patterns

DLQ handling process:

  1. Manual review: Operations team investigates DLQ messages
  2. Reprocessing: Fixed malformed events can be reprocessed from DLQ
  3. System alerting: Critical flag change failures trigger immediate alerts

Cross-service Event Flow

graph TD
    A[Feature Flag Service] --> B[Kafka Topic: flag-changes]
    B --> C[Flag Evaluation Service]
    B --> D[Analytics Service]
    B --> E[Audit Service]
    C --> F[Flag Cache Invalidation]
    D --> G[Usage Metrics Collection]
    E --> H[Compliance Logs]

Event Payload Format

FlagChangeEvent structure:

{
  "eventId": "uuid",
  "flagKey": "feature-123",
  "flagValue": true,
  "userContext": {
    "userId": "user-123",
    "groupId": "group-456"
  },
  "timestamp": "2023-12-01T10:00:00Z",
  "changeType": "UPDATE|CREATE|DELETE",
  "version": "1.0"
}

Event Processing Pipeline

Producer side:

  • Flag updates from admin UI or API are published to Kafka
  • Schema validation occurs before publishing

Consumer side:

  1. FlagChangeProcessor:
    • Consumes flag changes
    • Updates local caches and invalidates stale entries
  2. AnalyticsProcessor:
    • Aggregates usage statistics
    • Triggers A/B test analytics
  3. AuditProcessor:
    • Logs all changes for compliance and audit trails

Scalability Considerations

Partitioning strategy:

  • Hash-based partitioning: Distributes flag changes evenly across partitions
  • Shard-aware consumers: Services can consume from specific partition ranges if needed

Consumer scaling:

  • Horizontal scaling: Add more consumer instances to handle increased flag change volume
  • Load balancing: Kafka's consumer group mechanism ensures balanced workload distribution

Integration with External Systems

External event sources:

  • CI/CD pipeline: Flag updates from automated deployment systems
  • Third-party integrations: External flag management tools (LaunchDarkly, Flagsmith)
  • Analytics platforms: Flag usage data for business intelligence

Event transformation:

  • Format conversion: Convert external flag formats to internal event schema
  • Metadata enrichment: Add system context and audit information to events

Monitoring and Alerting

Kafka metrics tracking:

  • Producer lag: Monitor for delayed flag change publishing
  • Consumer lag: Track processing delays in consumer groups
  • Partition utilization: Ensure even distribution of flag change events

Alert thresholds:

  • High consumer lag: >5 minutes triggers alert
  • DLQ size: >100 messages in DLQ triggers investigation
  • Producer errors: >5% error rate in flag change publishing

This messaging architecture ensures reliable, scalable propagation of feature flags while maintaining auditability and supporting future extensibility for analytics and compliance use cases.

8. Reliability Engineering

Failure Mode Analysis

Single Points of Failure:

  • Feature Flag Service Primary Instance: Single point for all flag evaluations
  • Database Layer: Failure of primary database causes flag retrieval issues
  • Configuration Store: S3/GCS backend unavailability affects flag state
  • Cache Layer: Redis cluster failure causes cache misses and DB load spikes
  • API Gateway: Gateway failure blocks all client requests to feature flags

Failure Scenarios:

  • Database connection pool exhaustion under high load
  • Cache warming failures during service restarts
  • Network partition between services and data stores
  • Configuration drift between environments (dev/staging/prod)
  • Race conditions in flag updates and evaluations

Fault Tolerance Patterns

Circuit Breaker Pattern:

  • Applied to database connections and external configuration stores
  • Trip when 50% of requests fail within 10 seconds (timeout + error rate)
  • Resets after 30 seconds with half-open state for testing
  • Per-service circuit breaker (e.g., PostgreSQL, Redis, S3)

Bulkhead Pattern:

  • Service-level isolation using thread pools for database operations
  • Separate connection pools for read vs. write operations (20% vs. 80% of total)
  • Rate limiting per client to prevent individual user from overwhelming system

Timeout & Retry Strategy:

  • 500ms timeout for database queries (with 200ms buffer for network)
  • Exponential backoff retry with jitter (100ms → 500ms → 1s) for transient failures
  • Retry limit of 3 attempts before returning default flag state

Graceful Degradation:

  • Default flag values when service is unavailable (e.g., "off" for all flags)
  • Cached flag states with TTL of 5 minutes during outages
  • Health check endpoint returns degraded status when service is unhealthy

Multi-Region / Multi-AZ Strategy

Active-Active Architecture:

  • Deploy in 3 regions (us-east-1, eu-west-1, ap-southeast-1)
  • Each region maintains independent database and cache clusters
  • Global load balancer routes traffic to nearest healthy region
  • Cross-region replication for critical configuration data (30s sync window)

Regional Failover:

  • Auto-failover to secondary region when primary region experiences >90% latency
  • Health checks every 10 seconds with 3 consecutive failures required for failover trigger
  • DNS-based routing with weighted round-robin to distribute traffic across regions

Chaos Engineering Strategy

GameDays:

  • Weekly 2-hour GameDay sessions targeting feature flag service resilience
  • Simulate database outages, cache unavailability, and network partitions
  • Test circuit breaker behavior under high load conditions
  • Validate graceful degradation scenarios with realistic traffic patterns

Steady-State Hypothesis:

  • Service availability >99.9% under normal conditions
  • Flag evaluation latency <50ms p99 (under 100ms p99 for peak)
  • Cache hit rate >95% during normal operation
  • No data loss in configuration changes or system restarts

Disaster Recovery Plan

RTO/RPO Targets:

  • RTO: 5 minutes for service recovery (including failover)
  • RPO: 1 minute for data consistency (via replication and journaling)
  • Recovery Time: 30 minutes for full region restoration

Recovery Procedures:

  1. Database Failover: Promote standby replica to primary within 2 minutes
  2. Cache Restoration: Rehydrate Redis from backup within 5 minutes
  3. Configuration Restore: Rollback to last known good configuration state
  4. Traffic Redirection: Route all traffic to healthy region within 30 seconds

Runbook Design for Top-5 Failure Scenarios

Failure ScenarioDetectionImmediate ActionsRecovery Steps
Database OutageHealth check failure, >50% error rateDisable circuit breaker, switch to default flagsPromote standby DB, restore from backup
Cache UnavailabilityCache miss rate >80%, latency spikesBypass cache, use direct DB queriesRestart Redis cluster, restore from snapshot
High LatencyP99 latency >100ms for 5 minutesEnable circuit breaker, reduce rate limitsScale cache instances, optimize queries
Configuration DriftFlag inconsistency reportedValidate flags against source of truthRevert to stable configuration, audit changes
Network PartitionService unavailability in specific regionRoute traffic to other regionsFix network routing, re-enable partitioned region

Monitoring & Alerting:

  • Critical alerts for service unavailability (P0)
  • Warning alerts for latency degradation (P1)
  • Info alerts for cache miss rate >5% (P2)
  • Automated runbook execution via PagerDuty integration for P0 incidents

9. Observability Architecture

Logging Stack

The logging architecture follows a centralized, structured approach using JSON-formatted logs with consistent field schemas across all services. Logs are collected via Fluentd or Vector to a centralized logging system (Loki for open-source stack or CloudWatch for AWS). Each log entry includes service name, timestamp, log level, trace ID, and relevant contextual metadata. Structured logging enables efficient querying and filtering across services.

Distributed Tracing

Distributed tracing is implemented using OpenTelemetry with Jaeger as the backend for trace visualization. All service calls are instrumented to propagate trace context (W3C TraceContext) across service boundaries. Critical paths such as feature flag evaluation and configuration changes are traced end-to-end to identify performance bottlenecks. Traces include span names, durations, and error details for root cause analysis.

Metrics Stack

Prometheus is selected as the primary metrics backend with Grafana for visualization. Key metrics collected include:

  • Feature flag evaluation rates (per flag, per environment)
  • Service QPS and latency distributions (p50/p95/p99)
  • Cache hit rates and cache miss counts
  • Database query latency and throughput
  • Error rates by service and error type

Metrics are collected at 15-second intervals with 5-minute aggregation windows for dashboarding and alerting.

Alerting Strategy

Alerts are organized into severity levels:

  • Critical (P0): Feature flag service downtime, cache failure, >5% error rate in flag evaluation
  • High (P1): Cache hit rate <70%, latency >500ms p99, database connection pool exhaustion
  • Medium (P2): Cache warming failures, configuration change delays >30s

Alerting is managed via Prometheus Alertmanager with PagerDuty integration for on-call routing. Alerts are grouped by service and severity, with escalation policies defined for each.

SLI/SLO Definition and Error Budget Tracking

SLIs are defined as:

  • Feature flag evaluation success rate: (successful evaluations / total evaluations)
  • Flag evaluation latency: p99 < 200ms
  • Service availability: >99.9% uptime

SLOs are set at 99.9% availability and 99.9% success rate for flag evaluations. Error budget is calculated as (1 - SLO) * working hours, with automatic alerting when error budget is consumed at 80% and 100%.

Capacity Planning and Load Forecasting

Capacity planning is driven by historical flag evaluation patterns, with forecasting models built using Prophet or similar time-series libraries. Metrics are monitored for trends in:

  • Peak evaluation QPS (expected to scale with user base)
  • Cache size growth and hit rate trends
  • Database connection pool utilization

Load forecasting includes seasonal patterns (e.g., feature releases) and growth projections to guide auto-scaling decisions. Dashboard alerts trigger capacity planning reviews when predicted utilization exceeds 80% for >24h.

graph TD
    A[Feature Flag Service] --> B[Prometheus]
    A --> C[Jaeger]
    A --> D[Loki]
    B --> E[Grafana]
    C --> F[Grafana]
    D --> G[Grafana]
    A --> H[Alertmanager]
    H --> I[PagerDuty]

10. API Gateway & Edge Layer

API Gateway Selection

For a Feature Flag Service, I recommend AWS API Gateway as the primary API gateway with custom edge proxy for advanced use cases. The selection is based on:

  • Managed service benefits: Reduced operational overhead, automatic scaling, built-in WAF, and DDoS protection
  • Native integration: Seamless integration with AWS Lambda, Cognito, and other AWS services
  • Rate limiting and throttling: Built-in rate limiting with per-client and global limits
  • Protocol support: HTTP/HTTPS, WebSocket, and REST APIs with OpenAPI/Swagger support
  • Cost efficiency: Pay-per-request model that scales with traffic

For hybrid or multi-cloud environments, a custom edge proxy using Nginx + custom middleware would be appropriate to maintain control over routing, authentication, and transformation logic.

Request Routing Strategy

The API gateway will implement a multi-tier routing strategy:

  1. Path-based routing: /flags/{flagKey} for feature flag operations, /environments/{envId}/flags for environment-specific queries
  2. Header-based routing: Route by X-Client-ID, X-Environment, or X-Feature-Context for client-specific configurations
  3. Content-based routing: Route based on request payload structure (e.g., feature flag evaluation vs. configuration updates)
  4. Service discovery integration: Route to appropriate microservices using service registry (e.g., Consul or Eureka)

Authentication and Authorization at Gateway Layer

Authentication will be handled at the API gateway level using JWT tokens with the following flow:

  1. OAuth2/OIDC integration: For external service authentication via Auth0 or AWS Cognito
  2. JWT validation: Gateway validates JWT tokens with public keys from JWKS endpoint
  3. Role-based access control (RBAC):
    • Admins can read/write all flags and environments
    • Developers can read/write flags within their environment
    • Read-only users can only read flags

Rate Limiting and Throttling Design

Implement multi-tier rate limiting:

  1. Global rate limiting: 10,000 requests/minute for all clients (to prevent abuse)
  2. Per-client rate limiting: 1,000 requests/minute per client ID (to prevent individual client overuse)
  3. Per-flag evaluation rate limiting: 100 evaluations/second per flag key (to prevent hot flag abuse)
  4. Dynamic throttling: Based on system load and latency metrics to prevent cascading failures

Request Transformation and Protocol Translation

The gateway will handle:

  1. Protocol translation: Convert HTTP to gRPC for internal microservices where appropriate
  2. Request/response transformation:
    • Normalize request formats across different client SDKs
    • Transform response payloads to maintain backward compatibility
    • Add standard headers for tracing and logging (e.g., X-Request-ID, X-Client-Version)
  3. Content negotiation: Handle different content types (JSON, YAML) and versioning

BFF (Backend for Frontend) Design

For client applications, we'll implement a BFF pattern:

  1. Client-specific transformations:
    • For web clients: Return optimized JSON with pre-computed flag states
    • For mobile clients: Handle offline capability and caching strategies
  2. Caching layer integration: BFF will integrate with Redis cache to reduce database load
  3. Feature flag evaluation optimization: Pre-compute flag states based on client context (user ID, device type, etc.)

The BFF pattern allows us to:

  • Reduce client-side complexity by handling flag evaluation logic
  • Implement client-specific optimizations (e.g., caching strategies, offline support)
  • Maintain a consistent API surface while adapting to different client requirements

Security Considerations

  1. TLS termination: All traffic will be terminated at the gateway with TLS 1.3
  2. Request validation: Input sanitization and validation before forwarding to services
  3. Rate limiting enforcement: Prevent abuse and DDoS attacks
  4. WAF integration: AWS WAF to block malicious traffic patterns and SQL injection attempts

Performance Targets

  • P50 latency: < 20ms for flag evaluation requests
  • P95 latency: < 100ms for all API endpoints
  • Throughput: Support 50,000 concurrent requests with 100ms tail latency
  • Availability: 99.9% uptime for API gateway layer

Scalability Considerations

  1. Horizontal scaling: Gateway instances will scale automatically based on traffic
  2. Multi-region deployment: Active-active configuration across regions for low-latency global access
  3. Connection pooling: Efficient handling of persistent connections to backend services
  4. Circuit breaker pattern: Prevent cascading failures when downstream services are unavailable

This design provides a robust, scalable, and secure edge layer that can handle the high-throughput requirements of feature flag evaluation while maintaining flexibility for future enhancements.

11. Authentication & Authorization Architecture

Identity Provider Integration

For a Feature Flag Service, we'll integrate with AWS Cognito as the primary identity provider due to its seamless integration with AWS services, robust federation capabilities, and built-in support for OAuth2/OIDC flows. Cognito provides managed user pools that can handle both enterprise SSO (SAML/ADFS) and social login providers, making it ideal for enterprise customers with existing identity infrastructure.

OAuth2/OIDC Flow Design

sequenceDiagram
    participant Client
    participant AuthN
    participant Cognito
    participant AuthZ

    Client->>AuthN: Request access to Feature Flag Service
    AuthN->>Cognito: Redirect to Cognito for authentication
    Cognito-->>Client: Redirect with Authorization Code
    Client->>AuthN: Exchange code for tokens
    AuthN->>Cognito: Validate token signature and claims
    AuthN-->>Client: Return access token with scopes
    Client->>AuthN: Request feature flags with token
    AuthN->>AuthZ: Validate permissions for feature flag access
    AuthZ-->>AuthN: Permission result
    AuthN-->>Client: Feature flags or access denied

Service-to-Service Authentication

For service-to-service communication, we'll implement mTLS using SPIFFE/SPIRE for secure identity validation. Each service will have a unique SPIFFE ID, and certificates will be managed through a centralized certificate authority within the service mesh. This ensures that all internal communications are authenticated and encrypted, preventing unauthorized access between services.

RBAC vs ABAC Model

We'll implement a hybrid approach combining RBAC and ABAC for optimal flexibility:

RBAC (Role-Based Access Control) - Primary model for simple access control:

  • Roles: admin, developer, viewer
  • Permissions tied to roles (e.g., feature_flag.read, feature_flag.write)
  • Users assigned to one or more roles

ABAC (Attribute-Based Access Control) - Secondary model for complex conditions:

  • Context-aware permissions (e.g., "allow read access to feature flags in environment 'staging' only for users in team 'backend'")
  • Attributes: user roles, teams, environment, time windows, feature flag states

This hybrid model allows us to maintain simple role-based access for most use cases while supporting complex conditional logic where needed.

Token Revocation Strategy

We'll implement a combination of short-lived JWT tokens (15-minute TTL) with refresh token rotation:

  • Short-lived Access Tokens: 15-minute expiration for API access
  • Refresh Token Rotation: Each refresh token is single-use and rotated on each successful refresh
  • Blacklist Mechanism: Token revocation list maintained in Redis cache for immediate invalidation of compromised tokens
  • Token Validation: All tokens validated against the revocation list before processing

This approach balances security (short-lived tokens) with usability (refresh token rotation) while maintaining performance through efficient cache invalidation strategies.

12. Search Architecture

Search Indexing Pipeline Design

The search functionality in a feature flag service is primarily used for searching flags by name, description, tags, or associated metadata. The indexing pipeline follows a multi-stage approach:

  1. Source: Feature flag data is sourced from the main feature flag database (PostgreSQL) and potentially from external sources like user metadata or project configurations.
  2. Transform: During indexing, flag data is normalized and enriched with additional fields such as:
    • Flag name (tokenized for full-text search)
    • Description (for relevance scoring)
    • Tags (structured metadata for filtering)
    • Project ID and environment
    • Owner information (for access control)
  3. Index: Transformed data is indexed into a dedicated search engine.

Index Schema and Query Pattern Design

The search index schema is designed for fast retrieval and filtering:

  • Primary Fields:

    • flag_id (unique identifier)
    • name (full-text searchable)
    • description (searchable with relevance scoring)
    • tags (array of string tags for filtering)
    • project_id (for project-level search)
    • environment (for environment-specific queries)
    • created_at, updated_at (for time-based filtering)
  • Query Patterns:

    • Full-text search on flag name/description
    • Tag-based filtering (AND/OR combinations)
    • Project/environment scoped search
    • Search with relevance ranking based on name match and metadata

Real-time vs. Near-real-time Indexing Trade-offs

The system uses near-real-time indexing with a 1-2 second delay to balance performance and consistency:

  • Real-time indexing (high latency, strong consistency): Would require synchronous writes to the search index on every flag update, causing significant latency and potential system bottlenecks.
  • Near-real-time indexing (lower latency, eventual consistency): Uses a message queue to asynchronously index flag updates with a small delay (1-2 seconds) for better performance and scalability.

Relevance Tuning Strategy

Relevance scoring is implemented using a combination of:

  • TF-IDF (Term Frequency-Inverse Document Frequency) for text matching
  • Field boosting to prioritize name matches over description matches
  • Custom scoring logic based on:
    • Recent flag updates (boosts recently modified flags)
    • Project popularity (boosts flags in frequently accessed projects)
    • User role-based relevance (e.g., owner-specific flags get higher score)

Search Scaling Design

To support horizontal scaling:

  • Sharding Strategy: Indexes are sharded by project ID to allow parallel processing and reduce query latency.
  • Replication: Each shard has a primary and replica node for high availability.
  • Query Distribution: Search queries are routed to the appropriate shard based on project ID or tag filters.
  • Caching: Frequently accessed search results are cached in Redis to reduce load on the search engine.

This design ensures that feature flag search remains performant as the system scales to support thousands of flags and users, while maintaining flexibility for future enhancements like advanced filtering or analytics.

13. Scalability Deep Dive

Bottleneck Identification per Component

API Layer Bottlenecks:

  • Request parsing and validation: 500-1000ms per request at peak
  • Authentication/authorization overhead: 20-50ms per request
  • Rate limiting enforcement: 10-25ms per request

Database Bottlenecks:

  • Feature flag evaluation queries: 10-50ms per query
  • Read replicas: 2-5ms latency with proper sharding
  • Write operations: 15-30ms for flag creation/update

Cache Layer Bottlenecks:

  • Cache warming during service startup: 5-10s per cache instance
  • Cache invalidation propagation: 50-200ms across cluster

Service Layer Bottlenecks:

  • Flag evaluation logic: 5-20ms per flag check
  • Complex targeting rules processing: 10-50ms per rule

Horizontal vs. Vertical Scaling Decisions

Vertical Scaling:

  • Primary database (PostgreSQL) - vertical scaling up to 64vCPU/256GB RAM
  • Cache layer (Redis) - vertical scaling up to 32GB memory capacity
  • API gateway - vertical scaling for higher throughput

Horizontal Scaling:

  • Feature flag service instances - horizontal scaling via Kubernetes deployment
  • Cache cluster - horizontal scaling across multiple Redis instances with consistent hashing
  • Database - horizontal sharding by feature flag namespace or user segment

Database Scaling Path

  1. Single PostgreSQL instance - initial state with read replicas (2-3)
  2. Read replicas + connection pooling - handles 10k QPS peak
  3. Horizontal sharding by namespace - 500+ shards for 1M+ feature flags
  4. Distributed database (CockroachDB) - for cross-shard queries and global consistency

Stateless vs. Stateful Service Design Implications

Stateless Services:

  • Feature flag service instances can be scaled independently
  • No session affinity required for horizontal scaling
  • Easier to maintain consistent behavior across instances

Stateful Considerations:

  • Cache warming requires coordination between instances
  • Flag evaluation logic must be identical across all instances
  • Session-based targeting rules require state management

Session Affinity and Its Implications

Session Affinity Requirements:

  • No session affinity needed for feature flag evaluation
  • Targeting rules based on user identifiers require consistent hash routing

Impact of Session Affinity:

  • Increases cache hit rates by 15-25% for user-specific flags
  • Reduces need for cross-instance cache invalidation
  • Adds complexity to load balancing and service discovery

Performance Characteristics at Scale

Peak QPS Scaling:

  • 10k QPS → 50-100 feature flag evaluations per second
  • 100k QPS → 500-1000 feature flag evaluations per second
  • 1M QPS → 5k-10k feature flag evaluations per second

Memory Usage Projections:

  • 1M feature flags with 500 targets each = ~2GB cache memory
  • 10M feature flags with 500 targets each = ~20GB cache memory
  • Cache warming time increases linearly with flag count

Network Bandwidth Requirements:

  • 10k QPS peak = 5-10MB/s network traffic for cache updates
  • 100k QPS peak = 50-100MB/s network traffic for cache updates
  • Cache invalidation traffic increases by 20-30% during hot flag updates

Auto-scaling Strategy

Horizontal Pod Autoscaler (HPA):

  • Target: 70% CPU utilization per pod
  • Scale up: 5 pods per 1000 QPS increase
  • Scale down: 2 pods per 500 QPS decrease

Vertical Pod Autoscaler (VPA):

  • Target: 80% memory utilization per pod
  • Memory adjustment: 256MB increments for cache-heavy workloads

KEDA Scaling:

  • Target: 1000 pending feature flag evaluations per pod
  • Scale up: 1 pod per 500 pending requests
  • Scale down: 1 pod per 250 pending requests

Cache Invalidation Strategy Scaling

Cache Invalidation Patterns:

  • Real-time invalidation: 50ms delay for cache cluster propagation
  • Batch invalidation: 100-500ms delay for large flag updates
  • TTL-based invalidation: 30-60 second window for stale cache data

Scalability Impact:

  • 10k concurrent users = 500-1000 cache invalidations per second
  • 100k concurrent users = 5k-10k cache invalidations per second
  • Cache cluster size must scale linearly with concurrent user count

Data Partitioning Strategy for Scalability

Sharding by Feature Flag Namespace:

  • 1000 namespaces = 1000 shards for horizontal scaling
  • Each namespace can handle 10k feature flags
  • Cross-shard queries require distributed processing

Sharding by User Segment:

  • 1000 user segments = 1000 shards for targeting rules
  • Each segment can handle 10k concurrent users
  • Complex targeting logic requires cross-segment queries

Load Distribution Patterns

Request Distribution:

  • Round-robin distribution for basic feature flag queries
  • Consistent hashing for targeting-based queries to maintain cache locality
  • Priority-based distribution for critical feature flags

Traffic Shaping:

  • 80% of traffic to hot flags (pre-cached)
  • 20% of traffic to cold flags (evaluated on-demand)
  • Burst handling for 10x peak traffic scenarios

Performance Optimization Techniques

Pre-caching Strategy:

  • Hot flags pre-loaded into cache during service startup
  • User segment flags cached based on historical usage patterns
  • Flag evaluation logic compiled and cached for faster execution

Query Optimization:

  • Indexing strategies for feature flag metadata queries
  • Batch processing for multiple flag evaluations in single request
  • Caching of complex targeting rule results

Capacity Planning Considerations

Peak Load Projections:

  • 1M concurrent users = 50k QPS peak for feature flag evaluation
  • 10M concurrent users = 500k QPS peak for feature flag evaluation
  • 100M concurrent users = 5M QPS peak for feature flag evaluation

Resource Allocation:

  • CPU: 2-4 cores per pod for feature flag evaluation
  • Memory: 512MB-2GB per pod for cache and processing
  • Network: 100-500MB/s bandwidth for cache synchronization

Scaling Factors:

  • 10x increase in concurrent users = 10x increase in cache size
  • 10x increase in QPS = 5x increase in service instances
  • 10x increase in feature flags = 2x increase in database shards

14. Infrastructure & Deployment Architecture

Cloud Provider and Region Selection

For a global feature flag service, we'll target AWS as the primary cloud provider due to its mature ecosystem, extensive global footprint, and robust service offerings. The service will be deployed across multiple regions (us-east-1, us-west-2, eu-west-1) to ensure low-latency access and high availability. This multi-region strategy enables active-active deployment with automatic failover capabilities.

Kubernetes Cluster Design

We'll implement a multi-tenant Kubernetes architecture with dedicated clusters per environment (dev, staging, prod) to ensure isolation and security. Each cluster will use a namespace-based organization model:

  • feature-flag-dev for development
  • feature-flag-staging for pre-production testing
  • feature-flag-prod for production workloads

Resource quotas will be enforced per namespace to prevent resource contention. Cluster autoscaling will be enabled with appropriate node pool configurations for different workload types (compute-intensive vs. memory-intensive).

Container Image Strategy

All services will use multi-stage Docker builds to minimize image size and attack surface. Base images will be sourced from official repositories with regular security scanning integration. Images will be stored in AWS ECR (Elastic Container Registry) with immutable tags and automated vulnerability scanning via Trivy integration in CI/CD pipelines.

Deployment Strategy

The service will implement a blue-green deployment strategy with traffic shifting managed through AWS Application Load Balancer. Canary deployments will be used for new feature flag configurations with automated rollback triggers based on error rate thresholds (5% error rate over 5 minutes). Rollback procedures will be automated with pre-defined "safe" versions stored in the image registry.

Auto-Scaling Design

Horizontal Pod Autoscaling (HPA) will be configured for all stateless services based on CPU and memory utilization. Vertical Pod Autoscaling (VPA) will be used for services with unpredictable resource requirements. For event-driven workloads, KEDA (Kubernetes Event-Driven Autoscaler) will be implemented to scale based on message queue depth and feature flag evaluation rates.

Infrastructure as Code Approach

Infrastructure will be provisioned using Terraform with a modular approach:

  • VPC design with public and private subnets across multiple availability zones
  • IAM roles and policies for service-level permissions
  • Kubernetes cluster configuration with managed node groups
  • Network ACLs and security groups for traffic control

All infrastructure changes will be version-controlled in Git with automated validation through Terraform's plan/apply workflow. CI/CD pipelines will enforce infrastructure testing and compliance checks before any deployment.

Multi-Cluster Considerations

Production clusters will be deployed across multiple AWS regions with cross-region replication for disaster recovery. Cross-cluster communication will be handled through service mesh (Istio) to ensure consistent security policies and observability across all environments.

Resource Management

Resource requests and limits will be carefully tuned based on historical usage patterns. CPU and memory limits will be set to prevent resource starvation while allowing for burst capacity during peak load periods. Pod disruption budgets will be configured to ensure availability during maintenance windows.

Network Architecture

Services will communicate through internal Kubernetes services with mTLS enabled for cross-service communication. External traffic will be routed through AWS Application Load Balancer with WAF integration for DDoS protection and request filtering. All inter-service communication will utilize service mesh for observability, rate limiting, and security policy enforcement.

Monitoring Integration

Kubernetes cluster metrics will be collected through Prometheus with Grafana dashboards for capacity planning and performance monitoring. Cluster-level alerts will be configured for resource exhaustion, pod failures, and network connectivity issues. Auto-scaling policies will be integrated with alerting systems to prevent over-provisioning or under-provisioning scenarios.

15. Security Architecture

VPC Design and Network Segmentation

The Feature Flag Service operates within a multi-AZ VPC with public and private subnets. Public subnets host load balancers and API gateways, while private subnets contain application services and databases. All inter-service communication occurs within the private network using service mesh for mTLS and policy enforcement. Network ACLs and security groups implement strict ingress/egress rules with least-privilege access patterns.

Zero-Trust Network Model

All network traffic is treated as untrusted, requiring authentication and authorization at every hop. Service-to-service communication uses mTLS with certificate-based authentication through a service mesh (Istio). All external API calls are routed through the API gateway with strict validation and rate limiting. Network segmentation isolates sensitive data flows from general traffic.

TLS Termination Strategy

TLS termination occurs at the API gateway layer with certificate management handled by AWS Certificate Manager. All internal service-to-service communication uses mTLS through the service mesh, ensuring end-to-end encryption without exposing plaintext traffic within the cluster. Certificate rotation is automated with 90-day TTLs.

DDoS Protection Strategy

AWS Shield Advanced provides managed DDoS protection with automatic mitigation for Layer 3/4 attacks. Rate limiting and request throttling at the API gateway layer provide additional defense-in-depth against Layer 7 attacks. CloudFront integration provides global DDoS protection for public endpoints.

Secrets Management Architecture

Secrets are managed through AWS Secrets Manager with automatic rotation for credentials and tokens. Service accounts use IAM roles with least-privilege policies rather than hard-coded credentials. All secrets are encrypted at rest and in transit, with access controlled through IAM policies and service mesh identity.

Vulnerability Scanning in CI/CD

Container images are scanned for vulnerabilities using Trivy during the build process. Security scanning is integrated into the CI pipeline with automated blocking of images containing critical vulnerabilities. Dependency scanning ensures all third-party libraries meet security thresholds.

WAF Rules for Critical Endpoints

AWS WAF is configured with custom rules to protect critical endpoints from common attack patterns including SQL injection, XSS, and brute force attempts. Rules are updated quarterly based on threat intelligence feeds and security audit findings. WAF is configured to block malicious traffic before it reaches application services.

Data Protection and Encryption

All data at rest is encrypted using AWS KMS with customer-managed keys. Data in transit is protected through TLS 1.3 for external communications and mTLS for internal services. Database encryption uses AWS RDS encryption with automatic key rotation.

Access Control and Authentication

Authentication is handled through AWS Cognito with OAuth2/OIDC flows for external users. Internal service authentication uses JWT tokens with short TTLs (5-10 minutes) and automatic refresh mechanisms. Role-based access control (RBAC) is implemented with fine-grained permissions for feature flag operations.

Audit Logging and Compliance

All security-relevant events are logged to CloudWatch with structured JSON format for easy parsing. Audit logs include authentication attempts, authorization decisions, and configuration changes. Logs are retained for 90 days with automated archiving to S3 for compliance purposes.

Incident Response and Security Monitoring

Security monitoring is implemented through AWS Security Hub with automated security checks. Alerts are routed to PagerDuty for immediate response, with predefined runbooks for common security incidents. Security events are correlated across services to detect potential compromise scenarios.

Compliance and Regulatory Considerations

The system design addresses GDPR compliance through data encryption, access logging, and user consent mechanisms. Data residency is maintained within EU regions for customers requiring compliance with local data regulations. Audit trails support compliance reporting requirements.

Security Testing and Validation

Security testing includes regular penetration testing, vulnerability scanning, and automated security checks in CI/CD. Security controls are validated through periodic compliance audits and threat modeling exercises. All security measures undergo regular review and update cycles.

16. Deployment & Release Strategy

Deployment Strategy and Traffic Management

The Feature Flag Service will utilize a canary deployment strategy with progressive traffic shifting to ensure safe rollouts and minimize blast radius. The deployment pipeline will follow a blue-green approach for major version releases, with the new version running in parallel to the existing production environment.

Traffic management will be implemented through:

  • Gradual traffic shift (5% → 25% → 50% → 75% → 100%) over 30-minute intervals
  • Health check-based routing that monitors latency, error rates, and system load before shifting traffic
  • Automatic rollback triggers when error rates exceed 1% or latency exceeds p99 threshold of 500ms
  • Feature flag-based traffic control to allow fine-grained traffic routing by user segments, regions, or cohorts

Artifact Promotion Model

The deployment pipeline will follow a staged promotion model:

  1. Dev Environment: Continuous integration with automated unit and integration tests
  2. Staging Environment: Full end-to-end testing including performance and security scans
  3. Production Gates:
    • Manual approval for major version changes
    • Automated canary analysis with success criteria (95% of requests under 200ms latency)
    • Rollback capability if any threshold is exceeded

Zero-Downtime Database Migration Strategy

Database migrations will be executed using blue-green database strategy:

  • New schema is deployed to a separate database instance
  • Data is synchronized using CDC (Change Data Capture) or logical replication
  • Traffic is shifted to new database instance once synchronization is complete
  • Old database instance is decommissioned after validation period

Feature Flag Integration and Progressive Rollout Design

Feature flags will support progressive rollout through:

  • Gradual rollouts by user ID hash ranges (e.g., 0-10% → 10-20% → ... → 100%)
  • Segment-based rollouts (user attributes, cohorts, regions)
  • Time-based rollouts with scheduled flag activation/deactivation
  • Percentage-based rollouts using consistent hashing for stable user experience

Canary Analysis Automation and Auto-Rollback Triggers

Canary analysis will include:

  • Performance monitoring (p95 latency < 200ms, error rate < 1%)
  • System health checks (CPU utilization < 80%, memory usage < 85%)
  • Business metric validation (conversion rate, user engagement metrics)
  • Automated rollback when any metric exceeds thresholds for 5 consecutive minutes

Release Cadence and Branching Strategy

The system will follow a trunk-based development model with:

  • Daily builds for feature branches
  • Weekly major releases for stable feature sets
  • Hotfix branches for critical production issues (merged to trunk and hotfix branch)
  • Release branches created only for major version releases with feature freeze
  • Automated testing pipeline including unit, integration, performance, and security tests

Release Automation and Validation

Release automation will include:

  • Automated smoke testing on every deployment
  • Performance regression testing for all major releases
  • Security scanning in CI/CD pipeline (Snyk, Trivy)
  • Compliance validation checks for data protection and access control
  • Post-deployment monitoring with alerting thresholds for all critical metrics

Rollback and Recovery Strategy

The rollback strategy includes:

  • Automated rollback for failed canary deployments
  • Manual rollback capability with version pinning for production issues
  • Database schema rollback using migration scripts with reverse operations
  • Configuration backup and restore capability for feature flag settings
  • Service version rollback to previous stable versions with traffic shifting

Release Coordination and Communication

Release coordination will involve:

  • Pre-release communication to all stakeholders including product, QA, and operations teams
  • Release windows with defined maintenance periods (2-hour window for major releases)
  • Post-release validation monitoring for 24 hours after deployment
  • Release notes with impact assessment and rollback procedures
  • Incident response procedures for release-related issues with defined escalation paths

17. Cost Architecture

Major Cost Drivers Analysis

Compute Costs:

  • Container orchestration (Kubernetes) - 20-30% of total compute costs
  • API gateway and edge services - 15-25% of compute costs
  • Feature flag evaluation services - 10-15% of compute costs
  • Background processing and event handling - 10-20% of compute costs

Storage Costs:

  • Database storage (PostgreSQL, Redis) - 25-35% of total storage costs
  • Configuration and flag data - 15-20% of storage costs
  • Audit logs and telemetry - 10-15% of storage costs

Network & Data Transfer:

  • Cross-region data replication - 10-20% of network costs
  • API request/response traffic - 15-25% of data transfer costs
  • CDN and edge caching - 5-10% of network costs

External Service Costs:

  • Authentication provider (Auth0/Cognito) - 5-10% of total costs
  • Monitoring and observability tools (Datadog, X-Ray) - 5-10% of costs

Cost Optimization Strategy

Compute Optimization:

  • Use spot instances for non-critical background services (30% cost savings)
  • Implement auto-scaling with HPA and VPA to reduce idle compute (25% reduction)
  • Use multi-zone deployments to optimize for regional pricing (10-15% savings)
  • Implement connection pooling and efficient resource utilization in database clients

Storage Optimization:

  • Implement tiered storage with hot/warm/cold data classification (20-30% savings)
  • Use database query optimization and indexing to reduce I/O costs (15-20% savings)
  • Implement data compression for flag configurations and audit logs (10-15% savings)

Network Optimization:

  • Use CDN for static content and frequently accessed flag data (20-25% savings)
  • Implement efficient API response compression (10-15% savings)
  • Optimize cross-region replication timing and frequency (15-20% savings)

Reserved vs. Spot Instance Strategy

Reserved Instances:

  • Primary database instances (PostgreSQL) - 30% cost reduction
  • Core API services - 25% cost reduction
  • Monitoring and observability services - 20% cost reduction

Spot Instances:

  • Background processing jobs (flag evaluation, analytics) - 70% cost reduction
  • Non-critical event processing services - 60% cost reduction
  • Testing and staging environments - 50% cost reduction

Data Egress Cost Minimization

Cross-Region Traffic:

  • Implement regional edge caching to minimize cross-region data transfers (30-40% reduction)
  • Use service mesh for efficient inter-service communication within regions
  • Implement data locality patterns to reduce cross-region database queries

API Response Optimization:

  • Implement response compression (gzip/brotli) - 25% reduction in data transfer
  • Use selective field projection for flag configurations - 15% reduction in payload size
  • Implement efficient caching strategies to reduce redundant API calls

FinOps Dashboards and Budget Alerts

Cost Monitoring Dashboard:

  • Real-time cost allocation by service, region, and team
  • Historical trend analysis and forecasting
  • Anomaly detection for cost spikes and usage patterns

Budget Alerting:

  • Weekly budget alerts with 80%, 90%, and 100% thresholds
  • Monthly cost trend analysis with variance from budget
  • Automated alerting for over-provisioned resources (50%+ utilization)
  • Team-level cost allocation with budget tracking

Cost Optimization Recommendations:

  • Monthly resource optimization reports
  • Automated rightsizing recommendations for compute resources
  • Cost allocation tagging strategy for better visibility
  • Quarterly cost optimization review cycles with business stakeholders

18. Open Questions, Risks & Trade-offs

Decisions requiring product / engineering alignment

  • Feature flag vs. A/B testing strategy: Should feature flags be used for A/B testing, or should they be separate systems? This affects the API surface and data model complexity.
  • Flag evaluation vs. flag management: How granular should the flag evaluation logic be? Should it support complex conditional logic or remain simple for performance reasons?
  • Rollout strategy: What is the preferred rollout approach (gradual, percentage-based, or environment-based) and how should it be implemented in the system?

Key Architectural Risks

RiskImpactLikelihoodMitigation
Cache inconsistency across servicesHighMediumImplement cache invalidation strategies and use distributed locks for flag updates
Flag evaluation latency at scaleHighHighUse caching layers, pre-compute flag states, and implement efficient evaluation algorithms
Data loss in flag state persistenceHighMediumImplement multi-region replication and regular backups with strict RPO targets
Race conditions during flag updatesMediumMediumUse optimistic concurrency control or distributed locks for atomic updates
Feature flag drift between environmentsMediumHighImplement strict versioning and environment-specific flag management

Trade-offs made with justification

  • Consistency vs. Availability: Chose eventual consistency for flag evaluation to ensure high availability during network partitions, with strong consistency guarantees for critical flags through cache warming and sync mechanisms.
  • Performance vs. Flexibility: Prioritized fast flag evaluation over complex conditional logic, limiting flags to simple on/off or percentage-based rollouts with precomputed states.
  • Centralized vs. Distributed Flag Management: Chose centralized flag management for better control and auditability, accepting the single point of failure risk in exchange for simpler deployment and maintenance.
  • Real-time vs. Batch Updates: Implemented batched updates with real-time notifications for critical flags to reduce system load while maintaining responsiveness.

Alternatives considered and rejected

  • Redis-based flag service: Rejected due to single point of failure risks and complexity in maintaining consistent state across multiple instances.
  • Monolithic flag service: Rejected due to tight coupling with application code and difficulty in scaling independently.
  • Event-driven flag updates: Rejected due to increased complexity in managing event ordering and consistency, preferring simpler polling mechanisms for better reliability.
  • Full A/B testing platform: Rejected due to over-engineering for a feature flag service, focusing on core flag functionality and deferring advanced analytics to separate systems.

Technical debt acknowledged

  • Flag evaluation logic complexity: The current implementation assumes simple flag evaluation logic, which may require refactoring to support complex conditional expressions in future iterations.
  • Cache warming strategy: Current cache warming is basic and may not handle large-scale flag updates efficiently, requiring future enhancements to support dynamic warm-up strategies.
  • Audit logging granularity: Audit logs currently capture basic flag changes but lack detailed contextual information for debugging and compliance purposes, requiring future improvements to support comprehensive audit trails.

19. Phased Implementation Roadmap

Phase 1: MVP (Minimum Viable Product)

Timeline: 8-12 weeks Critical Path: Core feature flag management and evaluation

Deliverables:

  • Basic feature flag CRUD operations (create, read, update, delete)
  • Simple flag evaluation API with client-side SDK support
  • Core database schema for flags and targets
  • Basic configuration management (flag values, targeting rules)
  • Simple UI dashboard for flag management (read-only)
  • Basic authentication and authorization for admin users
  • Core service deployment pipeline with CI/CD

Dependencies:

  • Authentication & Authorization system (completed)
  • API Gateway integration (completed)
  • Basic Kubernetes cluster setup (completed)
  • Core database infrastructure (completed)

Milestones:

  • Week 4: Basic flag CRUD API ready
  • Week 6: Client SDK support (Java, Node.js)
  • Week 8: UI dashboard with basic flag management
  • Week 12: MVP deployment to staging environment

Phase 2: Scale & Hardening

Timeline: 12-16 weeks
Critical Path: Performance, reliability, and operational capabilities

Deliverables:

  • Advanced targeting rules (user segments, percentage rollouts)
  • Real-time flag updates with WebSocket or Server-Sent Events
  • Enhanced monitoring and alerting (SLIs/SLOs, error budgets)
  • Multi-region support with failover capability
  • Advanced caching layer with cache warming strategies
  • Database sharding and read replica configuration
  • Feature flag versioning and rollback capabilities
  • Comprehensive testing suite (unit, integration, load)
  • Enhanced security features (audit logs, compliance reporting)

Dependencies:

  • Caching architecture implementation (completed)
  • Messaging system for real-time updates (completed)
  • Multi-region infrastructure (completed)
  • Observability stack (completed)
  • Reliability engineering patterns (completed)

Milestones:

  • Week 16: Advanced targeting and rollout support
  • Week 20: Real-time flag updates capability
  • Week 24: Multi-region deployment and failover
  • Week 28: Enhanced monitoring and alerting system
  • Week 32: Production deployment with full feature set

Phase 3: Excellence & Optimization

Timeline: 16-20 weeks Critical Path: Advanced features, cost optimization, and operational excellence

Deliverables:

  • Advanced analytics and reporting dashboard
  • A/B testing capabilities with statistical significance calculations
  • Cost optimization features (storage tiering, query optimization)
  • Advanced security and compliance features (SOC2, GDPR)
  • Performance tuning and capacity planning tools
  • Automated migration and upgrade paths for legacy systems
  • Advanced feature flag lifecycle management (deprecation, retirement)
  • Integration with popular CI/CD tools and platforms
  • Comprehensive documentation and developer experience improvements

Dependencies:

  • Advanced observability stack (completed)
  • Cost architecture analysis (completed)
  • Security and compliance framework (completed)
  • CI/CD pipeline enhancements (completed)
  • Advanced caching strategies (completed)

Milestones:

  • Week 36: A/B testing and analytics dashboard
  • Week 40: Cost optimization and performance tuning
  • Week 44: Advanced security and compliance features
  • Week 48: Integration with popular platforms (GitHub, Jenkins, etc.)
  • Week 52: Production-grade excellence and documentation

Critical Path Dependencies:

  1. Authentication & Authorization system (Phase 1)
  2. API Gateway and edge layer (Phase 1)
  3. Database and caching architecture (Phase 1)
  4. Multi-region infrastructure (Phase 2)
  5. Observability stack (Phase 2)

Risk Mitigation:

  • Technical Debt: Regular refactoring cycles every 6 weeks
  • Performance Bottlenecks: Load testing and capacity planning in Phase 2
  • Security Gaps: Security review cycles every 4 weeks across all phases
  • Operational Risks: Comprehensive runbook development for each phase

Success Metrics:

  • 99.9% availability target across all phases
  • <200ms p95 response time for flag evaluation API
  • <50ms p99 response time for real-time updates
  • 100% feature flag coverage in production systems by Phase 3
  • <5% error rate in flag evaluation operations

Was this article helpful?

Topics in this article

More from Backend HLD

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.