System designLoading progress…

Entities and invariants

Choose representations and storage boundaries from access patterns, ownership and retention requirements.

Entities and invariants

Start by naming the entities (users, documents, orders), giving each a stable identity, deciding who owns it and writing down the invariants: conditions that must hold across valid operations, such as "ids are unique", "every document has an existing owner", "a balance never goes below zero". A display name is a poor identifier: names repeat and change.

iddisplay nameowner (click to change)
1Report
2Plan
3Report
4Notes
display names: Report, Plan, Report, Notes, Report duplicated: Report (3 documents) unique ids 1…5: the stable identity ownership invariant (owner must be a known user, users: u1, u2): 1 violation(s)

An invariant is a condition that must stay true across valid operations: unique ids, an existing owner, non-negative balances. Choose identifiers that are stable and unique, and let the system enforce the invariants rather than hoping every writer does.

Break the ownership invariant by changing an owner.

Predict first. Is a document's display name necessarily a safe unique identifier?

Chapter context

A data model describes the facts a system owns and the relationships it must preserve. Storage choices should follow how those facts are queried, updated and retained, rather than a blanket preference for one database category.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

A simple retained-payload estimate is

M=w s d r,M=w\,s\,d\,r,

where w is writes/day, s payload bytes/write, d retained days and r full-copy count. Add indexes, metadata, compaction headroom and backups separately; replication schemes may store more than exactly r payload copies.

Worked example

Two million records per day at 500 bytes each produce one decimal GB/day of raw payload. Thirty days retained across three full copies require 2,000,000×500×30×3=90,000,000,000 bytes, or 90 decimal GB before other storage. Compressibility and index size are separate measured factors.

Reference code

The following example uses the Python standard library and does not call a remote service.

daily,size,days,copies=2_000_000,500,30,3
assert daily*size == 1_000_000_000
retained=daily*size*days*copies
assert retained == 90_000_000_000
assert retained/1e9 == 90

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

NoSQL is not a single consistency or query model. Denormalization creates a maintenance responsibility. Payload estimates must not silently stand in for provisioned disk requirements.