Why typed feature flags matter

A feature flag system often starts as a map of strings:

  • "new_checkout" = "true"
  • "max_upload_mb" = "50"
  • "search_mode" = "beta"

That approach works until you need to distinguish between:

  • boolean flags,
  • numeric thresholds,
  • enumerated modes,
  • missing or malformed values,
  • environment overrides such as dev, staging, and prod.

A typed loader solves these problems by parsing raw configuration into domain-specific Rust types. Instead of checking string keys everywhere, your application receives a validated FeatureFlags struct with clear fields and predictable behavior.

What we will build

We will build a loader that:

  • reads a base flag file and an optional environment-specific override file,
  • supports boolean, integer, and enum-like flags,
  • validates values at startup,
  • exposes a typed API to the rest of the application.

Project structure

A simple layout keeps the example easy to extend:

feature-flags/
├── Cargo.toml
└── src/
    └── main.rs

We will use serde and toml for parsing. TOML is a good fit because it is human-readable and supports nested structures cleanly.

Dependencies

[package]
name = "feature-flags"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1", features = ["derive"] }
toml = "0.8"
thiserror = "1"

Designing the typed model

The core idea is to separate raw input from validated application state.

Raw configuration shape

We will parse TOML into a raw structure first:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct RawFlags {
    features: RawFeatureFlags,
}

#[derive(Debug, Deserialize, Default)]
struct RawFeatureFlags {
    new_checkout: Option<bool>,
    max_upload_mb: Option<u32>,
    search_mode: Option<String>,
}

This raw model is intentionally permissive. Each field is optional so that a base file can omit values and an environment file can override only what it needs.

Typed application model

Now define the validated version:

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchMode {
    Stable,
    Beta,
    Experimental,
}

#[derive(Debug)]
struct FeatureFlags {
    new_checkout: bool,
    max_upload_mb: u32,
    search_mode: SearchMode,
}

This is the type the rest of your application should use. Notice that search_mode is no longer a string. Invalid values are rejected during loading, not at runtime in random call sites.


Loading and merging configuration

A common pattern is to load a base file and then apply environment-specific overrides. For example:

  • flags.toml
  • flags.dev.toml
  • flags.staging.toml
  • flags.prod.toml

The override file should only replace fields it explicitly sets.

Example TOML files

flags.toml:

[features]
new_checkout = false
max_upload_mb = 25
search_mode = "stable"

flags.staging.toml:

[features]
new_checkout = true
search_mode = "beta"

In staging, max_upload_mb stays at 25, while the other two values are overridden.

Merge strategy

We will parse both files into RawFlags, then merge the optional fields manually.

impl RawFeatureFlags {
    fn merge(self, override_flags: Self) -> Self {
        Self {
            new_checkout: override_flags.new_checkout.or(self.new_checkout),
            max_upload_mb: override_flags.max_upload_mb.or(self.max_upload_mb),
            search_mode: override_flags.search_mode.or(self.search_mode),
        }
    }
}

impl RawFlags {
    fn merge(self, override_flags: Self) -> Self {
        Self {
            features: self.features.merge(override_flags.features),
        }
    }
}

This is simple and explicit. For a small config surface, manual merging is often clearer than introducing a more complex deep-merge library.


Validating and converting raw values

Now we convert RawFlags into FeatureFlags. This is where invalid values become errors.

Error type

Use thiserror to define a clean error enum:

use thiserror::Error;

#[derive(Debug, Error)]
enum FlagError {
    #[error("failed to read {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },

    #[error("failed to parse TOML in {path}: {source}")]
    Parse {
        path: String,
        #[source]
        source: toml::de::Error,
    },

    #[error("missing required flag: {0}")]
    Missing(&'static str),

    #[error("invalid search_mode: {0}")]
    InvalidSearchMode(String),
}

Conversion logic

impl TryFrom<RawFlags> for FeatureFlags {
    type Error = FlagError;

    fn try_from(raw: RawFlags) -> Result<Self, Self::Error> {
        let features = raw.features;

        let new_checkout = features.new_checkout.unwrap_or(false);
        let max_upload_mb = features
            .max_upload_mb
            .ok_or(FlagError::Missing("features.max_upload_mb"))?;

        let search_mode = match features.search_mode.as_deref() {
            Some("stable") => SearchMode::Stable,
            Some("beta") => SearchMode::Beta,
            Some("experimental") => SearchMode::Experimental,
            Some(other) => return Err(FlagError::InvalidSearchMode(other.to_string())),
            None => return Err(FlagError::Missing("features.search_mode")),
        };

        Ok(Self {
            new_checkout,
            max_upload_mb,
            search_mode,
        })
    }
}

This conversion does three important things:

  1. supplies a default for new_checkout,
  2. requires max_upload_mb,
  3. validates search_mode against a fixed set of allowed values.

Reading files from disk

Next, implement a loader that reads the base file and optional override file.

use std::fs;
use std::path::Path;

fn load_raw_flags(base_path: &Path, override_path: Option<&Path>) -> Result<RawFlags, FlagError> {
    let base_text = fs::read_to_string(base_path).map_err(|source| FlagError::Io {
        path: base_path.display().to_string(),
        source,
    })?;

    let base: RawFlags = toml::from_str(&base_text).map_err(|source| FlagError::Parse {
        path: base_path.display().to_string(),
        source,
    })?;

    if let Some(path) = override_path {
        let override_text = fs::read_to_string(path).map_err(|source| FlagError::Io {
            path: path.display().to_string(),
            source,
        })?;

        let override_flags: RawFlags = toml::from_str(&override_text).map_err(|source| FlagError::Parse {
            path: path.display().to_string(),
            source,
        })?;

        Ok(base.merge(override_flags))
    } else {
        Ok(base)
    }
}

This function is intentionally narrow: it reads, parses, and merges. It does not know anything about business logic.


Putting it together in main

Here is a complete example that loads flags based on the APP_ENV environment variable.

use serde::Deserialize;
use std::convert::TryFrom;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

#[derive(Debug, Deserialize)]
struct RawFlags {
    features: RawFeatureFlags,
}

#[derive(Debug, Deserialize, Default)]
struct RawFeatureFlags {
    new_checkout: Option<bool>,
    max_upload_mb: Option<u32>,
    search_mode: Option<String>,
}

impl RawFeatureFlags {
    fn merge(self, override_flags: Self) -> Self {
        Self {
            new_checkout: override_flags.new_checkout.or(self.new_checkout),
            max_upload_mb: override_flags.max_upload_mb.or(self.max_upload_mb),
            search_mode: override_flags.search_mode.or(self.search_mode),
        }
    }
}

impl RawFlags {
    fn merge(self, override_flags: Self) -> Self {
        Self {
            features: self.features.merge(override_flags.features),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SearchMode {
    Stable,
    Beta,
    Experimental,
}

#[derive(Debug)]
struct FeatureFlags {
    new_checkout: bool,
    max_upload_mb: u32,
    search_mode: SearchMode,
}

#[derive(Debug, Error)]
enum FlagError {
    #[error("failed to read {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to parse TOML in {path}: {source}")]
    Parse {
        path: String,
        #[source]
        source: toml::de::Error,
    },
    #[error("missing required flag: {0}")]
    Missing(&'static str),
    #[error("invalid search_mode: {0}")]
    InvalidSearchMode(String),
}

impl TryFrom<RawFlags> for FeatureFlags {
    type Error = FlagError;

    fn try_from(raw: RawFlags) -> Result<Self, Self::Error> {
        let features = raw.features;

        let new_checkout = features.new_checkout.unwrap_or(false);
        let max_upload_mb = features
            .max_upload_mb
            .ok_or(FlagError::Missing("features.max_upload_mb"))?;

        let search_mode = match features.search_mode.as_deref() {
            Some("stable") => SearchMode::Stable,
            Some("beta") => SearchMode::Beta,
            Some("experimental") => SearchMode::Experimental,
            Some(other) => return Err(FlagError::InvalidSearchMode(other.to_string())),
            None => return Err(FlagError::Missing("features.search_mode")),
        };

        Ok(Self {
            new_checkout,
            max_upload_mb,
            search_mode,
        })
    }
}

fn load_raw_flags(base_path: &Path, override_path: Option<&Path>) -> Result<RawFlags, FlagError> {
    let base_text = fs::read_to_string(base_path).map_err(|source| FlagError::Io {
        path: base_path.display().to_string(),
        source,
    })?;

    let base: RawFlags = toml::from_str(&base_text).map_err(|source| FlagError::Parse {
        path: base_path.display().to_string(),
        source,
    })?;

    if let Some(path) = override_path {
        let override_text = fs::read_to_string(path).map_err(|source| FlagError::Io {
            path: path.display().to_string(),
            source,
        })?;

        let override_flags: RawFlags = toml::from_str(&override_text).map_err(|source| FlagError::Parse {
            path: path.display().to_string(),
            source,
        })?;

        Ok(base.merge(override_flags))
    } else {
        Ok(base)
    }
}

fn load_feature_flags() -> Result<FeatureFlags, FlagError> {
    let env_name = env::var("APP_ENV").unwrap_or_else(|_| "dev".to_string());

    let base_path = PathBuf::from("flags.toml");
    let override_path = PathBuf::from(format!("flags.{env_name}.toml"));

    let override_ref = if override_path.exists() {
        Some(override_path.as_path())
    } else {
        None
    };

    let raw = load_raw_flags(&base_path, override_ref)?;
    FeatureFlags::try_from(raw)
}

fn main() {
    match load_feature_flags() {
        Ok(flags) => {
            println!("Loaded feature flags: {flags:?}");
            if flags.new_checkout {
                println!("New checkout flow is enabled");
            }
        }
        Err(err) => {
            eprintln!("Failed to load feature flags: {err}");
            std::process::exit(1);
        }
    }
}

Practical usage patterns

A typed flag loader becomes more useful when you use it consistently across the codebase.

1. Gate behavior at the edge

Check flags near request handling or command dispatch, not deep inside utility functions. That keeps business logic readable.

if flags.new_checkout {
    render_new_checkout();
} else {
    render_legacy_checkout();
}

2. Pass flags explicitly

Avoid global mutable state. Pass &FeatureFlags into components that need it.

fn handle_request(flags: &FeatureFlags) {
    if matches!(flags.search_mode, SearchMode::Experimental) {
        // enable experimental search pipeline
    }
}

3. Fail fast on invalid config

If a flag file is malformed, exit during startup. Do not let the service run with partial or guessed values.

4. Keep defaults intentional

Only default values that are safe and well understood. For example, new_checkout = false is a conservative default. A missing max_upload_mb is not acceptable if the application depends on it.


Extending the model

As your flag set grows, you can improve the design in a few ways.

NeedSuggested approach
More flag typesAdd typed fields such as Duration, usize, or custom enums
Nested groupsUse nested structs like features.checkout or features.search
Environment variablesLoad env overrides before file overrides, or vice versa
Per-tenant flagsAdd a lookup layer keyed by tenant ID | region | plan
Runtime refreshReload files on a timer or filesystem event, then swap an Arc<FeatureFlags>

If you add runtime refresh, be careful: the type system still helps, but you must also manage concurrency and consistency.


Best practices

A few rules make this pattern robust in production:

  • Prefer enums over free-form strings.
  • Validate once at startup, not repeatedly at call sites.
  • Keep raw parsing and typed conversion separate.
  • Use explicit merge rules for overrides.
  • Treat missing required flags as startup failures.
  • Document each flag’s purpose and safe default.

A good feature flag system is not just a collection of booleans. It is a controlled interface for operational behavior, and Rust’s type system is well suited to making that interface precise.


Learn more with useful resources