backstage icon indicating copy to clipboard operation
backstage copied to clipboard

Support Schema Name Prefix Configuration for `pluginDivisionMode: schema`

Open Fortune-Ndlovu opened this issue 3 months ago • 7 comments

📜 Issue Labels

  • [x] Please familiarize yourself with the issue labels used in this project: LABELS.md

🔎 Search Terms

pluginDivisionMode: schema schemaPrefix

🗃️ Project Area

Core Framework

🔖 Need

Backstage currently supports customizable database name prefixes via backend.database.prefix (defaults to backstage_plugin_), as documented in the Configuring Plugin Databases tutorial. The implementation is in DatabaseManager.ts:257.

However, when using pluginDivisionMode: schema, schema names are hardcoded to plugin IDs with no equivalent prefix option.

This creates an inconsistency in the configuration model:

  • ✅ Database names: Configurable via backend.database.prefix
  • ❌ Schema names: Hardcoded to plugin IDs

Why This Matters:

  1. Schema naming conflicts in PostgreSQL are common

    • PostgreSQL extensions (pgvector, PostGIS, TimescaleDB) often create their own schemas
    • The extensions schema name is particularly common for extension management
    • Users migrating to Backstage may have existing schemas in their databases
  2. Standard PostgreSQL practice uses prefixes for namespacing

    • Application schemas are typically prefixed to avoid conflicts (e.g., app_*, service_*)
    • This is a well-established pattern in multi-application databases
    • Backstage already follows this pattern for database names, but not schema names
  3. Completing the existing feature

    • The pluginDivisionMode: schema feature introduced schema-based isolation
    • But it's missing the prefix configuration that database mode has
    • This feels like an incomplete implementation

Who Will Benefit:

  1. Users with existing PostgreSQL databases

    • Adopting Backstage into databases that already have schemas
    • Sharing databases with other applications
    • Using PostgreSQL extensions that create schemas
  2. Multi-environment deployments

    • Running multiple Backstage instances against one database
    • Wanting environment-specific schema prefixes (prod_*, staging_*, dev_*)
  3. Users following PostgreSQL naming conventions

    • Organizations with schema naming standards
    • Teams wanting consistent namespace prefixing across all applications

Common Scenarios:

  • Running Backstage in a database that has pgvector installed → conflict with extensions schema
  • Deploying multiple Backstage environments to one database → need to differentiate schemas
  • Migrating from another application → existing catalog or auth schemas already exist
  • Following a naming convention where all application schemas start with a prefix

Current Limitations:

Without schema prefixes, users must either:

  • Rename their existing database schemas (disruptive, requires coordination)
  • Not use pluginDivisionMode: schema (defeats the purpose for single-database deployments)
  • Work around the conflict at the database level (grants, search_path manipulation)

Adding schema prefix support would complete the feature and align with how database names work.

📝 Proposal

Add a schemaPrefix configuration option to backend.database, mirroring the existing prefix option for database names.

Configuration

backend:
  database:
    client: pg
    pluginDivisionMode: schema
    prefix: backstage_plugin_           # Existing: prefixes database names
    schemaPrefix: backstage_            # NEW: prefixes schema names
    connection:
      host: localhost
      user: backstage
      password: secret
      database: backstage_db

Behavior

With schemaPrefix: backstage_, plugin schemas would be created as:

Plugin ID Current Schema Name Proposed Schema Name
catalog catalog backstage_catalog
scaffolder scaffolder backstage_scaffolder
auth auth backstage_auth
extensions extensions backstage_extensions

Implementation Overview

  1. Config Schema - config.d.ts#L682-L683

    • Add optional schemaPrefix?: string field next to existing prefix option
  2. DatabaseManager - DatabaseManager.ts#L257

    • Read schemaPrefix from config (default to '' for backward compatibility)
    • Pass to PgConnector constructor (similar to how prefix is passed)
  3. PgConnector - postgres.ts

Backward Compatibility

  • Default: Empty string ('') maintains current behavior
  • Existing deployments: Continue working without changes
  • Opt-in: Users explicitly add schemaPrefix when needed

🔄 Alternatives

Alternative 1: Per-Plugin Schema Name Override

Allow explicit schema configuration per plugin:

backend:
  database:
    pluginDivisionMode: schema
    plugin:
      extensions:
        schemaName: custom_extensions
      catalog:
        schemaName: custom_catalog

Why Not Preferred:

  • Requires configuring every plugin individually
  • Inconsistent with how database names work (global prefix, not per-plugin)
  • Doesn't help users who just want a systematic prefix
  • More verbose and error-prone

Note: This could complement schema prefixes as a future enhancement for edge cases.


Alternative 2: Schema Name Template

Support template strings with placeholders:

backend:
  database:
    schemaNameTemplate: "app_{{pluginId}}_schema"

Why Not Preferred:

  • Over-engineered for the common case (most users just want a prefix)
  • Adds parsing complexity and potential for errors
  • Can be added later without breaking the simpler prefix approach

Alternative 3: Automatic Conflict Resolution

Detect schema conflicts at startup and auto-append a suffix:

backend:
  database:
    autoResolveSchemaConflicts: true

Why Not Preferred:

  • Unpredictable behavior (different schemas in different environments)
  • Harder to debug and reason about
  • Users need to know exact schema names for database administration

Alternative 4: Do Nothing

Keep the current behavior and document workarounds.

Why Not Sufficient:

  • Doesn't address the inconsistency with database name prefixes
  • Forces users to modify their existing database schemas
  • Makes pluginDivisionMode: schema less practical for shared databases
  • Missing an obvious feature that users would expect based on database prefix support

Why Global Prefix is Best

A global schemaPrefix option is the right solution because:

  • ✅ Mirrors the existing database.prefix pattern (consistent API)
  • ✅ Solves the common case with minimal configuration
  • ✅ Backward compatible (opt-in)
  • ✅ Aligns with PostgreSQL naming best practices
  • ✅ Simple to understand and use
  • ✅ Doesn't prevent future per-plugin overrides

Additional Context

Example Conflict Scenario

-- Existing database has pgvector installed
CREATE SCHEMA extensions;
CREATE EXTENSION vector SCHEMA extensions;

-- Backstage starts with pluginDivisionMode: schema
-- Tries to create schema "extensions" for the extensions plugin
-- (via ensurePgSchemaExists at postgres.ts:703)
-- Conflict: schema already exists

Current code that causes the conflict:

With schemaPrefix: backstage_:

-- Backstage creates schema "backstage_extensions" instead
-- No conflict with existing "extensions" schema

Implementation Reference

The database prefix already works this way:

// DatabaseManager.ts:257
// https://github.com/backstage/backstage/blob/master/packages/backend-defaults/src/entrypoints/database/DatabaseManager.ts#L257
const prefix = databaseConfig.getOptionalString('prefix') || 'backstage_plugin_';

// Database name becomes: backstage_plugin_catalog

Schema names should work the same:

// Proposed in postgres.ts
const schemaPrefix = config.getOptionalString('schemaPrefix') || '';
const schemaName = `${schemaPrefix}${pluginId}`;

// Schema name becomes: backstage_catalog (if schemaPrefix: 'backstage_')

Related Code

Key files that would need changes:

  1. Config schema - packages/backend-defaults/config.d.ts

    • Add schemaPrefix?: string option to backend.database
  2. DatabaseManager - packages/backend-defaults/src/entrypoints/database/DatabaseManager.ts

    • Read schemaPrefix from config and pass to PgConnector
  3. PgConnector - packages/backend-defaults/src/entrypoints/database/connectors/postgres.ts

    • Line 641: searchPath: [pluginId] ← needs to use prefixed name
    • Line 703: ensurePgSchemaExists(this.config, pluginId) ← needs to use prefixed name
    • Line 551-666: computePgPluginConfig() function needs schemaPrefix parameter

Reference

Have you read the Code of Conduct?

Are you willing to submit a PR?

Yes, and I have enough information to get started

Fortune-Ndlovu avatar Aug 25 '26 12:08 Fortune-Ndlovu

Hi @Fortune-Ndlovu, thanks for logging this, overall seems like a worthwhile feature to add but I have a few things I'd like to hear from you before you move on to creating a PR:

  1. What is the migration story? What happens when someone uses this in an existing deployment?
  2. How is this validated? There are schema name length limitations in Postgres that need to be taken into account.

Small nit: can you update the issue to list it as Core Framework for the Project Area, please?

awanlin avatar Aug 27 '26 14:08 awanlin

Hi @awanlin, thank you for the feedback! I appreciate you taking the time to review this. Let me address your questions:

1. Migration Story

For existing deployments: The change would be fully backward compatible with an opt-in model:

  • Default behavior: If schemaPrefix is not configured (or set to empty string ''), schemas continue to use raw plugin IDs exactly as they do today
  • No breaking changes: Existing deployments would see zero impact unless they explicitly add the schemaPrefix config option
  • Migration path for new prefix: If someone decides to add a prefix to an existing deployment:
    • Their existing schemas (e.g., catalog, auth) would remain unchanged
    • New schemas would be created with the prefix (e.g., backstage_catalog)
    • They would need to migrate data and drop old schemas, OR
    • They could temporarily run both schemas during migration with appropriate search_path configuration

Best practice recommendation: We should document that schemaPrefix is best configured at initial deployment. For existing deployments wanting to add a prefix, we'd recommend:

  1. Set up a new database with the prefix configured
  2. Migrate data using standard PostgreSQL dump/restore
  3. Or accept the prefix only applies to newly-created schemas going forward

This mirrors how the existing backend.database.prefix works for database names today (implementation).

2. Validation for Schema Name Length

Yes! PostgreSQL limits schema names to 63 characters (that is 63 bytes in the default encoding). We have add validation:

Pseudo Example :

// In computePgPluginConfig() or ensurePgSchemaExists()
const schemaName = `${schemaPrefix}${pluginId}`;

if (schemaName.length > 63) {
  throw new Error(
    `PostgreSQL schema name "${schemaName}" exceeds the 63-character limit. ` +
    `Consider using a shorter schemaPrefix (current: "${schemaPrefix}") or ` +
    `plugin ID (current: "${pluginId}").`
  );
}

Where to validate:

Additional considerations:

  • PostgreSQL will truncate names > 63 chars, but that could cause silent collisions
  • Better to fail loudly with a clear error message
  • We could also add a warning if the combined length is > 50 chars (leaving headroom)

Community Context

I wanted to highlight that this issue has been raised several times by the community over the years. Similar requests were closed as "not planned":

  • #15914 - "ability to change the schema name for postgres"
  • #13415 - "Support custom database schema names"
  • #17838 - "Allow configuration of database schema name"

Real-world impact we're seeing:

  1. PostgreSQL extension conflicts: Users with pgvector, PostGIS, or other extensions that create an extensions schema hit immediate conflicts when using pluginDivisionMode: schema (current behavior at postgres.ts:641 and postgres.ts:703)

  2. Multi-environment databases: Organizations running multiple Backstage environments (prod/staging/dev) in separate schemas on one database can't differentiate them without prefixes

  3. Migration barriers: Teams with existing databases can't adopt pluginDivisionMode: schema without renaming their existing schemas, which may not be allowed by their DBA policies

  4. Inconsistency with database mode: Users naturally expect schema prefix support because backend.database.prefix already exists for database names (config.d.ts:682). The current behavior feels like an incomplete feature.

Why now?

The pluginDivisionMode: schema feature has matured, and more organizations are using it for cost-effective single-database deployments. As adoption grows, the schema naming conflict becomes a more frequent blocker.

We believe this would significantly improve the usability of the schema division mode and align it with PostgreSQL best practices and existing Backstage patterns.

Small note: I have updated the Project Area to "Core Framework" as you requested. Thanks again for considering this!

Fortune-Ndlovu avatar Sep 07 '26 10:09 Fortune-Ndlovu

I would be more than happy to open a PR implementing this feature and iterate based on maintainer feedback, with:

  • The opt-in schemaPrefix config option (defaults to '') - would be added to config.d.ts:682-683
  • Validation for the 63-character PostgreSQL limit with clear error messages
  • Implementation in computePgPluginConfig() to apply the prefix
  • Tests covering the length validation and prefix application
  • Documentation updates for the schema mode configuration

Please let me know if this approach sounds reasonable or if you'd like me to explore it differently!

Fortune-Ndlovu avatar Sep 08 '26 11:09 Fortune-Ndlovu

Hi @Fortune-Ndlovu, thanks for the follow up. Appreciate the clarity on the the two items I mentioned. That clears up my concerns. Feel free to raise a PR, and post it here for visibility. As this isn't something we have prioritized within the Core Framework Maintainers group reviews will be on the slow side due to capacity but that's not an indicator of lack of interest simply our need to balance our time.

I do have some constructive feedback to share. I'm a human with a limited amount of time. I shared two questions. I got back from you a extremely long, clearly AI generated, reply that I had to read over to parse where the answers to my questions were instead of a human written message that would have be much more direct. When speaking with people it's best to avoid simply posting what the AI tooling shared or having it post on your behalf.

awanlin avatar Sep 08 '26 12:09 awanlin

Hey @awanlin, thank you so much for the constructive feedback and acceptance to raise a PR. Moving forward in our communication, I will ensure to be more direct. I appreciate your time.

Fortune-Ndlovu avatar Sep 08 '26 12:09 Fortune-Ndlovu

Hey @awanlin, please take a look whenever you're ready:

PR: https://github.com/backstage/backstage/pull/35603 Testing: https://github.com/backstage/backstage/pull/35603#issuecomment-5614156737

Thanks!

Fortune-Ndlovu avatar Sep 10 '26 09:09 Fortune-Ndlovu

Thank you @awanlin and @freben !!

Fortune-Ndlovu avatar Sep 11 '26 15:09 Fortune-Ndlovu