Sub topic 7
Data Model and Choosing a Datastore
This chapter assumes you have read the earlier chapters on requirements, capacity estimation, API design, and short code generation. You should know basic SQL, understand what a primary key and an index are, and be able to read simple Python. Here you will design the table that stores links and decide what kind of database should hold it.
What the data model must support
The requirements from earlier chapters shape the data model. The service has two operations that touch storage:
- Create: store a new mapping from a short code to a long URL.
- Resolve: given a short code, return the long URL.
Resolve dominates the traffic. If the estimate was a read-to-write ratio of 100:1, then for every new link the system serves roughly 100 redirects. The data model should therefore make one query fast: look up a row by its short code. Almost every other design choice follows from that.
The access pattern is also simple. There are no joins and no range scans on the core path. Each request names exactly one key and wants exactly one value.
The core table
Here is the table from the spine, with the reasoning for each column.
CREATE TABLE urls (
short_code VARCHAR(10) PRIMARY KEY,
long_url TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NULL
);| Column | Purpose | Notes |
|---|---|---|
| `short_code` | The key that appears in the short link | Primary key, so lookups use an index and duplicates are rejected |
| `long_url` | The destination | `TEXT` because URLs have no fixed maximum in practice. Browsers and servers commonly accept a few thousand characters |
| `created_at` | When the link was made | Useful for cleanup, auditing, and debugging |
| `expires_at` | When the link stops working | `NULL` means the link never expires |
Why the primary key does two jobs
The primary key on short_code gives you two things at once.
- Fast lookup. The database builds an index on the primary key. A lookup by code walks that index instead of scanning the table.
- Collision detection. If two requests try to insert the same code, the second insert fails with a uniqueness violation. The application catches that error and retries with a new code. This is the mechanism described in the collision chapter, and the database enforces it even when many servers insert at the same time.
Do not rely on an application-level "check if it exists, then insert" sequence. Two servers can both see that a code is free and then both insert it. A unique constraint closes that race, because the database serializes the conflict.
Choosing the column type for the code
VARCHAR(10) leaves room for 7-character generated codes and for longer custom aliases. Two details matter:
- Case sensitivity. Base62 uses both upper and lower case letters, so
aB3andab3are different codes. Some databases compare strings case-insensitively by default. MySQL with a default collation does this, which would make those two codes collide. Use a case-sensitive collation, or a binary column type, forshort_code. - Storing the number instead. If you generate codes from a counter, you could store the integer ID as the primary key and compute the code on the fly with base62 encoding. Integer keys are smaller and faster to compare. The cost is that custom aliases do not fit the scheme, so you would need a second column or table for them. Storing the string keeps one uniform lookup path, so this design uses the string.
Estimating row size and total storage
Use the numbers from the capacity chapter. Suppose the service creates 100 million links per year and keeps them for 5 years, giving 500 million rows.
A rough row size:
| Field | Approximate bytes |
|---|---|
| `short_code` | 7 |
| `long_url` (average) | 100 |
| `created_at` | 8 |
| `expires_at` | 8 |
| Index and row overhead | about 50 to 70 |
That is roughly 200 bytes per row. 500 million rows times 200 bytes is about 100 GB. This fits on a single modern server's disk. Total size alone does not force you to shard.
The index is a separate concern. A B-tree index on a 7-byte key over 500 million rows takes tens of gigabytes. If the hot part of the index fits in memory, lookups are fast. If it does not, each lookup can cost a disk read. The cache chapter returns to this.
Choosing a datastore
The two realistic options are a relational database and a key-value store.
Relational database (PostgreSQL, MySQL)
Strengths:
- Unique constraints give you collision detection with no extra code.
- Transactions let you insert a row and update related data together.
- Familiar tooling for backups, migrations, and queries.
- Secondary indexes make queries like "all links created by this user" easy.
Weaknesses:
- Scaling writes beyond one primary server needs sharding, which you must build and operate yourself.
- Features you do not need on the core path, such as joins and complex transactions, add overhead.
Key-value or wide-column store (DynamoDB, Cassandra, Redis as a store)
Strengths:
- The access pattern is a single key lookup, which is what these systems are built for.
- Horizontal scaling and replication are built in. Partitioning by
short_codespreads data evenly because codes are effectively random. - Predictable low latency at high request rates.
Weaknesses:
- Uniqueness enforcement is weaker or needs a specific feature. DynamoDB, for example, offers conditional writes (
attribute_not_exists) to reject duplicates. Cassandra offers lightweight transactions, which are slower than normal writes. - Queries on anything other than the key, such as listing a user's links, need extra indexes or a second table.
Comparing them for this problem
| Criterion | Relational | Key-value |
|---|---|---|
| Lookup by code | Fast with a primary key index | Fast, its native operation |
| Duplicate rejection | Built-in unique constraint | Conditional write or similar feature |
| Scaling to very high writes | Manual sharding | Built-in partitioning |
| Queries by user or date | Easy with secondary indexes | Needs extra design |
| Operational familiarity | High for most teams | Varies |
At 100 GB and a modest write rate, a single relational database with read replicas handles this workload well. The write rate is small: 100 million links per year is about 3 writes per second on average. Reads are about 100 times that, and a cache absorbs most of them. A key-value store becomes attractive when you expect storage or write volume far beyond these numbers, or when you want to avoid running your own sharding layer.
State your choice with its reason in an interview or a design review. A sound answer is: "Start with a relational database because uniqueness is built in and the data fits on one node. Move to a key-value store or shard the relational database if volume grows by an order of magnitude." Either choice is defensible if you tie it to the numbers.
Extending the model
The core table is deliberately small. Real services add a few things, and each has a cost.
User ownership
If users can manage their links, add a user_id column and a secondary index on it:
ALTER TABLE urls ADD COLUMN user_id BIGINT NULL;
CREATE INDEX idx_urls_user_id ON urls (user_id);Every extra index slows inserts slightly and uses more memory. Add one only when a feature needs the query.
Expired links
The expires_at column lets you reject expired links at read time. A background job can delete old rows later. The resolve path should check expiry itself and not depend on the cleanup job having run. A later chapter covers this in detail.
SELECT long_url
FROM urls
WHERE short_code = 'aB3xY9Z'
AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP);Deduplicating long URLs
You may be tempted to give the same long URL the same short code each time. That needs a unique index on long_url, which is a large text column and makes the index expensive. It also removes per-user ownership and per-link analytics, because everyone shares one code. Most designs skip deduplication and allow many codes per URL.
Analytics
Do not write click counts to the urls table on every redirect. That turns a read into a write on the hottest path. Record clicks in a separate log or stream, as the analytics chapter describes.
Writing the data access layer
This Python sketch shows the insert path with collision retry, using the hash-based generator from the earlier chapter. It uses SQLite so you can run it as written, and it needs the short_code_from_url and encode functions from the code generation chapter.
import sqlite3
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
digits = []
while n > 0:
n, r = divmod(n, 62)
digits.append(ALPHABET[r])
return "".join(reversed(digits))
import hashlib
def short_code_from_url(url: str, attempt: int = 0, length: int = 7) -> str:
digest = hashlib.sha256(f"{url}:{attempt}".encode()).digest()
n = int.from_bytes(digest[:8], "big") % (62 ** length)
return encode(n).rjust(length, ALPHABET[0])
def create_table(conn: sqlite3.Connection) -> None:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS urls (
short_code TEXT PRIMARY KEY,
long_url TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TEXT NULL
)
"""
)
def insert_url(conn: sqlite3.Connection, long_url: str, max_attempts: int = 5) -> str:
for attempt in range(max_attempts):
code = short_code_from_url(long_url, attempt)
try:
conn.execute(
"INSERT INTO urls (short_code, long_url) VALUES (?, ?)",
(code, long_url),
)
conn.commit()
return code
except sqlite3.IntegrityError:
conn.rollback()
raise RuntimeError("could not allocate a short code")
def get_long_url(conn: sqlite3.Connection, code: str):
row = conn.execute(
"SELECT long_url FROM urls WHERE short_code = ? "
"AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)",
(code,),
).fetchone()
return row[0] if row else None
if __name__ == "__main__":
conn = sqlite3.connect(":memory:")
create_table(conn)
code = insert_url(conn, "https://example.com/some/very/long/path")
print(code, get_long_url(conn, code))Note the parameterized queries. The long URL comes from users, so never build SQL by string concatenation.
One edge case: if the same long URL is submitted twice, the hash is identical on attempt 0. The second insert then fails on the primary key, and the retry produces a different code through the next attempt number. The function cannot tell this apart from a true collision between two different URLs, so each submission still gets its own code. If you want to detect a repeat of the same URL by the same user, you must check explicitly.
Common errors
- Case-insensitive collation on
short_code. Distinct codes collide, and redirects go to the wrong place. - Check-then-insert without a unique constraint. Races produce duplicate codes under concurrent load.
- Indexing
long_urlwithout a reason. It inflates storage and slows writes. - Updating a counter on every redirect. It turns the read path into a write path.
- Treating expiry as a cleanup-job concern. Expired links keep working until the job runs.
- Choosing a datastore before estimating. A 100 GB data set with 3 writes per second does not need a distributed database.
Exercise
Your service stores 2 billion links at about 200 bytes each, and 20,000 new links per second arrive at peak. Would you still use one relational server? Name the two numbers that drive your answer and one option you would consider.
Show answer
Probably not. Total storage is about 400 GB, which a single server could hold. The write rate of 20,000 per second is the stronger signal, because one primary server may struggle to sustain it with an index update per insert, and it leaves little headroom. Move to a key-value store with built-in partitioning, such as DynamoDB or Cassandra, or shard the relational database by a hash of short_code. Use conditional writes or a unique constraint on each shard to keep rejecting duplicate codes.
Exercise
A teammate proposes checking whether a code exists with a SELECT and inserting only if it does not. Why is this unsafe with several servers, and what should replace it?
Show answer
Two servers can run the SELECT at nearly the same time, both see that the code is free, and both insert it. One insert overwrites or duplicates the other, depending on the schema. Replace the check with a primary key or unique constraint and insert directly. Catch the uniqueness violation and retry with a new code, so the database makes the decision atomically.