Feature flags are a powerful technique that allows you to control the availability of features in real time. Let's explore how to implement them effectively in your production environment.
What are Feature Flags?
Feature flags (or feature toggles) are mechanisms that allow:
- Activate/deactivate features without deployment
- Test features with specific users
- Make quick rollbacks in case of problems
- Implement gradual rollouts
Types of Feature Flags
1. By Environment
interface EnvironmentFlag { name: string; environments: { development: boolean; staging: boolean; production: boolean; }; default: boolean; }
2. Per User
interface UserFlag { name: string; type: 'percentage' | 'specific' | 'custom'; rules: { percentage?: number; userIds?: string[]; customRule?: (user: User) => boolean; }; }
Practical Implementation
1. Base Structure
class FeatureFlagManager { private flags: Map<string, FeatureFlag>; constructor() { this.flags = new Map(); } isEnabled(flagName: string, context: FlagContext): boolean { const flag = this.flags.get(flagName); if (!flag) return false; return flag.evaluate(context); } async updateFlag(flagName: string, config: FlagConfig): Promise<void> { // Implementação da atualização } }
2. Backend Integration
// Exemplo com Express app.use(async (req, res, next) => { const context = { userId: req.user?.id, environment: process.env.NODE_ENV, timestamp: Date.now() }; req.featureFlags = await featureFlagManager.getFlags(context); next(); });
Gradual Rollouts
1. Rollout Strategies
A gradual rollout progresses in stages, broadening exposure as confidence grows. A typical progression starts from the finished feature and goes like this:
- 5%, beta users, the first group to receive the news.
- 25%, active users, with the feature already validated in the initial group.
- 50%, majority of users.
- 100%, availability for the entire base.
Each jump only happens after the metrics from the previous stage confirm stability.
2. Monitoring
interface RolloutMetrics { flagName: string; totalUsers: number; enabledUsers: number; errorRate: number; performanceMetrics: { responseTime: number; errorCount: number; }; }
Tools and Services
1. Self-hosted
-
🏠 Unleash
- Open source
- Full control
- REST API
- Dashboard
-
🏢 Flagsmith
- SDKs for multiple languages
- A/B testing
- Analytics
2. Cloud-based
-
☁️ LaunchDarkly
- Centralized management
- Advanced analytics
- Ready-made integrations
-
🌐 Split.io
- Experimentation
- Advanced segmentation
- Real-time monitoring
Good Practices
1. Nomenclature
// Exemplos de nomes claros const FLAGS = { NEW_CHECKOUT_FLOW: 'new-checkout-flow-v2', DARK_MODE_BETA: 'dark-mode-beta-test', PAYMENT_GATEWAY_MIGRATION: 'payment-gateway-migration' };
2. Documentation
Each flag deserves a short, standardized form. For new-checkout-flow-v2, for example, the documentation would cover:
- Description: implementation of the new version of the checkout flow.
- States: Development enabled, Staging enabled, Production in gradual rollout (25%).
- Dependencies: Payment Gateway v2 and Address Validation Service.
- Rollout plan: 5% (beta), 25% (active), 50% (majority), 100% (all).
This record prevents flags from becoming forgotten technical debt and gives context to those who need to decide whether to move forward or remove the flag.
Monitoring and Alerts
1. Essential Metrics
interface FlagMetrics { name: string; enabledCount: number; totalRequests: number; errorRate: number; performanceImpact: { p50: number; p95: number; p99: number; }; }
2. Alerts
alerts: - name: high_error_rate condition: error_rate > 1% action: disable_flag - name: performance_degradation condition: p95 > 500ms action: notify_team
Use Cases
1. Secure Rollout
The safe rollout cycle closes a feedback loop between four actors. The developer activates the flag for an initial fraction of users (5%). The feature flag feeds the monitoring system with usage, error and performance metrics. Monitoring compares these numbers with the defined thresholds and, whenever a limit is exceeded, the alert system notifies the developer, who decides to advance the rollout or reverse it. It is this continuous loop that makes incremental delivery safe.
2. Fast Rollback
async function handleError(flagName: string, error: Error) { // Desativa flag imediatamente await featureFlagManager.disable(flagName); // Notifica equipe await notifyTeam({ type: 'FLAG_ERROR', flagName, error: error.message, timestamp: new Date() }); // Registra métricas await metrics.recordRollback(flagName); }
Conclusion
Feature flags are essential for:
- Secure deployment
- Production testing
- Fast Rollbacks
- Controlled experiments
- Effective monitoring
Next Steps
- Choose your tool
- Define naming standards
- Implement monitoring
- Create documentation
- Train the team
Want to share your experience with feature flags? Leave a comment below!
Also read
- Feature Flags: Complete Guide to Secure Releases
- Feature flags: tools and what to consider before adopting in the company
- Feature flags in startups: the tools that are worth the investment
- KV for rate limiting, feature flags and distributed configuration: where it works and where it breaks
- Docker for Production: Building Light and Secure Images
- Kubernetes in production: what no one tells you before you migrate
