Schema-on-Read vs Schema-on-Write
Whether the database checks the shape of data when it is written, or the reading code interprets it later, and how each choice changes the way you evolve a schema.
Overview
Every dataset has a schema: some assumption about which fields exist and what types they hold. Even 'schemaless' data has one, because the code that reads it expects certain fields. The real question is who checks the shape, and when.
With schema-on-write, the database checks every write against a declared schema and rejects data that does not fit. Relational databases work this way. With schema-on-read, the store accepts whatever it is given, and the code that reads the data decides how to interpret it. Document stores, JSON logs and files in a data lake usually work this way.
Where the check happens
The two approaches put the check at opposite ends of the data's path. Schema-on-write rejects a bad record before it is stored; schema-on-read stores it and leaves every reader to cope.
A useful comparison is typing in programming languages. Schema-on-write is like static type checking: mistakes are caught early, at the cost of declaring types up front. Schema-on-read is like dynamic typing: flexible, but a wrong shape shows up only when some code trips over it.
The difference runs through everything else. With schema-on-write, the database enforces the shape on every write, so bad data is rejected before it is stored. Changing the shape takes a migration (ALTER TABLE, sometimes a backfill). It fits best when many writers and readers share one structure. With schema-on-read, every reader enforces the shape in its own code, so bad data is stored and found only when it is read. Changing the shape just means writing the new shape, and readers handle old and new. It fits best with mixed or fast-changing shapes and data from outside sources.
Key concepts
- Schema-on-write
- Schema-on-read
- Implicit schema
- Migration
- Expand-contract
- Online schema change
- NOT VALID constraint
- Reader and writer schema
Interview questions
- How do you change the schema of a large production table without downtime?
- When would you prefer schema-on-read?
- Is a schemaless database really schemaless?
Sign up free to read the full topic
More DDIA topics
- Partitioning Strategies: Range vs Hash
- Rebalancing Partitions
- Relational vs Document Data Models
- Reliability, Scalability, and Maintainability
- Replication Lag and Consistency Anomalies
- Schema Evolution and Backward/Forward Compatibility
- Secondary Indexes and Index Trade-offs
- Secondary Indexes on Partitioned Data
- Single-Leader Replication
- SLAs, SLOs, and Percentile Latency
- Unbundling the Database
- What Is a Data-Intensive Application?
Start free on Cariara · Coding problems · System design studio