Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Worked example · 25 min · revision 1

Code generation and the data model

Choose how lnk.example makes its codes by weighing a counter, random codes with a conditional write and a pre-generated key pool against this system's numbers, then design the key-value record, its access patterns, custom aliases without races, and expiry that never frees a code.

Contentsand lesson path

What you will learn

  • Design code generation, redirect semantics (301 versus 302) and a key-value data model with expiry and custom aliases.

Prerequisites: Requirements & Estimation, Caching Strategies, Unique ID Generation

01. The problem

Lesson 1 left lnk.example with these numbers for the worst case: 7.3 billion links after five years, at most 463 new links a second, and up to 100,000 redirects a second. The product adds four rules: links are public, business accounts may pick custom aliases such as spring-sale, links may expire, and owners or the trust-and-safety team may change or disable a link.

This lesson decides how codes are made and how a link is stored: the redirect must be one lookup by key, no two people may own one code, and an expired code must never point somewhere new. It applies the base62, n / N and guessing maths of short codes and the birthday bound. The code needs Python 3.10 or newer.

02. Step 1: The calls the data model must serve

A data model exists to serve calls, so sketch the API first. Each call becomes an access pattern: which key is read or written, and how often.

API sketch · lnk.example
POST  /v1/links                {url, alias?, expires_at?} -> 201 {code, short_url}
GET   /{code}                  -> redirect to the long URL (status: lesson 3)
PATCH /v1/links/{code}         {url?, status?}   owner, or trust and safety
GET   /v1/links?owner=me       the owner's links, newest first, one page a call
GET   /v1/links/{code}/stats   clicks and unique visitors per day (lesson 4)

Only the redirect is hot; everything else runs at a few hundred calls a second at most, so creation can afford to be careful rather than fast.

03. Step 2: How long must a code be?

With n links in a space of N possible codes, a random new code collides with probability n / N, and a random guess finds a live link with the same probability. The command prints both for 7.3 billion links.

Terminal · code length for 7.3 billion links
python3 - <<'PY'
n = 7.3e9  # links after five years, worst case from lesson 1
print("length         codes  share in use  1 guess in N hits  retries per 1M inserts")
for length in (6, 7, 8):
    space = 62**length
    share = n / space  # = chance that a random insert collides
    print(f"{length:>6}  {space:12.2e}  {share:12.3%}  {space / n:17,.0f}"
          f"  {share / (1 - share) * 1e6:22,.0f}")
PY
Expected output
length         codes  share in use  1 guess in N hits  retries per 1M inserts
     6      5.68e+10       12.852%                  8                 147,474
     7      3.52e+12        0.207%                482                   2,077
     8      2.18e+14        0.003%             29,910                      33

Six characters hold every link, but a random code would then hit a taken one about one time in eight, and so would a guess. Seven characters bring both down to 0.2%: about 2,000 retries per million inserts by year five, and one random guess in about 480 finds a link. Eight characters would make guessing 62 times harder for one more character in every link.

04. Step 3: Three ways to make codes, judged for this system

A counter in base62 gives the shortest codes (six characters for every link here) and cannot collide as long as no number is issued twice, which makes it the natural first idea. It works well for an internal tool or for codes that are not sensitive. Its costs show up at our scale: many servers need one shared counter, or blocks of numbers handed out by a range service; codes are consecutive, so anyone can walk them and watch the growth; and a store that keeps keys in sorted ranges sends all new, hot codes to one machine unless the keys are hashed. A secret permutation would hide the order but leave the space just as full (see short codes).

Random codes with a conditional write need no coordination: any server draws seven characters from a secure random source and writes them only if the key is free, retrying about twice per thousand inserts by year five. Random keys spread evenly across machines. The space stays sparse, though it is not secret: one guess in 480 finds someone's link.

A pre-generated key pool fills a table with unused random codes ahead of time, and app servers take them in batches of, say, 1,000. That moves the uniqueness check off the write path. But the pool must record a batch as taken before handing it out, or a crash and restart can hand the same batch out twice; codes held by a server that crashes are simply wasted. A pool pays off when the store has no conditional write, or when codes must be so short that the space is dense: at six characters, random inserts would retry about 147,000 times per million.

A fourth idea, hashing the long URL, gives the same code to everyone who shortens the same URL. That saves rows but mixes owners: two accounts would share one record, its statistics and its disable switch. A truncated hash can still collide, and anyone can hash a URL they suspect and test whether it was shortened.

Decision for lnk.example: random seven-character codes with a conditional write. We would revisit it if codes had to be typed from print (use an alphabet without look-alike characters and recompute the length) or kept private (use 12 or more characters, as the share-link lesson shows).

05. Step 4: The record and its access patterns

Every hot access reads or writes one link by its exact code, so a key-value store, which stores items under a key and spreads keys over machines, fits the main table. A relational table keyed by code works too: at the best-case 1.1 TB, one database with read replicas is a reasonable start, and the case for a key-value store grows with the data.

Data model and access patterns
links             key: code (case-sensitive)
  url             https://shop.example/spring?utm_source=sms
  owner           acct_7, or empty for anonymous links
  kind            random | alias
  created         1800000000            (Unix seconds)
  expires         1802592000 or empty
  status          active | disabled | expired
  version         1, 2, 3...            (+1 on every edit or status change)

links_by_owner    key: owner, sorted by created, newest first
  code, url       a copy, so the owner's list needs no second lookup

access pattern                       rate at peak (lesson 1, worst case)
get links[code]                      100,000/s
put links[code] if absent            463/s, plus one links_by_owner write
update links[code] if version = v    rare: edits, disables
query links_by_owner[owner]          a few per second

The owner's list is a second table because the main one cannot answer newest links of acct_7 without scanning; see access patterns first. It is written after the link itself. If a crash falls between the two writes, a link exists without its list entry, which a nightly repair job fixes; the reverse order would list a link that does not exist. version lets a write say only if nobody changed it since I read version 3; Step 6 and lesson 3 rely on it.

06. Step 5: Aliases and a race that tests rarely show

Aliases and random codes share one key space, the links table. Two rules keep them apart. First, every write of a new key is conditional: it succeeds only if the key is absent. Second, aliases must contain a hyphen, which no random base62 code has, so the two kinds can never collide; aliases are also lowercase and checked against words the service needs itself. A toy store models the writes a real one offers. Save kv.py and links.py in one folder.

Python · kv.py
"""A toy key-value store with the three writes a real one offers."""


class KV:
    def __init__(self) -> None:
        self._items: dict[str, dict] = {}

    def get(self, key: str) -> dict | None:
        item = self._items.get(key)
        return dict(item) if item else None  # a copy, as a network read returns

    def put(self, key: str, value: dict) -> None:
        """Plain write: silently replaces whatever the key held."""
        self._items[key] = value

    def put_if_absent(self, key: str, value: dict) -> bool:
        """Create only if the key is free, atomically. Redis: SET key value NX.
        DynamoDB: PutItem with the condition attribute_not_exists on the key."""
        if key in self._items:
            return False
        self._items[key] = value
        return True

    def put_if_version(self, key: str, value: dict, expected: int) -> bool:
        """Compare-and-set: replace only if the stored version is still `expected`.
        DynamoDB: a condition such as version = :v. Redis: WATCH, then MULTI/EXEC."""
        if key not in self._items or self._items[key]["version"] != expected:
            return False
        self._items[key] = value
        return True
Python · links.py
"""Create and resolve short links on top of kv.py (standard library only)."""
import re
import secrets
import string

from kv import KV

ALPHABET = string.digits + string.ascii_uppercase + string.ascii_lowercase
CODE_LEN = 7  # random codes are exactly 7 base62 characters
ALIAS = re.compile(r"[a-z0-9]+(-[a-z0-9]+)+")  # aliases need a hyphen: spring-sale
RESERVED = {"api-v1", "help-center", "log-in"}  # paths the service uses itself


def new_link(url: str, owner: str | None, kind: str, now: int, expires: int | None):
    return {"url": url, "owner": owner, "kind": kind, "created": now,
            "expires": expires, "status": "active", "version": 1}


def create_random(db: KV, url: str, owner: str | None, now: int,
                  expires: int | None = None, attempts: int = 5) -> str:
    for _ in range(attempts):
        code = "".join(secrets.choice(ALPHABET) for _ in range(CODE_LEN))
        if db.put_if_absent(code, new_link(url, owner, "random", now, expires)):
            return code
    raise RuntimeError("no free code after 5 attempts: check the random source")


def claim_alias(db: KV, alias: str, url: str, owner: str, now: int,
                expires: int | None = None) -> str:
    if not ALIAS.fullmatch(alias) or len(alias) > 40 or alias in RESERVED:
        return "invalid"
    if db.put_if_absent(alias, new_link(url, owner, "alias", now, expires)):
        return "created"
    return "taken"


def resolve(db: KV, code: str, now: int) -> tuple[str, str | None]:
    link = db.get(code)
    if link is None:
        return "missing", None
    if link["status"] != "active":
        return link["status"], None
    if link["expires"] is not None and now >= link["expires"]:
        return "expired", None  # exact, whenever the cleanup job runs
    return "active", link["url"]


def renew(db: KV, code: str, seen: dict, new_expiry: int) -> bool:
    """Owner extends a link, only if nobody changed it since `seen` was read."""
    if seen["status"] != "active":
        return False  # a tombstone stays dead
    new = dict(seen, expires=new_expiry, version=seen["version"] + 1)
    return db.put_if_version(code, new, seen["version"])


def tombstone(db: KV, code: str, seen: dict, now: int) -> bool:
    """Cleanup job: drop the target but keep the key, so the code is never reused.
    Writes only if the link is unchanged since the job read it as `seen`."""
    if seen["expires"] is None or now < seen["expires"]:
        return False  # not expired: nothing to clean up
    stone = {"status": "expired", "kind": seen["kind"], "owner": seen["owner"],
             "version": seen["version"] + 1}
    return db.put_if_version(code, stone, seen["version"])

Why is the conditional write needed if the code checks first? Because check and write are two steps. Run two claims of spring-sale with their steps interleaved by hand, first with check-then-put, then with put-if-absent:

Terminal · two owners claim one alias
python3 - <<'PY'
from kv import KV

A = {"url": "https://shop-a.example/spring"}
B = {"url": "https://shop-b.example/sale"}
db = KV()
# Two owners claim "spring-sale" at the same moment. Each request checks,
# then writes. We interleave their steps by hand to show the bad order.
a_sees = db.get("spring-sale")  # request A: is it free?
b_sees = db.get("spring-sale")  # request B: is it free?
if a_sees is None:
    db.put("spring-sale", A)
    print("A is told: created")
if b_sees is None:
    db.put("spring-sale", B)
    print("B is told: created")
print("spring-sale ->", db.get("spring-sale")["url"])

db = KV()  # the same two requests, now with a conditional write
print("A created:", db.put_if_absent("spring-sale", A))
print("B created:", db.put_if_absent("spring-sale", B))
print("spring-sale ->", db.get("spring-sale")["url"])
PY
Expected output
A is told: created
B is told: created
spring-sale -> https://shop-b.example/sale
A created: True
B created: False
spring-sale -> https://shop-a.example/spring

With check-then-put both owners were told created, and B silently replaced A's target: A's printed posters now send people to B's shop. Tests that send one request at a time cannot see this. The conditional write lets the store decide atomically. The same rule protects a design where codes come from a counter in the same key space: it eventually produces a string that a user already claimed, and only a conditional write, or a namespace rule like the hyphen, stops it overwriting that alias.

07. Step 6: Expiry that is exact and never frees a code

resolve compares expires with the clock on every read, so a link stops working at its expiry time, however late cleanup runs. Cleanup is often lazy: DynamoDB's built-in TTL, for example, deletes expired items typically within a few days. lnk.example does not let the store delete links, because that would free the code; a cleanup job reads each expired link and calls tombstone, which removes the target but keeps the key. Run the life of one alias:

Terminal · create, claim, expire, clean up
python3 - <<'PY'
from kv import KV
from links import claim_alias, create_random, resolve, tombstone

db, t0, day = KV(), 1_800_000_000, 86_400  # a fixed clock in Unix seconds
code = create_random(db, "https://docs.example/guide", None, t0)
print("random code:", len(code), "chars,", resolve(db, code, t0))
url = "https://shop.example/spring"
print("claim 1:", claim_alias(db, "spring-sale", url, "acct_7", t0, t0 + 30 * day))
print("claim 2:", claim_alias(db, "spring-sale", "https://x.example/", "acct_9", t0))
print("claim 3:", claim_alias(db, "springsale", "https://x.example/", "acct_9", t0))
print("day 29:", resolve(db, "spring-sale", t0 + 29 * day))
print("day 31:", resolve(db, "spring-sale", t0 + 31 * day))
seen = db.get("spring-sale")  # the cleanup job runs on day 35
print("cleanup:", tombstone(db, "spring-sale", seen, t0 + 35 * day))
print("day 40 claim:", claim_alias(db, "spring-sale", "https://x.example/", "acct_9",
                                   t0 + 40 * day))
print("day 40:", resolve(db, "spring-sale", t0 + 40 * day))
PY
Expected output
random code: 7 chars, ('active', 'https://docs.example/guide')
claim 1: created
claim 2: taken
claim 3: invalid
day 29: ('active', 'https://shop.example/spring')
day 31: ('expired', None)
cleanup: True
day 40 claim: taken
day 40: ('expired', None)

The alias works on day 29, stops on day 31, and on day 40 nobody can claim it again. If cleanup deleted the item instead, the conditional write on day 40 would succeed, because the key is gone, and every old email and poster would lead to the new owner's page.

Owners may renew an expired link until cleanup reaches it, so the two can race: both read the link, then both write. A plain put in the job would erase a renewal made between its read and its write, which is check-then-put again. So renew and tombstone both write with put_if_version, only if the version is still the one they read. Run both orders:

Terminal · a renewal and the cleanup job race
python3 - <<'PY'
from kv import KV
from links import claim_alias, renew, resolve, tombstone

t0, day = 1_800_000_000, 86_400
for first in ("renewal", "cleanup"):  # the two orders of two racing writes
    db = KV()
    claim_alias(db, "spring-sale", "https://shop.example/spring", "acct_7", t0,
                t0 + 30 * day)
    job_saw = db.get("spring-sale")  # day 31: the cleanup job reads version 1
    owner_saw = db.get("spring-sale")  # so does the owner's renewal
    if first == "renewal":
        r = renew(db, "spring-sale", owner_saw, t0 + 61 * day)
        c = tombstone(db, "spring-sale", job_saw, t0 + 31 * day)
    else:
        c = tombstone(db, "spring-sale", job_saw, t0 + 31 * day)
        r = renew(db, "spring-sale", owner_saw, t0 + 61 * day)
    print(f"{first} first: renewed {r}, cleaned {c}")
    print("  day 32:", resolve(db, "spring-sale", t0 + 32 * day))
PY
Expected output
renewal first: renewed True, cleaned False
  day 32: ('active', 'https://shop.example/spring')
cleanup first: renewed False, cleaned True
  day 32: ('expired', None)

Whichever writes second fails: cleanup cannot erase a renewal, and a renewal cannot revive a tombstone, so the owner is told the link was already retired. This holds only while every writer of a link, edits and disables included, uses the version condition; one plain put anywhere reopens the race.

08. Check your understanding

Practice check · 3 questions

Codes and records under pressure

Apply the generation strategies and the record design to three changes.

Q1. To save rows, a design makes each code the first seven base62 characters of SHA-256(long URL), so everyone who shortens one URL gets one code. For lnk.example, what is the main problem, and what should it do instead?
Q2. A key-pool service sends a batch of 1,000 codes to an app server, then marks the batch as taken. App servers insert pool codes with a plain put. What can happen if the service crashes between those two steps and restarts?
Q3. The alias spring-sale expired after 30 days, and the store's TTL feature deleted the item a few days later. Weeks on, another account claims spring-sale and the conditional write succeeds. What is the risk, and what prevents it?
Practice only: not graded, not saved, not evidence.

09. Apply it

Continue your design doc for 100 million new links a month:

  1. Use your link count from lesson 1 to choose a code length, and say which of the three strategies you pick and the condition under which you would switch.
  2. Write the record and the access-pattern table for your API, with a rate for each pattern.
  3. Add disable(db, code, seen) for the trust-and-safety team, using put_if_version. When the write fails, re-read the link and retry, since a disable must win over an edit. Show with both orders that a disable racing with an owner's edit is never lost.
  4. State your alias rules (characters, length, reserved words) and why they cannot clash with generated codes.

10. Review prompt

Without looking back: what does n / N tell you about retries and guessing? When does a counter, a random code or a key pool fit best? Why must creating a key be one conditional write? How do aliases and generated codes share one table safely? Why keep a tombstone?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check