GetClaps
Ücretsiz DenetimFiyatlandırmaSözlükAkademi
  1. Ana sayfa
  2. /Akademi
  3. /L13 · Operations: verification, deployment, observability, incidents

Ana sayfa / Akademi / L13 · Operations: verification, deployment, observability, incidents

L13Bölüm D · Şirket olarak yönetmekOrtaKod doğrulama tarihi: 2026-12-04

Operations: verification, deployment, observability, incidents

How the verification gate proves code on every machine, how deployment and backups work, and how you contain incidents safely.

24 dk·4663 kelime·7 soru·34 terim·docs/lessons/13-operations.md
Ön koşul:L02 · How we build: git, pull requests, tests, CI, waves and agents
Tüm derslere dön
●

Ders içerikleri İngilizce yayınlanır (OD-23)

Sayfa çerçevesi Türkçe ve İngilizce olarak sunulur. Teknik ders metinleri, kod örnekleri ve kendini sına soruları doğrudan ortak kaynak dosyalarından İngilizce okunur; hukuk ve ürün terimlerinde Türkçe karşılıklar yer alır.

0%
▲Yanıtlanan sorular
0 / 7
—
○Doğruluk oranı
Henüz yanıt yok

Bu dersteki bölümler

  1. 1.Why this matters
  2. 2.The ideas
  3. 3.How this repository does it
  4. 4.What went wrong once
  5. 5.Try it yourself
  6. 6.Check yourself
  7. 7.Words to know
  8. 8.Go deeper

Why this matters

Good application code still fails a business if you cannot prove it works on a clean machine, start it without silent misconfiguration, restore it after a disk loss, or stop a runaway bug in minutes. On 2 December 2026, an independent review re-ran this repository from a clean Linux clone and proved two facts: starting the API with NODE_ENV=production and no database URL still opened its port and answered "dataSource":"sample_memory" on /health, while database migrations were applied by nothing outside tests. Shipping silent fallbacks like that puts empty protections in front of real customers. Today the verification gate, fail-fast startup checks, migration CLI, local backup drills and offline smoke checks are built and verified locally. Nothing is deployed yet, no real Meta or Google call has been made, and there are no live customers.

●

In plain words

operations turns working code on a laptop into a service you can verify reproducibly, deploy safely, watch clearly, restore on time and freeze calmly during an incident.

The ideas

One manifest, two runners, zero silent skips

In How we build, you met bash tools/verify from the user's seat. Underneath, operations rests on one rule: your computer and continuous integration must run the exact same checks in the exact same order, and a skipped check must never pass quietly.

When a team maintains one list in a local shell script and another hand-typed list in .github/workflows/verify.yml, the two drift apart quickly. If a test runner also skips database tests when PostgreSQL is missing, a broken migration reports green. This repository avoids both traps by storing every step once in a gate manifest, organising steps into eight gate groups, declaring external prerequisites as gate needs, and checking strict two-way agreement with a parity gate.

Gate groupStepsWhat it verifiesTypical needs
core4Typecheck, workspace tests, closed UI tokens, schema DDLpg18
static42File audits (--self-test plus live), gate parity, learning checknone
suites5Contract parity, chaos and races, release journeys, fuzz suitespg18 (2 of 5)
postgres5Live PostgreSQL 18 security matrix, DB/vault suites, collector E2E, pg_dump drillspg18, pg_dump
deploy6Caddy headers, Docker hardening, VPS dry run, offline smoke, restore dry run, dev-stack checkbash, pg18
scanners3Working-tree and git-history secret scans (gitleaks), lockfile CVE scan (osv-scanner)gitleaks, osv-scanner, network
build1Production Next.js web buildnone
browser4Real Chromium sign-in, connect, event-and-approval and full-stack journeyspg18, chromium

Every step in the verification gate finishes as passed, failed, or not run (<reason>). Missing osv-scanner or passing --offline marks that step not run, never passed; passing --require-pg turns missing PostgreSQL 18 into a hard failure. A static gate reads files directly without starting a server or database and ships its own --self-test that injects faults to prove it fails closed.

On GitHub, a fresh Linux CI runner (ubuntu-latest) installs Node 24, pnpm 12, PostgreSQL 18 from PGDG, gitleaks, osv-scanner and Chromium, then executes all 70 steps in manifest order. Under OD-17, the CI trigger fires on every push to main, every pull request into main and manual workflow_dispatch. The common mistake is trusting a headline pass count without reading the not run column, commit SHA and tool versions.

Security gates and the human go/no-go decision

Automated tests prove code invariants, not legal or partner readiness. Operations separates technical verification from human launch approval into two layers.

First, six mandatory security gates (G1 to G6) test the core threat model: cross-tenant FORCE ROW LEVEL SECURITY isolation, encrypted vault denial, expiring SHA-256 preview approvals, hash-on-ingest personal data and consent gating, SSRF-isolated crawling plus zero-tool AI red-teaming, and raw-body HMAC verification plus immutable tax and audit ledgers, paired with gitleaks and osv-scanner. One honest detail to know when reading older docs: docs/THREAT-MODEL.md and AGENTS.md rule 21 order G3 through G6 slightly differently because rule 21 kept an older research list, though both enforce the exact same automated suites. Always read the topic name beside the gate number.

Second, AGENTS.md rule 22 requires an explicit human go/no-go decision. A green CI run never opens live users, real ad accounts or live money automatically. Under OD-05, launch splits into two founder-signed stages:

  1. Stage 1 (single-player SaaS): requires a locked brand name and domain (OD-01), written KVKK counsel sign-off (issue 3, C1–C3), clean Turkey-resident PostgreSQL hosting (OD-04), a passing restore drill, full bash tools/verify receipts, external auth review (OD-14, issue 97) and written founder sign-off.
  2. Stage 2 (marketplace safeguarded payments): keeps live checkout in sandbox until fintech counsel and a sworn financial adviser (YMM) sign off on Law 6493, 3/10 VAT withholding (KDV tevkifatı), 1 percent e-commerce withholding (e-ticaret stopajı) and e-invoicing (issue 3, C4–C10), sandbox rehearsals pass with zero kuruş drift, and both owners approve.

The usual mistake is mistaking green software tests for legal clearance. Software cannot sign a tax opinion or approve a Meta or Shopify app review.

Four environments and clean cutover

An environment is an isolated copy of the system with its own database, secrets and data rules. Only the first two exist live today:

EnvironmentStatus todayPurposeData allowed
Local workstationActiveDaily development and local testsSynthetic Sample data only
Hosted CI (ubuntu-latest)ActiveClean-machine verification on push and PREphemeral fixtures only
StagingDesigned (not provisioned)Rehearsing containers, migrations, sign-in and backupsSynthetic Sample data only (OD-04)
ProductionNot built or provisionedLive shops, live ad accounts and live paymentsReal customer data after OD-04, OD-05 and owner sign-off

Under OD-04, staging can run on a low-cost EU server strictly because it holds zero live Turkish personal data. In private staging, the proxy binds only to server loopback, the firewall opens only SSH (port 22), and owners open the app through an ssh -L tunnel on localhost, which browsers treat as a secure context for passkeys and __Host- cookies without needing a public domain.

Moving to production requires a clean cutover. Under OD-04, you never dump synthetic EU staging rows into production: you build a fresh Turkey-resident PostgreSQL 18 server and separate Turkey-resident backup bucket, run migrations and least-privilege role setup, pass restore-drill.sh --enforce-tr-local, and verify zero non-TR_LOCAL Turkish workspaces before admitting live businesses.

Configuration that fails fast

Think of fail-fast configuration like an aircraft pre-flight checklist that stops takeoff on a missing sensor instead of flying anyway. Software goes one step further: it can also inspect its own database schema automatically before opening a port.

Development allows convenient shortcuts such as sample memory and an ephemeral vault key. Production forbids every one of them. Under NODE_ENV=production, the loader refuses to start if DATABASE_URL is missing or uses a local dev password, if signing secrets are under 32 bytes, if VAULT_MASTER_KEK_BASE64 is missing, malformed or all-zero, if mail or WEB_ORIGIN settings are missing, or if the test-only fake provider switch is set. It also rejects invalid values like NODE_ENV=staging or NODE_ENV=prod.

On any error, the process logs one structured JSON line (api.config_error or dispatch.config_error) with stable codes only — never secret values — and exits 1 before creating a pool or listening. Once running, GET /health reports the data source label (postgres_rls or sample_memory). The usual mistake is generating a random key or falling back to sample memory quietly, which hides broken deployments until a restart destroys every stored token.

Packaging on one origin: Docker Compose, Caddy, migrations and roles

Under AGENTS.md rule 20, deployment stays intentionally simple: Docker Compose and Caddy on one Linux host, with zero Kubernetes or microservices until a measured bottleneck justifies them.

text
Internet / SSH tunnel
        |
        v
  [ Caddy reverse proxy ]  (TLS 1.2/1.3, security headers, scrubbed logs)
        |
        +--> Web app (Next.js standalone, :3000) ---- zero DB or vault creds
        |
        +--> Core API (Fastify, :4000) -------------- app_login + vault_login + KEK
        |
        v
  [ internal_zone2 (no internet egress) ]
        |
        +--> PostgreSQL 18.7 (:5432, loopback only)
        |      ^-- pnpm db:migrate (migration role, before app boot)
        |      ^-- dispatch process (app_login + vault_login + KEK, no port)
        |      ^-- general worker (app_login only, zero vault creds)
        |
  [ egress_zone3 (isolated crawler network) ]
        +--> seo-worker (2 GB RAM cap, zero DB or vault creds)

Four rules anchor this layout:

  1. One origin for host-only cookies. Because __Host-gd_session carries the __Host- prefix (ADR-0010), browsers send it only to the exact host that issued it. Routing both web pages and /v1/* API paths through one reverse proxy origin lets authenticated browser calls carry the cookie cleanly.
  2. Hardened containers. Application services run as a non-root container with cap_drop: [ALL], no-new-privileges:true, a read-only root filesystem, a process cap (pids_limit: 256) and a small noexec /tmp.
  3. Explicit migrations and split roles. Every new database runs in strict order: docs/schema.sql, then deploy/postgres/init-roles.sql, then pnpm db:migrate using MIGRATION_DATABASE_URL (read only from the environment, never placed in web, API or worker env files). On boot in production, the API, worker and dispatch compare public.schema_migrations against shipped files and refuse to start if the schema is behind, unreadable or unreachable (API exits 1; worker and dispatch exit 78 for behind/unreadable and 13 for unreachable).
  4. Immediate verification. Right after deployment, a smoke test checks /health, Caddy headers, 404 blocks on /metrics and /internal/*, and live PostgreSQL role restrictions.

The mistake people usually make is running web or worker processes as the database superuser, which lets a single query bug bypass every row-level security policy and read vault.*.

Backups, restore drills, RPO and RTO

Two metrics define recovery readiness:

  • Recovery point objective (RPO): the oldest unbacked writes you accept losing. Nightly backups alone risk losing up to 24 hours; continuous WAL archiving with archive_timeout=300 targets RPO under 15 minutes (900 s).
  • Recovery time objective (RTO): total elapsed time to decrypt a backup, restore it cleanly, replay WAL and prove integrity. The target here is RTO under 30 minutes (1,800 s).

An untested backup is a guess. A restore drill unpacks an encrypted backup into an isolated scratch folder on a non-production port (refusing 5432 and forcing archive_mode=off), times elapsed recovery against the RTO budget, and runs six automated SQL proofs: audit_log SHA-256 hash-chain continuity against vault.audit_chain_head, all base tables and 23 FORCE ROW LEVEL SECURITY tables, {product}_app vault denial, all 7 security triggers plus kuruş balance invariants, zero retained PII on erased contacts, and TR_LOCAL residency when --enforce-tr-local is passed.

One legal rule is easy to forget: KVKK erasure replay. Because encrypted backups stay immutable for 14 days, restoring yesterday's snapshot can resurrect a contact erased under KVKK Article 7 this morning. Before reopening traffic after any point-in-time restore, operators must replay the minimal PII-free erasure tombstone journal (workspace_id, contact_id, erased_at) so deleted people never resurface or fire ad conversions.

Observability, health checks, proxy rate limits and graceful shutdown

Four built-in mechanisms let you observe and control running services safely:

  1. PII-free structured logging and bounded metrics. Pino emits one JSON line per event with [REDACTED] scrubbing across headers, cookies, tokens, emails, phones, IBANs, tax IDs and config secrets. Caddy strips secret headers and query keys, masks IPs to /24 (IPv4) or /48 (IPv6), and uses log_skip so OAuth callback URLs carrying one-time codes never reach access logs. For Prometheus metrics, a closed sanitiser allows only eight low-cardinality labels (service, route_group, status_class, data_source, provider, queue, mode, result) and rejects personal data or UUIDs.
  2. Honest health checks. GET /health returns HTTP 200 with status, service, dataSource, schema and timestamp, exposing database mode and migration state immediately.
  3. Proxy-aware rate limits (trust proxy). Production enables fixed-window IP limits on /v1/auth/* (60 per 60 s), /v1/audit/preview (30 per 60 s) and /v1/marketers/apply (10 per 3600 s), returning 429 RATE_LIMITED with Retry-After. Setting TRUST_PROXY=loopback (or explicit proxy CIDRs) lets Fastify read the client IP from Caddy instead of collapsing every user into one 127.0.0.1 bucket; numeric hop counts are rejected so direct clients cannot forge X-Forwarded-For.
  4. Graceful shutdown. On SIGTERM, SIGINT or a Windows test IPC shutdown message, the API stops accepting new traffic, drains active work up to a 10-second hard timeout, closes both database pools, calls zeroizeBuffer on the vault KEK, logs api.shutdown_complete and exits 0.

Load testing and chaos testing

A load test sends bursts and sustained waves of concurrent requests to measure p50, p95 and p99 latency, throughput (RPS) and error rate. Averages hide pain: 99 fast 10 ms replies and 1 stalled 5-second reply average 60 ms while one user waited five seconds. Local loopback benchmarks catch regressions early, yet never prove live wide-area-network SLAs.

A chaos test injects failures and simultaneous conflicting writes — such as racing KVKK erasure against event dispatch or replaying signed webhooks — to prove invariants survive under real concurrency.

Incidents: hard-stops, the kill switch, runbooks and blameless post-mortems

Six non-negotiable failures are SEV-0 hard-stops: cross-tenant leakage, credential or raw PII exposure, unconsented or post-erasure dispatch, unapproved spend mutation, fabricated KPIs or missing-as-zero defects, and kuruş tax drift or trial auto-charges. Either owner may freeze the affected surface immediately (halt under 15 minutes, full lock under 1 hour).

The primary brake is the global kill switch (workspaces.kill_switch_active = true). Enforced in both API code and PostgreSQL trigger trg_approval_requests_guardrails, it blocks budget raises, campaign launches and tracking edits while keeping META_PAUSE_ENTITY, GOOGLE_PAUSE_ENTITY and safeguarded-payment dispute holds open so owners can stop active spend right away.

During an incident, responders follow a written runbook: contain first, preserve audit_log rows and request IDs, revoke compromised marketer grants in one click, rotate exposed KEKs and begin the 72-hour KVKK Article 12 breach-assessment clock if personal data may be affected. Afterwards, you write a blameless post-mortem fixing the systemic gap and adding a negative-control test before reopening the frozen path.

How this repository does it

Every operational safeguard built on this branch maps to verified files:

CapabilityFiles on this branchWhat breaks if removedStatus
Verification manifest & runnertools/verify, tools/run-gates.mjs, tools/gates.manifest.jsonLocal runs drift from CI; missing tools skip silentlyBuilt, verified locally
CI workflow & parity gate.github/workflows/verify.yml, tools/check-gate-parity.mjsMissing CI steps, unlisted triggers or count ratchets slip inBuilt, verified locally
Fail-fast runtime configruntime-config.ts, server.ts, dispatch-main.tsProduction silently serves sample_memory, dev passwords or fake providersBuilt, verified locally
Migration CLI & schema guardcli.ts, schema-guard.ts, deploy/postgres/README.mdNew code serves against an outdated schema missing triggersBuilt, verified locally
Pool safety & clean shutdowndb-connection-errors.ts, server-lifecycle.ts, worker-main.tsDB restarts crash processes; deploys drop work without wiping keysBuilt, verified locally
Logs, health, rate limits & metricslogger.ts, app.ts, hardening.ts, rate-limit.ts, metrics-sanitizer.tsSecrets/PII leak into logs; proxied clients share one rate-limit bucketBuilt, verified locally
Deploy, proxy & VPS blueprintsdocker-compose.staging.yml, Caddyfile, env.staging.example, bootstrap-vps.sh, deploy/systemdRoot containers, exposed DB ports, logged OAuth codes or env-name driftBuilt, verified locally (not deployed)
Restore drills & smoke testbackup-restore-drill.mjs, restore-drill.sh, staging-smoke.mjsCorrupt backups, tampered dumps or broken RLS go undetectedBuilt, verified locally
Load, chaos & runbooksload-bench.mjs, chaos-and-races.test.mjs, RUNBOOK.md, INCIDENT-RESPONSE-AND-KILL-SWITCH-PLAYBOOK.md, DISASTER-RECOVERY-AND-BCP-CHARTER.md, docs/runbooksRaces go untested; responders improvise during SEV-0 outagesBuilt / drafted

Process privileges split cleanly across server.ts, dispatch-main.ts and worker-main.ts. Only the API and dispatch process hold VAULT_DATABASE_URL and VAULT_MASTER_KEK_BASE64. The general worker stays vault-less (APP_DATABASE_URL only), purges expired sign-in and OAuth flows hourly, logs worker.heartbeat every 15 seconds, and refuses built-in dry-run adapters in production unless opted into explicitly for synthetic staging. The unit templates under deploy/systemd ({product}-api.service, {product}-dispatch.service, {product}-web.service and {product}-worker.service) isolate each service under its own user and 0600 env file.

ts
// apps/api/src/app.ts — exact /health payload verified by Docker and staging-smoke.mjs
app.get('/health', async () => ({
  status: 'ok',
  service: 'api',
  dataSource,
  schema: schemaHealth,
  timestamp: now().toISOString(),
}));

The manual benchmark tests/perf/load-bench.mjs starts an ephemeral local PostgreSQL 18 cluster and Fastify server to run 6,880 HTTP requests across 86 endpoints (30 x 86 burst plus 50 x 86 sustained at concurrency 25) and sits outside tools/gates.manifest.json so timing runs stay intentional.

◆

Not built yet

single-origin Caddy routing, private staging over an SSH tunnel (ssh -L), a one-shot Compose migrate service, and a loopback-only console mailer switch are designed in WS-A.md and are not merged onto this branch yet. On this branch today, deploy/caddy/Caddyfile still serves APP_DOMAIN and API_DOMAIN separately, so host-only __Host-gd_session cookies cannot reach the API until single-origin routing lands (issue 20).

◆

Not built yet

no live EU staging VPS, no Turkey-resident production PostgreSQL VPS (OD-04, issue 20), no scheduled off-VPS pgBackRest bucket, no live Prometheus/alerting stack or status page, no live 48 GB GPU vLLM node (issue 27), and no written counsel/YMM sign-off (OD-05, issue 3) or external auth review (OD-14, issue 97) exist yet.

What went wrong once

Production quietly served sample data and stub workers (findings P-1 and P-3)

During the 2 December 2026 review (INDEPENDENT-REVIEW-2026-12-02.md), starting NODE_ENV=production node src/server.ts without DATABASE_URL bound its port and answered "dataSource":"sample_memory" on /health, while the worker defaulted to stub adapters returning fake trace IDs. Leaving development fallbacks on the production path caused both defects. Wave 45 (C-REPORT.md) added fail-fast validation in runtime-config.ts and dry-run refusal in worker-main.ts, and Wave 48 (A-REPORT.md) moved real dispatch to dispatch-main.ts. Lesson: a server must refuse to start rather than boot silently wrong.

A PostgreSQL restart crashed the API and the worker (finding P-12)

Wave 45 API suites failed teardown with exit code 1 (57P01) after every test had passed. Reading the pg driver exposed a real production flaw: no error listener was attached to the pool, so a dead idle socket crashed Node.js. Fixing that revealed a second bug: once the worker lost its sockets, nothing kept its event loop alive and it exited 12 ms later. Wave 45 (G-REPORT.md) wired createDbConnectionErrorLogger (db-connection-errors.ts) into every pool, added a keep-alive timer, and pinned both with red-control tests. Lesson: flaky teardown noise often hides a real production outage.

Process signals on Windows broke graceful-shutdown tests

Running bash tools/verify on Windows in Wave 46 (E-REPORT.md) failed seven shutdown tests because child.kill('SIGTERM') hard-kills Windows processes without running cleanup handlers. Adding installIpcShutdownHandler in server-lifecycle.ts let test parents send { type: 'shutdown', signal } over an IPC channel while leaving Linux SIGTERM handlers untouched. Lesson: when owners develop on Windows and deploy on Linux, the gate must pass on both.

A backup round trip caught a CHECK constraint that came back different

In Wave 48 (A-REPORT.md), a new CHECK constraint using BETWEEN ... AND ... AND ... failed pg_dump_drills because PostgreSQL reformatted its parentheses on dump and restore. Rewriting it as a flat >= AND <= AND chain restored exact parity (5/5 drills passing). Lesson: automated restore drills catch subtle schema drift before real data depends on it.

Deploy templates and runtime disagreed on the vault master key's name

In Wave 48 (A-REPORT.md), runtime-config.ts read VAULT_MASTER_KEK_BASE64 while compose and bootstrap templates still set VAULT_KEK_V1. Wave 48 unified every template on VAULT_MASTER_KEK_BASE64 and added deploy-env-runtime-agreement.test.ts to validate every deploy template directly through the production loader. Lesson: test deploy files against the program's own loader so your first deploy is never the test.

Try it yourself

Every step below is read-only or in-memory. None touches your running local dev stack (ports 3000, 4000, 5432), edits repository files or calls external providers. Run from the repository root.

Step 1: print the full verification plan without running anything

Run in Git Bash:

bash
bash tools/verify --list

Expected output: all 70 ordered steps across eight groups with their needs, ending in exit code 0.

Step 2: run the gate-parity check and its fail-closed self-test

Run in Windows PowerShell or Git Bash:

bash
node tools/check-gate-parity.mjs --self-test
node tools/check-gate-parity.mjs

Expected output: negative-mutation self-tests pass and the live audit confirms tools/gates.manifest.json matches .github/workflows/verify.yml 1:1.

Step 3: dry-run the encrypted backup restore-drill script

Run in Git Bash:

bash
bash deploy/backups/restore-drill.sh --dry-run

Expected output: planned scratch folder, non-production port (55432), RPO (900s) and RTO (1800s) budgets, all six SQL checks, and STATUS: dry-run (not executed against a live backup).

Step 4: run the offline staging smoke check and Caddy header tests

Run in Windows PowerShell or Git Bash:

bash
node deploy/staging-smoke.mjs --offline
node --test deploy/caddy/security-headers.test.mjs

Expected output: both exit 0, confirming offline deploy blueprints, OpenAPI route parity, Caddy security headers, /metrics blocks and OAuth log_skip rules.

Step 5: test deploy templates against the fail-fast production loader

Run in Windows PowerShell or Git Bash:

bash
pnpm --filter @{product}/api exec vitest run test/deploy-env-runtime-agreement.test.ts

Expected output: every test passes, proving deploy/env.staging.example, deploy/docker-compose.staging.yml and deploy/scripts/bootstrap-vps.sh satisfy loadApiRuntimeConfig and loadDispatchRuntimeConfig while keeping vault keys out of the worker template.

○

Note

the full local encrypted pg_dump drill (node --test tests/db/backup-restore-drill.mjs) starts its own temporary PostgreSQL 18 cluster on a free port and cleans up afterwards, leaving port 5432 untouched.

Check yourself

0 / 7

Q1.Why does tools/gates.manifest.json declare explicit needs (such as pg18 or network) on steps?

Q2.What happens if you start a newly deployed API in NODE_ENV=production before running pnpm db:migrate?

Q3.Why must TRUST_PROXY be set to loopback (or explicit proxy CIDRs) behind Caddy rather than left unset or set to 1?

Q4.Why does apps/api/src/dispatch-main.ts run separately from apps/api/src/worker-main.ts?

Q5.After restoring a 12-hour-old PostgreSQL backup during a disaster, what mandatory privacy step must finish before reopening traffic?

Q6.When kill_switch_active = true is set, why are META_PAUSE_ENTITY and GOOGLE_PAUSE_ENTITY still permitted?

Q7.All 70 steps of bash tools/verify pass in GitHub Actions. May you open live Turkish safeguarded payments immediately?

Words to know

34
Caddy

An open-source web server and reverse proxy configured in one Caddyfile, with automatic HTTPS certificates.

Operasyon ve doğrulamaSözlükte incele
chaos testTR: kaos testi

An automated test that triggers crashes, errors or competing simultaneous requests to prove safety rules hold under stress.

Operasyon ve doğrulamaSözlükte incele
CI runner

A fresh temporary Linux server that GitHub spins up to execute one continuous-integration workflow run.

Operasyon ve doğrulamaSözlükte incele
CI trigger

The repository event that automatically starts a continuous-integration workflow run.

Operasyon ve doğrulamaSözlükte incele
cutover

The planned move from a rehearsal or old environment to the real production system serving live traffic.

Operasyon ve doğrulamaSözlükte incele
data source label

The field returned by the API health check stating whether answers come from real PostgreSQL or built-in sample memory.

Operasyon ve doğrulamaSözlükte incele
Docker Compose

A Docker tool and YAML file format that defines and runs a multi-container stack as one coordinated unit.

Operasyon ve doğrulamaSözlükte incele
environmentTR: ortam

An isolated copy of the system with its own database, secrets and settings, such as local, CI, staging or production.

Operasyon ve doğrulamaSözlükte incele
fail-fast configuration

Validating every required setting at boot and exiting immediately on any error instead of starting in a broken mode.

Operasyon ve doğrulamaSözlükte incele
gate group

A named slice of the verification gate manifest that lets you run related checks together.

Operasyon ve doğrulamaSözlükte incele
gate manifest

The single JSON file that lists every required verification step, command, group and prerequisite in exact order.

Operasyon ve doğrulamaSözlükte incele
gate need

An external tool or capability declared on a gate step so missing prerequisites report not run instead of passed.

Operasyon ve doğrulamaSözlükte incele
go/no-go decision

A formal human release decision made against written evidence before opening live users, ad accounts or payments.

Operasyon ve doğrulamaSözlükte incele
graceful shutdown

Stopping a running server by finishing active work, closing connections and wiping secrets from memory before exiting.

Operasyon ve doğrulamaSözlükte incele
hard-stopTR: sert durdurma kuralı

A non-negotiable safety failure that immediately freezes the affected feature regardless of business pressure.

Operasyon ve doğrulamaSözlükte incele
health checkTR: sağlık kontrolü

A lightweight endpoint a proxy, container platform or operator calls to verify that a service is alive and ready.

Operasyon ve doğrulamaSözlükte incele
load testTR: yük testi

A test that fires many concurrent requests at a running server to measure throughput, latency and stability.

Operasyon ve doğrulamaSözlükte incele
non-root container

A container hardened to run as an unprivileged user with Linux capabilities dropped and a read-only root filesystem.

Operasyon ve doğrulamaSözlükte incele
parity gate

An automated check that fails whenever the local gate manifest and the CI workflow run different steps, order or env.

Operasyon ve doğrulamaSözlükte incele
pnpm db:migrate

The repository command that applies pending numbered SQL migrations to PostgreSQL before a new release starts.

Operasyon ve doğrulamaSözlükte incele
post-mortemTR: olay sonrası inceleme

A blameless written review after an incident detailing what happened, why controls missed it and what fixes prevent repeats.

Operasyon ve doğrulamaSözlükte incele
private staging

A staging deployment bound only to the server's loopback interface so owners reach it solely through an SSH tunnel.

Operasyon ve doğrulamaSözlükte incele
productionTR: üretim ortamı

The live customer environment that holds real business data, real ad-account connections and real payments.

Operasyon ve doğrulamaSözlükte incele
recovery point objectiveRPO

The maximum age of recent data, measured in minutes, that a business accepts losing during a disaster restore.

Operasyon ve doğrulamaSözlükte incele
recovery time objectiveRTOTR: kurtarma süresi hedefi

The maximum time allowed to rebuild a failed service, restore its backup and verify integrity before reopening traffic.

Operasyon ve doğrulamaSözlükte incele
restore drillTR: yedek geri yükleme tatbikatı

An automated rehearsal that restores an encrypted database backup into a scratch instance and verifies every security rule.

Operasyon ve doğrulamaSözlükte incele
reverse proxyTR: ters vekil

A front-door server that accepts public HTTPS requests, enforces security policies and forwards traffic to internal apps.

Operasyon ve doğrulamaSözlükte incele
runbook

A step-by-step operational guide with exact commands and checks for running routine procedures or handling incidents.

Operasyon ve doğrulamaSözlükte incele
smoke test

A fast post-deployment check verifying that core endpoints, security headers and database permissions work before opening traffic.

Operasyon ve doğrulamaSözlükte incele
staging

A private pre-production copy of the system built like production but holding only synthetic sample data for rehearsals.

Operasyon ve doğrulamaSözlükte incele
static gateTR: statik kapı

A fast automated check that scans source, schema and doc files directly without starting a server or database.

Operasyon ve doğrulamaSözlükte incele
structured loggingTR: yapısal günlükleme

Emitting every log entry as a single JSON object with stable field names rather than unformatted free text.

Operasyon ve doğrulamaSözlükte incele
trust proxy

The server setting naming which upstream reverse proxies are allowed to report the real client IP address.

Operasyon ve doğrulamaSözlükte incele
verification gate

The single ordered suite of automated checks run by bash tools/verify locally and mirrored step-for-step in CI.

Operasyon ve doğrulamaSözlükte incele

Go deeper

In this repository

  • Master operations runbook and OD-04/OD-05 checklists: docs/RUNBOOK.md
  • Verification gate contract and branch protection: docs/VERIFICATION.md
  • Incident playbooks and SEV-0 hard-stops: docs/INCIDENT-RESPONSE-AND-KILL-SWITCH-PLAYBOOK.md
  • Disaster recovery and business continuity charter: docs/DISASTER-RECOVERY-AND-BCP-CHARTER.md
  • Local benchmark honesty policy (TR): docs/LOCAL-ENGINEERING-BENCHMARKS-AND-VERIFICATION-POLICY-TR.md
  • Release 1 owner go/no-go evidence pack: docs/RELEASE-1-GO-NO-GO-EVIDENCE-PACK.md
  • Wave 49 private staging design brief: docs/wave49/briefs/WS-A.md
  • Threat model (T1–T8, G1–G6) and repository rules: docs/THREAT-MODEL.md and AGENTS.md
  • PostgreSQL roles and migration workflow: deploy/postgres/README.md

Archived lessons replaced by this lesson

  • Archived lesson 11: load testing, chaos and observability
  • Archived lesson 17: hands-on lab workbook and drills
  • Archived lesson 18: incident postmortems and security audit playbook
  • Archived lesson 29: operational SLA, webhook delivery health and rollout readiness
  • Archive index: docs/lessons/archive/README.md

Official external documentation

  • Docker Compose overview and profiles
  • Docker Engine security and container hardening
  • Caddy 2 documentation and log directive
  • PostgreSQL 18 backup and continuous archiving (PITR)
  • pgBackRest user guide
  • Fastify trustProxy reference
  • Pino structured logger documentation
  • GitHub Actions workflow triggers and hosted runners
  • Node.js EventEmitter error events and process signals
  • systemd service unit manual
◆

NOT LEGAL OR TAX ADVICE · Açık karar kapıları dürüstlüğü

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Önceki ders: L12Sonraki ders: L14

L13 · Part D · intermediate · Verified 2026-12-04 · 24 min

Operations: verification, deployment, observability, incidents

How the verification gate proves code on every machine, how deployment and backups work, and how you contain incidents safely.

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Why this matters

Good application code still fails a business if you cannot prove it works on a clean machine, start it without silent misconfiguration, restore it after a disk loss, or stop a runaway bug in minutes. On 2 December 2026, an independent review re-ran this repository from a clean Linux clone and proved two facts: starting the API with NODE_ENV=production and no database URL still opened its port and answered "dataSource":"sample_memory" on /health, while database migrations were applied by nothing outside tests. Shipping silent fallbacks like that puts empty protections in front of real customers. Today the verification gate, fail-fast startup checks, migration CLI, local backup drills and offline smoke checks are built and verified locally. Nothing is deployed yet, no real Meta or Google call has been made, and there are no live customers.

●

In plain words

operations turns working code on a laptop into a service you can verify reproducibly, deploy safely, watch clearly, restore on time and freeze calmly during an incident.

The ideas

One manifest, two runners, zero silent skips

In How we build, you met bash tools/verify from the user's seat. Underneath, operations rests on one rule: your computer and continuous integration must run the exact same checks in the exact same order, and a skipped check must never pass quietly.

When a team maintains one list in a local shell script and another hand-typed list in .github/workflows/verify.yml, the two drift apart quickly. If a test runner also skips database tests when PostgreSQL is missing, a broken migration reports green. This repository avoids both traps by storing every step once in a gate manifest, organising steps into eight gate groups, declaring external prerequisites as gate needs, and checking strict two-way agreement with a parity gate.

Gate groupStepsWhat it verifiesTypical needs
core4Typecheck, workspace tests, closed UI tokens, schema DDLpg18
static42File audits (--self-test plus live), gate parity, learning checknone
suites5Contract parity, chaos and races, release journeys, fuzz suitespg18 (2 of 5)
postgres5Live PostgreSQL 18 security matrix, DB/vault suites, collector E2E, pg_dump drillspg18, pg_dump
deploy6Caddy headers, Docker hardening, VPS dry run, offline smoke, restore dry run, dev-stack checkbash, pg18
scanners3Working-tree and git-history secret scans (gitleaks), lockfile CVE scan (osv-scanner)gitleaks, osv-scanner, network
build1Production Next.js web buildnone
browser4Real Chromium sign-in, connect, event-and-approval and full-stack journeyspg18, chromium

Every step in the verification gate finishes as passed, failed, or not run (<reason>). Missing osv-scanner or passing --offline marks that step not run, never passed; passing --require-pg turns missing PostgreSQL 18 into a hard failure. A static gate reads files directly without starting a server or database and ships its own --self-test that injects faults to prove it fails closed.

On GitHub, a fresh Linux CI runner (ubuntu-latest) installs Node 24, pnpm 12, PostgreSQL 18 from PGDG, gitleaks, osv-scanner and Chromium, then executes all 70 steps in manifest order. Under OD-17, the CI trigger fires on every push to main, every pull request into main and manual workflow_dispatch. The common mistake is trusting a headline pass count without reading the not run column, commit SHA and tool versions.

Security gates and the human go/no-go decision

Automated tests prove code invariants, not legal or partner readiness. Operations separates technical verification from human launch approval into two layers.

First, six mandatory security gates (G1 to G6) test the core threat model: cross-tenant FORCE ROW LEVEL SECURITY isolation, encrypted vault denial, expiring SHA-256 preview approvals, hash-on-ingest personal data and consent gating, SSRF-isolated crawling plus zero-tool AI red-teaming, and raw-body HMAC verification plus immutable tax and audit ledgers, paired with gitleaks and osv-scanner. One honest detail to know when reading older docs: docs/THREAT-MODEL.md and AGENTS.md rule 21 order G3 through G6 slightly differently because rule 21 kept an older research list, though both enforce the exact same automated suites. Always read the topic name beside the gate number.

Second, AGENTS.md rule 22 requires an explicit human go/no-go decision. A green CI run never opens live users, real ad accounts or live money automatically. Under OD-05, launch splits into two founder-signed stages:

  1. Stage 1 (single-player SaaS): requires a locked brand name and domain (OD-01), written KVKK counsel sign-off (issue 3, C1–C3), clean Turkey-resident PostgreSQL hosting (OD-04), a passing restore drill, full bash tools/verify receipts, external auth review (OD-14, issue 97) and written founder sign-off.
  2. Stage 2 (marketplace safeguarded payments): keeps live checkout in sandbox until fintech counsel and a sworn financial adviser (YMM) sign off on Law 6493, 3/10 VAT withholding (KDV tevkifatı), 1 percent e-commerce withholding (e-ticaret stopajı) and e-invoicing (issue 3, C4–C10), sandbox rehearsals pass with zero kuruş drift, and both owners approve.

The usual mistake is mistaking green software tests for legal clearance. Software cannot sign a tax opinion or approve a Meta or Shopify app review.

Four environments and clean cutover

An environment is an isolated copy of the system with its own database, secrets and data rules. Only the first two exist live today:

EnvironmentStatus todayPurposeData allowed
Local workstationActiveDaily development and local testsSynthetic Sample data only
Hosted CI (ubuntu-latest)ActiveClean-machine verification on push and PREphemeral fixtures only
StagingDesigned (not provisioned)Rehearsing containers, migrations, sign-in and backupsSynthetic Sample data only (OD-04)
ProductionNot built or provisionedLive shops, live ad accounts and live paymentsReal customer data after OD-04, OD-05 and owner sign-off

Under OD-04, staging can run on a low-cost EU server strictly because it holds zero live Turkish personal data. In private staging, the proxy binds only to server loopback, the firewall opens only SSH (port 22), and owners open the app through an ssh -L tunnel on localhost, which browsers treat as a secure context for passkeys and __Host- cookies without needing a public domain.

Moving to production requires a clean cutover. Under OD-04, you never dump synthetic EU staging rows into production: you build a fresh Turkey-resident PostgreSQL 18 server and separate Turkey-resident backup bucket, run migrations and least-privilege role setup, pass restore-drill.sh --enforce-tr-local, and verify zero non-TR_LOCAL Turkish workspaces before admitting live businesses.

Configuration that fails fast

Think of fail-fast configuration like an aircraft pre-flight checklist that stops takeoff on a missing sensor instead of flying anyway. Software goes one step further: it can also inspect its own database schema automatically before opening a port.

Development allows convenient shortcuts such as sample memory and an ephemeral vault key. Production forbids every one of them. Under NODE_ENV=production, the loader refuses to start if DATABASE_URL is missing or uses a local dev password, if signing secrets are under 32 bytes, if VAULT_MASTER_KEK_BASE64 is missing, malformed or all-zero, if mail or WEB_ORIGIN settings are missing, or if the test-only fake provider switch is set. It also rejects invalid values like NODE_ENV=staging or NODE_ENV=prod.

On any error, the process logs one structured JSON line (api.config_error or dispatch.config_error) with stable codes only — never secret values — and exits 1 before creating a pool or listening. Once running, GET /health reports the data source label (postgres_rls or sample_memory). The usual mistake is generating a random key or falling back to sample memory quietly, which hides broken deployments until a restart destroys every stored token.

Packaging on one origin: Docker Compose, Caddy, migrations and roles

Under AGENTS.md rule 20, deployment stays intentionally simple: Docker Compose and Caddy on one Linux host, with zero Kubernetes or microservices until a measured bottleneck justifies them.

Internet / SSH tunnel
        |
        v
  [ Caddy reverse proxy ]  (TLS 1.2/1.3, security headers, scrubbed logs)
        |
        +--> Web app (Next.js standalone, :3000) ---- zero DB or vault creds
        |
        +--> Core API (Fastify, :4000) -------------- app_login + vault_login + KEK
        |
        v
  [ internal_zone2 (no internet egress) ]
        |
        +--> PostgreSQL 18.7 (:5432, loopback only)
        |      ^-- pnpm db:migrate (migration role, before app boot)
        |      ^-- dispatch process (app_login + vault_login + KEK, no port)
        |      ^-- general worker (app_login only, zero vault creds)
        |
  [ egress_zone3 (isolated crawler network) ]
        +--> seo-worker (2 GB RAM cap, zero DB or vault creds)

Four rules anchor this layout:

  1. One origin for host-only cookies. Because __Host-gd_session carries the __Host- prefix (ADR-0010), browsers send it only to the exact host that issued it. Routing both web pages and /v1/* API paths through one reverse proxy origin lets authenticated browser calls carry the cookie cleanly.
  2. Hardened containers. Application services run as a non-root container with cap_drop: [ALL], no-new-privileges:true, a read-only root filesystem, a process cap (pids_limit: 256) and a small noexec /tmp.
  3. Explicit migrations and split roles. Every new database runs in strict order: docs/schema.sql, then deploy/postgres/init-roles.sql, then pnpm db:migrate using MIGRATION_DATABASE_URL (read only from the environment, never placed in web, API or worker env files). On boot in production, the API, worker and dispatch compare public.schema_migrations against shipped files and refuse to start if the schema is behind, unreadable or unreachable (API exits 1; worker and dispatch exit 78 for behind/unreadable and 13 for unreachable).
  4. Immediate verification. Right after deployment, a smoke test checks /health, Caddy headers, 404 blocks on /metrics and /internal/*, and live PostgreSQL role restrictions.

The mistake people usually make is running web or worker processes as the database superuser, which lets a single query bug bypass every row-level security policy and read vault.*.

Backups, restore drills, RPO and RTO

Two metrics define recovery readiness:

  • Recovery point objective (RPO): the oldest unbacked writes you accept losing. Nightly backups alone risk losing up to 24 hours; continuous WAL archiving with archive_timeout=300 targets RPO under 15 minutes (900 s).
  • Recovery time objective (RTO): total elapsed time to decrypt a backup, restore it cleanly, replay WAL and prove integrity. The target here is RTO under 30 minutes (1,800 s).

An untested backup is a guess. A restore drill unpacks an encrypted backup into an isolated scratch folder on a non-production port (refusing 5432 and forcing archive_mode=off), times elapsed recovery against the RTO budget, and runs six automated SQL proofs: audit_log SHA-256 hash-chain continuity against vault.audit_chain_head, all base tables and 23 FORCE ROW LEVEL SECURITY tables, {product}_app vault denial, all 7 security triggers plus kuruş balance invariants, zero retained PII on erased contacts, and TR_LOCAL residency when --enforce-tr-local is passed.

One legal rule is easy to forget: KVKK erasure replay. Because encrypted backups stay immutable for 14 days, restoring yesterday's snapshot can resurrect a contact erased under KVKK Article 7 this morning. Before reopening traffic after any point-in-time restore, operators must replay the minimal PII-free erasure tombstone journal (workspace_id, contact_id, erased_at) so deleted people never resurface or fire ad conversions.

Observability, health checks, proxy rate limits and graceful shutdown

Four built-in mechanisms let you observe and control running services safely:

  1. PII-free structured logging and bounded metrics. Pino emits one JSON line per event with [REDACTED] scrubbing across headers, cookies, tokens, emails, phones, IBANs, tax IDs and config secrets. Caddy strips secret headers and query keys, masks IPs to /24 (IPv4) or /48 (IPv6), and uses log_skip so OAuth callback URLs carrying one-time codes never reach access logs. For Prometheus metrics, a closed sanitiser allows only eight low-cardinality labels (service, route_group, status_class, data_source, provider, queue, mode, result) and rejects personal data or UUIDs.
  2. Honest health checks. GET /health returns HTTP 200 with status, service, dataSource, schema and timestamp, exposing database mode and migration state immediately.
  3. Proxy-aware rate limits (trust proxy). Production enables fixed-window IP limits on /v1/auth/* (60 per 60 s), /v1/audit/preview (30 per 60 s) and /v1/marketers/apply (10 per 3600 s), returning 429 RATE_LIMITED with Retry-After. Setting TRUST_PROXY=loopback (or explicit proxy CIDRs) lets Fastify read the client IP from Caddy instead of collapsing every user into one 127.0.0.1 bucket; numeric hop counts are rejected so direct clients cannot forge X-Forwarded-For.
  4. Graceful shutdown. On SIGTERM, SIGINT or a Windows test IPC shutdown message, the API stops accepting new traffic, drains active work up to a 10-second hard timeout, closes both database pools, calls zeroizeBuffer on the vault KEK, logs api.shutdown_complete and exits 0.

Load testing and chaos testing

A load test sends bursts and sustained waves of concurrent requests to measure p50, p95 and p99 latency, throughput (RPS) and error rate. Averages hide pain: 99 fast 10 ms replies and 1 stalled 5-second reply average 60 ms while one user waited five seconds. Local loopback benchmarks catch regressions early, yet never prove live wide-area-network SLAs.

A chaos test injects failures and simultaneous conflicting writes — such as racing KVKK erasure against event dispatch or replaying signed webhooks — to prove invariants survive under real concurrency.

Incidents: hard-stops, the kill switch, runbooks and blameless post-mortems

Six non-negotiable failures are SEV-0 hard-stops: cross-tenant leakage, credential or raw PII exposure, unconsented or post-erasure dispatch, unapproved spend mutation, fabricated KPIs or missing-as-zero defects, and kuruş tax drift or trial auto-charges. Either owner may freeze the affected surface immediately (halt under 15 minutes, full lock under 1 hour).

The primary brake is the global kill switch (workspaces.kill_switch_active = true). Enforced in both API code and PostgreSQL trigger trg_approval_requests_guardrails, it blocks budget raises, campaign launches and tracking edits while keeping META_PAUSE_ENTITY, GOOGLE_PAUSE_ENTITY and safeguarded-payment dispute holds open so owners can stop active spend right away.

During an incident, responders follow a written runbook: contain first, preserve audit_log rows and request IDs, revoke compromised marketer grants in one click, rotate exposed KEKs and begin the 72-hour KVKK Article 12 breach-assessment clock if personal data may be affected. Afterwards, you write a blameless post-mortem fixing the systemic gap and adding a negative-control test before reopening the frozen path.

How this repository does it

Every operational safeguard built on this branch maps to verified files:

CapabilityFiles on this branchWhat breaks if removedStatus
Verification manifest & runnertools/verify, tools/run-gates.mjs, tools/gates.manifest.jsonLocal runs drift from CI; missing tools skip silentlyBuilt, verified locally
CI workflow & parity gate.github/workflows/verify.yml, tools/check-gate-parity.mjsMissing CI steps, unlisted triggers or count ratchets slip inBuilt, verified locally
Fail-fast runtime configruntime-config.ts, server.ts, dispatch-main.tsProduction silently serves sample_memory, dev passwords or fake providersBuilt, verified locally
Migration CLI & schema guardcli.ts, schema-guard.ts, deploy/postgres/README.mdNew code serves against an outdated schema missing triggersBuilt, verified locally
Pool safety & clean shutdowndb-connection-errors.ts, server-lifecycle.ts, worker-main.tsDB restarts crash processes; deploys drop work without wiping keysBuilt, verified locally
Logs, health, rate limits & metricslogger.ts, app.ts, hardening.ts, rate-limit.ts, metrics-sanitizer.tsSecrets/PII leak into logs; proxied clients share one rate-limit bucketBuilt, verified locally
Deploy, proxy & VPS blueprintsdocker-compose.staging.yml, Caddyfile, env.staging.example, bootstrap-vps.sh, deploy/systemdRoot containers, exposed DB ports, logged OAuth codes or env-name driftBuilt, verified locally (not deployed)
Restore drills & smoke testbackup-restore-drill.mjs, restore-drill.sh, staging-smoke.mjsCorrupt backups, tampered dumps or broken RLS go undetectedBuilt, verified locally
Load, chaos & runbooksload-bench.mjs, chaos-and-races.test.mjs, RUNBOOK.md, INCIDENT-RESPONSE-AND-KILL-SWITCH-PLAYBOOK.md, DISASTER-RECOVERY-AND-BCP-CHARTER.md, docs/runbooksRaces go untested; responders improvise during SEV-0 outagesBuilt / drafted

Process privileges split cleanly across server.ts, dispatch-main.ts and worker-main.ts. Only the API and dispatch process hold VAULT_DATABASE_URL and VAULT_MASTER_KEK_BASE64. The general worker stays vault-less (APP_DATABASE_URL only), purges expired sign-in and OAuth flows hourly, logs worker.heartbeat every 15 seconds, and refuses built-in dry-run adapters in production unless opted into explicitly for synthetic staging. The unit templates under deploy/systemd ({product}-api.service, {product}-dispatch.service, {product}-web.service and {product}-worker.service) isolate each service under its own user and 0600 env file.

// apps/api/src/app.ts — exact /health payload verified by Docker and staging-smoke.mjs
app.get('/health', async () => ({
  status: 'ok',
  service: 'api',
  dataSource,
  schema: schemaHealth,
  timestamp: now().toISOString(),
}));

The manual benchmark tests/perf/load-bench.mjs starts an ephemeral local PostgreSQL 18 cluster and Fastify server to run 6,880 HTTP requests across 86 endpoints (30 x 86 burst plus 50 x 86 sustained at concurrency 25) and sits outside tools/gates.manifest.json so timing runs stay intentional.

◆

Not built yet

single-origin Caddy routing, private staging over an SSH tunnel (ssh -L), a one-shot Compose migrate service, and a loopback-only console mailer switch are designed in WS-A.md and are not merged onto this branch yet. On this branch today, deploy/caddy/Caddyfile still serves APP_DOMAIN and API_DOMAIN separately, so host-only __Host-gd_session cookies cannot reach the API until single-origin routing lands (issue 20).

◆

Not built yet

no live EU staging VPS, no Turkey-resident production PostgreSQL VPS (OD-04, issue 20), no scheduled off-VPS pgBackRest bucket, no live Prometheus/alerting stack or status page, no live 48 GB GPU vLLM node (issue 27), and no written counsel/YMM sign-off (OD-05, issue 3) or external auth review (OD-14, issue 97) exist yet.

What went wrong once

Production quietly served sample data and stub workers (findings P-1 and P-3)

During the 2 December 2026 review (INDEPENDENT-REVIEW-2026-12-02.md), starting NODE_ENV=production node src/server.ts without DATABASE_URL bound its port and answered "dataSource":"sample_memory" on /health, while the worker defaulted to stub adapters returning fake trace IDs. Leaving development fallbacks on the production path caused both defects. Wave 45 (C-REPORT.md) added fail-fast validation in runtime-config.ts and dry-run refusal in worker-main.ts, and Wave 48 (A-REPORT.md) moved real dispatch to dispatch-main.ts. Lesson: a server must refuse to start rather than boot silently wrong.

A PostgreSQL restart crashed the API and the worker (finding P-12)

Wave 45 API suites failed teardown with exit code 1 (57P01) after every test had passed. Reading the pg driver exposed a real production flaw: no error listener was attached to the pool, so a dead idle socket crashed Node.js. Fixing that revealed a second bug: once the worker lost its sockets, nothing kept its event loop alive and it exited 12 ms later. Wave 45 (G-REPORT.md) wired createDbConnectionErrorLogger (db-connection-errors.ts) into every pool, added a keep-alive timer, and pinned both with red-control tests. Lesson: flaky teardown noise often hides a real production outage.

Process signals on Windows broke graceful-shutdown tests

Running bash tools/verify on Windows in Wave 46 (E-REPORT.md) failed seven shutdown tests because child.kill('SIGTERM') hard-kills Windows processes without running cleanup handlers. Adding installIpcShutdownHandler in server-lifecycle.ts let test parents send { type: 'shutdown', signal } over an IPC channel while leaving Linux SIGTERM handlers untouched. Lesson: when owners develop on Windows and deploy on Linux, the gate must pass on both.

A backup round trip caught a CHECK constraint that came back different

In Wave 48 (A-REPORT.md), a new CHECK constraint using BETWEEN ... AND ... AND ... failed pg_dump_drills because PostgreSQL reformatted its parentheses on dump and restore. Rewriting it as a flat >= AND <= AND chain restored exact parity (5/5 drills passing). Lesson: automated restore drills catch subtle schema drift before real data depends on it.

Deploy templates and runtime disagreed on the vault master key's name

In Wave 48 (A-REPORT.md), runtime-config.ts read VAULT_MASTER_KEK_BASE64 while compose and bootstrap templates still set VAULT_KEK_V1. Wave 48 unified every template on VAULT_MASTER_KEK_BASE64 and added deploy-env-runtime-agreement.test.ts to validate every deploy template directly through the production loader. Lesson: test deploy files against the program's own loader so your first deploy is never the test.

Try it yourself

Every step below is read-only or in-memory. None touches your running local dev stack (ports 3000, 4000, 5432), edits repository files or calls external providers. Run from the repository root.

Step 1: print the full verification plan without running anything

Run in Git Bash:

bash tools/verify --list

Expected output: all 70 ordered steps across eight groups with their needs, ending in exit code 0.

Step 2: run the gate-parity check and its fail-closed self-test

Run in Windows PowerShell or Git Bash:

node tools/check-gate-parity.mjs --self-test
node tools/check-gate-parity.mjs

Expected output: negative-mutation self-tests pass and the live audit confirms tools/gates.manifest.json matches .github/workflows/verify.yml 1:1.

Step 3: dry-run the encrypted backup restore-drill script

Run in Git Bash:

bash deploy/backups/restore-drill.sh --dry-run

Expected output: planned scratch folder, non-production port (55432), RPO (900s) and RTO (1800s) budgets, all six SQL checks, and STATUS: dry-run (not executed against a live backup).

Step 4: run the offline staging smoke check and Caddy header tests

Run in Windows PowerShell or Git Bash:

node deploy/staging-smoke.mjs --offline
node --test deploy/caddy/security-headers.test.mjs

Expected output: both exit 0, confirming offline deploy blueprints, OpenAPI route parity, Caddy security headers, /metrics blocks and OAuth log_skip rules.

Step 5: test deploy templates against the fail-fast production loader

Run in Windows PowerShell or Git Bash:

pnpm --filter @{product}/api exec vitest run test/deploy-env-runtime-agreement.test.ts

Expected output: every test passes, proving deploy/env.staging.example, deploy/docker-compose.staging.yml and deploy/scripts/bootstrap-vps.sh satisfy loadApiRuntimeConfig and loadDispatchRuntimeConfig while keeping vault keys out of the worker template.

○

Note

the full local encrypted pg_dump drill (node --test tests/db/backup-restore-drill.mjs) starts its own temporary PostgreSQL 18 cluster on a free port and cleans up afterwards, leaving port 5432 untouched.

Words to know

  • Caddy
  • Chaos test
  • CI runner
  • CI trigger
  • Cutover
  • Data source label
  • Docker Compose
  • Environment
  • Fail-fast configuration
  • Gate group
  • Gate manifest
  • Gate need
  • Go/no-go decision
  • Graceful shutdown
  • Hard-stop
  • Health check
  • Load test
  • Non-root container
  • Parity gate
  • pnpm db:migrate
  • Post-mortem
  • Private staging
  • Production
  • Recovery point objective
  • Recovery time objective
  • Restore drill
  • Reverse proxy
  • Runbook
  • Smoke test
  • Staging
  • Static gate
  • Structured logging
  • Trust proxy
  • Verification gate

Go deeper

In this repository

  • Master operations runbook and OD-04/OD-05 checklists: docs/RUNBOOK.md
  • Verification gate contract and branch protection: docs/VERIFICATION.md
  • Incident playbooks and SEV-0 hard-stops: docs/INCIDENT-RESPONSE-AND-KILL-SWITCH-PLAYBOOK.md
  • Disaster recovery and business continuity charter: docs/DISASTER-RECOVERY-AND-BCP-CHARTER.md
  • Local benchmark honesty policy (TR): docs/LOCAL-ENGINEERING-BENCHMARKS-AND-VERIFICATION-POLICY-TR.md
  • Release 1 owner go/no-go evidence pack: docs/RELEASE-1-GO-NO-GO-EVIDENCE-PACK.md
  • Wave 49 private staging design brief: docs/wave49/briefs/WS-A.md
  • Threat model (T1–T8, G1–G6) and repository rules: docs/THREAT-MODEL.md and AGENTS.md
  • PostgreSQL roles and migration workflow: deploy/postgres/README.md

Archived lessons replaced by this lesson

  • Archived lesson 11: load testing, chaos and observability
  • Archived lesson 17: hands-on lab workbook and drills
  • Archived lesson 18: incident postmortems and security audit playbook
  • Archived lesson 29: operational SLA, webhook delivery health and rollout readiness
  • Archive index: docs/lessons/archive/README.md

Official external documentation

  • Docker Compose overview and profiles
  • Docker Engine security and container hardening
  • Caddy 2 documentation and log directive
  • PostgreSQL 18 backup and continuous archiving (PITR)
  • pgBackRest user guide
  • Fastify trustProxy reference
  • Pino structured logger documentation
  • GitHub Actions workflow triggers and hosted runners
  • Node.js EventEmitter error events and process signals
  • systemd service unit manual

Kendini sına soru özeti ve yanıt anahtarı

Q1. Why does tools/gates.manifest.json declare explicit needs (such as pg18 or network) on steps?

Answer: B

Explicit needs let tools/run-gates.mjs probe the host upfront and label unrunnable steps not run (<reason>) instead of faking a green pass. Silent skipping (A) is the exact defect that hid broken suites before Wave 45.

Q2. What happens if you start a newly deployed API in NODE_ENV=production before running pnpm db:migrate?

Answer: C

runSchemaGuard checks public.schema_migrations before listening and refuses to start in production when the schema is behind. Option A cannot work because {product}_app_login does not own tables, and option B would reintroduce finding P-1.

Q3. Why must TRUST_PROXY be set to loopback (or explicit proxy CIDRs) behind Caddy rather than left unset or set to 1?

Answer: A

Behind local Caddy, every socket arrives from 127.0.0.1; without TRUST_PROXY=loopback all users share one bucket, whereas parseTrustProxy refuses numeric hop counts (TRUST_PROXY_HOP_COUNT_UNSUPPORTED) to stop header spoofing. Trusting * (D) would let anyone forge IPs to bypass limits.

Q4. Why does apps/api/src/dispatch-main.ts run separately from apps/api/src/worker-main.ts?

Answer: B

Event delivery and token refresh need vault decryption, while housekeeping and general queues do not. Keeping dispatch separate keeps every VAULT_* secret out of worker.env. Node.js supports multiple pools easily (A — server.ts already uses two).

Q5. After restoring a 12-hour-old PostgreSQL backup during a disaster, what mandatory privacy step must finish before reopening traffic?

Answer: C

Restoring an older backup can restore contacts erased under KVKK Article 7 afterwards; replaying the erasure tombstone log first ensures deleted people stay erased. Clearing audit_log (A) destroys forensic evidence, and shifting live Turkish PII to the EU (B) violates OD-04.

Q6. When kill_switch_active = true is set, why are META_PAUSE_ENTITY and GOOGLE_PAUSE_ENTITY still permitted?

Answer: B

Halting a runaway live campaign requires pausing it on Meta or Google. Allowing PAUSE actions (and safeguarded-payment dispute holds) while hard-blocking spend increases and launches is an intentional T031 control, not an omission (A).

Q7. All 70 steps of bash tools/verify pass in GitHub Actions. May you open live Turkish safeguarded payments immediately?

Answer: C

Passing automated tests proves technical contracts on synthetic fixtures; it never provisions TR-local servers, closes legal/tax sign-off (OD-05) or overrides AGENTS.md rule 22. Treating green CI (A) or a local benchmark (D) as launch permission breaks repository truth rules.

GetClaps Kurucu Akademisi · Tarayıcı açılışında ağ çağrısı yapılmaz; ilerleme yalnızca cihazındaki yerel depolamada tutulur.