Course contentsShow
← Databases & SQL
Lesson 1919 of 1,95318. Application Integration PatternsFree lesson

Feature Flagging for Schema Changes

Use application-level flags to toggle between old and new schema structures during a phased rollout.

In this lesson, you will learn how to decouple your database schema deployments from your application logic by using feature flags to manage the transition between old and new data structures.

The Problem: Schema Rigidity

When performing non-trivial schema changes—such as splitting a users table or migrating from a single-column address to a normalized addresses table—the database migration and the code deployment are rarely perfectly synchronized. If your application code expects the new structure but the database migration hasn't finished, your application crashes. Conversely, if the code isn't ready for the new structure, the new schema might break existing queries.

The Pattern: Toggle-Driven Persistence

Feature flagging allows you to bridge the "deployment gap" by embedding conditional logic directly into your Repository or Data Access layer. Instead of forcing a hard cutover, you use an application-level flag to dictate which schema "version" the application should read from or write to.

Consider a migration where we are moving email from a users table to a user_credentials table:

def save_user_email(user_id, email):
    if feature_flags.is_enabled('use_new_credentials_schema'):
        # Write to the new, normalized table
        db.execute("INSERT INTO user_credentials (user_id, email) VALUES (?, ?)", (user_id, email))
    else:
        # Fallback to the legacy schema
        db.execute("UPDATE users SET email = ? WHERE id = ?", (email, user_id))

Execution Strategy

  1. Expand: Deploy the new schema (e.g., the user_credentials table) alongside the old one.
  2. Read Path: Use the flag to keep the application reading from the old table while writing to both (dual-writing) or keeping them in sync via a background process.
  3. Toggle: Once data consistency is verified, flip the feature flag to switch the application to the new schema for all read and write operations.
  4. Contract: After a stabilization period, perform the final migration to drop the legacy columns or tables.

This approach provides an instantaneous "kill switch" if the new schema exhibits performance degradation or data anomalies, preventing a costly rollback of the entire database deployment.

Key Takeaway: Use application-level feature flags to control the persistence layer, allowing you to transition between schema structures safely without requiring a simultaneous, risky deployment of code and database changes.