TT Lab
Blog Get started
Learn Learning paths Courses

Production Backend API Capstone

Capstone: An Idempotent Order API That Holds the Tenant Boundary

Continue in TT Lab

Goal

You complete one order API with its production responsibilities attached. You connect the data contract, transactional idempotency, organization-boundary authorization, running HTTP, the three observability signals, a safe deployment object, and documentation you can hand to someone else, all in one project.

Each of the eight steps is graded on a different axis (correctness, security, problem solving, operations, documentation).

Warning about time and storage: read this first

So it is designed on the assumption that you finish in one sitting. If you think you will run short of time, it is better to make a shallow pass through all 8 steps than to go deep on the first 3 and lose everything. If you have to leave midway, bundle the project folder with tar and download it by hand.

Environment

PostgreSQL 16 is already running.

postgresql://lab@127.0.0.1:5432/labdb

The project root is /root/work/backend-capstone, and the grader looks only at this path. Create it first.

mkdir -p /root/work/backend-capstone
cd /root/work/backend-capstone
mkdir -p migrations tests docs deploy

Files to create

app.py                          psycopg 로 붙고 --host/--port 로 뜬다
migrations/001_create_orders.sql  BEGIN/COMMIT 으로 감싼 순방향 마이그레이션
tests/test_integration.py       재시도와 다른 조직 반례를 행동으로 검증
deploy/deployment.yaml          JSON 으로도 읽히는 YAML
docs/ADR-001.md                 status/context/alternatives/decision/consequences
docs/incident-report.md         impact/timeline/root cause/detection/corrective actions
portfolio.json                  backend-capstone-v2 스키마

One check that runs before every step

Before the step checks, the grader scans the whole project for secrets. If anything is found, it fails with the same message no matter which step is being graded, so it is easy to waste time looking for the cause in that step.

비밀번호가 들어간 접속 문자열   postgresql://lab:1234@...
클러스터 내부 주소             *.svc.cluster.local
Bearer 토큰 원문               Authorization: Bearer eyJ...
password/api_key/secret 대입   password = "hunter2"
개인 키                        -----BEGIN PRIVATE KEY-----

Take connection details from environment variables, and write example tokens as placeholders such as <token>. Size limits are checked too: within 4,096 files, 1 MB per file, and 8 MB in total. .git and __pycache__ are not counted.

Steps

  1. Data contract: In the orders table, add an identity PK, an amount_cents > 0 check, owner_id and org_id, created_at timestamptz, unique(org_id, idempotency_key), and a lookup index on (org_id, owner_id). Wrap all of it in BEGIN;/COMMIT;.
  2. Transactional idempotency: Absorb retries with ON CONFLICT (org_id, idempotency_key), and roll back on exceptions. Always bind values as parameters.
  3. Authorization: authenticate builds the identity, and authorize(identity, order) looks at the organization first, then the owner and admin. This file must print nothing at all, even when only imported.
  4. HTTP: It must start with python3 app.py --host 127.0.0.1 --port <포트> (replace the placeholder with a port number). Provide POST /orders, GET /orders/{id}, POST /orders/{id}/cancel, and /healthz, plus X-Trace-Id on every response. Distinguish the status codes 201/200/400/401/403.
  5. Observability: orders_created_total, http_request_duration_seconds, and a JSON log containing event, route, status, duration_ms, and trace_id. Do not record the authorization header or internal DNS.
  6. Deployment: In deploy/deployment.yaml, include non-root, seccompProfile: RuntimeDefault, allowPrivilegeEscalation: false, a read-only root, requests/limits, two probes, secretKeyRef, and a digest-pinned image.
  7. Documentation: An ADR and an incident report. In the incident report, list an owner and a due date for every action.
  8. Portfolio: Put only the five allowed summaries in portfolio.json. Do not include original headers, tokens, private IPs, internal DNS, or terminal history.

Notes

The condition in step 3, "it must be quiet even when imported," is where you get caught every time. If you connect to the database or call print at the top of the module, the grader sees that output. Move the connecting into main() and diagnostics into a logger.

Run the PostgreSQL 16 schema

Data contract: In the orders table, add an identity PK, an amount_cents > 0 check, owner_id and org_id, created_at timestamptz, unique(org_id, idempotency_key), and a lookup index on (org_id, owner_id). Wrap all of it in BEGIN;/COMMIT;.

In migrations/001_create_orders.sql, create the identity PK, a positive amount, owner/org, an organization-scoped idempotency UNIQUE, TIMESTAMPTZ, and the lookup index, and wrap it in a transaction. app.py must use psycopg.

Implement transactional idempotent creation

Transactional idempotency: Absorb retries with ON CONFLICT (org_id, idempotency_key), and roll back on exceptions. Always bind values as parameters.

Use a psycopg transaction/cursor with parameter binding and ON CONFLICT (org_id, idempotency_key), and roll back on exceptions. Write the retry and other-organization counterexamples as behavior tests.

Separate authentication from owner and organization authorization

Authorization: authenticate builds the identity, and authorize(identity, order) looks at the organization first, then the owner and admin. This file must print nothing at all, even when only imported.

authenticate builds a Bearer identity, and authorize(identity, order) judges the organization first, then the owner/admin relationship. Do not leave tokens in import-time output or error output.

Open up the real HTTP API contract

HTTP: It must start with python3 app.py --host 127.0.0.1 --port <포트> (replace the placeholder with a port number). Provide POST /orders, GET /orders/{id}, POST /orders/{id}/cancel, and /healthz, plus X-Trace-Id on every response. Distinguish the status codes 201/200/400/401/403.

Support app.py --host ... --port ... using the standard library or an installed runtime. Implement POST /orders, GET /orders/id, POST /orders/id/cancel, health/readiness, and the status, JSON, and X-Trace-Id contract.

Connect the three observability signals to the request

Observability: orders_created_total, http_request_duration_seconds, and a JSON log containing event, route, status, duration_ms, and trace_id. Do not record the authorization header or internal DNS.

Connect orders_created_total, http_request_duration_seconds, the event/route/status/duration_ms in the JSON log, and the response trace ID. Do not record Authorization or internal DNS.

Create a parseable, safe deployment object

Deployment: In deploy/deployment.yaml, include non-root, seccompProfile: RuntimeDefault, allowPrivilegeEscalation: false, a read-only root, requests/limits, two probes, secretKeyRef, and a digest-pinned image.

Write deploy/deployment.yaml as JSON-compatible YAML. Put non-root/seccomp/no privilege escalation/read-only root, resources, two probes, the Secret reference, and the digest image at the exact object paths.

Connect the ADR and incident learning

Documentation: An ADR and an incident report. In the incident report, list an owner and a due date for every action.

Write status/context/alternatives/decision/consequences in the ADR, and impact/timeline/root cause/detection/corrective actions with owners and due dates in the incident report, and remove secrets and internal addresses.

Publish an allowlist-only portfolio

Portfolio: Put only the five allowed summaries in portfolio.json. Do not include original headers, tokens, private IPs, internal DNS, or terminal history.

Pin portfolio.json to backend-capstone-v2 and include only test_summary, metric_names, deployment_summary, adr_summary, and incident_summary. Original headers, tokens, private IPs, internal DNS, and terminal logs are forbidden.