Skip to main content
CRUCIBLE
Legacy Reference Archive: This 44-chapter book reference has been distilled into Academy A01 (8 Executable Modules) with Tier-Adaptive Productive Failure, Kore/Puck voice, and live Firecracker labs.
Open Academy A01 →
COURSE 0 · SERVER BUILDING & LIFECYCLE MASTERY

Zero-to-Production Linux, Containers, Networking & Recovery

PROGRESS: 0 / 72 (0%)0/44L · 0Q · 0VM
CH 03 · PART I · FOUNDATIONS & LOCAL SERVER (CH 00–05) · 1,050 WORDS (6 MIN)

3 Build and run your first complete service

The client sends JSON containing one text field and an Idempotency-Key header. A configured bearer token identifies its tenant. The API validates the input, inserts a job in a transaction, and returns HTTP 202 with an ID. A worker processes the job.

FULL WAR-ROOM →
INTERACTIVE REQUEST FLOW · CLICK ANY HOP TO INSPECT LIVE

Production Request Path: HTTPS Edge -> App -> PgBouncer -> Postgres

Trace every hop from a browser TLS 1.3 connection to an indexed PostgreSQL row lookup.

HTTPSQLPooledNGINX EdgeTLS 1.3 · :8443 / :443FastAPI Worker127.0.0.1 :8000PgBouncer PoolTX Mux · :6432PostgreSQL 15B-Tree · :5432
SELECTED LAYER · NGINX EDGE
Terminates HTTPS, enforces timeouts and rate limits, and reverse-proxies clean HTTP to loopback.
Common failure: HTTP 502 Bad Gateway when upstream keepalive_timeout is shorter than proxy idle timeout.
$ nginx -t

Outcome: submit a durable job and retrieve its result. Prerequisites: Python basics and terminal navigation. Environment: your laptop, Python 3.12 and uv, from the included ~/playground/automation-service directory. Cost: no paid API calls. Proof: API and worker tests are recorded in the companion verification report.

Start with the contract

The client sends JSON containing one text field and an Idempotency-Key header. A configured bearer token identifies its tenant. The API validates the input, inserts a job in a transaction, and returns HTTP 202 with an ID. A worker processes the job. The client polls GET /jobs/{id} until it succeeds or fails.

The same tenant and idempotency key identify the same request. Reusing the key with identical input returns the existing job. Reusing it with different input returns 409. Another tenant cannot read the first tenant's job, even with its UUID. This is authorization in the database query, not secrecy based on an unguessable identifier.

The sample result counts words and characters. It performs no external writes, sends no messages, and calls no AI provider. That makes worker retries safe while you learn the lifecycle.

Understand the files

FileResponsibility
app.pyConfiguration, validation, API routes, persistence model, job claim/complete logic
worker.pyPolling process and graceful stop handling
mcp_adapter.pyRead-only local MCP access to jobs
setup_lab.pyCreates fresh local credentials without printing them
pyproject.toml and uv.lockRuntime requirements and exact dependency resolution
tests/Behavioral, access-control, concurrency and failure tests
Dockerfile and compose.yamlContainer packaging and local PostgreSQL environment
deploy/CaddyfileHTTPS proxy recipe for a domain you control

Read the source next to each lesson. The repository is the complete example; the PDF explains its decisions. Do not retype abbreviated excerpts and assume they contain the entire application.

Install and initialize

Install Python and uv using their official instructions if absent. Verify python3 --version and uv --version. Then, local terminal from the example directory:

bash
uv sync --frozen
uv run python setup_lab.py
set -a
. ./.env
set +a
uv run alembic upgrade head
uv run python operator_cli.py seed
uv run uvicorn app:create_app --factory --host 127.0.0.1 --port 8000

setup_lab.py uses exclusive file creation: a second run refuses to overwrite .env. That is expected. Reuse the existing file for your current lab. Source only files you trust; sourcing a shell file executes its content. This generated file contains locally generated values, not downloaded instructions.

Alembic creates or upgrades the versioned schema; the seed command installs the generated tenant credential. Review Chapter 15 before upgrading an existing v2 database. Uvicorn starts the HTTP process and keeps that terminal occupied. Leave it running. 127.0.0.1 keeps the local exercise off the public network.

In terminal 2, enter the same example directory, load the same .env, and start the worker:

bash
set -a
. ./.env
set +a
uv run python worker.py

In terminal 3, load .env again and submit a job:

bash
curl --fail-with-body http://127.0.0.1:8000/health/live
curl --fail-with-body http://127.0.0.1:8000/jobs \
  -H "Authorization: Bearer $LAB_TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: first-job' \
  --data '{"text":"hello useful servers"}'

Copy the returned UUID into JOB_ID and read it:

bash
JOB_ID='replace-with-returned-uuid'
curl --fail-with-body "http://127.0.0.1:8000/jobs/$JOB_ID" \
  -H "Authorization: Bearer $LAB_TOKEN"

Expect queued briefly, then succeeded with words: 3 and characters: 20. If it remains queued, verify that the worker is running and both processes use the same database URL and working directory. A relative SQLite path in different directories means different databases.

Shell expansion puts a bearer value into curl's arguments while it runs. Use only the disposable lab token here. For sensitive operational automation prefer a client that reads secrets internally, or a protected curl configuration supplied through a file descriptor; avoid command tracing and shared terminal recordings.

Explain the implementation

JobInput rejects unknown fields and limits text length. The middleware bounds the request body to 64 KiB. The token map is configured by the operator, so the request cannot choose its tenant. The unique database constraint enforces (tenant, request_key) even when two requests arrive concurrently. A Python-only check before insertion would have a race.

The API returns a response model containing only the ID, status, attempts, and result. It does not return stored input, tenant IDs, or credential information. Readiness queries the jobs table to detect a missing schema or unavailable database; liveness does not.

The database-backed limiter coordinates120 authenticated requests per minute per tenant across API processes. Chapter 15 explains fixed-window bursts, daily admission and retention. Edge controls are still required for unauthenticated abuse.

Run the tests

bash
uv run pytest -q
uv run pytest --cov=app --cov=mcp_adapter --cov-report=term-missing
uv run ruff check app.py worker.py mcp_adapter.py tests
uv run mypy app.py worker.py mcp_adapter.py

Tests create disposable databases and generated credentials. They do not need your live .env values. Read a failed assertion before editing the application: it tells you which contract changed. A successful test run proves the tested scenarios, not all possible inputs or workloads.

Failure exercises

Stop only the lab worker with Ctrl-C. Submit a new key, confirm the job remains queued, restart the worker, and confirm completion. Repeat the original submission and check that the ID remains unchanged. Change its text while retaining its key and expect a conflict. Remove the Authorization header and expect 401.

Create a second tenant token in a disposable configuration and prove its GET request for the first tenant's job returns 404. Never accept a client-supplied tenant field as proof of identity. Extend the test suite before changing the permission logic.

Exit and cleanup

You pass when you can explain why 202 precedes completion, why duplicate submissions do not create duplicate jobs, and why persistence survives a worker restart. Stop your API and worker with Ctrl-C. The SQLite file remains for your next session. Keep .env private and excluded from source control. Deleting that file or database is optional lab cleanup, not a required repair step.

Known limits: this reference app adds API login, scoped credentials, monitoring examples and pre-issued JWT remote MCP. It has no billing, browser UI, arbitrary code execution or complete OAuth authorization server. See Chapters 15–18 for implemented boundaries and remaining deployment work.

ACTIVE-RECALL MASTERY CHECKPOINT · CH 03

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.Why define the HTTP API contract (routes, status codes, JSON schemas, error shapes) BEFORE coding handlers?
Q2.What should a server /health endpoint verify to be useful without causing cascading outages?
Q3.Why separate configuration files/environment variables from application source code?
Answered 0 / 3