Sub topic 7
Data model and choosing a datastore
This chapter assumes you know basic HTTP, have used a relational or key-value database, and can read simple Python. By now you have an API and a way to generate short codes. Next you need a place to store the mapping from short code to long URL.
What the service needs to store
The core record is small. Each link needs a short code, the original URL, a creation time, and an optional expiry time. The access pattern is simple:
- Write once: create a link.
- Read many times: look up a long URL by short code.
- No joins, no range scans, and no updates to the URL after creation.
Reads far outnumber writes, and every read is a lookup by exact key. That shapes the choice of datastore.
The schema
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
);The primary key on short_code does two jobs. It builds an index, so a lookup by code does not scan the table. It also makes the database reject a second row with the same code. That rejection is how you detect a collision, as the collision chapter describes.
VARCHAR(10) leaves room for seven-character generated codes plus longer custom aliases. expires_at is nullable because most links never expire.
Sizing a row
Estimate the storage per row before choosing a store. A seven-character code takes about 7 bytes. The long URL averages roughly 100 bytes. Timestamps take 8 bytes each. Add index and row overhead and you get about 200 to 500 bytes per link.
At 100 million new links a year, that is 20 to 50 GB per year. Five years is 100 to 250 GB. This fits on one modern database server. The size is a reason to plan for replication and sharding later. It is not a reason to start with them.
Relational or key-value?
Both fit this workload. The deciding factors are scale and what else you need.
| Factor | Relational (PostgreSQL, MySQL) | Key-value or wide-column (DynamoDB, Cassandra) |
|---|---|---|
| Lookup by key | Fast with the primary key index | Fast, the native access pattern |
| Uniqueness check | Primary key constraint | Conditional write, such as "put if absent" |
| Horizontal scaling | Possible, but you shard it yourself | Built in, with automatic partitioning |
| Extra queries (links per user, reports) | Easy with SQL and secondary indexes | Needs extra indexes or a design for each query |
| Operational familiarity | High | Depends on the team |
A relational database is a good default. It handles the expected data size, gives you transactions and constraints, and supports user and analytics queries without extra design. Choose a key-value store when you expect billions of rows, very high write rates, or want partitioning handled for you.
Writing safely
Insert the row and let the primary key reject duplicates. Do not check first and insert second, because two requests can pass the check at the same moment.
import sqlite3
def create_link(conn, short_code: str, long_url: str) -> bool:
try:
conn.execute(
"INSERT INTO urls (short_code, long_url) VALUES (?, ?)",
(short_code, long_url),
)
conn.commit()
return True
except sqlite3.IntegrityError:
return FalseA return value of False means the code already exists. The caller can then retry with a new code or report that a custom alias is taken.
Common errors
- Storing the long URL in a
VARCHAR(255). URLs can be much longer, so useTEXTor a larger limit. - Adding a separate index on
short_code. The primary key already provides one. - Checking for duplicates in application code instead of relying on the constraint.
Exercise
Why does the design insert the row and handle a constraint error, rather than querying for the code first?
Show answer
Two concurrent requests can both see that the code is free and then both insert it. The primary key constraint is checked atomically by the database, so exactly one insert succeeds and the other fails with an error that the code can handle.