Database Design Fundamentals for Backend Engineers
From Mid-Level to Senior · Part 7 of 18
- #databases
- #sql
- #data-modeling
- #senior-engineer
- #engineering-practices
Here's something you notice after a few years on the same system: the code gets rewritten all the time. Services get split, frameworks get upgraded, whole modules get thrown away and done again. The database schema is still sitting there, mostly unchanged, with every decision someone made in the first month baked into it.
That's why data modelling deserves more of your attention than it usually gets. A bad method costs you an afternoon. A bad table design costs you a migration plan, a backfill script, and a few nervous deploys.
In Part 6 we talked about API contracts. The schema is the contract underneath that contract, and it's even harder to change, because the data is already in it. If you went through Persisting Data with Spring Data JPA in Track 1, you know how to map an entity. This part is about the decisions that come before the mapping, and the ones that show up later, in production, when the table has forty million rows.
What are the fundamentals of database design?
For a backend engineer working on a real system, it comes down to seven things. Each one gets its own section below.
- Keys and constraints. Surrogate primary keys, natural keys as
UNIQUE, and rules enforced by the database, not only by your Java code. - Normalization. One fact in one place, by default.
- Deliberate denormalization. Duplicate data only on purpose, with a source of truth and a way to rebuild the copy.
- Indexes. Designed for the queries you actually run, because every index makes every write a little slower.
- Query shape. Catching N+1 queries before production does.
- Transactions and isolation. Knowing what
@Transactionalprotects you from, and what it doesn't. - Migrations. Versioned schema changes you can run on a live system (expand and contract).
The examples use SQL, PostgreSQL and Spring Data JPA, but the ideas carry over to any relational database. For how the data model fits into the wider architecture, see System Design Basics.
Keys, relationships, and constraints
Primary keys. Use a surrogate key (a generated bigint or a UUID) as
the primary key, and enforce the natural key, like an email or a tax ID,
with a separate UNIQUE constraint. Natural keys feel elegant until the
business tells you emails can change, or that two companies in different
countries can share a registration number. Changing a primary key means
updating every foreign key that points at it. Changing a unique column is
just an UPDATE.
If you go with UUIDs, prefer a time-ordered kind (UUIDv7). Random UUIDs scatter inserts all over the index, and on a big table you'll feel that.
Relationships. One-to-many is a foreign key on the "many" side.
Many-to-many is a join table, and that join table very often turns into
a real entity once someone asks "when was this student enrolled?" or
"who granted this role?". Give it a name that means something
(enrollment, not student_course) and room to grow.
Constraints belong in the database. This is where I see mid-level engineers trip most often. Your Java validation is good, but it's not the only code that writes to the table. There's the migration someone ran by hand, the batch job, the second service, the support engineer with a SQL console. The database is the only layer that sees every write. So:
NOT NULLon everything that can't be null, which is most columns.FOREIGN KEYon every reference, so you can't end up with orders for a customer that doesn't exist.UNIQUEfor every rule that says "only one of these".CHECKfor simple invariants, likequantity > 0or a status in a known set.
The application check gives users a nice error message. The constraint makes sure the bad data never gets in, even when the application check has a bug. You want both.
While you're at it, pick your types carefully. Money goes in numeric /
DECIMAL (or integer cents), never float or double. Timestamps go in
timestamptz and are stored in UTC. And an enum stored as an ordinal
integer will break the day someone reorders the Java enum, so store the
name.
Normalization: one fact, one place
You don't need to recite the normal forms. The useful version fits in one sentence: every fact should live in exactly one place.
If the customer's email is stored on the customer row and also copied
onto every order, then changing it means updating many rows, and the
day one of those updates fails you have two "true" emails. That's the
problem normalization solves. Split the data so each piece has one owner,
and join when you need them together.
Most of the time, a schema where each table describes one thing and every non-key column depends only on that table's key is the right default. You start there.
When to bend it
Normalization is a default, not a religion. There are good reasons to store something twice, and the senior skill is knowing which ones are real.
Snapshots aren't duplication. The price on an order_item isn't a
copy of the product price. It's a different fact: the price the customer
actually paid, at that moment. If you "normalize" it by joining to the
current product price, you've rewritten history every time marketing
changes a price. Same for shipping addresses on an order, or a person's
name on a signed contract. Ask "is this the current value, or the value
at the time?" and you'll know.
Read models. A dashboard that joins eight tables on every page load might be better served by a table (or a materialized view) built for exactly that screen. That's fine, as long as you're clear about which table is the source of truth and how the copy gets rebuilt when it drifts.
Counters and aggregates. Storing comment_count on a post saves a
COUNT(*) on every read. It also means every insert and delete has to
keep it right, including concurrent ones. Sometimes that's worth it.
Measure first.
The rule I'd suggest: denormalize on purpose, in writing, with a single source of truth and a way to rebuild the copy. If you can't say which side wins when the two disagree, you're not ready to duplicate it.
Indexes: fast reads, paid for by every write
An index is a separate, sorted data structure the database keeps next to the table so it can find rows without scanning all of them. That's the part everyone knows. The part people forget is the bill:
- Every write maintains every index. A table with nine indexes does ten writes for each insert. On a write-heavy table, that adds up fast.
- Indexes take disk and memory. Ideally the hot part of your indexes fits in RAM. Unused indexes push useful ones out.
- The planner can ignore them. If the query isn't shaped the way the index is, it won't help.
That last point is mostly about composite indexes, and it's worth understanding properly:
A composite index is sorted by the first column, then by the second within each first value, and so on, like a phone book sorted by last name and then first name. You can look up "everyone named Silva" quickly. You can't look up "everyone named José" without reading the whole book.
Some practical habits:
- Index for the queries you actually run, not for every column that
appears in a
WHEREsomewhere. Start from the slow query log. - Put equality columns first, then the range or sort column. For
WHERE customer_id = ? AND status = ? ORDER BY created_at DESC, the index(customer_id, status, created_at)serves both the filter and the sort. - Index your foreign keys. PostgreSQL doesn't do it for you (MySQL's InnoDB does). Without it, every join on that column and every delete on the parent table turns into a scan.
- Read the plan.
EXPLAIN ANALYZEtells you what the database actually did. Guessing about indexes is how teams end up with twelve of them and the same slow query. - Drop what nobody uses. PostgreSQL tracks index usage in
pg_stat_user_indexes. An index with zero scans after a month is pure cost.
N+1: the query you didn't know you were running
If you use an ORM, this one will find you eventually. You load a list of
orders with one query. Then, while rendering them, you touch
order.getCustomer().getName(), and lazy loading quietly fires one more
query per order.
It's invisible in development, because your local database has five rows and sits on the same machine. In production it's fifty rows, then five hundred, each one a network round trip.
The fixes, roughly in the order I'd reach for them in Spring Data JPA:
- Fetch what you need in the query. A
JOIN FETCHin JPQL, or an@EntityGraphon the repository method, loads orders and customers in one go. - Project to a DTO. If the screen only needs three columns, select three columns into a record. No entities, no lazy loading, no surprises.
- Batch the lazy loads.
hibernate.default_batch_fetch_size(or@BatchSize) turns N single-row queries into a fewWHERE id IN (...)queries. It's a good safety net to turn on globally.
Then make it visible. Turn on SQL logging in development, and consider a
test that asserts the number of queries for your important endpoints
(Hibernate's Statistics can count them). N+1 bugs come back every time
someone adds a field to a response, so a test that catches them beats
remembering to check.
Also turn off spring.jpa.open-in-view. It's on by default and keeps the
session open while the response is being written, which is exactly what
lets lazy loading happen in places you never meant it to.
Transactions and isolation, in practice
Most of us learned ACID as an acronym for an exam. The part that matters day to day is the "I": isolation. It answers "what can my transaction see of other transactions that are running at the same time?"
PostgreSQL defaults to Read Committed (MySQL's InnoDB defaults to Repeatable Read). Under Read Committed, each statement sees data that was committed before it started. That prevents a lot, but not this very common bug:
@Transactional
public void reserve(long productId, int qty) {
Product p = products.findById(productId).orElseThrow();
if (p.getStock() < qty) throw new OutOfStockException();
p.setStock(p.getStock() - qty); // two requests can both get here
}
Two requests read stock = 1 at the same time. Both pass the check. Both
write stock = 0. You've sold two units you didn't have. This is a lost
update, and the @Transactional doesn't stop it.
Three ways out, depending on the situation:
- Let the database do the math.
UPDATE product SET stock = stock - :qty WHERE id = :id AND stock >= :qtyand check that one row was updated. It's atomic, and usually the simplest answer. - Optimistic locking. Add a
@Versioncolumn. If someone else changed the row since you read it, your update fails with an exception you can retry or show to the user. Good when conflicts are rare. - Pessimistic locking.
SELECT ... FOR UPDATE(in JPA,@Lock(PESSIMISTIC_WRITE)) makes the second transaction wait. Good when conflicts are frequent and retrying is expensive, but watch the lock order or you'll meet deadlocks.
Two more habits that save a lot of pain:
- Keep transactions short. Never call an HTTP API, send an email, or wait on a queue inside a database transaction. You hold locks and a connection for the whole time, and if the remote call fails after you commit, or succeeds before you roll back, you're inconsistent anyway.
- Know where your transaction boundaries are.
@Transactionalon a private method, or on a method called from the same class, does nothing, because Spring's proxy never sees the call. That one has surprised plenty of experienced people.
Migrations are code
The schema should be built by versioned scripts that live in the repo, get reviewed in PRs, and run the same way in every environment. Flyway and Liquibase both do this well. Pick one and use it from the first table. Database Migrations with Flyway and Liquibase in Spring Boot shows the setup end to end.
What that rules out:
spring.jpa.hibernate.ddl-auto=updateanywhere past your laptop. It can add columns. It won't rename, it won't drop, it won't backfill, and it won't tell you what it did.- Editing a migration that already ran. Once a migration is merged and applied somewhere, it's history. Fix things with a new migration.
- Changes made by hand in production. If it's not in a migration, the next environment won't have it, and nobody will know why.
The harder part is changing a schema while the application is running, because during a rolling deploy the old and new versions of your code run side by side, against the same database. A rename that's one statement on your laptop is an outage in production. The pattern that works is expand and contract:
It's more steps and more PRs. It's also the only way a schema change stays boring, and boring is the goal. A few related rules for big tables:
- Create indexes without blocking writes. In PostgreSQL that's
CREATE INDEX CONCURRENTLY. A plainCREATE INDEXon a large table locks it against writes for the whole build. - Backfill in batches. One
UPDATEacross forty million rows holds locks for a long time and bloats the table. A thousand rows at a time, in a loop, doesn't. - Add new columns as nullable or with a constant default, so the
database doesn't have to rewrite the table. Add
NOT NULLafter the backfill is done. - Make migrations part of CI. Run them against a real database in your pipeline, not just against H2. That's a big part of what Part 8 is about.
What to try this week
- Pick your busiest table and list its indexes. Run
EXPLAIN ANALYZEon the two or three queries that hit it most. Is every index earning its keep? - Check your foreign key columns for indexes, especially in PostgreSQL.
- Turn on SQL logging locally and click through your main screen. Count the queries. Any N+1 hiding there?
- Find one read-modify-write in your code (read a value, change it in Java, save it back) and ask what happens if two requests do it at the same time.
- Look for constraints that only exist in Java. Pick one and add it to the database.
The short version
- The schema outlives the code. Spend the design time there.
- Surrogate primary keys, natural keys as
UNIQUE. Constraints live in the database, because it's the only layer that sees every write. - Normalize by default: one fact, one place. Denormalize on purpose, with a source of truth and a way to rebuild. Snapshots aren't duplication.
- Indexes speed up reads and slow down every write. Design them for real queries, mind the column order, index foreign keys, and read the plan.
- N+1 is invisible locally. Fetch what you need, project to DTOs, batch lazy loads, and test the query count.
@Transactionaldoesn't prevent lost updates. Use atomic updates,@Version, or locks, and keep transactions short.- Migrations are versioned code. Change running systems with expand and contract.
A schema migration is only as safe as the pipeline that runs it. In Part 8 we'll start Module B with CI/CD: how to build a pipeline your team actually trusts, from fast feedback to flaky tests to rollback.
This is Part 7 of 18 in the series. The Senior Engineer Roadmap maps the whole series, with a short self-assessment and four reading orders.