URL Shortener
The same classic problem, but worked through the TOGAF ADM phases — so you see how an enterprise method drives a real technical design.
URL shortener, the ADM way, in 30 seconds
- Why TOGAF here: it forces you to move from business intent → requirements → data/app → technology in order, so no decision is made before its justification.
- A (Vision): a fast, reliable shortening service; principles — read-optimized, horizontally scalable, cheap to run.
- B (Business): two capabilities — create short link and resolve + redirect; resolve dominates.
- C (Data/App): a key-value mapping
code → URL; a stateless app tier; an async analytics stream. - D (Technology): the real meat — code generation, caching, the datastore, sharding, the redirect, and every cross-cutting concern.
- E–H: phased rollout, then governance (SLOs, quotas) and change management.
- The lesson: each phase hands the next a constraint, so the technology choices in D are consequences, not guesses.
A coat-check ticket for the web
Picture a coat check at a theatre. You hand over a bulky coat and get back a tiny numbered ticket. The ticket is short, easy to pocket, and means nothing on its own — but hand it back and the attendant walks straight to your exact coat. A URL shortener is the same idea for web links: you give it a long, unwieldy address and it hands back a tiny code like sysc.ft/8M0kz. Later, anyone who visits that code gets walked straight to the original page. The short code is the ticket; the lookup is the attendant finding your coat.
So why is something this simple worth a whole interview? Because the quiet parts are hard. The attendant has to find your coat in a few milliseconds, the coat room holds tens of billions of coats, almost everyone is collecting coats rather than dropping them off, and two people must never be handed the same ticket number. Getting those four things right — fast reads, huge storage, a lopsided read/write ratio, and no collisions — is the real design, and it's why this 'tiny' problem teaches so much.
What makes it hard — the problem before the solution
- Reads dwarf writes. A link is created once and then clicked hundreds of times. The whole system should be optimized for the read, even if that makes the write a little more work.
- The dataset is enormous. Billions of short-code → URL mappings won't fit on one machine's disk, let alone its memory.
- Redirects must feel instant. A visitor clicking a link expects the page, not a spinner — the lookup has a tight latency budget.
- Codes must be unique and short. Two different long URLs can never collide onto the same code, yet the code should stay just a few characters long.
Why work a small problem through TOGAF?
A URL shortener is tiny, so it's the perfect place to see the method clearly. The TOGAF ADM isn't just for giant enterprises — its real value is the discipline of order: you don't choose a database until the data architecture demands it, and you don't choose the data architecture until the business capabilities define it. By the time we reach the technology decisions in Phase D, every one of them is a consequence of something decided earlier, not a gut call. That traceability is exactly what makes an architecture defensible.
Phase A — Architecture Vision
Intent: agree what we're building, for whom, and the principles that will constrain every later choice.
- Vision: a service that turns long URLs into short links and redirects visitors quickly and reliably, at large scale and low cost.
- Stakeholders: end users (want instant redirects), link creators (want reliable creation + maybe analytics), the business (wants low per-link cost).
- Principles (the constraints that cascade): read-optimized first (redirects vastly outnumber creates); horizontally scalable (no single box is the ceiling); operationally cheap (favor simple, boring technology).
Phase B — Business Architecture
Intent: model the business capabilities and value streams before any technology talk.
- Value stream: submit long URL → receive short link → share it → visitor clicks → visitor lands on the original page.
- Capability 1 — Create short link: low volume, must be correct (no collisions), can tolerate a few ms more latency.
- Capability 2 — Resolve & redirect: very high volume, must be fast, tolerant of eventual consistency.
- Capability 3 — Report clicks (optional): analytics, must never slow down resolve.
Impact: these capabilities are not equal. Resolve dominates traffic and sets the non-functional targets; create is where correctness lives; report must be kept off the critical path. That asymmetry, discovered here in Phase B, drives everything in Phase D.
Phase C — Information Systems Architecture (Data & Application)
Intent: define the data and application architecture, and the gap from today (today = nothing; greenfield).
Data architecture
- Core entity: a mapping of
shortCode → longURL(plus createdAt, optional ownerId, optional expiry). - Access pattern: almost always look up by shortCode — a pure key lookup. No joins, no complex queries.
- Conclusion: this is a key-value shape, not a relational one. (See SQL vs NoSQL.) The access pattern, defined by the capabilities, chose the data model — not the other way around.
Application architecture
- Stateless app tier for both create and resolve, so it can scale horizontally per the Phase A principle.
- Separation of the two capabilities so resolve (hot) can scale independently of create (cold).
- An asynchronous analytics path, decoupled via a queue, so reporting never touches the redirect's latency.
Phase D — Technology Architecture (the core)
Intent: choose the concrete technologies and the physical/deployment design that realize Phase C — and justify each one against the principles and requirements. This is where a technical interviewer spends most of the time, so we'll cover every step.
D1 — Estimate the load (sizing drives technology)
# 100M new links/day
create_per_sec = 100_000_000 / 86_400 # ~1,160 writes/sec
# Read-heavy: ~100 resolves per create
resolve_per_sec = create_per_sec * 100 # ~116,000 reads/sec
# Storage: 100M/day * 365 * 5y ~ 180B rows, ~500B each -> ~90 TB
# Verdict: one node can't hold or serve this -> cache + shard (set in D3/D4)The numbers confirm the Phase B asymmetry quantitatively: a 100:1 read:write ratio and a dataset far too big for one machine. Those two facts dictate the next steps.
D2 — Short-code generation
| Option | How | Pros | Cons |
|---|---|---|---|
| Counter + base62 | Global counter; encode as base62. | No collisions; short, fixed-length codes. | Needs a distributed counter; sequential/guessable. |
| Hash of URL | Hash the URL; take first N base62 chars. | Stateless; same URL → same code. | Collisions must be detected and retried. |
Decision: counter + base62, with each app server pre-allocated a block of IDs (e.g. 1,000 at a time) from a central source so there's no per-request coordination — satisfying the horizontally scalable principle. Add random bits to the encoding if links must be unguessable.
Why a counter, and why not the obvious alternatives?
The instinct many people reach for first is 'just hash the URL.' It feels stateless and clean — same URL in, same code out, no counter to coordinate. Here's the gap that approach can't fill: hashes collide. Two different URLs can land on the same first-N characters of a hash, and now two destinations fight over one code. To stay correct you'd have to read the store on every create to check 'is this code already taken by a different URL?', and retry with more characters when it is. That turns the write path into a read-check-retry loop and quietly lengthens codes as the space fills up. A counter sidesteps all of it: every number is unique by construction, so there is nothing to check and nothing to retry.
But a naive counter has its own gap: a single global counter that every server increments becomes a coordination bottleneck and a single point of failure — every create in the world would queue behind it. The fix is ID-block allocation: a server asks the central source once for a block of 1,000 IDs, then hands them out locally with zero network chatter until the block runs dry. You keep the uniqueness of a counter without the per-request coordination.
| Approach | What it buys | The gap it can't fill |
|---|---|---|
| One global counter | Perfect uniqueness, shortest codes. | Every create coordinates on one number — a bottleneck and single point of failure. |
| Hash of the URL | Stateless; same URL maps to the same code. | Collisions force a read-check-retry on every write and grow code length over time. |
| Random code + check | Unguessable, no central counter. | Needs a uniqueness check per create, and collisions rise sharply as the space fills. |
| Counter + ID blocks (chosen) | Unique by construction, no per-request coordination, short codes. | Codes are sequential/guessable — add random bits if that matters. |
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # 62 chars
def encode(num):
# Turn the counter ID into a compact base62 string.
if num == 0:
return ALPHABET[0]
code = []
while num > 0:
num, rem = divmod(num, 62) # peel off one base62 digit at a time
code.append(ALPHABET[rem])
return "".join(reversed(code)) # e.g. 125_000_000 -> "8M0kz"
# ID 1 -> '1', ID 62 -> '10'. ~3.5B URLs fit in 6 chars, 62^6.D3 — The datastore
- Choice: a horizontally scalable key-value store (e.g. a wide-column or KV database) — matches the Phase C data shape and the scale from D1.
- Why not relational: we have no joins, no transactions across records, and a need to scale writes horizontally — relational would be fighting the access pattern.
- Durability: replicate each partition (see Replication) so a node loss doesn't lose links.
The question an interviewer will press on is 'why not just a SQL database?' It's a fair instinct — relational databases are mature, well-understood, and great at a lot. The gap they can't fill here isn't about features, it's about shape and scale. Our only query is SELECT url WHERE code = ? — a single-row lookup by primary key. We never join, never run a report, never update many rows in one transaction. A relational engine's strengths (joins, multi-row transactions, flexible queries) are exactly the parts we don't use, and its weaker spot — spreading writes across many machines — is precisely what 90 TB forces us to do. A key-value store is built around that one access pattern, so it gives us the horizontal scale without the ceremony.
| Option | Strong at | Why it's wrong here |
|---|---|---|
| Single SQL instance | Transactions, joins, familiar tooling. | One box can't hold ~90 TB or serve 116k reads/sec; the rich query engine goes unused. |
| Sharded SQL | Keeps SQL while splitting data across nodes. | Cross-shard joins/transactions get painful for a workload that needs neither. |
| Key-value / wide-column (chosen) | Single-key lookups at huge scale, easy horizontal growth. | No ad-hoc queries — fine, because we only ever look up by code. |
D4 — Sharding the data
- 90 TB won't fit on one node, so we shard (see Sharding).
- Shard key: the
shortCode— it's uniformly distributed and every lookup already has it, so reads hit exactly one shard. - Scheme: consistent hashing (see Consistent hashing) so adding capacity moves only a slice of keys.
D5 — Caching the hot path
- Resolve is the dominant, latency-critical capability, so put an in-memory cache (e.g. Redis) in front of the store (see Caching).
- Strategy: cache-aside with a TTL; the data is tiny and highly reused, so hit rates are excellent.
- Payoff: the vast majority of 116k resolves/sec never touch the datastore — directly realizing the read-optimized first principle from Phase A.
def resolve(short_code):
long_url = cache.get(short_code) # 1. hot path: in-memory cache
if long_url is None: # cache miss
long_url = kv_store.get(short_code) # 2. fall back to the sharded KV store
if long_url is None:
return http_404() # unknown code
cache.set(short_code, long_url, ttl=3600) # 3. populate for next time
emit_click_event(short_code) # 4. async analytics, off the hot path
return http_301(location=long_url) # 5. redirect the browserD6 — The redirect & the edge
- Return an HTTP redirect: 301 (permanent) lets browsers cache it and cuts load, but hides clicks; 302 (temporary) always hits us so analytics works. Choose per whether click tracking matters.
- Front everything with a reverse proxy / load balancer (see Load balancing) and optionally a CDN / edge (see CDN) for geographic proximity.
- Put a rate limiter at the gateway (see Rate limiting) so abusive creation or scraping can't overwhelm the service.
D7 — Cross-cutting concerns
- Analytics: emit a click event to a queue (see Message queues); workers aggregate counts off the critical path.
- Idempotency: creating the same link twice should be safe (see Idempotency).
- Observability: trace the resolve path and alert on cache hit-rate and p99 (tracing: Distributed tracing).
- Consistency: a brand-new link being resolvable a second later is fine — eventual consistency is an accepted trade (see Consistency models).
Scaling & bottlenecks — what breaks first
A good answer doesn't stop at the happy path. The most revealing interview question is 'now turn the traffic up 10× — what falls over first, and what do you do about it?' Walk the request and name the pressure points in order.
| Breaks first as you scale | The symptom | The fix |
|---|---|---|
| Cache hit rate drops | More reads leak through to the datastore; p99 climbs. | Add cache nodes / memory; raise TTL; warm hot codes; consider an edge cache (CDN). |
| A single shard gets hot | One code or one key range takes disproportionate traffic. | Finer sharding, replicate the hot shard for reads, or cache that code aggressively. |
| The ID allocator stalls | Creates stall waiting on the central counter source. | Hand out bigger ID blocks per server so allocations happen far less often. |
| Analytics backs up | The click-event queue grows faster than workers drain it. | Scale workers out; it's off the hot path, so resolves stay fast while it catches up. |
Notice the ordering is deliberate: because resolve is cache-served, the cache is your first and most important line of defense, and it's the first thing to feel pressure. The datastore only hurts when the cache stops absorbing load — which is why the read path is designed to keep the cache in front at all costs.
# A viral link means one short_code gets, say, 60% of all reads.
# Sharding by code sends ALL of that to ONE shard -> that node melts.
#
# Mitigations, cheapest first:
# 1. Cache absorbs it: a hot code stays in memory, so the shard rarely sees it.
# 2. Read replicas: fan the hot shard's reads across N copies.
# 3. Code-level replication: store the hottest codes on several shards.
#
# The cache does 99% of the work here -- which is WHY it sits on the hot path.Phases E & F — Opportunities, Solutions & Migration Planning
- Greenfield, so sequence by risk: ship resolve + create against a single replicated KV store first; add the cache; then introduce sharding once data volume approaches a single node's limit.
- Analytics last, behind the queue, so it never blocks the launch of the core service.
- Each step is independently shippable and reversible — the same strangler-fig / expand-contract spirit from the TOGAF commerce scenario.
Phases G & H — Governance & Change Management
- Governance (G): define SLOs (e.g. resolve p99 < 50ms, 99.99% availability), set per-client creation quotas, and review that the build still honors the Phase A principles.
- Change management (H): let the design evolve within guardrails — adding custom aliases or expiry is a bounded change, not a re-architecture, precisely because the boundaries were drawn cleanly.
This page is where the portal's two halves meet — the enterprise-architecture method (TOGAF) and the hands-on component knowledge — showing that they're the same craft at different zoom levels.
Why it matters
- It proves the ADM scales down to a single service, not just giant enterprises — the discipline of order helps any design.
- It makes technology choices defensible by tracing each one back to a principle, capability, or number.
- It turns the component pages from isolated facts into a connected, phase-ordered design method.
If ignored
- You pick technologies before the requirements justify them, and can't defend the choices under questioning.
- Cross-cutting concerns (analytics, limits, observability) get bolted on late and leak into the hot path.
- Without governance (G/H), the clean boundaries erode and the service drifts back toward a tangled monolith.
Where it fits
- Phase D is the technical-design core — code generation, datastore, sharding, cache, edge, cross-cutting concerns.
- Earlier phases (A–C) supply the constraints; later phases (E–H) handle rollout and keeping it honest.
- It sits alongside the interview framework as a second, complementary way to structure a design answer.
Related topics
- TOGAF in practice: the full enterprise version of this same ADM method
- Caching: the Phase D decision that realizes 'read-optimized first'
- Sharding: the Phase D answer to the 90 TB sizing
- The key trade-offs: every phase makes an explicit, defensible trade-off
Interview lens
Questions it unlocks
- Design TinyURL — but structure it like an architect, not just an engineer.
- How would TOGAF's ADM shape a concrete technical design?
- Walk me through the technology architecture (Phase D) for a read-heavy service.
60-second answer
I'd frame it as an ADM walk so every choice is traceable. Phase A sets principles — read-optimized, horizontally scalable, cheap. Phase B finds two capabilities, resolve and create, with resolve dominating. Phase C sees a pure key lookup, so the data model is key-value with a stateless app tier. Then Phase D does the technical design: counter+base62 codes with ID-block allocation, a sharded KV store keyed by code with consistent hashing, a cache-aside layer that absorbs the 100:1 read load, an HTTP redirect behind a load balancer and CDN, and cross-cutting concerns — async analytics via a queue, rate limiting, tracing, and accepted eventual consistency. E–H handle a risk-ordered rollout and governance via SLOs and quotas. The power is that every Phase D technology is a consequence of an earlier phase, not a guess.
Common traps
- Jumping straight to technology (Phase D) without the vision, capabilities, and data architecture that justify it.
- Letting analytics or other cross-cutting concerns creep onto the latency-critical resolve path.
- Skipping governance, so SLOs and quotas are never defined and the design can't be held accountable.