All lessons · Guided routes

Capstone 7 of 10

Capstone 7: A small internal developer platform

Every team builds its services differently and new ones take weeks. You build a small platform: a catalog, a golden-path template, self-service environments behind policy checks, platform SLOs, and a feedback loop from developers to the platform backlog.

What you build

  1. Service catalog

    Every service has a name, an owner, a tier, an on-call rotation, a runbook, and an SLO, in one place.

    Lessons: Internal Developer Platforms, Self-Service Infrastructure: Backstage Golden Paths and Crossplane Platform APIs

  2. Golden path

    A template scaffolds a new service: code, tests, Dockerfile, and its catalog entry.

    Lessons: Golden Paths, Software Templates, and Platform APIs: From Tickets to Self-Service

  3. Environments

    Self-service environments: a running instance per environment, created from the template.

    Lessons: Preview Environments and Environment Management: Ephemeral, Seeded, and Cleaned Up

  4. Policy

    Checks run before an environment is created: a complete catalog entry, a non-root user, a health check, and a pinned base image. A service that runs as root is rejected with the reason.

    Lessons: Policy as Code with OPA and Kubernetes

  5. Platform SLOs

    Provisioning succeeds for at least 99% of valid requests, with a p95 under 30 seconds, measured from provisioning records.

    Lessons: Platform Scorecards, SLOs, Cost Allocation, and Deprecation

  6. Developer feedback

    A survey turns into a satisfaction score and the next items for the platform backlog.

    Lessons: Platform as a Product: Team Topologies, Developer Experience, and Adoption

Before you start

ToolVersion
python33.10 or later

Ports: 18100 to 18119 on 127.0.0.1. Resources: Under 300 MB of memory; standard library only.

What it creates (and the reset removes): up to 20 python3 app.py processes (one per environment); ~/labs/capstones/platform. Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.

Get the files

One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.

mkdir -p ~/labs && cd ~/labs
curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz
tar -xzf capstones-lab.tar.gz && cd capstones-lab
ls

Run it

All in one, with the reset afterwards even if a step fails:

bash run.sh 07-platform

Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):

python3 07-platform/platform.py setup
python3 07-platform/platform.py verify
python3 07-platform/platform.py reset

Expected output

This is a real run of run.sh 07-platform, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.

== 1. Golden path: scaffold two services from the template
   orders: owner team-orders, tier 1, SLO 99.9%
   invoices: owner team-billing, tier 2, SLO 99.5%
== 2. A team hand-edits its Dockerfile to run as root, off the golden path
== 3. Self-service environments: dev and staging for orders, dev for invoices
   orders/dev: ready in 0.11 s on port 18100
   orders/staging: ready in 0.1 s on port 18101
   invoices/dev: rejected: the Dockerfile must run as a non-root user
== 4. Developers answer the quarterly platform survey
== Catalog and golden path
  PASS  2 services in the catalog, each with owner, tier, on-call, runbook, and SLO
  PASS  the scaffolded service's own tests pass: OK
== Policy
  PASS  orders, on the golden path, passes every policy
  PASS  invoices is rejected with a clear reason: ['the Dockerfile must run as a non-root user']
== Environments
  PASS  orders/dev answers on port 18100 as orders-dev
  PASS  orders/staging answers on port 18101 as orders-staging
== Fix the rejected service the golden-path way, and provision again
  PASS  invoices/dev is ready in 0.1 s
== Platform SLOs, from the provisioning records
  PASS  provisioning success 100% of 3 valid requests (SLO 99%)
  PASS  provisioning time p95 0.11 s (SLO: under 30 s)
== Developer feedback
  PASS  satisfaction score (NPS) 10; next platform work: slow environment creation (2 developers); unclear policy errors (2 developers)

RESULT: all checks passed

The files

07-platform/platform.py
#!/usr/bin/env python3
"""Capstone 7, platform engineering: service catalog -> golden path -> templates -> environment
provisioning -> policy -> platform SLOs -> developer feedback.

A small internal platform in one script: a catalog of services, a golden-path template that
scaffolds a new service (code, tests, Dockerfile, catalog entry), self-service environment
provisioning (a running instance per environment, from the template), policy checks before
anything runs, platform SLOs measured from provisioning records, and a developer survey that
feeds the platform backlog. Standard library only; ~/labs/capstones/platform; ports 18100-18119.
  python3 platform.py setup | verify | reset
"""
import json
import os
import shutil
import signal
import subprocess
import sys
import time
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
APP = os.path.join(HERE, "..", "app")
WORK = os.path.expanduser("~/labs/capstones/platform")
FAILS = []
REQUIRED = ["name", "owner", "tier", "on_call", "runbook", "slo"]


def p(*x): return os.path.join(WORK, *x)
def ok(m): print("  PASS ", m)
def bad(m): FAILS.append(m); print("  FAIL ", m)


def scaffold(name, owner, tier):
    """The golden path: one command gives a new service everything the platform expects."""
    d = p("services", name)
    os.makedirs(d, exist_ok=True)
    shutil.copy(os.path.join(APP, "orders.py"), os.path.join(d, "app.py"))
    shutil.copy(os.path.join(APP, "test_orders.py"), os.path.join(d, "test_app.py"))
    open(os.path.join(d, "test_app.py"), "a").write("")
    t = open(os.path.join(d, "test_app.py")).read().replace('"orders.py"', '"app.py"')
    open(os.path.join(d, "test_app.py"), "w").write(t)
    shutil.copy(os.path.join(APP, "Dockerfile"), os.path.join(d, "Dockerfile"))
    entry = {"name": name, "owner": owner, "tier": tier, "on_call": f"{owner}-oncall", "runbook": f"https://runbooks.example/{name}",
             "slo": {"availability": 99.9 if tier == 1 else 99.5}, "template": "python-http-service@1", "health": "/healthz"}
    json.dump(entry, open(os.path.join(d, "catalog-info.json"), "w"), indent=1)
    return entry


def catalog():
    out = []
    for n in sorted(os.listdir(p("services"))):
        f = p("services", n, "catalog-info.json")
        if os.path.exists(f):
            out.append(json.load(open(f)))
    return out


def policy(service_dir):
    """Checks every service must pass before an environment is created for it."""
    errs = []
    entry = json.load(open(os.path.join(service_dir, "catalog-info.json")))
    errs += [f"catalog entry lacks {k}" for k in REQUIRED if not entry.get(k)]
    df = open(os.path.join(service_dir, "Dockerfile")).read()
    if "USER " not in df or "USER root" in df:
        errs.append("the Dockerfile must run as a non-root user")
    if "HEALTHCHECK" not in df:
        errs.append("the Dockerfile has no HEALTHCHECK")
    if ":latest" in df:
        errs.append("base image must be pinned, not :latest")
    return errs


def provision(name, env, port):
    """Self-service: one request gives a running environment, recorded for the platform SLOs."""
    t0 = time.time()
    d = p("services", name)
    errs = policy(d)
    rec = {"service": name, "env": env, "requested": t0}
    if errs:
        rec.update(result="rejected", reasons=errs, seconds=round(time.time() - t0, 2))
    else:
        env_vars = dict(os.environ, PORT=str(port), VERSION=f"{name}-{env}")
        proc = subprocess.Popen([sys.executable, os.path.join(d, "app.py")], env=env_vars, stdout=open(p(f"{name}-{env}.log"), "w"), stderr=subprocess.STDOUT, start_new_session=True)
        up = False
        for _ in range(60):
            try:
                urllib.request.urlopen(f"http://127.0.0.1:{port}/healthz", timeout=1); up = True; break
            except OSError:
                time.sleep(0.1)
        rec.update(result="ready" if up else "failed", pid=proc.pid, port=port, seconds=round(time.time() - t0, 2))
    with open(p("provisioning.jsonl"), "a") as f:
        f.write(json.dumps(rec) + "\n")
    return rec


def setup():
    shutil.rmtree(WORK, ignore_errors=True); os.makedirs(p("services"))
    print("== 1. Golden path: scaffold two services from the template")
    for name, owner, tier in (("orders", "team-orders", 1), ("invoices", "team-billing", 2)):
        e = scaffold(name, owner, tier); print(f"   {name}: owner {e['owner']}, tier {e['tier']}, SLO {e['slo']['availability']}%")
    print("== 2. A team hand-edits its Dockerfile to run as root, off the golden path")
    d = p("services", "invoices", "Dockerfile")
    text = open(d).read()                      # read first: opening for "w" empties the file
    open(d, "w").write(text.replace("USER 10001:10001", "USER root"))
    print("== 3. Self-service environments: dev and staging for orders, dev for invoices")
    port = 18100
    for name, env in (("orders", "dev"), ("orders", "staging"), ("invoices", "dev")):
        r = provision(name, env, port); port += 1
        print(f"   {name}/{env}: {r['result']}" + (f" in {r['seconds']} s on port {r['port']}" if r["result"] == "ready" else f": {'; '.join(r['reasons'])}"))
    print("== 4. Developers answer the quarterly platform survey")
    survey = [{"score": s, "pain": pain} for s, pain in [(9, None), (8, "slow environment creation"), (10, None), (6, "unclear policy errors"), (9, None),
                                                          (4, "unclear policy errors"), (8, None), (7, "docs"), (9, None), (5, "slow environment creation")]]
    json.dump(survey, open(p("survey.json"), "w"), indent=1)


def verify():
    print("== Catalog and golden path")
    cat = catalog()
    (ok if len(cat) == 2 and all(all(c.get(k) for k in REQUIRED) for c in cat) else bad)(f"{len(cat)} services in the catalog, each with owner, tier, on-call, runbook, and SLO")
    t = subprocess.run([sys.executable, "-m", "unittest", "-q", "test_app.py"], cwd=p("services", "orders"), capture_output=True, text=True)
    (ok if t.returncode == 0 else bad)("the scaffolded service's own tests pass: " + t.stderr.strip().splitlines()[-1])
    print("== Policy")
    (ok if not policy(p("services", "orders")) else bad)("orders, on the golden path, passes every policy")
    errs = policy(p("services", "invoices"))
    (ok if errs == ["the Dockerfile must run as a non-root user"] else bad)(f"invoices is rejected with a clear reason: {errs}")
    print("== Environments")
    recs = [json.loads(l) for l in open(p("provisioning.jsonl"))]
    ready = [r for r in recs if r["result"] == "ready"]
    for r in ready:
        v = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{r['port']}/version", timeout=2).read())["version"]
        (ok if v == f"{r['service']}-{r['env']}" else bad)(f"{r['service']}/{r['env']} answers on port {r['port']} as {v}")
    print("== Fix the rejected service the golden-path way, and provision again")
    d = p("services", "invoices", "Dockerfile"); text = open(d).read()
    open(d, "w").write(text.replace("USER root", "USER 10001:10001"))
    r = provision("invoices", "dev", 18110)
    (ok if r["result"] == "ready" else bad)(f"invoices/dev is ready in {r['seconds']} s")
    print("== Platform SLOs, from the provisioning records")
    recs = [json.loads(l) for l in open(p("provisioning.jsonl"))]
    valid = [x for x in recs if x["result"] != "rejected"]          # policy rejections are correct outcomes, not platform failures
    success = sum(x["result"] == "ready" for x in valid) / len(valid) * 100
    p95 = sorted(x["seconds"] for x in valid)[max(0, -(-95 * len(valid) // 100) - 1)]
    (ok if success >= 99 else bad)(f"provisioning success {success:.0f}% of {len(valid)} valid requests (SLO 99%)")
    (ok if p95 <= 30 else bad)(f"provisioning time p95 {p95} s (SLO: under 30 s)")
    print("== Developer feedback")
    sv = json.load(open(p("survey.json")))
    promoters = sum(s["score"] >= 9 for s in sv); detractors = sum(s["score"] <= 6 for s in sv)
    nps = round((promoters - detractors) / len(sv) * 100)
    pains = {}
    for s in sv:
        if s["pain"]:
            pains[s["pain"]] = pains.get(s["pain"], 0) + 1
    top = sorted(pains.items(), key=lambda x: -x[1])
    backlog = [f"{pain} ({n} developers)" for pain, n in top]
    json.dump({"nps": nps, "backlog": backlog}, open(p("platform-backlog.json"), "w"), indent=1)
    (ok if top and top[0][1] >= 2 else bad)(f"satisfaction score (NPS) {nps}; next platform work: {'; '.join(backlog[:2])}")
    print("\nRESULT:", "all checks passed" if not FAILS else f"{len(FAILS)} check(s) failed")
    stop_all()
    sys.exit(1 if FAILS else 0)


def stop_all():
    if os.path.exists(p("provisioning.jsonl")):
        for l in open(p("provisioning.jsonl")):
            r = json.loads(l)
            if r.get("pid"):
                try:
                    os.kill(r["pid"], signal.SIGTERM)
                except OSError:
                    pass


def reset():
    stop_all(); time.sleep(0.5)
    shutil.rmtree(WORK, ignore_errors=True); print(f"capstone 7 reset: environments stopped, {WORK} removed")


if __name__ == "__main__":
    {"setup": setup, "verify": verify, "reset": reset}.get(sys.argv[1] if len(sys.argv) > 1 else "", lambda: sys.exit(__doc__))()

If it fails

SymptomCauseFix
An environment is not readyA port in 18100 to 18119 is taken.Free the port, or reset and run again.
A policy check fails on your own template changeThe change broke a platform rule, which is the point.Read the rule in platform.py and fix the template.

Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.

Clean up

python3 07-platform/platform.py reset

It removes: up to 20 python3 app.py processes (one per environment); ~/labs/capstones/platform. Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.

In the cloud

Not run by this course. The local capstone above is the tested part. These are the managed services that do the same jobs on each provider; they cost money while they exist, and their names and prices change, so check the provider's current documentation before you build them. Use a separate learning account with a budget alert, as Start here explains.
ProviderEquivalent
AWSBackstage on EKS or AWS Proton for templates, with Service Catalog products for environments.
AzureAzure Deployment Environments with dev center catalogs, and Backstage on AKS.
Google CloudBackstage on GKE with Config Connector or Infrastructure Manager for environments.

How it is assessed

verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.

CriterionMeetsExceeds
Self-serviceA developer can create an environment without a ticket.Within a measured SLO, with a reason when it fails.
GuardrailsPolicy blocks unsafe services before they run.Developers can see and test the policy themselves.
Product thinkingThe platform has an owner and a backlog.The backlog is ordered by developer feedback and SLO data.
CatalogEvery service has an owner.Dependencies and lifecycle drive scorecards.

Take it further

Then test what you know with the assessments.

Next capstone: A model from data contract to safe rollback. All capstones · Guided routes