Skip to content

Part 5 · Blueprint 23

URL Shortener Architecture

15 min reading · Sources · Editorial review pending

Fast redirects cannot rely on a stale copy after a required withdrawal.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: SQL vs. NoSQL vs. NewSQL Storage Engines, Distributed Caching & Stampede Prevention, Database Sharding & Consistent Hashing, Idempotency Keys & Distributed Retries.

Sixty-second mental model

Problem: Fast redirects cannot rely on a stale copy after a required withdrawal.

Use: Separate allocation, redirect authority and analytics.

Design boundary: Create and resolve short links, including withdrawal and abusive destinations. Start with an indexed code-to-destination record; an allocated code is not a published link until its authorized destination and state are committed. Exclude crawling destination content.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing url shortening. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one redirect means and which component owns the short-code record.

Think of a cloakroom issuing compact claim tickets. Separate the requester from short-code record, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.
Read path
The ordered operations used to retrieve and return a result. Analogy: The route a clerk follows to answer a customer's question.
Write path
The ordered operations that accept, validate and record a state change. Analogy: The route a new order takes into the official ledger.

Architecture and worked reasoning

Design boundary: Create and resolve short links, including withdrawal and abusive destinations. Start with an indexed code-to-destination record; an allocated code is not a published link until its authorized destination and state are committed. Exclude crawling destination content.

Responsibilities on the request path

URL shortening: responsibilities and request directionCreate and resolve short links, including withdrawal and abusive destinations. Start with an indexed code-to-destination record; an allocated code is not a published link until its authorized destination and state are committed. Exclude crawling destination content.Creator APICode allocatorLink databaseRedirect cache
Create and resolve short links, including withdrawal and abusive destinations. Start with an indexed code-to-destination record; an allocated code is not a published link until its authorized destination and state are committed. Exclude crawling destination content.

Domain interface and access patterns

POST /links → link_id, short_code; GET /r/{code} → redirect or withdrawn

links(code UNIQUE, tenant_id, owner_id, destination, state, version). Index code for redirect and (tenant_id, owner_id, created_at, link_id) for owner listing. Withdrawal changes state/version, not an unrelated cache-only flag.

Workload and limiting resource

Choose 1,000,000 new links/day and 100,000,000 redirects/day. Average redirects are 100,000,000 / 86,400 ≈ 1,157.41/s; a chosen 5× peak is 5,787.04/s. At 90% hits, normal origin load is about 578.70/s. With 300 bytes/new record, raw growth is 300 MB/day before indexes/replicas. Base62 codes of length seven have 62⁷ = 3,521,614,606,208 possible strings, but random allocation still needs collision detection.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

URL shortening: mutation boundaryAuthorize creation and normalize the destination under an explicit safety policy. Then: Allocate an unused code with a database uniqueness constraint. Then: Commit destination, owner, state and version before returning the short link.Step 1
Authorize creation and normalize the destination under an explicit safety policy.
Step 2
Allocate an unused code with a database uniqueness constraint.
Step 3
Commit destination, owner, state and version before returning the short link.
Authorize creation and normalize the destination under an explicit safety policy. Then: Allocate an unused code with a database uniqueness constraint. Then: Commit destination, owner, state and version before returning the short link.
  1. Authorize creation and normalize the destination under an explicit safety policy.
  2. Allocate an unused code with a database uniqueness constraint.
  3. Commit destination, owner, state and version before returning the short link.

Observation and recovery path

URL shortening: observation boundaryResolve the code to its current permitted destination. Then: Use a versioned cache only within the withdrawal freshness policy. Then: Return a redirect or an explicit unavailable/withdrawn response.Step 1
Resolve the code to its current permitted destination.
Step 2
Use a versioned cache only within the withdrawal freshness policy.
Step 3
Return a redirect or an explicit unavailable/withdrawn response.
Resolve the code to its current permitted destination. Then: Use a versioned cache only within the withdrawal freshness policy. Then: Return a redirect or an explicit unavailable/withdrawn response.
  1. Resolve the code to its current permitted destination.
  2. Use a versioned cache only within the withdrawal freshness policy.
  3. Return a redirect or an explicit unavailable/withdrawn response.

Failure that changes the decision

Hypothetical scenario: A withdrawn malicious destination remains in a redirect cache. Tie the allowed cache lifetime and invalidation behavior to a stated withdrawal promise, including failure of invalidation delivery.

Attempt this decision before reading the explanation

Should every redirect synchronously update a click-count row?

No. It turns a read-heavy hot code into a contended write path. Define analytics accuracy and loss tolerance separately, then buffer or sample events under that contract without weakening redirect safety.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

In short. Keep one authoritative token-to-destination decision. Make retries identify the same creation, and bound cache reuse by the promised withdrawal behavior.

A table with token and destination is a reasonable beginning. It becomes insufficient when the design silently assumes that a read replica is current, every cache honors immediate withdrawal, and every redirect event reaches analytics exactly once.

Split requirements by consequence. Losing an analytics event changes reporting; assigning one token to two destinations breaks the link's identity. A stale destination after withdrawal has a different risk from a delayed dashboard count. These requirements should not share an accidental best-effort policy.

Begin with a modular service and one authoritative database if it meets the chosen workload. Separate mapping, authorization and analytics boundaries in the design without requiring independently deployed microservices. Extract a component when isolation, ownership or measured scaling requirements justify the distributed recovery burden.

Creation authenticates the owner, validates destination policy, assigns a candidate token and atomically inserts a unique mapping. A repeated creation attempt carries a stable operation identity. A conflicting token candidate is retried under a bounded allocation policy; the uniqueness constraint decides ownership rather than an optimistic precheck.

Redirect lookup checks the mapping's active state and returns the selected HTTP redirect semantics. RFC 9110 defines redirect status behavior; the service must choose intentionally rather than assuming all redirects have identical method and caching consequences.

Withdrawal changes authoritative state and records invalidation intent. Internal cache version checks prevent an older refill from replacing a newer withdrawn state. Browser or intermediary caching is a separate boundary governed by the actual response and cache semantics described in RFC 9111 . Promise immediate withdrawal only if the complete served path can enforce it.

Northwind’s first mapping authority is a Postgres table with a unique token index. A Redis cache serves permitted reusable lookups; the creation transaction binds owner, request identity, destination and token. The public redirect path uses a narrow token lookup rather than the owner’s search interface. Administrative creation and withdrawal require authorization even when following an active public link does not.

Additional toy allocation calculation. In the illustrative 100-value namespace, ten assigned values leave a collision probability of 10/100 = 0.1 for the next independent uniform candidate. Holding occupancy fixed for this one allocation, the probability of three successive collisions is 0.1³ = 0.001, or 0.1%. Success within those three attempts is 1 − 0.001 = 99.9%. Those are derived toy probabilities, not measured availability or a recommended production namespace. Bound attempts even when collision probability is small.

At the much larger 62¹⁰ namespace, occupancy fraction for one next draw is only one part of planning. Across many allocations, collision opportunities accumulate. Unpredictability, uniqueness and authority also remain distinct: an unguessable public token is not a substitute for authentication on destination edits, and uniqueness says nothing about whether a destination is abusive.

Hypothetical scenario. Choose 100,000 new mappings per day and ten million redirect requests per day. Mean creation demand is 100,000 ÷ 86,400 ≈ 1.16 requests per second; mean redirect demand is 10,000,000 ÷ 86,400 ≈ 115.74 per second. Choose a planning peak multiplier of ten for redirects, yielding approximately 1,157.4 per second. That multiplier is an assumption to validate, not an industry constant.

With a chosen logical mapping payload of 300 bytes and 365 days of retention, payload is 100,000 × 365 × 300 = 10,950,000,000 bytes, or 10.95 GB. Three full copies require 10.95 × 3 = 32.85 GB of that payload. Indexes, WAL, backups, allocation, deleted records and metadata are additional.

Choose a hypothetical cache hit fraction of 0.9. At the chosen redirect peak, lookup misses are 1,157.4 × (1 − 0.9) = 115.74 per second. During an empty-cache recovery they can approach the full 1,157.4, before retries and refill amplification. Size and admission decisions must consider that path, not only the warm-cache mean.

A ten-character token over an alphabet of 62 symbols has 62¹⁰ = 839,299,365,868,340,224 possible strings. This namespace size does not guarantee collision-free random allocation or confidentiality. For a separate toy namespace of 100 values with ten already assigned, a uniform next candidate collides with probability 10 ÷ 100 = 0.1. Always enforce uniqueness; use a suitable unpredictable identifier when enumeration is a concern.

Finally, choose 100 bytes of logical analytics payload per redirect. Ten million events produce 10,000,000 × 100 = 1 GB per day before stream and storage overhead. The reporting path can exceed mapping growth even though it is not authoritative business state.

Bitly’s official short-link tutorial separates basic shortening, custom domains and customized back-halves. Its operations carry group identity as well as the long destination. Its deletion documentation also distinguishes an unedited link from one whose destination or back-half has changed. These are public product and API contracts, not a description of Bitly’s internal database.

Northwind should likewise decide whether changing a destination preserves a token, what owner scope applies and which withdrawal promises are enforceable. Writing those rules before choosing a cache policy makes the architecture review concrete. A short string alone does not specify lifecycle, authority or the meaning of deleting a link.

Destination validation is a policy boundary. Parse consistently, restrict supported schemes, and consider phishing and abuse response. Following arbitrary destinations server-side to generate previews creates a different network-access risk; keep that feature outside this design unless its fetching authority and isolation are specified.

Hypothetical scenario. A popular link is requested while caches restart. Every process attempts the same database refill. Meanwhile, an owner withdraws the link. A delayed refill returns the older active mapping after invalidation and tries to store it.

Coalesce refill work within a clearly stated scope, bound concurrent source lookups and use mapping versions to reject obsolete results. If processes coordinate only locally, estimate their combined refill pressure. A database that handled the warm path may not handle an uncontrolled cold burst.

Observe accepted creations, redirect outcomes, withdrawal visibility, source demand and analytics lag separately. Report unresolved invalidation work and define recovery ownership. A high redirect success ratio does not establish that withdrawn links stopped resolving correctly.

Layer 3 · Internals

Trade-offs and limits

ApproachProvidesRequires
Persistent redirect cacheabilityCan reduce repeated redirect work for stable destinations.Withdrawal and analytics visibility must tolerate cached responses.
Revalidated redirect behaviorCan preserve a more current origin decision.Additional origin requests and failure exposure must fit the capacity plan.

Recovery decision

Hypothetical scenario: A withdrawn malicious destination remains in a redirect cache. Tie the allowed cache lifetime and invalidation behavior to a stated withdrawal promise, including failure of invalidation delivery.

No. It turns a read-heavy hot code into a contended write path. Define analytics accuracy and loss tolerance separately, then buffer or sample events under that contract without weakening redirect safety.

Write your design before revealing the review

Should every redirect synchronously update a click-count row?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

No. It turns a read-heavy hot code into a contended write path. Define analytics accuracy and loss tolerance separately, then buffer or sample events under that contract without weakening redirect safety.

A withdrawn malicious destination remains in a redirect cache. Tie the allowed cache lifetime and invalidation behavior to a stated withdrawal promise, including failure of invalidation delivery.

Check your understanding

Should every redirect synchronously update a click-count row?

No. It turns a read-heavy hot code into a contended write path. Define analytics accuracy and loss tolerance separately, then buffer or sample events under that contract without weakening redirect safety.

How would you recover from this failure: A withdrawn malicious destination remains in a redirect cache. Tie the allowed cache lifetime and invalidation behavior to a stated withdrawal promise, including failure of invalidation delivery.

Start with the exact boundary that failed. Authorize creation and normalize the destination under an explicit safety policy. Allocate an unused code with a database uniqueness constraint. Commit destination, owner, state and version before returning the short link. Then recover evidence through the observation path: Resolve the code to its current permitted destination. Use a versioned cache only within the withdrawal freshness policy. Return a redirect or an explicit unavailable/withdrawn response. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Choose 1,000,000 new links/day and 100,000,000 redirects/day. Average redirects are 100,000,000 / 86,400 ≈ 1,157.41/s; a chosen 5× peak is 5,787.04/s. At 90% hits, normal origin load is about 578.70/s. With 300 bytes/new record, raw growth is 300 MB/day before indexes/replicas. Base62 codes of length seven have 62⁷ = 3,521,614,606,208 possible strings, but random allocation still needs collision detection. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Create and resolve short links, including withdrawal and abusive destinations. Start with an indexed code-to-destination record; an allocated code is not a published link until its authorized destination and state are committed. Exclude crawling destination content.

Which component in this topology could be removed from a smaller first deployment?

Creator API, Code allocator, Link database, Redirect cache name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Authorize creation and normalize the destination under an explicit safety policy.

What evidence must a caller have before relying on the observation path?

Resolve the code to its current permitted destination. Use a versioned cache only within the withdrawal freshness policy. Return a redirect or an explicit unavailable/withdrawn response. No. It turns a read-heavy hot code into a contended write path. Define analytics accuracy and loss tolerance separately, then buffer or sample events under that contract without weakening redirect safety.

45-minute interview rubric

  1. 00–05: scope redirect and short-code record.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw short-code record, numbered writes and reads.
  4. 28–40: challenge recovery: Separate allocation, redirect authority and analytics.
  5. 40–45: defend code placement, observations and remaining assumptions.

Go deeper

Decision log

Separate allocation, redirect authority and analytics.

Preserve redirect identity and short-code record ownership.

Revisit changed workload, observations or recovery objectives.