A production application rarely changes in just one way. Developers introduce new features, modify existing workflows, integrate third-party services, and update business rules. However, deploying a new version does not always mean every user should immediately receive those changes.
Consider an e-commerce application running on Google Cloud Run. The development team has completed a new checkout experience, but the product team wants to release it to only 10% of users initially. If the checkout process causes unexpected errors, the team should be able to disable the new experience without rebuilding or redeploying the application.
This is where feature flags become useful.
Feature flags allow developers to control application behavior independently of the deployment process. Instead of maintaining separate code branches or deploying different application versions for every release decision, developers can use configuration to decide which features are active.
When combined with Cloud Run, feature flags provide a practical approach to gradual releases, controlled rollouts, experiments, and emergency feature shutdowns.
Understanding Feature Flags
A feature flag is a configuration value that determines whether a particular feature or behavior should be enabled.
For example, an application might contain the following features:
- New checkout experience.
- AI-powered product recommendations.
- Updated dashboard.
- Additional payment provider.
- New customer registration workflow.
Without feature flags, enabling or disabling these features may require code changes and a new deployment.
With feature flags, the application checks a configuration value before executing the relevant functionality.
Consider a simple C# example:
if (featureFlags.EnableNewCheckout)
{
return await ProcessNewCheckoutAsync(request);
}
return await ProcessLegacyCheckoutAsync(request);The application contains both implementations, but the configuration determines which one executes.
The important distinction is that deploying code and enabling a feature become two separate operations.
A new feature can be deployed but remain disabled until the team is ready to activate it.
Why Feature Flags Are Useful in Cloud Run
Cloud Run makes it straightforward to deploy containerized applications without managing servers. It supports revisions, traffic allocation, automatic scaling, and configuration through environment variables and other runtime settings.
Cloud Run traffic splitting can direct a percentage of requests to different revisions. This is useful for testing a new application version alongside an existing version.
However, revision-based traffic splitting and feature flags solve different problems.
Suppose an application contains three new features:
- New checkout.
- Updated dashboard.
- AI recommendations.
If all three features are included in a new Cloud Run revision, traffic splitting sends requests to that revision as a whole. It does not independently control each feature.
A feature flag allows the application to make those decisions separately.
For example:
Cloud Run Application
|
v
Feature Flag Configuration
|
+---- New Checkout: Enabled
|
+---- Updated Dashboard: Disabled
|
+---- AI Recommendations: EnabledThis gives product teams more control over individual capabilities without creating a separate deployment for every combination of features.
Feature flags can also help with:
- Gradual feature releases.
- Internal testing before public release.
- Customer-specific functionality.
- A/B testing.
- Emergency feature shutdowns.
- Separating deployment decisions from release decisions.
Using Environment Variables for Simple Feature Flags
The simplest way to introduce feature flags in a Cloud Run application is through environment variables.
This approach works well when the application has only a few flags and configuration changes do not need to happen frequently.
Consider an ASP.NET Core application.
Add the following configuration to appsettings.json:
{
"FeatureFlags": {
"EnableNewCheckout": false,
"EnableAiRecommendations": true
}
}Create a configuration model:
public class FeatureFlags
{
public bool EnableNewCheckout { get; set; }
public bool EnableAiRecommendations { get; set; }
}Register the configuration in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<FeatureFlags>(
builder.Configuration.GetSection("FeatureFlags"));
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();The application can now access the feature settings through dependency injection.
For example:
using Microsoft.Extensions.Options;
[ApiController]
[Route("api/checkout")]
public class CheckoutController : ControllerBase
{
private readonly FeatureFlags _features;
public CheckoutController(
IOptions<FeatureFlags> options)
{
_features = options.Value;
}
[HttpPost]
public IActionResult ProcessCheckout()
{
if (_features.EnableNewCheckout)
{
return Ok("New checkout is enabled");
}
return Ok("Legacy checkout is active");
}
}When deploying the application to Cloud Run, override the configuration using environment variables.
gcloud run deploy ecommerce-api \
--image=us-docker.pkg.dev/my-project/apps/ecommerce-api:latest \
--region=us-central1 \
--set-env-vars="FeatureFlags__EnableNewCheckout=false,FeatureFlags__EnableAiRecommendations=true"The double underscore maps to the configuration hierarchy used by ASP.NET Core.
For example, FeatureFlags__EnableNewCheckout maps to FeatureFlags:EnableNewCheckout.
This allows the same container image to run with different feature settings.
However, environment variables are part of the Cloud Run revision configuration. Changing them creates a new revision. This means environment variables are suitable for deployment-specific configuration, but they are not ideal when a product team needs to enable or disable a feature immediately without creating another revision.
Managing Feature Flags With Cloud Run and Firestore
When feature flags need to change independently of deployments, a centralized configuration store is a better option.
Firestore can store feature flag definitions and allow an application to retrieve them at runtime.
Consider the following document in a Firestore collection named FeatureFlags:
{
"EnableNewCheckout": true,
"EnableAiRecommendations": false,
"EnableNewDashboard": true
}The application reads this document and uses its values to decide which features are active.
A simple C# service can represent the configuration:
public class FeatureFlagSettings
{
public bool EnableNewCheckout { get; set; }
public bool EnableAiRecommendations { get; set; }
public bool EnableNewDashboard { get; set; }
}The following service reads the configuration from Firestore:
using Google.Cloud.Firestore;
public class FeatureFlagService
{
private readonly FirestoreDb _firestore;
public FeatureFlagService(FirestoreDb firestore)
{
_firestore = firestore;
}
public async Task<FeatureFlagSettings> GetFlagsAsync()
{
var document = _firestore
.Collection("FeatureFlags")
.Document("Application");
var snapshot = await document.GetSnapshotAsync();
if (!snapshot.Exists)
{
return new FeatureFlagSettings();
}
return snapshot.ConvertTo<FeatureFlagSettings>();
}
}Register the Firestore client and service:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(
_ => FirestoreDb.Create("my-project"));
builder.Services.AddScoped<FeatureFlagService>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();The application can retrieve the latest configuration when it needs to evaluate a feature.
For example:
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly FeatureFlagService _flags;
public ProductsController(FeatureFlagService flags)
{
_flags = flags;
}
[HttpGet("recommendations")]
public async Task<IActionResult> GetRecommendations()
{
var flags = await _flags.GetFlagsAsync();
if (!flags.EnableAiRecommendations)
{
return Ok(new
{
Message = "Recommendations are currently unavailable"
});
}
return Ok(new
{
Message = "AI recommendations are enabled"
});
}
}This example demonstrates the basic integration. A production application should avoid reading Firestore on every request. Instead, use a cache with a controlled refresh interval, handle Firestore failures, and define safe defaults for important features.
The key advantage is that the team can update the Firestore document without deploying a new Cloud Run revision.
Using Cloud Run With Remote Feature Flag Configuration
For applications with multiple services, environments, and development teams, maintaining feature flags in individual configuration documents can become difficult.
A dedicated feature management platform provides a more complete solution.
For example, OpenFeature offers a vendor-neutral API for evaluating feature flags. A feature flag provider supplies the actual flag values, while the application uses a consistent interface to evaluate them.
This separates the application code from the feature management platform.
A simplified example using the OpenFeature .NET SDK looks like this:
using OpenFeature;
using OpenFeature.Model;
var client = Api.Instance.GetClient();
var enabled = await client.GetBooleanValueAsync(
"new-checkout",
false,
EvaluationContext.Empty);
if (enabled)
{
Console.WriteLine("New checkout is enabled");
}
else
{
Console.WriteLine("Legacy checkout is active");
}The code evaluates a Boolean flag named new-checkout.
The default value is false. If the provider cannot return a valid value, the application has a defined fallback.
The OpenFeature API does not itself store or manage flag values. A compatible provider must be configured and initialized before the application evaluates flags.
This architecture is useful when an organization wants to change providers without rewriting feature evaluation throughout its application.
A dedicated platform can also provide targeting rules, percentage rollouts, user attributes, audit history, and management interfaces.
Implementing Percentage-Based Feature Rollouts
A common requirement is to release a new feature to a small percentage of users before enabling it for everyone.
For example, the product team may want to enable a new checkout experience for 10% of customers.
A simple implementation can use a stable user identifier and a deterministic hash.
public static class FeatureRollout
{
public static bool IsEnabledForUser(
string userId,
int rolloutPercentage)
{
if (rolloutPercentage <= 0)
return false;
if (rolloutPercentage >= 100)
return true;
var hash = System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.UTF8.GetBytes(userId));
var value = BitConverter.ToUInt32(hash, 0) % 100;
return value < rolloutPercentage;
}
}The application can use this method to decide whether a user belongs to the rollout group.
var enabled = FeatureRollout.IsEnabledForUser(
currentUser.Id,
10);Because the hash is based on a stable user identifier, the same user receives a consistent result across requests and application instances.
This is important in Cloud Run because requests can be handled by different container instances.
A random number generated for every request would not provide consistent behavior. The same user might see the new checkout on one request and the old checkout on another.
For production systems, percentage rollout logic should also consider tenant boundaries, user targeting, experiment assignment, and the need to keep related features consistent.
A dedicated feature management provider is usually preferable when these requirements become complex.
Managing Feature Flag Configuration Across Cloud Run Environments
Most applications have multiple environments, such as development, staging, and production.
A feature that is enabled in development may need to remain disabled in production until testing is complete.
Feature flag configuration should therefore be separated by environment.
For example:
| Feature | Development | Staging | Production |
|---|---|---|---|
| New Checkout | Enabled | Enabled | Disabled |
| AI Recommendations | Enabled | Enabled | 10% rollout |
| New Dashboard | Enabled | Disabled | Disabled |
The application should identify its environment and retrieve the corresponding configuration.
Do not use one shared feature flag document for every environment unless the application has a deliberate strategy for separating environment-specific values.
For a Firestore implementation, separate collections or documents can be used for each environment.
For example:
FeatureFlags
|
+---- Development
|
+---- Staging
|
+---- ProductionA centralized feature management platform can also provide environment-specific flag definitions and permissions.
This helps prevent accidental activation of unfinished features in production.
Handling Feature Flag Failures in Production
Feature flag configuration becomes part of the application's runtime dependency chain.
If the configuration provider becomes unavailable, the application must have a clear fallback strategy.
For example, consider a payment feature that is being introduced gradually.
If the application cannot retrieve the flag value, should it enable the new payment flow or continue using the existing implementation?
The answer depends on the business risk.
A useful approach is to define safe defaults for every flag.
var enabled = await client.GetBooleanValueAsync(
"new-payment-flow",
false,
EvaluationContext.Empty);In this example, the new payment flow remains disabled when the provider cannot return a value.
For a non-critical visual feature, a different fallback may be acceptable.
Production implementations should also consider:
- Caching recently evaluated flag values.
- Setting a maximum cache lifetime.
- Handling provider timeouts.
- Monitoring configuration retrieval failures.
- Keeping critical functionality available when the provider is unavailable.
- Avoiding repeated configuration requests for every application operation.
A feature flag should not become a single point of failure for the entire application.
Feature Flags and Cloud Run Traffic Splitting Are Not the Same
Cloud Run supports traffic allocation across service revisions.
For example, a team can direct 90% of requests to an existing revision and 10% to a new revision.
This is useful for gradually introducing a new application version.
Feature flags operate at a different level.
| Capability | Cloud Run traffic splitting | Feature flags |
|---|---|---|
| Controls | Application revisions | Individual features |
| Main purpose | Version rollout | Feature release |
| Requires a new revision | Yes, when deploying a new version | Not necessarily |
| Percentage-based control | Based on traffic | Can be based on users or other targeting rules |
| Feature-level targeting | Not built in | Supported by the flag implementation |
These approaches can work together.
For example, a team can deploy a new Cloud Run revision, direct a small percentage of traffic to it, and keep its new checkout feature disabled until the team is ready.
This provides control over both application deployment and feature activation.
Best Practices for Production Applications
Feature flags are useful, but they can become difficult to maintain if every feature is controlled by a permanent configuration value.
A few practices help keep the implementation manageable.
Use descriptive names. Names such as enable-new-checkout or enable-ai-recommendations are easier to understand than feature1 or test-flag.
Define a default value. Every flag should have a safe fallback when configuration cannot be retrieved.
Keep flag evaluation consistent. Use stable user or tenant identifiers for percentage rollouts rather than random decisions on every request.
Avoid checking the same flag repeatedly within a single operation if its value could change during execution.
Protect configuration changes. Only authorized users or deployment systems should be able to modify production feature flags.
Monitor important changes. Record when a flag changes, who changed it, and which environment was affected.
Remove obsolete flags. Once a feature has been fully released and the old implementation is no longer required, remove the unused flag and its conditional code.
Finally, do not use feature flags as a replacement for authorization. A disabled feature is not a security boundary. Sensitive operations must still enforce authentication and authorization independently.
Summary
Feature flags allow development teams to control application functionality independently of deployment.
When used with Cloud Run, they provide a flexible approach to gradual releases, internal testing, percentage-based rollouts, and emergency feature shutdowns.
Environment variables are a simple starting point, but changing them creates a new Cloud Run revision. For runtime changes without redeployment, a centralized configuration store such as Firestore or a dedicated feature management platform is more appropriate.
OpenFeature can also help separate application code from the feature flag provider.
The most important design decision is choosing the right level of control. Cloud Run traffic splitting manages application revisions, while feature flags manage individual features. Using both together gives teams more control over how new functionality reaches production users.


Join the conversation! Your thoughts help the community grow.