Unit 3 of 8 · about 4 hours · explain, implement
Schema versions, compatibility and migrations
Schemas change while old readers are still running. An additive field with a default keeps both directions working, while a rename without a transition breaks one side silently. Version policy plus a tested downgrade makes evolution boring.
You'll be able to
- Derive the valid states of a versioned record across validation, quarantine, normalization and persistence.
- Design a backward-compatible schema change with explicit mixed-version behavior and a tested rollback.
- Classify DDL changes as compatible or breaking, and run a paired upgrade and downgrade on a scratch database.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Pydantic Extra data as a version policyOfficial docs typed-service build path
Extra data (
ignore,forbid,allow): old readers drop, keep or reject fields added by newer writers, set throughmodel_config - Pydantic Default valuesOfficial docs typed-service build path
Default values and Validate default values: a new field with a default lets old payloads validate against the new model
- Tutorial: migration scripts, running migrations, downgradingAlembic tutorial - migration scripts and downgrading
Create a Migration Script (
revision,down_revision,upgrade,downgrade); Running our First Migration and Running our Second Migration (upgrade head); Getting Information (history --verbose); Downgrading (downgrade base) - Creating and Modifying TablesAlgoMaster SQL - selected route
Constraints in DDL (primary and foreign keys,
UNIQUE,CHECK,DEFAULT);ALTER TABLE(adding and dropping columns, changing types, adding constraints);DROP TABLE,TRUNCATEandDELETE
Focus on
- Additive changes (a new optional field, a new table) keep old readers working. Renames, type narrows and new required fields break one direction until every reader upgrades.
- Every migration ships
upgradeanddowngradetogether, anddowngradeis executed, not just written. An emptydowngrademakes rollback untested. - Alembic orders by
down_revisionchains, not file names.history --verboseshows the chain andcurrentshows where the database stands. - Old payloads must validate against new models with defaults filling new fields, and new payloads must not crash old readers; the
extrapolicy decides whether unknowns drop, stay or raise.
Common mistakes · 3
extraforbidon a versioned reader. It rejects payloads from newer writers on unknown fields; versioned boundaries usuallyignoreorallowand stage the unknowns.- A new required field with existing rows. Old writers cannot supply it, and bulk backfill needs a default or a two-step migration.
- Renaming a column while mixed versions read it. Old readers query the old name, so expand (add new, dual-write, migrate readers) before contracting (drop old).
Try it yourself
Closed-book, before checking anything
upgrade and downgrade and run upgrade head, downgrade base, upgrade head on a scratch database.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A v2 model adds
nicknamewith a default. Does a v1 payload validate, and does a v1 model accept a v2 payload under default settings?AnswerYes to both: the default fills
nickname, and defaultextraignoredrops it on the old reader. Verified on Pydantic 2.14.2.What orders two Alembic revisions, and how do you inspect the chain?Answer
down_revisionlinks order them, not filenames.history --verboseshows parents andcurrentshows the database position.3.Name one DDL change that is safe under mixed versions and one that must wait.Answer
Adding a nullable column is safe. Renaming or dropping a column in use must wait until all readers upgrade.
4.Why run
downgrade baseand thenupgrade headwhen testing?AnswerIt executes the rollback path and proves re-upgrade reaches the same schema. An unwritten or unrun
downgradeis an untested promise.
Practice
- Alembic tutorial: first migration, second migration,
downgraderound tripRunning our First Migration; Running our Second Migration; Downgrading
Run on a scratch PostgreSQL 18 database (a throwaway
postgres:18container works). Assertalembic currentandhistory --verboseshow a clean chain, and that reads succeed after each step.
You're done when
Both validation directions pass with stated fill and drop behavior, three DDL changes are classified with reasons, and head to base to head succeeds on a scratch database.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 8 more in the section
- Official docs typed-service build pathPython typing, Pydantic, FastAPI and PostgreSQL · primary
Build one record service in this order: structural protocols and generics; Pydantic models, validators, strict mode, serialization and settings; FastAPI request bodies, dependencies, errors and tests; then PostgreSQL transactions and EXPLAIN. Replay valid, malformed, duplicate and previous-schema requests through CLI and HTTP.
- AlgoMaster SQL - selected routeAlgoMaster · required
Study SQL Foundations, Querying Data, Joins, Subqueries and CTEs, Window Functions, DDL, DML and Views, Performance Optimization, Transactions and Concurrency, and Data Modeling. Stop when the service queries and transaction tests pass.
- Alembic tutorial - migration scripts and downgradingSQLAlchemy · support
Use Create a Migration Script, Running our First and Second Migration, Getting Information and Downgrading to run a paired
upgradeanddowngraderound trip on a scratch database.
Also in this section
- PostgreSQL transactions and EXPLAINPostgreSQL · required
Use the transaction tutorial and EXPLAIN guide to demonstrate commit, rollback, one isolation anomaly or prevented anomaly, and a measured plan improvement on the database actually used.
- FastAPI tutorialFastAPI · support
Use Request Body, Dependencies, Handling Errors and Testing to expose the same service layer through HTTP. Keep framework models outside the domain core and preserve the same error semantics as the CLI.
- AlgoMaster Low-Level Design - one rehearsalAlgoMaster · support
Use one fitting design prompt to rehearse interface contracts, dependency direction and failure ownership. Treat the review as feedback, then verify behavior with your own tests.
- Stas' Python Cookbook - data and interfacesStas Bekman · support
Use Serialization and Deserialization plus Environment and Arguments for focused implementation help. Compare JSON, JSONL, CSV and compressed data, and never use pickle for untrusted interchange.
- AlgoMaster Python - interfaces, generics and data filesAlgoMaster · support
Use Interfaces and Protocols plus Generic Types for structural typing, and Working with JSON plus Working with CSV for JSONL, error handling,
newlineandDictReaderbehavior. Lesson quizzes check recall; implementation is verified with your own scripts. - SQLAlchemy 2.1 documentation - select, Session and eager loadingSQLAlchemy · reference
Use the
select()tutorial for 2.x query style,Sessionbasics for the transaction boundary and identity map, and relationship loading for lazy versusselectinloadversusjoinedloadplusraiseload. Useselect()style andSession.executeorSession.scalarsonly, never the legacyQueryAPI. - PyArrow Parquet read and write docsApache Arrow · support
Use Reading and Writing Single Files plus
Tablefrom_pydictandfrom_pylistto convert normalized records to Parquet and test types, nulls, column projection and schema. - Stripe idempotent requestsStripe · support
Use the
Idempotency-Keyheader contract, stored-response replay, parameter-mismatch errors andPOST-only scope to implement keyed replay for one endpoint.