Once you know your requirements, you turn the real-world things in your system (entities) into tables or collections. Every table needs a primary key for identity, plus foreign keys (or logical references) that connect it to other tables. Get this right early and the rest of the design (APIs, indexes, sharding) falls into place.
Entities and keys#
Here's what that looks like for a small online course platform. Each table is one entity, and the arrows show which key points where:
| Table | Columns |
|---|---|
students |
id (PK), name, email, created_at |
courses |
id (PK), title, price, created_at |
lessons |
id (PK), course_id (FK → courses.id), title, position |
enrollments |
student_id (FK → students.id), course_id (FK → courses.id), enrolled_at. A join table for a many-to-many relationship. |
reviews |
id (PK), course_id (FK → courses.id), student_id (FK → students.id), rating, body |
Choosing primary keys: every id above is generated by the system, and that's on purpose. Prefer system-generated IDs (auto-increment, UUIDs, or Snowflake-style IDs) over business data like an email address, which can change. In a distributed system, UUIDs or Snowflake IDs let many servers generate unique IDs without a central bottleneck.
The three relationship types#
The foreign keys in that schema are how tables connect. Every connection is one of three types:
| Relationship | Example | How to implement it |
|---|---|---|
| One-to-many (1:N) | A course has many lessons | Store course_id on lessons |
| Many-to-many (N:M) | A student takes many courses; a course has many students | A separate join table (enrollments) |
| One-to-one (1:1) | A student has one billing profile | Rare. Usually merge it into students |
Constraints: enforcing correctness#
Keys say how rows relate, but nothing yet stops a row from breaking those links. Constraints stop bad data from getting into the database:
- NOT NULL: a required field like
lessons.course_idcan't be empty. - UNIQUE: no duplicate emails, and no student enrolled in the same course twice.
- CHECK: values must make sense, e.g.
price > 0. - Foreign keys (referential integrity): no orphaned rows, such as a review pointing to a
course_idthat doesn't exist.
Here's the reviews table with those rules written into its definition:
CREATE TABLE reviews (
id BIGINT PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id),
student_id BIGINT NOT NULL REFERENCES students(id),
rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),
body TEXT,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
A UNIQUE constraint on students.email is worth keeping even at scale. If several auth servers race to create the same account, the database is the final guardrail.
Integrity at scale: hard checks vs soft checks#
On a single database, let the database enforce the rules. At very large scale, often with data spread across shards or services, foreign keys stop working across boundaries, so you have to choose who does the checking:
| Database enforces it (hard check) | Application enforces it (soft check) | |
|---|---|---|
| How | Foreign keys and constraints | Your service validates before writing |
| Guarantee | 100% | Best effort; race conditions are possible |
| Speed | Each write checks other tables, which adds locking and I/O | Can check a cache or run in parallel |
| Scope | One database instance only | Works across services and shards |
| Cost | Slower writes | Orphaned data is possible; you need cleanup jobs |
The application layer (also called the service layer) is your backend code, sitting between clients and storage. A soft check is validation that code does instead of the database. For example, before saving a review, the review service confirms the student exists, often by checking a cache like Redis first, and then calls GET /students/123 only if it isn't cached.
Soft checks give up the 100% guarantee, so why do teams accept them?
- Decoupling. A foreign key from reviews to students can't span two services. With a soft check, if the student service is briefly down, the review service can decide what to do, for example save the review and flag it for verification.
- Performance. At billions of rows, checking other tables on every insert adds real latency.
- Richer rules. Databases are good at "does this ID exist?". Code is better at "has this student finished enough of the course to leave a review?"
The price is cleanup: soft deletes (mark rows as deleted rather than removing them) and background jobs that find and remove orphans, like reviews of deleted courses.
Race conditions#
The "race conditions are possible" row in that table deserves a closer look. A race condition happens when the result depends on the timing of concurrent operations. The classic case: two ATMs read a $100 balance at the same moment, both allow an $80 withdrawal, and both write back $20. $160 left the account, but the balance only dropped by $80.
Soft checks have the same problem. Two signups ask "is the username alex taken?" at the same millisecond, both hear "no", and both insert it. There are two standard fixes.
Optimistic concurrency control (OCC)#
Assume conflicts are rare. Don't lock anything; check for a conflict at save time using a version column. Here's the ATM case done safely:
-- Read: id = 123, balance = 100, version = 5
UPDATE accounts
SET balance = 20, version = 6
WHERE id = 123 AND version = 5;
-- 0 rows updated → someone else changed it first:
-- re-read and retry
- Pros: no locks held, high throughput, works across shards, no deadlocks.
- Cons: under heavy contention ("hot" rows), many requests fail and retry, wasting work.
Version stamps#
The version column above is a version stamp: a field that changes every time the record changes. You note the stamp when you read, and check it when you write. If it changed, someone else wrote in between.
A counter is the most common stamp, but it can take several forms:
| Stamp | How it changes | Notes |
|---|---|---|
| Counter | version = version + 1 on every write |
Simple; needs one place that orders writes |
| Timestamp | Set to the write time | Clocks on different servers drift, so two writes can get the wrong order |
| Content hash | Hash of the record's data | Same data gives the same stamp; HTTP ETags often work this way |
| Version vector | One counter per replica | Shows whether two writes on different replicas were concurrent |
HTTP uses the same idea for web resources. A server returns an ETag header with a resource. The client sends it back in If-Match on an update, and the server answers 412 Precondition Failed if the resource has changed.
Conditional update vs record the conflict#
When a version check finds a conflict, you have two choices: refuse the second write, or keep both and sort it out later.
| Conditional update (check-and-set) | Accept both, record the conflict | |
|---|---|---|
| On conflict | Reject the second write; the client re-reads and retries | Apply both writes and flag the conflict |
| Locks | None | None |
| Outcome | One write wins; the loser knows it lost | Both writes are kept; someone resolves them later |
| Fits | A single database or primary that orders writes | Leaderless or multi-region stores, offline clients |
| Example | Two withdrawals from one balance | Two edits to one shopping cart or inventory note |
- Conditional update is the
UPDATE ... WHERE version = 5pattern above. Use it when a wrong value is worse than a retry, such as balances and seat counts. - Record the conflict keeps every concurrent version (some stores call them siblings). The application or the user merges them later. A cart can take the union of both versions. CouchDB, for example, keeps conflicting revisions until the app picks a winner.
Recording conflicts keeps writes available when replicas cannot talk to each other. The cost is merge logic in your application. See Replication Models for where conflicts come from.
Pessimistic locking#
Pessimistic locking is the opposite bet from OCC. Assume conflicts will happen, and take a lock before you start. Across many servers this is often a distributed lock in Redis:
# r is a redis.Redis client; token is a random string
# unique to this holder
acquired = r.set("lock:account:123", token, nx=True, px=5000)
nx=True(RedisNX): only set if the key doesn't exist, so there is one winner.px=5000(RedisPX 5000): auto-expire after 5 s in case the holder crashes.
Holding the lock, you read, compute, write, and then release it (only if the token is still yours). Others wait and retry.
- Pros: no conflicting write reaches the database.
- Cons: everyone else waits, which lowers throughput, and you must handle holders that crash.
Here's how the two approaches compare:
| Optimistic (versioning) | Pessimistic (lock) | |
|---|---|---|
| Philosophy | Try it; detect conflict at save | Get the key before you start |
| Throughput | High | Lower |
| Best for | Low contention: editing a lesson, updating a bio | High contention: flash sales, the last seat, wallet debits |
See Distributed Lock for more on locking across servers.
Deadlocks#
Locks fix races but bring a failure mode of their own. A deadlock is a circular wait. Transaction 1 locks row A and then wants B. Transaction 2 locks B and then wants A. Neither can move.
A deadlock needs all four Coffman conditions at once: mutual exclusion (locks are exclusive), hold and wait, no preemption (a lock can't be taken away), and circular wait.
In distributed locks, the common version is the zombie lock: a server takes a lock and crashes, and everyone waits forever. That's why a distributed lock should always have a TTL.
To prevent or recover from a deadlock:
- Lock in a consistent order. For example, always lock the lower account id first. That breaks the circular wait.
- Rely on deadlock detection. Databases like PostgreSQL detect cycles and abort one transaction. Your app should catch that error and retry with exponential backoff.
- Use timeouts. Never wait for a lock forever. Give up after, say, 500 ms and return an error.
Key takeaways#
- Every table needs a stable primary key. Prefer generated IDs (UUID or Snowflake-style) over business data.
- 1:N is a foreign key on the "many" side, N:M needs a join table, and 1:1 is usually merged into one table.
- Let the database enforce constraints when you can. At large scale, some checks move into application code, at the cost of possible races and cleanup jobs.
- Use optimistic concurrency (version column) for low contention and locks for hot, high-stakes data.
- A version stamp changes on every write. On conflict, either reject the write (conditional update) or keep both versions and resolve them later.
- Prevent deadlocks with consistent lock ordering, timeouts and TTLs on distributed locks.