Architecting a Global Link-Shortening Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a link-shortening platform that assigns compact keys to full-length destination URLs, resolves short-key requests back to their targets with low latency, and guarantees mapping integrity as traffic and stored links scale up.
Core workload parameters—request rates, data footprint, uptime objectives, link lifetimes, vanity slugs, HTTP status codes, and click tracking—are intentionally left open. State the clarifying assumptions you need before locking in storage or routing choices; if you introduce concrete capacity numbers to size your components, label them clearly as hypothetical assumptions rather than fixed requirements. In particular, define your stance on:
- Whether repeated submissions of the same destination URL can mint separate short keys, and whether creators may pick custom vanity slugs.
- Whether a link's destination stays fixed once created, supports scheduled expiration, or allows later edits or takedowns.
- What HTTP redirect behavior and safety/anti-abuse protections the platform must enforce.
- Whether the system runs across multiple geographic regions, and whether a newly created link must resolve worldwide right away.
Scope & Expectations
- Identifier minting & durable persistence: Show how generated keys and optional vanity slugs are allocated and stored without collisions or silent overwrites.
- Low-latency redirect path: Detail the HTTP redirect semantics, multi-tier caching strategy, and protections against viral hot-key spikes and malicious URLs.
- Lifecycle & cross-region consistency: Specify how scheduled expirations, manual takedowns, and newly created links behave across caches and geographic regions.
Step-by-step walkthrough
Clarify requirements and label the hypothetical workload
Because request rates, data footprint, link lifetimes, vanity slugs, and regional topology are intentionally left open, pin down those assumptions before choosing databases or caches—and explicitly label your sizing numbers as hypothetical assumptions so every architectural choice traces back to a stated requirement.
Functional requirements
- Shorten: accept a destination URL (with an optional vanity slug and optional expiration timestamp) and return a unique short link.
- Redirect: resolve
GET /{code}to the original destination URL with low latency. - Manage and measure: let link creators view click analytics, list their links, and disable a link immediately.
Answers to the clarifying questions (assumed for this design)
- Separate keys per destination & vanity slugs? Yes to both. Two marketing campaigns often shorten the exact same landing page to track clicks separately, so shortening is not a 1-to-1 deduplicating hash. Creators may also claim custom vanity slugs (
4–30characters from[A-Za-z0-9_-], excluding reserved paths likeapi,admin,login). - Fixed targets, scheduled expiry, or later edits? Destinations remain immutable once created (preventing bait-and-switch phishing), may carry an optional
expires_attimestamp, and can be disabled early by the owner or abuse team. - HTTP redirect behavior & anti-abuse safeguards? Default to HTTP
302 Foundwith explicit cache headers so expiration, takedowns, and analytics stay accurate. Allow onlyhttp://andhttps://URLs, block self-referential redirect loops, rate-limit creation, and screen destinations against phishing/malware feeds. - Geographic footprint & immediate global resolution? Operate active-active across 3 geographic regions (
US,EU,APAC). Redirects are served from the caller's nearest region, and a newly minted link must resolve in every region the instant its201 Createdresponse returns.
Hypothetical workload (explicitly labeled assumption)
- Write volume: 100M new short links per month, with peak traffic at 10x the average.
- Read volume: 10B redirects per month (a 100:1 read-to-write ratio), with peak traffic at 10x the average.
- Retention & availability: keep non-expiring links for 10 years; never reuse codes; target
99.99%availability for redirects (< 20 msserver p99 on cache hit) and99.9%for creation.
Back-of-the-envelope numbers
Using
30 days x 86,400 s = ~2.592M seconds/month, translate the hypothetical workload into concrete system rates:Throughput Link creation (writes) 100M / 2.592M s = ~39 links/s average -> ~400 links/s at 10x peak Redirects (reads) 10B / 2.592M s = ~3,858 reads/s avg -> ~40,000 reads/s at 10x peak Durable storage (10-year horizon) Record size ~500 bytes (code, long_url, owner_id, timestamps, status, metadata) Monthly / 10-year data 100M x 500 B = 50 GB/month = 600 GB/year = ~6 TB over 10 years 3 regions x 3 replicas each 6 TB x 9 copies = ~54 TB total SSD across the fleet over 10 years Identifier code space (Base62 = 0-9, A-Z, a-z -> 62 characters) 6 characters: 62^6 ~56.8 billion codes -> lasts ~47 years at 1.2B/year (tight + scannable) 7 characters: 62^7 3,521,614,606,208 (~3.52 trillion codes) -> lasts ~2,934 years! Why unchecked random 7-char codes silently corrupt links (Birthday Paradox after 10 years, n = 12B): Chance 1 new random code hits an existing one: 12B / 3.52T = ~0.34% Expected colliding pairs if never DB-checked: n^2 / (2 * 62^7) = (12e9)^2 / (7.04e12) = ~20.5M collisions! Hot cache & analytics stream Regional cache (top 10M links) 10M x 500 B = ~5 GB RAM per region (fits easily on one cache shard + replicas) Peak click event log 40,000 clicks/s x ~200 B = ~8 MB/s inbound streamThree crucial conclusions jump out of this math:
- Storage is small (~6 TB in 10 years), while reads dominate 100:1. Any modern distributed key-value store holds 6 TB effortlessly; our architecture lives or dies on caching, multi-region consistency, and viral hot-key protection.
- 7 Base62 characters are plenty forever, so we never reuse expired or deleted codes—eliminating the bug where an old link in an email suddenly points to a stranger's website years later.
- Even in a 3.5-trillion namespace, unchecked generation causes ~20.5 million collisions over 10 years. Minting a candidate string is only step one—atomic, durable storage is what keeps mappings trustworthy.
API design
Create a short link POST /v1/links Headers: Authorization: Bearer <token>, Idempotency-Key: <client_uuid> Body: { "long_url": "https://example.com/...", "custom_alias": "q4-launch", "expires_at": "2027-01-01T00:00:00Z" } -> 201 Created { "code": "q4-launch", "short_url": "https://sho.rt/q4-launch", "long_url": "...", "expires_at": "..." } -> 400 Bad Request INVALID_URL | INVALID_ALIAS (bad scheme, reserved word, or forbidden shape) -> 409 Conflict ALIAS_TAKEN -> 422 Unprocessable URL_BLOCKED (matched phishing/malware blocklist) -> 429 Too Many Req RATE_LIMITED Public redirect GET /{code} -> 302 Found Location: <long_url> Cache-Control: public, max-age=0, s-maxage=60 (capped at remaining expiry!) -> 404 Not Found Cache-Control: no-store (code does not exist) -> 410 Gone Cache-Control: public, max-age=0, s-maxage=60 (expired or disabled) Owner management & stats GET /v1/links?cursor=<opaque> DELETE /v1/links/{code} -- sets status = 'disabled' (never frees the code for reuse) GET /v1/links/{code}/stats?from=&to=&group_by=hour|country|referrerWhy each detail is deliberate:
Idempotency-KeyonPOST /v1/links: an idempotency key is a client-generated unique token stored by the server for 24 hours alongside the response. Because onelong_urlis allowed to have multiple distinct short links, retrying a timed-outPOSTwithout an idempotency key would accidentally mint a second short link (or return a false409 ALIAS_TAKENif the first custom-alias attempt actually succeeded!).410 Gonevs.404 Not Found:410tells browsers and search crawlers that the link used to exist and was intentionally retired, whereas404means the code has never been created.
Data model
The redirect path only ever performs a single-key point lookup by
code—never a relational join or range scan—so a partitioned key-value / wide-column store replicated in every region is ideal.links (Key-Value store, partition key = code; full replica in all 3 regions) code PK (7-char generated Base62 string OR custom alias) long_url string (<= 2,048 bytes) kind 'generated' | 'alias' owner_id string home_region 'us' | 'eu' | 'apac' created_at timestamp expires_at timestamp | NULL status 'active' | 'disabled' | 'pending_scan' version int id_blocks (Tiny replicated table managed by the Block Allocator) block_number PK (int; each block = 1,000,000 consecutive integers) owner_region 'us' | 'eu' | 'apac' leased_to_host string, leased_at timestamp alias_registry (Global linearizable consensus store — e.g., Spanner / CockroachDB / Raft KV across 3 regions) alias PK, long_url, owner_id, expires_at, status, created_at idempotency_kv (owner_id, idempotency_key) -> cached 201 response (TTL 24 hours) links_by_owner (owner_id, created_at DESC, code) -> async secondary index for "My Links" dashboard click_counts (code, hour_bucket) -> total_clicks, unique_visitors_hll_sketchHigh-level architecture
Link Clickers (Worldwide) Link Creators (Web / API) | | v v +---------------------+ caches 302s <= 60s +---------------------+ | Global CDN Edge | | API Gateway | (auth, rate limit) +----------+----------+ +----------+----------+ | cache miss | =================|========== Inside Each of 3 Regions ================|================= v v +---------------------+ +------------------+ +---------------------+ lease 1M range | Redirect Service | ---> | Regional Cache | | Create Service | ---------------+ | (stateless + 3s RAM | | (~5 GB hot KV) | | (validate URL, | | | cache + coalescing)| +------------------+ | mint code, persist)| v +---+----------+------+ +----+-----------+----+ +--------------------+ | | cache miss | | | Block Allocator | | v | | custom | (tiny global store)| | +-----------------------------+ PUT if absent | | alias +--------------------+ | | Regional Mapping Store | <-----------------+ v | | (full local copy of `links`)| +------------------------+ | +--------------+--------------+ | Global Alias Registry | | | semi-sync to partner region + | (3-region Raft quorum: | | | async replication to 3rd region | INSERT IF NOT EXISTS) | | v +------------------------+ | [If local store misses: ask Home Region (generated) or Alias Registry (alias)] | +---> async non-blocking buffer ---> Click Log (+ CDN Edge Logs) ---> Stream AggregatorNotice how the read path (
~40,000/s) and write path (~400/s) are completely decoupled: clicks never wait on analytics or global consensus locks, and link creation never scans hot redirect caches.Deep dive 1: collision-free identifier creation
Keep two responsibilities strictly separate: how a server proposes a candidate key versus how the storage layer enforces uniqueness and durability.
Comparing the three classic candidate generators:
Strategy How it works Pros Cons 1. Truncated URL hash First 7 Base62 chars of SHA-256(long_url)Stateless Collides across different URLs; breaks "multiple distinct links for the same URL" unless salted and retried 2. Random 7-char Base62 Cryptographic random pick from 62^7Zero generator state; unguessable Needs a globally synchronized uniqueness check on every write across 3 regions so two regions cannot pick the same random string 3. Leased counter blocks + permutation (Chosen) Lease disjoint 1M-integer ranges per server, scramble bijectively, Base62-encode Zero collisions across servers or regions; fast local writes Requires a tiny range allocator and a namespace split from custom aliases How scrambled counter blocks work step by step: 1. Lease disjoint blocks: Each Create Service host leases a block of
1,000,000integers ([block_no * 1M, (block_no + 1) * 1M)) from the Block Allocator, which recordsblock_no -> owner_regioninid_blocks. At peak (400/sacross all servers), 1M IDs last over 40 minutes (~7 hours at average load), and every host pre-fetches one spare block in memory so allocator hiccups never block writes. 2. Scramble sequential numbers one-to-one: Raw counters (0000001,0000002) leak business volume and let scrapers enumerate every link. We pass integernthrough a Feistel permutation—a lightweight, reversible bit-shuffling function keyed with a secret server key that maps[0, 62^7)onto[0, 62^7)strictly one-to-one, just like shuffling a deck of cards so two different inputs never land on the same output—and then Base62-encode the shuffled integer. 3. Keep generated codes and custom aliases in disjoint shapes: If a user claimed custom aliasXk3p9Qatoday, a counter block could eventually produceXk3p9Qanext year! We prevent that permanently with one crisp rule: generated codes are always 7 Base62 characters; custom aliases may not be 7 pure Base62 characters (sopromo,q4-launch,annual_report_26are all valid, whilewelcomeprompts"try go-welcome or welcome-26").ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def encode_base62(num: int, width: int = 7) -> str: """Convert 0 <= num < 62**width into a fixed-width 7-character Base62 string.""" chars = [] for _ in range(width): num, remainder = divmod(num, 62) chars.append(ALPHABET[remainder]) return "".join(reversed(chars)) def is_generated_code_shape(code: str) -> bool: """Return True iff `code` has the exact 7-char Base62 shape reserved for generated IDs.""" if len(code) != 7: return False return all(ch in ALPHABET for ch in code)Look at the double payoff of
is_generated_code_shape(code): 1. Generated codes and custom aliases can never collide, even across different regions. 2. On a cache miss anywhere in the world, inspectingcodealone tells the Redirect Service whether to look up a generated block'shome_regionor query thealias_registry!Authoritative conditional write + durable acknowledgment: - Even though counter blocks are unique by construction, we always write to the store with an atomic conditional write (
PUT links[code] IF NOT EXISTSfor generated codes;INSERT INTO alias_registry ... ON CONFLICT DO NOTHINGfor custom aliases) so bugs can never overwrite an existing link. - Before returning201 Created, the Create Service waits for quorum commit in its home region plus one partner region (US -> EU,EU -> APAC,APAC -> US). At ~400 writes/s, that single cross-region hop adds ~60–90 ms to link creation while guaranteeing zero acknowledged links are lost even if an entire region goes dark.Deep dive 2: fast redirects, HTTP caching, and exact expiration
The 5-tier lookup waterfall for
GET /{code}: 1. CDN Edge (serves viral links closest to the user for up to 60 seconds). 2. In-process server RAM cache (3-second TTL on each Redirect Service node to absorb sudden celebrity-tweet spikes without melting one Redis shard). 3. Regional Cache (~5 GB shared Redis/Memcached cluster holding hot records). 4. Local Regional Mapping Store (disk-backed full replica). 5. Cross-region miss fallback (only if steps 1–4 all missed—explained in the next step).Whenever a cache miss occurs at Tier 2 or Tier 3, the Redirect Service uses request coalescing (singleflight)—allowing only one in-flight request per server to query the database for a missing
codewhile 500 concurrent clicks for that samecodewait a few milliseconds and share its result, preventing a cache stampede (thousands of simultaneous misses overwhelming storage).Why
302 Foundbeats301 Moved Permanentlyhere: HTTP allows browsers to cache301 Moved Permanentlyindefinitely using local heuristics—meaning once someone clicks a301link, their browser may jump straight to the old destination next week without ever contacting our CDN or servers, completely bypassing expiration, abuse takedowns, and click counting! Returning302 FoundwithCache-Control: public, max-age=0, s-maxage=Ninstructs browsers not to cache locally (max-age=0), while letting our shared CDN edge cache absorb traffic bursts forNseconds (s-maxage=N).How expired links stop redirecting immediately without purge jobs: Every record stored inside our in-process cache and Regional Cache stores
{ long_url, status, expires_at }, and the Redirect Service checks expiration on every single cache hit:On hit in In-Process or Regional Cache: if record.status != 'active': return 410 Gone if record.expires_at != NULL and now >= record.expires_at: return 410 Gone otherwise: return 302 Location: record.long_urlBecause our own servers run that
now >= expires_atcheck on cached objects, we never need a background job to evict expiring keys from Redis! What about the CDN edge, which caches raw HTTP302responses and doesn't run our code? We caps-maxageso the CDN's copy cannot outlive the link:If expires_at is NULL: regional_cache_ttl = 3600 s, cdn_s_maxage = 60 s If expires_at is set: remaining_s = max(0, floor(expires_at - now)) regional_cache_ttl = min(3600 s, remaining_s) cdn_s_maxage = min(60 s, remaining_s)- Early manual disable / phishing takedown: Unlike scheduled expiration, an owner clicking Disable happens unpredictably. That write sets
status = 'disabled', broadcasts a cache-delete event to all 3 regions' caches, and calls the CDN's purge API—while the 60-seconds-maxageacts as a hard upper bound even if a purge packet drops. - Negative caching for random
404probes: Unknown codes are cached as"NOT_FOUND"for 10 seconds in the Regional Cache only (Cache-Control: no-storeto the CDN and browser). If a creator probes/my-alias(404) and then immediately createsmy-alias, the Create Service deletes that negative cache entry locally and broadcasts a delete event to peer regions.
- Early manual disable / phishing takedown: Unlike scheduled expiration, an owner clicking Disable happens unpredictably. That write sets
Deep dive 3: explicit multi-region consistency
Instead of paying for slow global consensus on every single operation, match each data type to the exact consistency guarantee it actually requires:
Operation Consistency level How we achieve it Create generated link Regionally linearizable + 2-region durable before 201Block belongs to 1 region -> zero cross-region write conflict; sync copy to partner region Create custom alias Globally linearizable (strictly 1 winner worldwide) Single atomic INSERT IF NOT EXISTSinto 3-region consensusalias_registry(~80–150 ms)Redirect newly created link Read-your-writes everywhere Async replication to 3rd region + deterministic home-region fallback on miss Scheduled expiration Exact (within NTP server clock sync of a few ms) Checked at read time ( now >= expires_at) + capped CDNs-maxageManual disable / takedown Bounded eventual consistency ( <= 60 s)Push cache invalidation + CDN purge + 60 s s-maxageceilingClick analytics Eventual consistency ( 1–2 minutes)Async event stream + hourly rollups Trace of "read-your-writes everywhere" during replication lag:
t = 0 ms Creator in New York (US region) shortens a URL -> gets `https://sho.rt/Xk3p9Qa` US commits locally + semi-sync to EU -> returns 201 Created. Async replication packet from US -> Tokyo (APAC) is still in flight (takes ~160 ms). t = 40 ms Creator pastes `https://sho.rt/Xk3p9Qa` in chat; colleague in Tokyo clicks it! 1. Tokyo CDN -> miss 2. Tokyo Regional Cache & Tokyo Mapping Store -> miss! 3. Tokyo checks `is_generated_code_shape("Xk3p9Qa")` -> True! 4. Tokyo unscrambles "Xk3p9Qa" -> integer 84,000,512 -> block #84 -> `id_blocks` says `us`! 5. Tokyo makes ONE read RPC to US (or partner EU if US is unreachable), gets the URL, caches it in Tokyo, and returns `302 Found`!Only the very first click in a remote region during that ~160 ms replication window pays a cross-region read; every click after that hits Tokyo's local cache in
< 5 ms.Abuse controls and non-blocking click analytics
Abuse & security controls: - Validate URL syntax and allow only
http/https(blockingjavascript:,data:, andfile:XSS/exploit vectors), cap length at2,048bytes, and reject URLs pointing back tosho.rt(infinite redirect loops). - Check destinations synchronously against cached phishing/malware threat lists (422 URL_BLOCKED), and continuously rescan existing links asynchronously as threat feeds update. - Enforce tiered rate limits by account, API key, and IP, and remind enterprise users that short codes are public pointers, not access control—sensitive destinations must still authenticate the viewer.Click analytics without slowing redirects (or losing CDN-cached clicks): - Never run
UPDATE links SET clicks = clicks + 1onGET /{code}—a single viral link at 30,000 clicks/s would lock one database row and bring down redirects. - Redirect servers append{ code, ts, country, referrer_domain, ua_family }to an in-memory ring buffer flushed asynchronously to the Click Log (dropping and counting overflow rather than ever blocking a redirect). - What about clicks served directly by the CDN edge during its 60-seconds-maxagewindow? Modern CDNs stream near-real-time edge access logs into the exact same Click Log pipeline, so we get both edge offload and complete total click counts! - Stream workers bucket total clicks by(code, hour)and estimate unique visitors using HyperLogLog—a compact probabilistic sketch that estimates distinct visitors within~1.6%error using just~3 KBof memory per counter instead of storing millions of raw IP addresses.Scaling, failure handling, and trade-off summary
Scaling & failure modes: - Viral celebrity link (50,000 clicks/s on 1 code): absorbed in layers—CDN edge (
s-maxage=60) takes ~95%+, the 3-second in-process RAM cache on each stateless Redirect server absorbs the rest, and request coalescing ensures at most 1 store read per server on expiry. - Even storage partitioning: because integers are Feistel-scrambled before Base62 encoding, new codes distribute uniformly across key-range or hash partitions instead of hot-spotting the "latest" shard. - Full regional outage (e.g.,USgoes completely offline): DNS/Anycast routes users toEUandAPAC, which already hold full mapping copies (includingUS's recent partner-replicated writes);EUandAPACcontinue minting generated links from their own blocks, and the 3-regionalias_registryretains a2-of-3consensus quorum so custom aliases still work! - Block Allocator or Malware Scanner outage: Create servers burn through their pre-leased spare 1M-ID blocks (hours of runway) if the allocator blips; if the external malware scanner times out, trusted paid accounts mint links inpending_scanstate (showing a brief interstitial warning until async scan completes) while anonymous creation pauses.Summary of key trade-offs:
- Leased counter blocks + Feistel permutation vs. random codes: eliminates cross-region collision checks on generated links and prevents enumeration, at the small cost of running a lightweight block allocator and reserving the 7-char Base62 shape.
- Global consensus for custom aliases only: pays the ~100 ms multi-region quorum penalty only on human-chosen aliases (where two users really can type
"summer-sale"simultaneously), keeping generated writes and 99.99% of reads region-local. 302+ cappeds-maxage+ read-timeexpires_atcheck vs.301: serves slightly more CDN/origin requests than permanent browser caching in exchange for exact expiration, working takedowns, and reliable click analytics.
Intuition & how it works
Think of a global URL shortener like an international coat-check service operating booths in New York, London, and Tokyo:
- Pre-printed ticket rolls per booth (generated codes): Instead of calling London and Tokyo before handing out every single ticket, New York gets pre-assigned roll
#84(numbers84,000,000to84,999,999) and scrambles each number with a reversible cipher so customers see tidy, unpredictable 7-character claim codes likeXk3p9Qarather than sequential numbers. Because London and Tokyo have their own rolls, two booths can never print the same generated ticket. - One shared VIP ledger for vanity names (custom aliases): When two customers both ask for the custom word
"summer-sale", pre-printed rolls cannot help—so custom aliases check one shared global ledger that awards"summer-sale"to whoever commits first. - Expiration printed right on the stub (read-time expiry): Every cached copy of a mapping carries its
expires_attimestamp, so any booth clerk glancing at a cached ticket sees immediately whether it has expired without waiting for someone to run around tearing up old stubs.
A naive design stumbles over three hidden traps. First, picking random 7-character strings and blindly inserting them causes ~20 million silent collisions over 12 billion links—and checking uniqueness across three continents on every write makes link creation slow and fragile. Second, returning HTTP 301 Moved Permanently lets browsers cache redirects forever on users' phones, breaking link expiration, phishing takedowns, and click tracking. Third, incrementing a database clicks = clicks + 1 row inside the redirect endpoint turns one viral link into a massive row-lock bottleneck.
Let's trace a concrete 4-event walkthrough:
- Minting a generated link (
t = 0 sin New York): Alice shortens a product URL with a 2-hour expiration. New York takes the next integer from its leased roll (84,000,512), scrambles it one-to-one intoXk3p9Qa, writes{ code: "Xk3p9Qa", long_url, expires_at: t + 7200 s, status: "active" }locally plus a backup copy in London, and returns201 Created. - Immediate click across the globe (
t = 0.05 sin Tokyo): Bob in Tokyo clickshttps://sho.rt/Xk3p9Qabefore async replication reaches Tokyo. Tokyo misses locally, seesXk3p9Qahas the 7-character generated shape, unscrambles it back to roll#84 -> New York, fetches the mapping once from New York, caches it locally, and returns302 Found(Cache-Control: public, max-age=0, s-maxage=60). - Viral burst (
t = 10 s): 20,000 people clickXk3p9Qa. The CDN serves edge hits for 60 seconds (streaming edge access logs to the analytics pipeline), while origin misses use request coalescing—sharing one database lookup across concurrent callers—and buffer click events asynchronously in memory. - Exact expiration (
t = 7200 s): During the final 45 seconds before expiry, our servers automatically shrink CDNs-maxagefrom60down tomin(60, expires_at - now)so the CDN copy expires right on time; att = 7200 s, any hit in our regional cache seesnow >= expires_atand immediately returns410 Gone.
Key trade-offs
- Leased counter blocks + Feistel permutation vs. random codes vs. URL hashes: Leasing 1M-integer blocks per server and passing each integer through a Feistel permutation—a reversible, key-based mathematical shuffle that maps each number in
[0, 62^7)to a unique scrambled number—guarantees zero collisions across servers and regions while hiding sequential order. Random 7-character Base62 (0-9,A-Z,a-z) strings avoid a block allocator but require a globally consistent uniqueness check on every write, while hashing the URL breaks when two campaigns want separate short links for the same page. - Disjoint shapes for generated codes vs. custom aliases: Reserving exact 7-character Base62 strings for generated IDs and requiring custom aliases to differ in length or include
-/_guarantees generated blocks can never collide with an existing alias and lets any cache-miss server tell instantly whether to unscramble a block owner or query the alias registry—trading away pure 7-letter alphanumeric vanity words like/welcome(which become/go-welcome). - Region-local writes + miss fallback vs. one global consensus database: Writing generated links to the home + partner regions and falling back to the home region only on a remote cache miss during replication lag keeps 99.99% of reads local (
< 5 ms). We pay for linearizable global consensus—multi-region quorum agreement so all regions see one strict order—only in thealias_registry, because custom aliases are the only operation where two regions can contend for the exact same key. - Partner-region acknowledgment vs. single-region acknowledgment: Waiting for one partner region (
US -> EU) before returning201 Createdadds ~60–90 ms to link creation (~400/s), in exchange for surviving a sudden region-wide outage without losing a single link already handed to a user. 302 Foundwithmax-age=0, s-maxage<=60vs.301 Moved Permanently:302forces browsers to ask our CDN rather than caching forever on-device, keeping expiration, abuse takedowns, and click metrics working at the cost of serving higher CDN traffic.- Read-time
expires_atchecks + capped TTLs vs. active expiration sweeps: Storingexpires_atinside cached entries and capping CDNs-maxageby remaining lifetime gives exact expiration with zero scheduled cache-invalidation traffic; active pub/sub cache deletes and CDN purges are reserved strictly for unpredictable manual disables. - Asynchronous analytics + HyperLogLog vs. synchronous SQL counters: Buffering click events asynchronously and estimating unique visitors with HyperLogLog—a ~3 KB probabilistic sketch with ~1.6% error—keeps redirects fast and immune to viral write hot spots, trading real-time exactness for ~1–2 minute analytics lag.
Common mistakes
- Confusing candidate generation with uniqueness enforcement: inserting hashed or random strings without an atomic
INSERT IF NOT EXISTSsilently overwrites existing links (~20.5M expected collisions at 12B links in62^7). - Using a read-then-write check (
SELECTthenINSERT) for custom aliases, allowing two simultaneous creators in the same or different regions to both pass theSELECTand overwrite each other. - Allowing custom aliases and generated codes to share the exact same 7-char Base62 namespace, creating a time bomb when a future counter block eventually lands on an old custom alias.
- Encoding raw sequential integers (
1, 2, 3) directly into Base62, exposing total link volume to competitors and letting attackers scrape every shortened URL in order. - Returning
301 Moved Permanentlyby default when the system also promises link expiration, takedowns, or click analytics—browsers cache301heuristically and stop contacting your servers. - Deleting expired rows in the database while leaving stale
302entries alive in Redis or the CDN, or reusing expired short codes so old printed QR codes and emails redirect to unrelated destinations. - Incrementing a click counter synchronously on
GET /{code}or forgetting request coalescing, letting one viral link trigger a database row-lock meltdown or cache stampede. - Accepting
javascript:/data:URLs or self-pointing short links, opening cross-site scripting (XSS) holes and infinite redirect loops.
Follow-up questions
- How do you guarantee that concurrent requests cannot claim the exact same vanity slug? Route all vanity-slug creations to a single global authority—a 3-region consensus table (
alias_registrybacked by Raft/Paxos quorum)—and claim the slug using one atomic conditional insert (INSERT INTO alias_registry ... ON CONFLICT DO NOTHING), never aSELECTfollowed by anINSERT. Exactly one creator commits and receives201 Created, while every concurrent contender across any region deterministically receives409 ALIAS_TAKEN. Pair this with a clientIdempotency-Key(so a creator whose network drops and retries gets their own201replayed instead of a false409) and the disjoint namespace rule (forbidding 7-character pure Base62 vanity slugs) so the automated generator can never collide with a vanity slug either. - How do you ensure links stop redirecting on schedule without serving stale cached redirects? Avoid relying on active deletion messages for scheduled expiration, because invalidation queues can lag or drop packets. Instead, store
{ long_url, status, expires_at }inside every entry of your own in-process and regional caches so the Redirect Service evaluatesnow >= expires_aton every hit and immediately returns410 Goneeven before the cache key's TTL (automatic expiration timer) elapses. Because an external CDN caches raw HTTP302responses and cannot run that check, bound its lifetime at write time usingCache-Control: public, max-age=0, s-maxage=min(60, expires_at - now)so browsers never cache locally and the CDN edge copy expires no later than the link itself. Physical database cleanup runs lazily days later and leaves a permanent tombstone so the retiredcodeis never reused; active pub/sub cache eviction and CDN purge API calls are needed only when an owner or abuse team disables a link before its scheduledexpires_at.
Follow-up questions
- How do you guarantee that concurrent requests cannot claim the exact same vanity slug?
- How do you ensure links stop redirecting on schedule without serving stale cached redirects?
Similar questions
- Recommendation Serving and Data Platform
- Emergency 911 Call Routing Platform
- Conversational AI Metrics and Analytics Platform
- Cafe Ordering and Barista Queue Platform
- Distributed Cafe Order Management and Kitchen Dispatch System
- High-Concurrency Vehicle Rental Booking System
More Salesforce interview questions
- Isolated Multi-Tenant Workspace Chat and Channel Platform Medium
- Hiring Manager Chat: Active Scope, Joining Salesforce, and Practical AI Medium
- Least Frequently Used Cache Hard Pro
- Longest Simple Path in a Tree Medium Pro
- Grid Square Area and Increasing Subsequence Length Medium Pro
- Minimum Total Peak Cost Across k Phases Medium Pro
- Hiring Manager Round: System Architecture, Greenfield Platforms, Load Surges, and Alignment Medium Pro
- Elevating Peers Through Mentorship and Sustainable Code Quality Norms Medium Pro
- Navigating Mid-Flight Course Corrections and Responsible Ownership Transitions Medium Pro
- Root-to-Leaf Path Sum Medium Pro