Lesson 2: Golden Paths, Backstage Software Templates (The Scaffolder) & Exception Handling
๐ง The Concept (Explain Like Iโm 5)
Imagine you want to start a brand-new business:
- The Traditional Enterprise Way (Jira Ticket Ping-Pong):
- You file a Jira ticket with IT for a computer (wait 5 days).
- You file a Jira ticket with Facilities for a desk (wait 4 days).
- You file a Jira ticket with Security for an access badge (wait 6 days).
- You file a Jira ticket with Finance for a credit card (wait 5 days).
- Total elapsed time: 3 to 4 weeks before you write a single line of business code!
- The Golden Path (Backstage Software Templates):
You walk up to a state-of-the-art automated kiosk:
- You press a button: โCreate Production Python FastAPI Microserviceโ.
- You enter two fields: Service Name (
payment-processor) and Owning Team (fintech-platform). - You press Execute.
- In 60 seconds, the kiosk automatically creates a private GitHub repository, configures pre-commit security hooks, sets up GitHub Actions CI/CD pipelines, provisions ArgoCD GitOps manifests, configures AWS IAM OIDC roles, and registers the service in the company catalog!
๐ข The Enterprise Context (Why Platform Architects Care)
- Developer Velocity vs. Security Governance: Historically, developers had to choose between speed (cutting security corners) and compliance (waiting weeks for approvals). Golden Paths eliminate this trade-off by encoding enterprise compliance (Trivy scanning, Cosign signing, non-root containers) directly into the template skeleton. Doing the right thing becomes the easiest thing.
- Cognitive Load Reduction: A junior engineer joining the company does not need to learn the intricate details of Kubernetes YAML, Helm chart helper templates, or AWS IAM trust policies. They use a vetted Golden Path and immediately begin delivering business value.
- Consistency Across the Microservice Fleet: When hundreds of services share the exact same standardized directory layout and CI/CD pipelines, site reliability engineering teams can rollout company-wide upgrades (e.g. updating a logging library or patching an OpenSSL vulnerability) via automated pull request bots in minutes.
๐บ๏ธ Visual Architecture: End-to-End Scaffolding Lifecycle
sequenceDiagram
autonumber
actor Dev as ๐ฉโ๐ป Developer
participant UI as ๐ฅ๏ธ Backstage Web UI
participant Scaffolder as โ๏ธ Backstage Scaffolder Backend
participant GitHub as ๐ GitHub Enterprise API
participant GitOps as ๐ ArgoCD Fleet Repository
participant Catalog as ๐ Backstage Software Catalog
Dev->>UI: Selects "Production FastAPI Golden Path"
UI->>Dev: Form Prompts: service_name, owner, database_type
Dev->>UI: Clicks "Create Component"
UI->>Scaffolder: POST /api/scaffolder/v2/tasks (Parameters JSON)
rect rgb(20, 30, 45)
Note over Scaffolder: 1. Action: fetch:template (Renders Cookiecutter/Nunjucks skeleton)
Scaffolder->>Scaffolder: Injects parameters into Dockerfile, CI/CD, and app code
end
rect rgb(25, 40, 35)
Note over Scaffolder: 2. Action: publish:github
Scaffolder->>GitHub: Create private repo: corp-org/payment-processor
Scaffolder->>GitHub: Commit templated code & apply branch protection rules
end
rect rgb(35, 25, 45)
Note over Scaffolder: 3. Action: gitops:register
Scaffolder->>GitOps: Commit ArgoCD Application YAML into GitOps fleet repo
Note over GitOps: ArgoCD automatically detects new manifest & deploys to EKS Dev!
end
rect rgb(45, 35, 25)
Note over Scaffolder: 4. Action: catalog:register
Scaffolder->>Catalog: Register 'catalog-info.yaml' into Software Catalog
end
Scaffolder-->>UI: Task Complete! Displays live URLs for Repo, ArgoCD & Catalog โ
๐ฌ Under the Hood: Scaffolder Engine Mechanics & Custom Actions
The Backstage Scaffolder runs as a background task engine inside the Backstage Node.js backend. Templates are defined using declarative YAML schemas conforming to apiVersion: scaffolder.backstage.io/v1beta3.
1. Template Parameter Validation (RJSF)
Backstage uses react-jsonschema-form (RJSF) to dynamically render frontend UI components from JSON Schema definitions:
- Validates regex patterns (e.g., ensuring
component_idcontains only lowercase letters and hyphens:^[a-z0-9-]+$). - Integrates custom UI pickers (e.g.,
ui:field: OwnerPickerautomatically queries the Backstage catalog to populate a searchable dropdown of registered teams).
2. Built-in vs. Custom Scaffolder Actions
Backstage ships with standard built-in actions (fetch:template, publish:github, catalog:register). Platform teams write custom actions in TypeScript to interact with internal infrastructure:
// packages/backend/src/plugins/scaffolder/actions/customAwsAction.ts
import { createTemplateAction } from '@backstage/plugin-scaffolder-node';
export const createS3BucketAction = () => {
return createTemplateAction<{ bucketName: string; environment: string }>({
id: 'corp:aws:s3:create',
description: 'Provisions an enterprise compliant S3 bucket with KMS encryption',
schema: {
input: {
type: 'object',
required: ['bucketName'],
properties: {
bucketName: { type: 'string', title: 'S3 Bucket Name' },
environment: { type: 'string', title: 'Target Environment' },
},
},
},
async handler(ctx) {
ctx.logger.info(`Provisioning KMS-encrypted S3 bucket: ${ctx.input.bucketName}`);
// Execute AWS SDK calls or trigger Crossplane claim here
},
});
};
๐ป Production Implementation: Hardened Golden Path Template
apiVersion: scaffolder.backstage.io/v1beta3
kind: Template
metadata:
name: fastapi-enterprise-golden-path
title: Production Python FastAPI Microservice
description: Scaffolds a production-grade FastAPI microservice with Trivy CVE scanning, Cosign signing, and ArgoCD GitOps deployment.
tags:
- python
- fastapi
- golden-path
- enterprise
spec:
owner: group:platform-team
type: service
parameters:
- title: Service Metadata
required:
- component_id
- description
- owner
properties:
component_id:
title: Service Identifier
type: string
description: Unique kebab-case name of the microservice (e.g., payment-service)
pattern: '^[a-z0-9-]+$'
ui:autofocus: true
description:
title: Description
type: string
description: A clear explanation of what this microservice does
owner:
title: Owning Engineering Group
type: string
description: The team responsible for maintaining this service
ui:field: OwnerPicker
- title: Deployment & Infrastructure Configuration
required:
- cloud_region
- environment
properties:
cloud_region:
title: Primary AWS Region
type: string
default: us-east-1
enum:
- us-east-1
- us-west-2
environment:
title: Initial Target Environment
type: string
default: development
enum:
- development
- staging
steps:
# Step 1: Render Cookiecutter Skeleton with Input Parameters
- id: fetch-template
name: Render Application Skeleton
action: fetch:template
input:
url: ./skeleton
values:
component_id: ${{ parameters.component_id }}
description: ${{ parameters.description }}
owner: ${{ parameters.owner }}
cloud_region: ${{ parameters.cloud_region }}
environment: ${{ parameters.environment }}
# Step 2: Publish Repository to GitHub Enterprise
- id: publish-github
name: Publish Repository to GitHub
action: publish:github
input:
allowedHosts: ['github.com']
description: ${{ parameters.description }}
repoUrl: github.com?owner=corp-enterprise&repo=${{ parameters.component_id }}
defaultBranch: main
repoVisibility: private
protectDefaultBranch: true
deleteBranchOnMerge: true
# Step 3: Register Service in GitOps Fleet for Auto-Deployment
- id: register-gitops
name: Register in ArgoCD Fleet
action: publish:github:pull-request
input:
repoUrl: github.com?owner=corp-enterprise&repo=gitops-fleet
branchName: add-service-${{ parameters.component_id }}
title: "feat(gitops): register ${{ parameters.component_id }} application"
description: "Automated ArgoCD registration generated by Backstage Golden Path."
# Step 4: Register Component in Backstage Software Catalog
- id: register-catalog
name: Register in Software Catalog
action: catalog:register
input:
repoContentsUrl: ${{ steps['publish-github'].output.repoContentsUrl }}
catalogInfoPath: '/catalog-info.yaml'
output:
links:
- title: GitHub Repository
url: ${{ steps['publish-github'].output.remoteUrl }}
- title: Backstage Catalog Entity
icon: catalog
entityRef: component:default/${{ parameters.component_id }}
โ ๏ธ Real-World Failure Modes, Exceptions & Break-Glass Playbooks
Exception 1: Partial Step Execution Failure & The โOrphaned Repoโ Trap
- The Disaster: A developer triggers a template. Step 1 renders files. Step 2 creates the private GitHub repository
corp-enterprise/order-billing. Step 3 attempts to submit an ArgoCD pull request, but fails due to a temporary GitHub API timeout (HTTP 504 Gateway Timeout). - The Failure: The Backstage task aborts. However, the GitHub repository in Step 2 already exists! If the developer clicks โTry Againโ, the template crashes with:
HttpError: Repository 'corp-enterprise/order-billing' already exists on this account. - The Architectural Fix (Idempotency & Compensation Actions):
- Configure
publish:githubwithaccess: checkExisting: trueto prevent collision aborts. - Implement an automated Compensation Hook / Rollback Action in the Scaffolder backend that traps task errors and issues compensatory cleanup calls (
DELETE /repos/corp-enterprise/...) if subsequent steps fail.
- Configure
Exception 2: GitHub API Rate Limiting During Hackathons or Mass Onboarding
- The Outage: During a company hackathon or mass new-hire onboarding session, 60 engineers execute Golden Path templates within a 15-minute window.
- The Failure: The Backstage backend utilizes a single GitHub Personal Access Token (PAT). GitHub rejects requests with
HTTP 403 Forbidden: API rate limit exceeded for user (5,000 requests/hour limit exhausted). All template scaffolding across the entire company grinds to an immediate halt! - The Enterprise Resolution:
- Migrate to GitHub App Authentication: Replace static Personal Access Tokens with a GitHub App. GitHub Apps receive higher rate limits calculated per installation (up to 15,000 requests/hour) and authenticate via short-lived installation tokens that rotate automatically.
- Implement Scaffolder Concurrency Limits: In
app-config.yaml, configure task queue concurrency limits:scaffolder: concurrency: 5 # Queue excess scaffolding requests to prevent rate limit spikes
Exception 3: Security Escalation via Unauthorized Template Parameters
- The Vulnerability: A junior engineer discovers that an experimental database template allows selecting
instance_class: db.m6i.32xlarge($15,000/month) or settingrepo_visibility: public, exposing internal corporate proprietary source code to the public internet! - The Enterprise Safeguards (Backstage Permission Framework):
Integrate the Backstage Permission Framework (
@backstage/plugin-permission-node). Implement strict policy evaluation rules:
Junior developers are prevented from even viewing or executing restricted high-cost or high-risk infrastructure templates.// Enforce template RBAC if (isResourcePermission(permission, 'scaffolder-template')) { if (template.name === 'production-database-cluster') { return isMemberOf(user, 'group:lead-database-architects') ? AuthorizeResult.ALLOW : AuthorizeResult.DENY; } }
๐ Staff Architect & SRE Interview Scenarios
โ ๐ข Low Difficulty: What is a `catalog-info.yaml` file?
Question: Why does every Backstage Software Template automatically generate a catalog-info.yaml file at the root of the target repository?
Answer: catalog-info.yaml is the core metadata descriptor parsed by the Backstage Software Catalog. It declares the componentโs identity (name, type), architectural relationships (consumesApi, dependsOn), ownership (owner: group:payment-team), and documentation location (backstage.io/techdocs-ref). Without this file, the repository exists as an unmanaged Git silo with no visibility in the companyโs developer portal.
โ ๐ก Medium Difficulty: Hardcoded Secrets in Skeleton Files
Question: If a software template provisions a microservice that requires connecting to a Redis cache, why should the skeleton template NEVER contain a secret variable like REDIS_PASSWORD = "${{ parameters.redis_password }}"?
Answer: Passing secrets as plaintext template parameters causes them to be logged in the Backstage task database, rendered into plaintext Git commits, and exposed to anyone viewing the Scaffolder task execution history.
The Golden Path Standard: The template should inject an ExternalSecret manifest (pointing to AWS Secrets Manager via IRSA) or a HashiCorp Vault annotation. The microservice retrieves credentials dynamically at runtime without human secrets ever traversing the template engine.
โ ๐ด Hard Difficulty: Handling Drift Between Scaffolder Skeletons and Deployed Services
Question: Once 200 microservices have been scaffolded from a template, the platform team updates the base Dockerfile and CI/CD security rules in the skeleton. How do you propagate these updates to the 200 existing repositories without manual PRs?
Answer: The primary limitation of templating engines is that scaffolding is a one-time operation; once created, repositories drift away from the template. Enterprise platform teams resolve this using Automated Renovate / Dependabot Bot Sweeps:
- Extract core infrastructure logic (e.g. GitHub Actions workflows, Docker base images, Helm charts) into shared central repositories (e.g., reusable GitHub Actions workflows).
- The skeleton references the central reusable workflow:
uses: corp-org/ci-workflows/.github/workflows/standard-build.yml@v2. - Updating the centralized workflow immediately updates security standards across all 200 microservices simultaneously with zero repository drift.
โ ๐ฃ Complex Difficulty: Distributed Transaction Failure in Multi-Step Scaffolding
Question: In an enterprise architecture where a Backstage template interacts with 4 independent external systems (GitHub, AWS, Datadog, PagerDuty), how do you prevent partial state inconsistencies if System 4 fails?
Answer: This is a classic distributed transaction problem. Because two-phase commit (2PC) is impossible across heterogeneous third-party SaaS APIs, platform architects implement the Saga Pattern (Compensating Transactions) within Backstage:
- Each Scaffolder step registers a forward action and a backward compensating rollback action in a task journal.
- If Step 4 (PagerDuty escalation creation) crashes, the Scaffolder runtime catches the exception and executes compensating rollback actions in reverse order:
- Rollback Step 3: Deletes Datadog synthetic monitors.
- Rollback Step 2: Deletes the AWS IAM role.
- Rollback Step 1: Archives or deletes the created GitHub repository.
- The system returns cleanly to a known zero-state, preventing infrastructure sprawl and billing leaks.