I hesitated for an hour before typing ALTER TABLE users ADD COLUMN is_archived BOOLEAN, dreading the invisible ripple effects. What should have been a five-minute migration bled into two days of hunting down silent failures: the Python ORM defaulting the new field to None, the API serializer quietly stripping it from the JSON payload, and the frontend TypeScript build collapsing because the contract had shifted. I wasn’t just adding a column; I was forcing three stubborn, isolated systems to translate a single, fragile truth.
1. The three-room metaphor
For years I had explained that pain to myself with a metaphor: Python, PostgreSQL and APIs as three separate rooms in a factory.
PostgreSQL was the warehouse: quiet, tidy, full of rows and columns. Python was the assembly line: it pulled boxes from the warehouse, opened them, worked inside with imperative and object-oriented logic, and closed them again. The APIs were conveyor belts: pipes carrying payloads from one room to another, or out into the world.
The metaphor is convenient, because it explains the flow. It is also wrong, because it describes movement where there is translation. A ferryman moves things without changing them — and that is exactly the misunderstanding.
2. The three traps
Your database is speaking through Python
When your DB leaks everywhere — when you see user["email_address"] in Python services instead of user.email, when SQL is scattered across twenty files, when nobody knows who is responsible for validating a field — you have lost the boundary. The database should be the only place where the structural truth of the data is defended. If Python is doing the dirty work of validation and normalisation that a constraint or a native Postgres type could do, you are duplicating complexity instead of containing it.
Take an email address. Three places lowercase it: the signup form, the CSV import, the admin panel. The fourth — a one-off migration script written at 11pm — doesn’t. Postgres accepts Foo@Example.com and foo@example.com as two different users; billing sends two invoices; support merges them by hand a week later.
I’ve been that fourth place more than once.
The fix is not a fourth .lower(). It’s moving the truth to where the data lives:
CREATE EXTENSION IF NOT EXISTS citext;
ALTER TABLE users ALTER COLUMN email TYPE citext;
Now every path that writes an email is case-insensitive by construction — including the scripts nobody has written yet. That is what “the database defends the truth” means: Python isn’t forbidden to touch it; Python can’t get it wrong.
Python is the glue, not the brain
The moment your Python code collapses into a sequence of SELECT → dict → transform → dict → INSERT, you have a role problem. Python should be where domain logic takes shape: business rules, flows, decisions. If you are using it as a glorified conveyor belt between the DB and the APIs, you are spending your most expressive language on a cursor’s job. And the fragility you feel starts right here: you put logic where there should only be movement.
# BEFORE — a JOIN written by hand, one query per row
def overdue_invoices():
rows = db.execute("SELECT * FROM invoices").fetchall()
out = []
for r in rows:
if r["status"] != "unpaid" or r["due_date"] >= date.today():
continue
customer = db.execute( # N+1: one query per invoice
"SELECT is_vip FROM customers WHERE id = %s", (r["customer_id"],)
).fetchone()
if customer["is_vip"]:
continue
out.append({**r, "is_vip": customer["is_vip"]})
return out
# AFTER — the database does the set work, Python owns the rule
@dataclass(frozen=True)
class Invoice:
id: str
due_date: date
status: str
customer_is_vip: bool
def is_overdue(self, today: date) -> bool: # the rule, once, with a name
return self.status == "unpaid" and self.due_date < today and not self.customer_is_vip
def overdue_invoices(today: date) -> list[Invoice]:
rows = db.execute("""
SELECT i.id, i.due_date, i.status, c.is_vip AS customer_is_vip
FROM invoices i JOIN customers c ON c.id = i.customer_id
""").fetchall()
return [inv for inv in (Invoice(**r) for r in rows) if inv.is_overdue(today)]
The Python in this piece is illustrative: db, repo and session are placeholders, not a library.
Your APIs expose the database, not the domain
If your JSON response has exactly the shape of your SQL table, you have a design problem. APIs should not be a window onto the database; they should be a promise made to the outside world. When the outside world depends on the internal structure of your DB, every refactor becomes an act of courage. And every time you change a column, you feel slightly guilty towards whoever is on the other side of the HTTP call.
Here is the version that costs a weekend. The endpoint returns {**row} — whatever the table has, the client gets. Six months later you rename email_address to email. Nothing in the response changes, because there is no contract to change: the client reads undefined, the server logs a 200, and a user finds the bug before you do.
The fix is not a to_dict(). It is a model that declares what you promise — and a framework that removes everything else:
class UserResponse(BaseModel):
id: str
email: EmailStr
archived_at: datetime | None
@app.get("/users/{user_id}", response_model=UserResponse)
def get_user(user_id: str):
...
With response_model, FastAPI validates what leaves and strips what you did not declare. A new column cannot leak into the JSON by accident — not even the one you add at 11pm. The boundary is enforced by the machine, not by discipline.
3. The three signals
A self-diagnosis. One answer per line:
- You are afraid to add a column, because you don’t know what will break.
- Business logic is spread across SQL queries, Python services and API validations, and nobody knows where the truth lives anymore.
- Every change requires touching five different files to do the same thing.
If two of those describe your week, keep reading.
4. From ferryman to boundary architect
The complexity you feel is not in the problem you are solving. It is in the fact that you maintain three separate truths — in the DB, in Python, in the APIs — and spend your life synchronising them by hand.
The fragility disappears the day you stop being a ferryman and start being a boundary architect:
- Postgres defends the truth of the data (types, constraints, relations).
- Python defends the truth of the domain (rules, flows, decisions).
- The APIs defend the truth of the contract (what you promise, what you accept, what you hide).
Here is the same feature twice — archiving a user. First the ferryman’s version:
# BEFORE — the ferryman
def archive_user(user_id: str):
row = db.execute("SELECT * FROM users WHERE id = %s", (user_id,)).fetchone()
if row is None:
return None # the API layer will turn this into 404
db.execute("UPDATE users SET is_archived = true WHERE id = %s", (user_id,))
return dict(row) | {"is_archived": True} # the table, wearing a JSON hat
@app.post("/users/{user_id}/archive")
def archive(user_id: str):
user = archive_user(user_id)
if user is None:
raise HTTPException(404)
return user # the shape of the DB leaks to the client
Then the boundary architect’s:
-- Postgres defends the truth: no user is archived without a timestamp
ALTER TABLE users ADD COLUMN archived_at timestamptz;
ALTER TABLE users ADD CONSTRAINT archived_needs_time
CHECK (is_archived = (archived_at IS NOT NULL));
def archive(user_id: UserId) -> User:
user = repo.get(user_id) # the domain decides what "missing" means
if user is None:
raise UserNotFound(user_id)
user.archive() # the rule lives here, once
repo.save(user)
return user
class UserArchived(BaseModel): # the contract, not the table
id: str
archived_at: datetime
When each layer does only its own job, and trusts the others for the rest, the system stops being a house of cards. It becomes something you can change without fear.
This costs you something: a constraint to write, a method to name, a model to declare.
And that feeling of fragility? It simply disappears.