DS ForgeCourses
기존 Lab
껍데기 제거
POSTGRESQL 18.4 · PRODUCTION LAB

00SQL 다음의 데이터베이스

Database,껍데기 제거

PROJECT POLICYrelation에서 page까지, query plan에서 crash recovery까지. marketplace 한 시스템을 망가뜨리고 복구하며 PostgreSQL의 실제 경계를 배운다.

marketplace / tx-042
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

UPDATE inventory
   SET reserved = reserved + 1
 WHERE product_id = 4207
   AND stock - reserved > 0;

-- heap tuple: xmin 842 → xmax 847
-- WAL: 0/3A7F2B8 · buffer: dirty
COMMIT;
-- ERROR 40001? retry the whole tx
relationplanpageWAL
12
모듈
14
장애 fixture
16
완료 조건 / 모듈
01

SPEC

SQL 표준 또는 PostgreSQL 문서가 정의하는 계약

02

VERIFIED BEHAVIOR

pin된 PostgreSQL에서 fixture로 관찰할 동작

04

PROJECT POLICY

이 lab이 재현성과 안전을 위해 강제하는 선택

CAPSTONE STAGE · Capstone 0 · 주문·상품·결제의 경계와 키 정의

관계형 모델

행을 저장하기 전에 불변식을 설계한다
75

분 코어 루프

16

학습 단면

2

자가시험

핵심 개념

  • relation
  • tuple
  • attribute
  • primary key
  • candidate key
  • foreign key
  • constraint
  • functional dependency
  • normalization
  • denormalization
  • NULL
  • three-valued logic
  • data invariant
  • application validation vs database constraint
01

1. 실체와 오해

SPEC

관계는 같은 속성 집합을 가진 튜플의 집합이며 후보 키와 함수 종속성이 의미를 제한한다. SQL table은 중복과 NULL을 허용할 수 있으므로 수학적 관계와 완전히 같지 않다. primary key는 선택된 후보 키이고 foreign key는 참조 무결성을 표현한다.

  • 오해: ORM model이 곧 관계형 모델이다.
  • 실체: 모델의 핵심은 저장 모양이 아니라 참인 상태의 집합이다.
02

2. 선수 지식

RECOMMENDED PRACTICE

집합, predicate, 논리곱과 SQL의 기본 DDL/DML을 알고 시작한다. marketplace에서 주문번호, 판매자 SKU, 결제사 거래 ID 중 무엇이 후보 키인지 말로 먼저 적는다.

03

3. 15분 구조

PROJECT POLICY

0–3분에는 엔터티와 불변식을 적고, 3–7분에는 키와 종속성을 찾고, 7–11분에는 3NF schema를 만들고, 11–15분에는 위반 INSERT와 NULL predicate를 실행한다.

04

4. 내부 실행

VERIFIED BEHAVIOR

PostgreSQL은 UNIQUE/PRIMARY KEY를 unique B-tree로 뒷받침하고, foreign key를 trigger로 검사하며, CHECK는 행이 삽입·변경될 때 평가한다. CHECK 결과가 TRUE 또는 UNKNOWN이면 통과하므로 NULL 허용 여부는 NOT NULL로 별도 표현해야 한다.

05

5. 최소 SQL / schema

SPEC

결제의 자연 후보 키는 provider와 provider_ref의 조합이다. 금액은 통화 최소 단위 정수로 저장하고 양수 불변식을 DB에 둔다.

CREATE TABLE payment (
  payment_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id bigint NOT NULL REFERENCES orders(order_id),
  provider text NOT NULL,
  provider_ref text NOT NULL,
  amount_minor bigint NOT NULL CHECK (amount_minor > 0),
  currency char(3) NOT NULL,
  UNIQUE (provider, provider_ref)
);
06

6. Production 확장

RECOMMENDED PRACTICE

반복 그룹을 order_item으로 분리하고 product 사실과 주문 당시 가격 snapshot을 구분한다. 정규화는 갱신 이상을 줄인다. 보고 성능을 위한 비정규화는 원본과 재생성 절차, 일관성 지연을 함께 문서화할 때만 도입한다.

07

7. Query와 plan 해부

VERIFIED BEHAVIOR

PRIMARY/UNIQUE/FK는 의미 제약이며 동시에 일부 접근 경로를 만든다. PostgreSQL은 foreign key의 참조하는 열에 index를 자동 생성하지 않는다. 조인 plan이 느리다면 의미 모델과 물리 index를 별도로 검토한다.

EXPLAIN SELECT o.order_id
FROM orders o JOIN payment p USING (order_id)
WHERE p.provider = 'stripe' AND p.provider_ref = 'pi_demo';
08

8. Transaction / storage trace

VERIFIED BEHAVIOR

INSERT는 heap tuple을 만들고 관련 index와 constraint를 갱신한다. 같은 transaction 안의 FK 검사는 기본적으로 statement 끝에 완료되며 DEFERRABLE로 선언한 제약은 transaction 끝까지 미룰 수 있다. 실패하면 transaction 전체가 abort 상태가 된다.

09

9. 장애 주입

PROJECT POLICY

CHECK를 application validation으로만 옮긴 분기를 만들고 두 세션이 음수 결제와 없는 주문 참조를 쓰게 한다. `discount = NULL`과 `discount IS NULL` 결과도 비교한다. 실패가 재현되지 않으면 이 실습은 통과가 아니다.

10

10. Test

PROJECT POLICY

정상 주문 graph가 commit되는지, 중복 provider_ref·음수 금액·orphan item이 SQLSTATE와 함께 거부되는지, ON DELETE 정책이 의도대로 동작하는지 transaction test로 확인한다.

11

11. 성능과 용량

RECOMMENDED PRACTICE

키 폭은 모든 참조 index와 join 비용에 전파된다. surrogate key를 쓰더라도 자연 후보 키의 UNIQUE를 버리지 않는다. 비정규화의 읽기 절감과 write fan-out, 재구축 시간, 추가 저장량을 함께 측정한다.

12

12. 보안

RECOMMENDED PRACTICE

tenant_id를 데이터 불변식과 권한 경계 양쪽에 포함하고 composite FK로 교차 tenant 참조를 막는다. 숨겨야 할 값에 NULL을 쓰는 것은 접근 제어가 아니다.

13

13. 운영

RECOMMENDED PRACTICE

constraint 이름과 SQLSTATE를 관찰 가능하게 남기고 위반률을 배포 회귀 신호로 본다. NOT VALID 제약은 검증 상태를 운영 항목으로 추적한다.

14

14. 산출물

PROJECT POLICY

산출물은 ERD, 불변식 표, 후보 키·함수 종속성 목록, 실행 가능한 schema와 위반 fixture다.

15

15. 완료 조건

PROJECT POLICY

각 불변식의 DB 표현 또는 의도적 application-only 사유가 있고, 모든 constraint 실패 test가 통과하며, NULL의 UNKNOWN 사례를 설명할 때 완료다.

16

16. 자가시험

PROJECT POLICY

답을 보기 전 설명하라: 후보 키와 primary key는 왜 다르며, `CHECK (amount > 0)`만으로 NULL을 막을 수 없는 이유는 무엇인가?

16 / CHECK

자가시험

Q01application validation만으로 충분하지 않은 이유는?정답 확인

정답다른 writer, race, 운영 SQL이 우회할 수 있다. DB constraint는 모든 writer의 commit 경계에 불변식을 둔다.

Q023-valued logic에서 UNKNOWN인 WHERE 행은?정답 확인

정답선택되지 않는다. WHERE는 TRUE인 행만 남긴다.

02 / EXECUTE

실행 가능한 lab

PROJECT POLICY읽기만 하는 문서가 아니다. 동일한 marketplace를 migration하고, 부하를 만들고, 충돌시키고, plan과 복구 결과를 증거로 남긴다.

권장 실행 경로

Docker가 기본 기준선이며 macOS와 Windows는 같은 SQL fixture를 호출한다.

  1. 01

    PostgreSQL 18.4 primary + replica → migration → seed

    (cd lab && ./scripts/lab.sh init)
  2. 02

    schema·constraint·RLS·reporting SQL test

    (cd lab && ./scripts/lab.sh test)
  3. 03

    대표 plan과 estimate 오차 기록

    (cd lab && ./scripts/lab.sh explain)
  4. 04

    deadlock·lost update·write skew·long transaction 재현

    (cd lab && ./scripts/lab.sh transactions)
  5. 05

    깨진 archive 거부 후 격리 복구·fingerprint 검증

    (cd lab && ./scripts/lab.sh backup-restore)
  6. 06

    workload·monitoring·모든 비파괴 fault 통합 실행

    (cd lab && LAB_WORKLOAD_SECONDS=5 ./scripts/lab.sh all)
  7. 07

    Windows PowerShell 동등 실행 경로

    Push-Location lab; .\scripts\lab.ps1 all; Pop-Location
CAPSTONE / MARKETPLACEone model, escalating pressure
OLTPorder APIpool · retry · idempotency
PRIMARYPostgreSQL 18.4heap · B-tree · MVCC · WAL
REPLICAreportinglag · stale read · recovery
migrationworkloadbackupmonitor

03 / BREAK

강제 장애 지도

PROJECT POLICY각 장애는 격리된 fixture다. disk-full과 role 우회는 안전 장치와 명시적 opt-in 없이는 실행되지 않는다.

01P03

cardinality estimate

fixturelab/fixtures/plans/cardinality_before.sql

02P02

missing index

fixturelab/fixtures/plans/missing_index_before.sql

03P02

excess indexes

fixturelab/fixtures/plans/excess_indexes.sql

04P04

deadlock

fixturelab/scripts/container/transactions.sh

05P04

lost update

fixturelab/scripts/container/transactions.sh

06P04

write skew

fixturelab/scripts/container/transactions.sh

07P01

long tx → vacuum lag

fixturelab/scripts/container/transactions.sh

08P06

pool exhaustion

fixturelab/harness/pool-exhaustion.mjs

09P08

replica lag

fixturelab/scripts/container/replica-stale-read.sh

10P08

stale read

fixturelab/scripts/container/replica-stale-read.sh

11P07

migration lock

fixturelab/scripts/container/migration-lock.sh

12P11

disk full (safe simulation)

fixturelab/scripts/container/disk-full.sh

13P08

backup exists / restore fails

fixturelab/scripts/container/backup-restore.sh

14P10

RLS bypass role

fixturelab/fixtures/security/rls_bypass.sql

04 / PROVE

검증 장부

PROJECT POLICY통과한 명령과 실제 학습 효과를 같은 말로 부르지 않는다.

01

Function

build, migration, seed, SQL test, anomaly, EXPLAIN, restore 명령이 종료 코드를 남긴다.

검증됨
02

Quality

12×16 섹션·14개 장애·공식 출처·KO/EN은 정적 검사했다. 실제 브라우저·screen reader·Windows UX는 별도 검증 전까지 unverified다.

정적 검증 / 브라우저 미검증
03

Product / workflow

실제 workload 성능과 학습자가 더 빨리 진단하는지는 별도 사용자 검증 전까지 unverified다.

UNVERIFIED

05 / SOURCES

원 자료 / 공식 문서

SPEC설명보다 원문을 우선한다. 링크는 PostgreSQL 18 공식 문서와 표준·원 논문으로 제한한다.

  1. 01PostgreSQL 18 ManualPinned major-version reference for all modules; lab image pins PostgreSQL 18.4.
  2. 02PostgreSQL 18 · ConstraintsP00 · CHECK, NOT NULL, UNIQUE, primary keys, foreign keys.
  3. 03PostgreSQL 18 · Comparison Functions and OperatorsP00/P05 · NULL predicates and three-valued comparison behavior.
  4. 04E. F. Codd (1970) · A Relational Model of Data for Large Shared Data BanksP00 · Primary academic source for the relational model and normalization foundations.
  5. 05PostgreSQL 18 · Database Page LayoutP01 · Page header, item identifiers, tuple layout, normally 8 KiB page size.
  6. 06PostgreSQL 18 · Free Space MapP01 · Approximate free-space tracking.
  7. 07PostgreSQL 18 · Visibility MapP01/P02 · all-visible/all-frozen bits and index-only scans.
  8. 08PostgreSQL 18 · Routine VacuumingP01/P04/P11 · VACUUM, reuse, freeze, autovacuum, long transactions; distinguishes ordinary VACUUM from VACUUM FULL.
  9. 09PostgreSQL 18 · Write-Ahead LoggingP01/P08 · WAL write-ahead rule and crash recovery basis.
  10. 10PostgreSQL 18 · WAL ConfigurationP01/P11 · Checkpoints, WAL volume, recovery and I/O tradeoffs.
  11. 11Mohan et al. (1992) · ARIES: A Transaction Recovery MethodP01 · Primary academic source for WAL-style physiological recovery; PostgreSQL is not claimed to implement ARIES verbatim.
  12. 12PostgreSQL 18 · B-Tree IndexesP02 · B-tree operator behavior and implementation properties.
  13. 13PostgreSQL 18 · Index TypesP02 · B-tree equality, range, and ordering capabilities.
  14. 14PostgreSQL 18 · Multicolumn IndexesP02 · Leading-column rules and PostgreSQL 18 B-tree skip scan nuance.
  15. 15PostgreSQL 18 · Index-Only Scans and Covering IndexesP02 · INCLUDE payloads, visibility map, heap fetch conditions.
  16. 16PostgreSQL 18 · Partial IndexesP02 · Predicate implication and parameterized-query limitations.
  17. 17PostgreSQL 18 · Indexes on ExpressionsP02 · Expression indexes and write cost.
  18. 18PostgreSQL 18 · CREATE INDEXP02/P07 · Unique/INCLUDE indexes and concurrent-build phases/limitations.
  19. 19Bayer & McCreight (1972) · Organization and Maintenance of Large Ordered IndicesP02 · Original B-tree family research; PostgreSQL-specific behavior comes from the PostgreSQL manual/source.
  20. 20PostgreSQL 18 · Using EXPLAINP03 · Costs, rows, loops, EXPLAIN ANALYZE execution and plan reading.
  21. 21PostgreSQL 18 · Statistics Used by the PlannerP03 · MCV, histograms, n_distinct and extended statistics.
  22. 22PostgreSQL 18 · Row Estimation ExamplesP03 · Selectivity and cardinality-estimation mechanics.
  23. 23PostgreSQL 18 · Planner/OptimizerP03 · Query-tree to plan-tree pipeline and path search.
  24. 24PostgreSQL 18 · Concurrency ControlP04 · MVCC, isolation, locking and consistency overview.
  25. 25PostgreSQL 18 · Transaction IsolationP04 · PostgreSQL isolation semantics, no dirty reads, serialization failures.
  26. 26PostgreSQL 18 · Explicit LockingP04/P07 · Table/row/advisory locks and deadlocks.
  27. 27Berenson et al. (1995) · A Critique of ANSI SQL Isolation LevelsP04 · Primary academic source for isolation anomaly terminology.
  28. 28Cahill, Röhm & Fekete (2008) · Serializable Isolation for Snapshot DatabasesP04 · Primary academic source for Serializable Snapshot Isolation.
  29. 29PostgreSQL 18 · Window FunctionsP05 · Window partitions, ordering, frames and row grain.
  30. 30PostgreSQL 18 · WITH QueriesP05 · CTE folding/materialization and recursive/data-modifying WITH.
  31. 31PostgreSQL 18 · LIMIT and OFFSETP05 · Deterministic ordering and OFFSET cost/semantics.
  32. 32PostgreSQL 18 · Date/Time TypesP05 · timestamptz, time zones and daylight-saving behavior.
  33. 33PostgreSQL 18 · Numeric TypesP05 · Exact numeric versus floating-point behavior for money models.
  34. 34PostgreSQL 18 · INSERTP05/P06 · ON CONFLICT, RETURNING and privilege rules.
  35. 35PostgreSQL 18 · Message FlowP06 · Connection/session protocol, extended query flow and cancellation context.
  36. 36PostgreSQL 18 · PREPAREP06 · Session scope and generic/custom prepared plans.
  37. 37PostgreSQL 18 · Client Connection DefaultsP06 · statement/lock/idle transaction timeouts and session settings.
  38. 38PostgreSQL 18 · Error CodesP04/P06/P07 · Stable SQLSTATE classification for retry/test policies.
  39. 39PostgreSQL 18 · Modifying TablesP07 · Add/drop columns and constraints with version-scoped behavior.
  40. 40PostgreSQL 18 · ALTER TABLEP07 · Lock levels, NOT VALID/VALIDATE, rewrite and partition operations.
  41. 41PostgreSQL 18 · Log-Shipping Standby ServersP08 · Physical streaming, asynchronous default, lag, failover and hot-standby conflicts.
  42. 42PostgreSQL 18 · Logical ReplicationP08 · Publications, subscriptions and row-change replication.
  43. 43PostgreSQL 18 · Logical Replication RestrictionsP08 · DDL, sequence state, replica identity and object compatibility limits.
  44. 44PostgreSQL 18 · Backup and RestoreP08/P11 · SQL dumps, file-system backups, continuous archiving and restore concepts.
  45. 45PostgreSQL 18 · Continuous Archiving and Point-in-Time RecoveryP08 · Base backups, WAL archives, recovery targets and timelines.
  46. 46PostgreSQL 18 · pg_basebackupP08 · Physical base-backup creation, manifests and WAL options.
  47. 47PostgreSQL 18 · pg_verifybackupP08 · Manifest/file verification and its explicit limits versus a restore drill.
  48. 48PostgreSQL 18 · Table PartitioningP09 · Routing, pruning, partitioned indexes, uniqueness and maintenance.
  49. 49PostgreSQL 18 · Database RolesP10 · Roles, attributes, ownership and membership.
  50. 50PostgreSQL 18 · PrivilegesP10 · Object ownership, grants and least privilege.
  51. 51PostgreSQL 18 · Row Security PoliciesP10 · USING/WITH CHECK, owner, FORCE RLS, superuser/BYPASSRLS behavior.
  52. 52PostgreSQL 18 · CREATE FUNCTIONP10 · SECURITY DEFINER and safe configuration/search_path guidance.
  53. 53PostgreSQL 18 · Cumulative Statistics SystemP01/P02/P03/P08/P11 · Activity, table/index, WAL, replication and progress statistics.
  54. 54PostgreSQL 18 · Viewing LocksP04/P07/P11 · pg_locks and lock-manager diagnostics.
  55. 55PostgreSQL 18 · Determining Disk UsageP01/P11 · Relation/database size inspection and disk planning.
  56. 56PostgreSQL 18 · pg_stat_statementsP03/P05/P06/P11 · Normalized query execution statistics and caveats.
  57. 57PostgreSQL 18 · Resource ConsumptionP03/P06/P11 · Memory, vacuum, disk and planner resource settings.
  58. 58PostgreSQL 18 · pg_visibilityP01 · Lab-only inspection of visibility-map state.
  59. 59PostgreSQL 18 · pgstattupleP01/P04 · Lab inspection of live/dead tuple and free-space state.
  60. 60PostgreSQL 18 · pageinspectP01/P02 · Lab-only heap and B-tree page inspection.
  61. 61PostgreSQL 18 · Serialization Failure HandlingP04/P06 · Whole-transaction retries for serialization/deadlock failures.
  62. 62PostgreSQL 18 · Role AttributesP10 · SUPERUSER, BYPASSRLS, LOGIN and connection-related role attributes.
  63. 63PostgreSQL 18 · Predefined RolesP10/P11 · pg_monitor and other privileged built-in roles.
  64. 64PostgreSQL 18 · Error Reporting and LoggingP10/P11 · Statement/parameter logging, redaction risk and operational telemetry.
  65. 65PostgreSQL 18 · Secure TCP/IP Connections with SSLP06/P10 · TLS transport protection and certificate configuration.
Database, 껍데기 제거

PostgreSQL 18.4 · marketplace production lab · KO / EN

TOP ↑