Your Data Structure Is Too Flexible

Your Data Structure Is Too Flexible
Photo by Shubham Dhage / Unsplash

Python makes it easy to pass data around as dicts, nested JSON blobs, and “whatever the client sent”.

That flexibility is useful when you own the shape. It gets expensive when the data crosses a trust boundary - an HTTP body, a webhook, a file from another team - and you treat it like it already matches your assumptions.

You may already know Pydantic. This article is not a tour of fields and validators.

It is about a design rule that is easy to skip when the happy path works: validate at the boundary, then move on.

Keep flexibility only where you chose it.


Staging lied (inbound API JSON)

Imagine a small HTTP handler that accepts a JSON body as a Python dict and charges a user’s account. ledger below is a stand-in for whatever typed client or service call sits deeper in your stack.

In staging, every client you control sends the same clean shape, so the happy path is the only path you ever see.

def charge_user(payload: dict) -> None:
    user_id = payload["user"]["id"]
    amount = payload["amount"]
    # Somewhere deeper in the stack — expects an int user_id
    ledger.debit(user_id=user_id, amount=amount)

Staging payload:

{
    "user": {"id": 42, "email": "dev@example.com"},
    "amount": 19.99,
}

That works. user.id is an int, amount is a float, and ledger.debit never complains.

Then production gets a request from a mobile client, a partner integration, or a retry queue that re-serialized the body. The JSON is still “valid”.

The shape is almost right:

{
    "user": {"id": "42", "email": "buyer@example.com"},
    "amount": 19.99,
}

Nothing fails in the handler. It forwards user_id as whatever JSON gave it.

The failure shows up later - in ledger.debit, a SQL parameter binder, or a comparison that assumes an int. If that deeper call type-checks or binds user_id as int, a str raises there.

Worse: the wrong type slips into storage and you notice even later.

The stack trace points at infrastructure code. The bug was at the door: user.id crossed the trust boundary as a string, and a flexible dict let it through.

Nuno Bispo

Nuno Bispo

Solutions Architect · Senior Python & AI Engineer · AI Audits · Helping teams fix what they shipped too fast
Netherlands