Production DeploymentVol. 16 · Part XVI
0 / 0

Shelves / Production Deployment

DP·187

The Application Lifecycle

One application traced through every stage from idea to evolution, as a chain of artefacts and gates: idea and requirements, architecture and its decision records, the data model as SQL run on PostgreSQL, the API contract in OpenAPI, the front end, tests at every level, reproducible builds and supply-chain metadata, containers, infrastructure as code, deployment pipelines and GitOps, observability designed in, security woven through, load testing, incident handling, and evolution (versioning, deprecation, debt, sunsetting); the walking-skeleton technique that wires all stages end to end on day one, a monorepo layout, a single pipeline definition tying the stages together, and a Go worker and Spring Boot API skeleton for TiffinBox.

30 topics · ~20 min read · 26-question quiz
Updated Suggest a correction

Start here: from an idea to running in production, and beyond

An application's lifecycle is the whole path: idea → requirements → design → build → test → release → operate → learn → change or retire. Each stage produces an artefact (a brief, a design record, code, a tested build, a deployed version, dashboards, a postmortem) and passes a gate before the next. The faster and safer you can go around this loop, the better the product gets.

A walking skeleton

The best way to start a new application is a walking skeleton: the thinnest possible version that runs end to end through every stage, including deployment, on day one. Features are then added to a pipeline that already works.

The lab built one for TiffinBox's "skip a day" rule: a small API, four tests, and a six-stage pipeline:

Text
1 lint (ruff)                    pass   0.01 s
2 type check (mypy)              pass   1.85 s
3 unit + API tests (pytest)      pass   1.11 s
4 build artefact (wheel)         pass   1.60 s
5 deploy to 'staging' + start    pass   1.10 s
6 smoke test against staging     pass   0.01 s
artefact sha256 961132762a07654a promoted

About six seconds from commit to a tested build running in a staging environment.

What each gate catches

The lab then planted mistakes:

  • a type error (returning "yes" where True was declared) stopped the pipeline at stage 2 in 0.1 s;
  • a boundary bug (< instead of <= at the 20:00 cut-off) passed every stage and was promoted, because no test checked exactly 20:00. Adding a one-line test of the boundary made stage 3 fail.

A pipeline only catches what its gates check: order them cheapest first, and add a test for every rule's edges.

How deep to go in the application lifecycle

Volume 17 defines six mastery levels; for the application lifecycle they look like this:

Level You can…
L1 name the lifecycle stages and their artefacts and gates
L2 build a walking skeleton with a working pipeline to staging
L3 design gates and ordering for fast, trustworthy feedback
L4 find which missing gate let a defect through and add it
L5 define the lifecycle and pipeline standards for a product or platform
L6 run lifecycle governance across many services, including deprecation and retirement

The lifecycle as a chain of artefacts

The roadmap asks that your application be understandable as one chain:

idea → requirements → architecture → data model → API → frontend → tests → build → container → infrastructure → deployment → observability → security → load → incident handling → evolution

Each stage produces an artefact the next stage consumes, and each has a gate that catches problems before they become expensive. Thinking in artefacts makes the lifecycle concrete and automatable.

Stage Artefact Gate Covered in depth
Idea Problem statement, outcome metric Evidence of a real problem Volume 15 (ch. 181–182)
Requirements Stories, rules, examples, NFRs Example mapping; ready criteria Ch. 185
Architecture Context and container diagrams, ADRs Design review against NFRs Volumes 12–13
Data model Schema migrations (SQL) Migration review; lock analysis Volume 3; ch. 191
API OpenAPI / protobuf contract Contract review; linting; breaking-change check Volume 2
Frontend Components, routes, design-system usage Accessibility and performance budgets Volume 4; ch. 184
Tests Unit, integration, contract, E2E, acceptance All green in CI; coverage of rules Volume 11
Build Versioned binaries/bundles, SBOM Reproducible; signed Volume 8
Container OCI image Vulnerability scan; non-root; small Volume 6
Infrastructure Terraform/Helm/Kustomize Plan review; policy checks Volumes 6–8
Deployment Release (image digest + config) Progressive rollout; automated rollback Ch. 192
Observability Dashboards, SLOs, alerts Alerts tested; runbooks linked Volume 9
Security Threat model, scans, secrets, policies No criticals; review of risky changes Volume 10
Load Load-test results, capacity model Meets SLOs at target load + headroom Ch. 189
Incident handling Runbooks, on-call, postmortems Game days; drills Volume 9; ch. 193
Evolution Versioned APIs, deprecations, ADR updates Usage-based deprecation; debt budget This chapter
design idea requirements architecture data model API frontend build tests build container infrastructure run deployment observability security load incidents evolution production learning feeds the next idea
The application lifecycle as a pipeline of artefacts with feedback loops. Design-time stages produce requirements, architecture, schema and API contracts; build-time stages produce tested, versioned images and infrastructure definitions; run-time stages deploy, observe, secure and load the system. Incidents and production metrics feed back into requirements and architecture, so the lifecycle is a loop rather than a line.

The running system

This volume deploys TiffinBox (introduced in Volume 15): office-lunch subscriptions in Hyderabad.

  • web: React/TypeScript single-page app (customers) and an admin console, served from a CDN.
  • api: Spring Boot 3 (Java 21) REST API: subscriptions, schedules, skips and credits, payments integration.
  • dispatch-worker: Go service consuming events (skips, orders) to update kitchen prep lists and rider batches.
  • Data: PostgreSQL (system of record), Redis (cache, rate limits), a queue (Amazon SQS or Kafka), object storage (invoices, menu images), OpenSearch (menu search), and a RAG assistant calling a model provider (Volume 14).
  • Platform: AWS, Kubernetes (EKS), Terraform, GitHub Actions, Argo CD, OpenTelemetry, Prometheus/Grafana.

The same ideas apply on any cloud or on-premises; substitutions are noted where they matter.

Stage by stage

Idea and requirements

Covered in Volume 15. The artefacts that matter downstream: the outcome metric (drives observability), NFRs (drive architecture, load tests and SLOs), acceptance tests (drive the test suite), constraints (drive infrastructure choices, e.g. data residency in India → AWS ap-south-1 Mumbai/ap-south-2 Hyderabad).

Architecture

Artefacts: a C4 context and container diagram (Volume 12), ADRs for consequential choices (modular monolith for the API, Postgres for money, async kitchen updates), a threat model (Volume 10), and NFR scenarios mapped to architectural tactics (caching for menu reads, idempotency keys for skips, outbox for events). Gate: a design review with the NFR table (chapter 185) and a production-readiness preview (chapter 189).

Data model

The schema is the hardest artefact to change later, so model the core entities carefully and evolve them with migrations (chapter 191). TiffinBox's core:

SQL
-- V1__core_schema.sql (Flyway naming); runs on PostgreSQL 16
CREATE TABLE subscriber (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  phone_e164    text NOT NULL UNIQUE,
  name          text NOT NULL,
  office_id     bigint NOT NULL,
  created_at    timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE subscription (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  subscriber_id bigint NOT NULL REFERENCES subscriber(id),
  plan          text NOT NULL CHECK (plan IN ('veg_5', 'veg_20', 'nonveg_5', 'nonveg_20')),
  status        text NOT NULL CHECK (status IN ('active', 'paused', 'cancelled')),
  starts_on     date NOT NULL,
  ends_on       date,
  CHECK (ends_on IS NULL OR ends_on >= starts_on)
);

CREATE TABLE delivery (
  id              bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  subscription_id bigint NOT NULL REFERENCES subscription(id),
  delivery_date   date NOT NULL,
  state           text NOT NULL DEFAULT 'scheduled'
                  CHECK (state IN ('scheduled', 'skipped', 'locked', 'out', 'delivered', 'failed')),
  updated_at      timestamptz NOT NULL DEFAULT now(),
  UNIQUE (subscription_id, delivery_date)
);

-- Append-only credit ledger (ADR 0012, Volume 15 chapter 186)
CREATE TABLE credit_entry (
  id              bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  subscription_id bigint NOT NULL REFERENCES subscription(id),
  delta           smallint NOT NULL CHECK (delta IN (-1, 1)),
  reason          text NOT NULL CHECK (reason IN ('skip', 'redeem', 'expire', 'adjust')),
  delivery_id     bigint REFERENCES delivery(id),
  idempotency_key text NOT NULL UNIQUE,
  created_at      timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX delivery_by_date ON delivery (delivery_date, state);
CREATE INDEX credit_by_subscription ON credit_entry (subscription_id);

-- Transactional outbox for events to the dispatch worker
CREATE TABLE outbox (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  aggregate_id bigint NOT NULL,
  event_type   text NOT NULL,
  payload      jsonb NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;

The skip operation as one transaction, enforcing chapter 185's rules in the database (conditional update, idempotent credit, outbox event):

SQL
-- skip(:subscription_id, :delivery_date, :idempotency_key); cut-off evaluated in IST by the database clock
WITH target AS (
  UPDATE delivery d
     SET state = 'skipped', updated_at = now()
   WHERE d.subscription_id = $1 AND d.delivery_date = $2 AND d.state = 'scheduled'
     AND now() < (($2::date + time '07:00') AT TIME ZONE 'Asia/Kolkata')
  RETURNING d.id, d.subscription_id
), credit AS (
  INSERT INTO credit_entry (subscription_id, delta, reason, delivery_id, idempotency_key)
  SELECT subscription_id, 1, 'skip', id, $3 FROM target
  ON CONFLICT (idempotency_key) DO NOTHING
  RETURNING delivery_id
)
INSERT INTO outbox (aggregate_id, event_type, payload)
SELECT t.id, 'DeliverySkipped', jsonb_build_object('deliveryId', t.id, 'date', $2::date)
FROM target t JOIN credit c ON c.delivery_id = t.id
RETURNING aggregate_id;
-- zero rows returned → not skippable (wrong state, past cut-off, or already processed)

API

The contract is an artefact reviewed before implementation (design-first), linted, versioned, and checked for breaking changes in CI:

YAML
# openapi.yaml (excerpt)
openapi: 3.1.0
info: { title: TiffinBox API, version: 1.4.0 }
paths:
  /v1/subscriptions/{subscriptionId}/deliveries/{date}/skip:
    post:
      operationId: skipDelivery
      parameters:
        - { name: subscriptionId, in: path, required: true, schema: { type: integer, format: int64 } }
        - { name: date, in: path, required: true, schema: { type: string, format: date } }
        - { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 64 } }
      responses:
        "200": { description: Skipped, content: { application/json: { schema: { $ref: "#/components/schemas/SkipResult" } } } }
        "409": { description: Not skippable (past cut-off or wrong state), content: { application/problem+json: { schema: { $ref: "#/components/schemas/Problem" } } } }
      security: [{ bearerAuth: [] }]
components:
  schemas:
    SkipResult:
      type: object
      required: [deliveryId, state, creditBalance]
      properties:
        deliveryId: { type: integer, format: int64 }
        state: { type: string, enum: [skipped] }
        creditBalance: { type: integer, minimum: 0 }
    Problem:   # RFC 9457 problem details
      type: object
      properties: { type: { type: string }, title: { type: string }, detail: { type: string }, status: { type: integer } }
  securitySchemes:
    bearerAuth: { type: http, scheme: bearer, bearerFormat: JWT }

Tooling: Spectral (linting), oasdiff or openapi-diff (breaking-change detection in CI), code generation for clients (TypeScript) and server stubs, and contract tests (Pact) between web and api (Volume 11).

Front end

The front end is built against the contract (generated TypeScript types), behind performance budgets (bundle size, LCP/INP) and accessibility checks in CI (chapter 184). It's deployed as static assets to object storage + CDN with immutable, content-hashed filenames, so releases are atomic and rollbacks are a pointer change of index.html.

Tests

Each layer of the test pyramid (Volume 11) is an artefact with a gate: unit tests for rules; integration tests with real Postgres (Testcontainers); contract tests for the API; acceptance tests (chapter 185); a few E2E journeys; plus migration tests (apply all migrations to a copy of production schema) and performance smoke tests on every merge.

Build

A build turns source into versioned, immutable artefacts: a JAR, a Go binary, a JS bundle, then images. Properties to aim for:

  • Reproducible: pinned dependencies (lock files), pinned base images by digest, deterministic build flags.
  • Versioned and traceable: the version (or git SHA) embedded in the artefact and exposed at /version and in telemetry.
  • Supply-chain metadata: an SBOM (CycloneDX or SPDX), provenance attestations (SLSA), signatures (Sigstore cosign), produced by CI (Volume 10, chapter 112).
  • Build once, deploy many: the same image digest moves through every environment; only configuration differs (chapter 190).

Container

Multi-stage builds; minimal base images (distroless, Chainguard-style, or Alpine where libc compatibility allows); non-root user; read-only root filesystem; health endpoints; one process per container; graceful SIGTERM handling (chapter 192). Example for the Go worker:

Dockerfile
# syntax=docker/dockerfile:1
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o /out/dispatch-worker ./cmd/worker

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/dispatch-worker /dispatch-worker
USER nonroot:nonroot
EXPOSE 8081
ENTRYPOINT ["/dispatch-worker"]

Infrastructure

Infrastructure as code (Volume 7–8): Terraform for cloud resources (VPC, EKS, RDS PostgreSQL, ElastiCache, SQS, S3, CloudFront, IAM); Helm or Kustomize for Kubernetes resources; policy as code (OPA/Conftest, Kyverno) as a gate. Every change goes through a pull request with a plan reviewed before apply.

Deployment

A release = an image digest + its configuration for an environment. GitOps (Argo CD or Flux) reconciles the cluster to the desired state in a Git repository; CI updates the image tag/digest in that repository after tests pass; progressive delivery (canary with automated analysis, chapter 192) limits blast radius.

Observability

Designed in from the start, not bolted on: structured logs, metrics (RED for services, USE for resources), traces with OpenTelemetry, SLOs on user journeys (skip confirmation, delivery tracking), dashboards and alerts with runbooks (Volume 9). The product's outcome metric (Volume 15) gets a dashboard too.

Security

Threat modelling at design; dependency, secret and image scanning in CI; least-privilege IAM and Kubernetes RBAC; secrets in a manager (AWS Secrets Manager, Vault) delivered at runtime; network policies; TLS everywhere; security headers; audit logs; incident response for security events (Volume 10).

Load

Load tests against production-like environments establish capacity and verify NFRs: the 06:45–07:00 skip rush, the 12:00–13:00 tracking peak (chapter 189).

Incident handling

On-call rotation, alert routing, runbooks, incident roles (commander, communications, operations), status page, blameless postmortems with action items (Volume 9; chapter 193 for disasters).

Evolution

Software spends most of its life being changed. Plan for it:

  • API versioning and deprecation: additive changes within a version; breaking changes in a new version; announce deprecations with dates; measure usage of old versions before removal; Deprecation and Sunset HTTP headers.
  • Schema evolution with expand/contract (chapter 191).
  • Dependency upkeep: automated update PRs (Renovate, Dependabot) with tests; regular runtime upgrades (Java LTS, Go releases, Node LTS, Kubernetes minor versions).
  • Technical debt budget: a fixed share of capacity (often 15–25%) for maintenance, informed by where change is frequent (Volume 15, chapter 186).
  • Revisit ADRs when their review triggers fire.
  • Sunsetting features and services: usage analytics, migration paths for users, data retention and deletion, removing code, infrastructure and dashboards (dead features still cost money and attack surface).

The walking skeleton

Before building features, build a walking skeleton (Alistair Cockburn): the thinnest possible implementation that exercises every stage end to end: a "hello" endpoint backed by a real database table, built by the real pipeline into a real image, deployed by GitOps to real staging and production clusters behind the real load balancer and CDN, emitting real traces and metrics, with one alert and one dashboard. It surfaces integration problems (networking, IAM, DNS, certificates, secrets) when they're cheap to fix, and every later feature flows through a proven path.

browser DNS · CDN LB / gateway api /hello Postgres row queue worker CI: test → build → scan → sign → push → bump digest GitOps sync OTel → dash+ 1 alert every stage real on day one; features are added later
A walking skeleton for TiffinBox. On day one a trivial request travels through every real component: DNS and CDN, the load balancer, the API reading one row from PostgreSQL, a message through the queue to the worker, and telemetry to the observability stack, all built and deployed by the real pipeline. Features are then added as flesh on these bones.

The worker of the skeleton, standard library only, with graceful shutdown and a health endpoint already in place:

Go
// cmd/worker/main.go — walking-skeleton dispatch worker (stdlib only)
package main

import (
	"context"
	"encoding/json"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"sync/atomic"
	"syscall"
	"time"
)

var version = "dev"

type Event struct {
	Type       string `json:"type"`
	DeliveryID int64  `json:"deliveryId"`
	Date       string `json:"date"`
}

func main() {
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "dispatch-worker", "version", version)
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
	defer stop()

	var ready atomic.Bool
	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
	mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) {
		if ready.Load() { w.WriteHeader(http.StatusOK); return }
		w.WriteHeader(http.StatusServiceUnavailable)
	})
	srv := &http.Server{Addr: ":8081", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	go func() { _ = srv.ListenAndServe() }()

	events := make(chan Event)              // stand-in for an SQS/Kafka consumer
	go func() {
		for _, raw := range []string{`{"type":"DeliverySkipped","deliveryId":42,"date":"2026-10-22"}`} {
			var e Event
			if json.Unmarshal([]byte(raw), &e) == nil { events <- e }
		}
	}()

	ready.Store(true)
	log.Info("started")
	for {
		select {
		case <-ctx.Done():                  // SIGTERM: stop taking work, finish in-flight, exit
			ready.Store(false)
			shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
			defer cancel()
			_ = srv.Shutdown(shutdownCtx)
			log.Info("stopped cleanly")
			return
		case e := <-events:
			log.Info("event processed", "type", e.Type, "deliveryId", e.DeliveryID, "date", e.Date)
		}
	}
}

And the API's first endpoint, with the version exposed for traceability:

Java
// api/src/main/java/com/tiffinbox/api/HelloController.java — walking-skeleton endpoint (Spring Boot 3, Java 21)
@RestController
class HelloController {
    private final JdbcClient jdbc;
    private final BuildProperties build;          // from spring-boot-maven-plugin build-info

    HelloController(JdbcClient jdbc, BuildProperties build) { this.jdbc = jdbc; this.build = build; }

    @GetMapping("/v1/hello")
    Map<String, Object> hello() {
        Integer ok = jdbc.sql("SELECT 1").query(Integer.class).single();     // proves DB connectivity end to end
        return Map.of("service", "api", "version", build.getVersion(), "db", ok == 1 ? "ok" : "unexpected");
    }
}

Repository layout

A monorepo suits a small team owning a few services: one place for code, infrastructure, contracts and docs; atomic changes across layers; one pipeline. (Polyrepos suit independent teams with independent release cycles.)

Text
tiffinbox/
├── api/                      Spring Boot service (Maven/Gradle), Flyway migrations in src/main/resources/db/migration
├── dispatch-worker/          Go service
├── web/                      React/TypeScript app (Vite), generated API client
├── contracts/openapi.yaml    API contract (source of truth for clients and server stubs)
├── deploy/
│   ├── helm/tiffinbox/       chart: deployments, services, HPAs, PDBs, network policies
│   └── envs/{dev,staging,prod}/values.yaml   per-environment configuration (no secrets)
├── infra/terraform/          VPC, EKS, RDS, ElastiCache, SQS, S3, CloudFront, IAM (modules + per-env stacks)
├── ops/runbooks/             runbooks linked from alerts
├── docs/adr/                 architecture decision records
├── load/                     k6 scenarios
└── .github/workflows/        CI/CD pipelines

One pipeline, all stages

The pipeline encodes the lifecycle's build-and-deploy gates. A GitHub Actions sketch (each job maps to stages above; Volume 8 covers CI/CD in depth):

YAML
name: ci-cd
on: { push: { branches: [main] }, pull_request: {} }
permissions: { contents: read, id-token: write, packages: write }   # OIDC to the cloud, no long-lived keys
jobs:
  contracts:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npx @stoplight/spectral-cli lint contracts/openapi.yaml
      - run: oasdiff breaking origin/main:contracts/openapi.yaml contracts/openapi.yaml --fail-on ERR
  test:
    runs-on: ubuntu-latest
    needs: contracts
    services:
      postgres: { image: "postgres:16", env: { POSTGRES_PASSWORD: test }, ports: ["5432:5432"] }
    steps:
      - uses: actions/checkout@v4
      - run: ./api/mvnw -f api verify                  # unit + integration + Flyway migrations + acceptance
      - run: cd dispatch-worker && go vet ./... && go test -race ./...
      - run: cd web && npm ci && npm test && npm run build && npm run check:budgets
  image:
    if: github.ref == 'refs/heads/main'
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t ghcr.io/acme/dispatch-worker:${{ github.sha }} --build-arg VERSION=${{ github.sha }} dispatch-worker
      - run: trivy image --exit-code 1 --severity CRITICAL ghcr.io/acme/dispatch-worker:${{ github.sha }}
      - run: syft ghcr.io/acme/dispatch-worker:${{ github.sha }} -o cyclonedx-json > sbom.json
      - run: docker push ghcr.io/acme/dispatch-worker:${{ github.sha }}
      - run: cosign sign --yes ghcr.io/acme/dispatch-worker@$(docker inspect --format='{{index .RepoDigests 0}}' ghcr.io/acme/dispatch-worker:${{ github.sha }} | cut -d@ -f2)
  promote-staging:
    needs: image
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: yq -i '.image.tag = "${{ github.sha }}"' deploy/envs/staging/values.yaml   # GitOps: Argo CD syncs this
      - run: git commit -am "staging → ${{ github.sha }}" && git push

Production promotion is a separate, approved step (chapter 190) that copies the same digest to production's values after staging checks pass.

Lab: a walking skeleton and its gates

Setup. Python 3.13 on the lab machine; a FastAPI app with one rule (can_skip: a delivery can be skipped until 20:00 the evening before) and a POST /skip endpoint; four pytest tests (19:59 allowed, 20:01 refused, the API happy path, the API "too late" path); ruff (rules E, F, I), mypy, a wheel build with SOURCE_DATE_EPOCH pinned, a "staging" deploy that installs the wheel into its own directory and starts it under uvicorn on another port, and a curl smoke test. Each stage's time is real; "staging" is a local stand-in for a real environment.

Experiment 1: the green path

Stage Result Time
1 lint (ruff) pass 0.01 s
2 type check (mypy) pass 1.85 s (0.11–0.14 s when cached)
3 unit + API tests pass 1.11 s
4 build wheel pass 1.60 s
5 deploy to staging + start + health check pass 1.10 s
6 smoke test pass 0.01 s

About 6 s from commit to a tested artefact (sha256 961132762a07654a…) running in staging. Real pipelines take minutes (container builds, integration tests with databases, scans), but the skeleton proves the path works before any feature depends on it.

Experiment 2: what the gates catch

Planted change Stopped at Time to feedback Evidence
/health returns {"ok": "yes"} against a dict[str, bool] annotation stage 2 0.11 s Dict entry 0 has incompatible type "str": "str"; expected "str": "bool"
cut-off changed from <= to <, existing tests nowhere: promoted — all six stages passed; artefact be1bf2219c90e208 promoted
same bug + a test at exactly 20:00 stage 3 1.01 s 1 failed, 4 passed

The existing tests checked one minute either side of the cut-off and none at it, which is exactly where < and <= differ. Two lessons: gates catch only what they check (boundary tests and property tests from chapter 185 are the cheap fix), and the order matters: the type error was reported in a tenth of a second, before any test, build or deploy ran.

The lab's first run failed at stage 1 for a different reason: a ruff configuration elsewhere on the machine enabled extra rules (import sorting, timezone-aware datetimes) the skeleton didn't follow. Pinning the linter's rules in the repository (here --isolated --select E,F,I) makes the gate behave the same on every machine; the timezone rule (DTZ) is worth adopting for real once the app handles time zones.

Try it yourself

  1. Add a stage that fails if the OpenAPI schema has a breaking change compared with the main branch (e.g. oasdiff).
  2. Add a property-based test for can_skip (chapter 185) and see whether it finds the < bug without the explicit boundary test.
  3. Run the stages in parallel where possible and measure the new wall-clock time.
  4. Write the "retire" stage for the skeleton: what must be done to switch it off safely?

Revision sheet: the application lifecycle

Key ideas

  • The lifecycle is a chain of artefacts and gates: idea/brief → requirements → design (ADRs, contracts) → code → tests → build → release → operate → learn → evolve or retire.
  • Walking skeleton first: the thinnest end-to-end slice, deployed, with the pipeline in place.
  • One pipeline, all stages: contract checks, lint, type check, tests, build once, scan, sign, promote by digest, deploy, smoke test, progressive rollout.
  • Order gates cheapest and fastest first; fail fast; parallelise where independent.
  • Repository layout and conventions that make the pipeline obvious.
  • Operate and learn: SLOs, incidents, postmortems, product metrics feed the next iteration.
  • Retire deliberately: deprecate, migrate users and data, remove infrastructure and access.

Numbers to remember

  • Lab: skeleton pipeline ≈ 6 s; type error caught in 0.11 s at stage 2.
  • Lab: a boundary bug passed all six stages until a test at exactly 20:00 was added.

Pitfalls

  • Building features for weeks before the first deploy.
  • Gates that don't test edges.
  • Tool configuration that differs between laptops and CI.
  • Rebuilding artefacts per environment.
  • Forgetting the lifecycle's end: zombie services nobody owns.

Glossary

  • Walking skeleton: minimal end-to-end implementation through all stages.
  • Gate: an automated or human check a change must pass.
  • Smoke test: a quick check that a deployment basically works.
  • Promotion: moving a tested artefact to the next environment.
  • Retirement: planned shutdown of a system.