Title: Best Practices Locale: en URL: https://sensorswave.com/en/docs/feature-gates/best-practices/ Description: Master the best practices and implementation recommendations for Feature Gates This article summarizes best practices for using Feature Gates, helping you use them more effectively and avoid common pitfalls. ## Business classification of Feature Gates > **Note**: The following gate type classification is a suggested management approach, not a built-in product feature. You can define your own classification standards based on your team's needs. Based on business needs and use cases, we recommend classifying Feature Gates into the following three types: ### Temporary gates **Definition**: Used for releasing and validating new features. Should be deleted once the feature is stable. **Use cases**: - Gradual rollout of new features - Feature stability validation - Pre-stage for short-term A/B tests **Lifecycle**: 1. Create the gate, disabled by default 2. Gradually roll out and verify stability 3. After full release, remove gate checks from code 4. Archive or delete the Feature Gate **Example**: ```javascript // Temporary gate: New recommendation algorithm const useNewAlgorithm = await SensorsWave.checkFeatureGate('new_recommendation_algorithm'); ``` **Best practice**: Temporary gates should be cleaned up within 1-2 months after full release to avoid accumulating unused gates. ### Permanent gates **Definition**: Used for long-term feature tiering, where different user groups see different features. **Use cases**: - Paid feature control - User tier permissions - Regional customization - Enterprise vs Basic edition features **Lifecycle**: - Exists long-term, tied to product features - Rules may be adjusted as the product evolves - Typically not deleted **Example**: ```javascript // Permanent gate: Advanced analytics (paid users only) const hasAdvancedAnalytics = await SensorsWave.checkFeatureGate('advanced_analytics_access'); ``` **Management recommendation**: Permanent gates are typically associated with user properties (such as `subscription_level`). It's recommended to reflect the business purpose in the gate name. ### Ops gates **Definition**: Used for system operations and emergency response, quickly disabling non-critical features. **Use cases**: - Feature degradation safeguard - Rate limiting and circuit breaking - Dependency service isolation - Emergency fault recovery **Lifecycle**: - Exists long-term, normally kept enabled - Quickly disabled during failures - Re-enabled after recovery **Example**: ```javascript // Ops gate: Recommendation system switch (disabled under high load) const recommendationEnabled = await SensorsWave.checkFeatureGate('recommendation_system_enabled'); if (recommendationEnabled) { // Call the recommendation algorithm recommendations = await getRecommendations(userId); } else { // Fallback: use default recommendations recommendations = getDefaultRecommendations(); } ``` **Management recommendation**: Core business workflows should have Ops Gates configured to ensure normal operation when dependent services fail. ### Type comparison | Dimension | Temporary gates | Permanent gates | Ops gates | |-----------|----------------|-----------------|-----------| | **Lifecycle** | Short-term (weeks to months) | Long-term (exists with the product) | Long-term (exists with the system) | | **Default state** | Typically disabled | Determined by user properties | Typically enabled | | **Adjustment frequency** | Frequently adjusted during rollout | Rarely adjusted | Operated during failures | | **Cleanup strategy** | Should be removed after full release | Not removed | Not removed | | **Typical scenarios** | New feature releases | Paid features, permission control | Feature degradation, rate limiting | ### How to apply classification in your team 1. **Establish naming conventions**: Reflect the type in the gate name, such as `temp_*`, `perm_*`, `ops_*` 2. **Document records**: Note the type and expected lifecycle in the gate description 3. **Regular review**: Review temporary gates monthly and clean up completed features promptly 4. **Periodic checks**: Periodically check the status and coverage of Ops Gates ## Naming conventions ### Gate naming principles **Use clear, descriptive names**: ``` ✅ Recommended recommendation_algorithm_v2 payment_wechat_pay_enabled user_profile_redesign_2024 ❌ Not recommended flag1 test new_feature temp_switch ``` ### Naming format **Use snake_case format**: - All lowercase letters - Words connected by underscores - Avoid camelCase naming **Add module prefixes**: ``` recommendation_new_algorithm payment_alipay_enabled user_email_verification checkout_express_mode ``` **Include version information (when applicable)**: ``` recommendation_algorithm_v2 checkout_flow_2024 ui_redesign_phase2 ``` ### Naming checklist Before creating a Feature Gate, verify the name meets these standards: - [ ] Uses snake_case format - [ ] Name clearly describes the feature - [ ] Appropriate length (15-40 characters) - [ ] Includes a module prefix - [ ] Doesn't use overly generic names (for example, test, flag) - [ ] Team members can understand its meaning ## Lifecycle management ### Temporary gate lifecycle **Creation phase**: 1. Define the gate's usage timeline 2. Specify the expected removal date in the description 3. Set a reminder to avoid forgetting **Usage phase**: 1. Proceed with the gradual rollout as planned 2. Monitor key metrics 3. Record important decisions and changes **Cleanup phase**: 1. After full release, run stably for 1-2 months 2. Remove gate checks from code 3. Archive the Feature Gate 4. Delete after confirming it's no longer needed ### Permanent gate management **Regular review**: - Review permanent gates quarterly - Confirm whether they are still needed - Evaluate whether rules can be simplified **Documentation maintenance**: - Keep description information current - Record use cases and considerations - Update related wiki documentation ### Ops gate management **Normally kept enabled**: - Default value set to enabled - Only disabled during failures **Drills and testing**: - Regularly drill the degradation process - Verify that the degradation plan works - Ensure the team is familiar with the operating procedures **Documentation**: - Record the reason for each use - Summarize lessons learned - Improve the degradation plan ## Code organization ### Code location **Centrally manage Feature Gates**: ```javascript // ✅ Recommended: Define Feature Gates centrally // src/config/featureGates.js NEW_RECOMMENDATION: 'recommendation_algorithm_v2', WECHAT_PAY: 'payment_wechat_pay_enabled', USER_PROFILE_REDESIGN: 'user_profile_redesign', }; // Reference when using const isEnabled = await SensorsWave.checkFeatureGate(FeatureGates.NEW_RECOMMENDATION); ``` ```javascript // ❌ Not recommended: Hardcoded strings const isEnabled = await SensorsWave.checkFeatureGate('recommendation_algorithm_v2'); ``` **Advantages**: - Centralized management for easy overview of all gates - Prevents typos - Easier to refactor and delete ### Code structure **Keep code concise**: ```javascript // ✅ Recommended: Concise conditional logic const useNewAlgorithm = await SensorsWave.checkFeatureGate('new_algorithm'); const recommendations = useNewAlgorithm ? await getRecommendationsV2(userId) : await getRecommendationsV1(userId); ``` ```javascript // ❌ Not recommended: Overly complex nesting const isEnabled = await SensorsWave.checkFeatureGate('new_algorithm'); if (isEnabled) { if (someOtherCondition) { // Multiple levels of nesting } } else { // ... } ``` **Extract functions**: ```javascript // ✅ Recommended: Extract a function to keep the main flow clear async function getRecommendations(userId) { const useNewAlgorithm = await SensorsWave.checkFeatureGate('new_algorithm'); return useNewAlgorithm ? await getRecommendationsV2(userId) : await getRecommendationsV1(userId); } // Main flow const recommendations = await getRecommendations(userId); displayRecommendations(recommendations); ``` ### Avoid overuse **Don't create a gate for every small change**: ```javascript // ❌ Not recommended: Overuse const buttonColor = await SensorsWave.checkFeatureGate('button_color_blue'); const fontSize = await SensorsWave.checkFeatureGate('font_size_14'); const padding = await SensorsWave.checkFeatureGate('padding_10'); ``` ```javascript // ✅ Recommended: Create gates for meaningful features const useNewTheme = await SensorsWave.checkFeatureGate('new_theme_2024'); if (useNewTheme) { applyNewTheme(); } else { applyLegacyTheme(); } ``` ## Testing strategy ### Unit tests **Test both scenarios**: ```javascript // Test behavior when the feature is enabled test('should use new algorithm when gate is enabled', async () => { // Mock the Feature Gate to return true jest.spyOn(SensorsWave, 'checkFeatureGate').mockResolvedValue(true); const recommendations = await getRecommendations('user_123'); expect(recommendations).toEqual(expectedV2Results); }); // Test behavior when the feature is disabled test('should use legacy algorithm when gate is disabled', async () => { // Mock the Feature Gate to return false jest.spyOn(SensorsWave, 'checkFeatureGate').mockResolvedValue(false); const recommendations = await getRecommendations('user_123'); expect(recommendations).toEqual(expectedV1Results); }); ``` ### Integration tests **Test the complete flow**: ```javascript test('should complete checkout with new flow', async () => { // Enable the new checkout flow await enableFeatureGate('new_checkout_flow'); // Execute the checkout flow await goToCheckoutPage(); await fillShippingInfo(); await selectPaymentMethod(); await confirmOrder(); // Verify the result expect(orderCreated).toBe(true); }); ``` ### Test coverage Ensure sufficient test coverage for Feature Gate-related code: - Feature enabled scenario - Feature disabled scenario - Fallback scenario (SDK failure) - Edge cases ## Performance optimization ### Caching strategy **Use local caching**: ```javascript // The SDK caches configuration by default, avoiding frequent requests const isEnabled = await SensorsWave.checkFeatureGate('new_feature'); ``` ### Reduce repeated queries **Cache query results at the call site**: ```javascript // ✅ Recommended: Query once, reuse in multiple places const isEnabled = await SensorsWave.checkFeatureGate('feature_1'); // Reuse the isEnabled variable in subsequent logic ``` ### Avoid too many gates **Control gate count**: - Recommended: fewer than 100 Feature Gates per project - Regularly clean up unused gates - Avoid creating a gate for every small change **Consolidate related gates**: ```javascript // ❌ Not recommended: Too many fine-grained gates const showButton = await SensorsWave.checkFeatureGate('show_button'); const showIcon = await SensorsWave.checkFeatureGate('show_icon'); const showText = await SensorsWave.checkFeatureGate('show_text'); // ✅ Recommended: Consolidate into one gate const useNewUI = await SensorsWave.checkFeatureGate('new_ui_redesign'); if (useNewUI) { // New UI includes all changes renderNewUI(); } ``` ## Team collaboration ### Documentation standards **Maintain documentation for each Feature Gate**: 1. **Console description**: ``` New recommendation algorithm (deep learning-based), expected to improve click-through rate by 15%. Used for gradual rollout to verify stability and effectiveness. Estimated 2 weeks for rollout, gate to be removed after full release. Related requirement: PROJ-1234 Owner: Zhang San ``` 2. **Code comments**: ```javascript // Feature Gate: New recommendation algorithm // Created: 2024-01-15 // Expected removal: 2024-03-15 // Documentation: https://wiki.example.com/recommendation-v2 const useNewAlgorithm = await SensorsWave.checkFeatureGate('recommendation_algorithm_v2'); ``` 3. **Wiki documentation**: - Feature description - Use cases - Configuration details - Considerations ### Communication practices **Pre-release communication**: - Share the gradual rollout plan in team meetings - Notify relevant teams (support, ops, QA) - Prepare contingency plans **During release communication**: - Share daily rollout progress - Promptly report discovered issues - Inform relevant people when plans change **Post-release retrospective**: - Record key data and decisions - Summarize lessons learned - Share with team members ### Permission management **Establish clear responsibility divisions**: - Developers: Create and edit Feature Gates - QA: Validate Feature Gate configurations - Ops: Operate Ops Gates during emergencies - Admins: Approve and archive **Exercise caution in production**: - Production configuration changes require approval - Critical Feature Gates require dual confirmation - All operations are recorded in audit logs ## Do's and don'ts ### Recommended practices **✅ Create Feature Gates for all new features**: - Reduce release risk - Enable progressive rollout **✅ Use clear, descriptive naming**: - Easy to understand and maintain - Avoid confusion and errors **✅ Specify default values in code**: - Serves as a fallback - Ensures the app runs even if the SDK fails **✅ Regularly clean up unused gates**: - Keep the codebase clean - Reduce maintenance costs **✅ Monitor key metrics**: - Discover issues promptly - Enable data-driven decisions **✅ Maintain documentation**: - Facilitate team collaboration - Knowledge preservation ### Practices to avoid **❌ Don't skip gradual rollout and go straight to full release**: - Problem impact scope is uncontrollable - Lose the opportunity for quick validation **❌ Don't use overly simple names**: - `flag1`, `test`, `temp`, etc. - Difficult to understand and maintain **❌ Don't call frequently within loops**: ```javascript // ❌ Not recommended for (const item of items) { const isEnabled = await SensorsWave.checkFeatureGate('feature'); // ... } // ✅ Recommended: Query once outside the loop const isEnabled = await SensorsWave.checkFeatureGate('feature'); for (const item of items) { // Use isEnabled } ``` **❌ Don't accumulate too many unused gates**: - Affects performance - Increases maintenance cost - Code becomes difficult to understand **❌ Don't test directly in production**: - Validate in development/staging environments first - Confirm configuration is correct before releasing to production **❌ Don't neglect fallback handling**: ```javascript // ❌ Not recommended: No fallback handling const isEnabled = await SensorsWave.checkFeatureGate('new_feature'); // ✅ Recommended: checkFeatureGate automatically returns false when configuration is unavailable const isEnabled = await SensorsWave.checkFeatureGate('new_feature'); // You can use the return value directly — the SDK has built-in fallback logic ``` ## Implementation recommendations ### Using Feature Gates for the first time **Start with a simple scenario**: 1. Choose a low-risk feature 2. Create and configure a Feature Gate 3. Implement a gradual rollout 4. Summarize the experience **Gradual adoption**: 1. Share the experience within the team 2. Establish team standards 3. Extend to more features 4. Continuously optimize the process ### Establishing team standards **Create standard documentation**: - Naming conventions - Usage workflows - Approval processes - Cleanup strategies **Tools and templates**: - Feature Gate creation template - Gradual rollout checklist - Monitoring dashboard template **Training and sharing**: - New member onboarding - Regular best practice sharing - Case study retrospectives ### Continuous improvement **Collect feedback**: - Team member usage experience - Problems and difficulties encountered - Improvement suggestions **Optimize processes**: - Simplify operational workflows - Improve tools and documentation - Automate common operations **Metric evaluation**: - Release success rate - Issue detection time - Rollback frequency - Team satisfaction ## Checklists ### When creating a Feature Gate - [ ] Name follows conventions - [ ] Description is clear and complete - [ ] Reasonable default value set - [ ] Related documentation links added ### Before release - [ ] Validated in the test environment - [ ] Gradual rollout plan created - [ ] Rollback plan prepared - [ ] Relevant teams notified ### During rollout - [ ] Check monitoring metrics daily - [ ] Collect user feedback - [ ] Record important decisions - [ ] Proceed or rollback according to plan ### After full release - [ ] Continue monitoring for 1-2 weeks - [ ] Confirm all metrics are stable - [ ] Plan Feature Gate cleanup - [ ] Summarize lessons learned ### During cleanup - [ ] Remove gate checks from code - [ ] Delete old code - [ ] Archive the Feature Gate - [ ] Update related documentation ## Next steps Now that you understand the best practices for Feature Gates, you can: 1. **[FAQ](faq.mdx)**: Find answers to common questions 2. **[Quick Start](quick-start.mdx)**: Create your first Feature Gate --- **Last updated**: January 28, 2026