{"id":10765,"date":"2026-12-04T04:47:50","date_gmt":"2026-12-04T04:47:50","guid":{"rendered":"https:\/\/cybersecurityinfocus.com\/?p=10765"},"modified":"2026-12-04T04:47:50","modified_gmt":"2026-12-04T04:47:50","slug":"design-a-url-shortener-from-a-single-database-to-global-redirects","status":"publish","type":"post","link":"https:\/\/cybersecurityinfocus.com\/?p=10765","title":{"rendered":"Design a URL Shortener: From a Single Database to Global Redirects"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Imagine a retailer sends a promotional SMS to millions of customers. The destination URL is long, contains campaign parameters and may change after the message is sent. A short link solves the presentation problem, but the engineering challenge begins when thousands of customers click simultaneously. A slow redirect can lose sales; a wrong redirect can destroy trust. In this hypothetical design workshop, we build a service that starts with one relational database and evolves into a geographically distributed redirect platform without sacrificing mapping correctness.<\/p>\n<p class=\"wp-block-paragraph\"><strong>Difficulty:<\/strong> Intermediate \u00b7 <strong>Prerequisites:<\/strong> HTTP, SQL, caching \u00b7 <strong>Reading time:<\/strong> 12 minutes. You will learn how to allocate unique codes, choose redirect semantics, isolate analytics and reason about cache consistency.<\/p>\n<h2 class=\"wp-block-heading\">Architecture at a glance<\/h2>\n<p>Create: Client \u2192 API \u2192 Mapping database \u2192 Cache invalidation<br \/>\nRead: Browser \u2192 Edge \u2192 Redirect service \u2192 Cache \u2192 Mapping database<br \/>\nEvents: Redirect service \u2192 Event queue \u2192 Analytics workers \u2192 Reports<\/p>\n<p class=\"wp-block-paragraph\">The creation path owns durable state; the redirect path is optimized for reads. Analytics is deliberately outside the critical path. An analytics outage must not turn a valid link into an error page.<\/p>\n<h2 class=\"wp-block-heading\">1. Define the problem before choosing technology<\/h2>\n<p class=\"wp-block-paragraph\">Users create short links, optionally choose aliases, configure expiry and disable links they own. Visitors resolve a code without authentication. Owners can inspect approximate click counts. We exclude custom domains and detailed attribution from the first release because certificate management and privacy requirements would expand the scope considerably.<\/p>\n<p>Functional requirementsNon-functional requirementsCreate, resolve, disable and expire links99.99% redirect availability target; regional p95 below 50 ms at service boundaryOptional unique custom aliasNo accidental mapping overwrite; durable acknowledged writesAsynchronous click reportingBounded cache staleness; abuse controls and tenant isolation<\/p>\n<p class=\"wp-block-paragraph\">Ask whether links are editable, whether deleted codes may be reused and whether analytics must be exact. Our answer is that links may be disabled, codes are never recycled, and analytics is approximate. These choices prevent an old printed QR code from unexpectedly redirecting to a different owner.<\/p>\n<h2 class=\"wp-block-heading\">2. Estimate capacity<\/h2>\n<p class=\"wp-block-paragraph\">Assume 10 million new links and 1 billion redirects per month, a 30-day month, a tenfold peak factor, and 500 bytes per mapping including a rough allowance for metadata. These are design assumptions, not measured production figures.<\/p>\n<p>QuantityCalculationResultAverage writes10M \/ 2,592,000 seconds3.86\/sAverage reads1B \/ 2,592,000 seconds386\/sPeak reads386 \u00d7 103,860\/sAnnual mapping storage120M \u00d7 500 bytes60 GB before replication\/index overheadPeak database reads at 95% cache hit rate3,860 \u00d7 0.05193\/s<\/p>\n<p class=\"wp-block-paragraph\">The read-to-write ratio is 100:1, so a cache is a natural optimization. However, the average conceals viral links: one code may receive most traffic. Benchmark skewed distributions rather than uniformly random keys. At this scale a well-tuned relational database may suffice for writes; sharding from day one would introduce avoidable operational complexity.<\/p>\n<h2 class=\"wp-block-heading\">3. Evolve the architecture<\/h2>\n<h3 class=\"wp-block-heading\">Stage A: one application and one database<\/h3>\n<p class=\"wp-block-paragraph\">Store a unique short code and destination in PostgreSQL. A redirect performs an indexed lookup and returns an HTTP Location header. This is inexpensive and easy to debug. The weakness is that every click consumes a database connection, and a single host failure affects both reads and writes.<\/p>\n<h3 class=\"wp-block-heading\">Stage B: stateless replicas and shared cache<\/h3>\n<p class=\"wp-block-paragraph\">Place multiple application replicas behind a load balancer and introduce Redis using cache-aside reads. On a miss, fetch the mapping and populate the cache with a bounded TTL. Connection pools protect the database. A cache outage must trigger rate-limited database fallback rather than unrestricted retries, which could overwhelm the remaining healthy component.<\/p>\n<h3 class=\"wp-block-heading\">Stage C: regional redirect services<\/h3>\n<p class=\"wp-block-paragraph\">Deploy redirect replicas near users, each with regional caches and read replicas. Keep creation and alias uniqueness under a single authoritative write domain initially. Replication lag means a newly created link may not immediately resolve in another region; on a regional miss, perform a bounded authoritative lookup before returning not found. Global active-active writes are a later optimization, not a prerequisite for global reads.<\/p>\n<h2 class=\"wp-block-heading\">4. High-level design and request flow<\/h2>\n<p>ComponentResponsibilityGatewayTLS, authentication on management endpoints, rate limitsCreation serviceValidate destination, allocate code, commit mappingRedirect serviceResolve active mapping, emit redirect, enqueue click eventMapping storeAuthoritative uniqueness, ownership and expiryRegional cacheFast reads with bounded stalenessAnalytics workersAggregate events independently of redirect latency<\/p>\n<p class=\"wp-block-paragraph\">Creation acknowledges success only after the database transaction commits. Redirect checks cache first, then a replica or authoritative store. It verifies status and expiry even on cache hits. The response is a 302 with a validated destination. A bounded asynchronous event buffer records the click; when full, drop or sample analytics rather than block the visitor. Track dropped events explicitly so reports do not imply exact counts.<\/p>\n<h2 class=\"wp-block-heading\">5. Low-level design: code allocation and concurrency<\/h2>\n<p class=\"wp-block-paragraph\">Base62 uses digits and upper- and lowercase letters. Seven characters provide 62\u2077 = 3,521,614,606,208 possibilities. Random allocation avoids exposing sequential business volume, but randomness alone cannot guarantee uniqueness. The database unique constraint is the final arbiter. Two concurrent creators may generate the same code; one insert succeeds and the other retries with a fresh code. Custom aliases instead return a conflict.<\/p>\n<p>import secrets<br \/>\nimport string<\/p>\n<p>ALPHABET = string.ascii_letters + string.digits<\/p>\n<p>def allocate(conn, owner, destination):<br \/>\n    for _ in range(8):<br \/>\n        code = &#8221;.join(secrets.choice(ALPHABET) for _ in range(7))<br \/>\n        row = conn.execute(<br \/>\n            &#8220;&#8221;&#8221;INSERT INTO links(code, owner_id, destination)<br \/>\n               VALUES (%s, %s, %s)<br \/>\n               ON CONFLICT (code) DO NOTHING<br \/>\n               RETURNING code&#8221;&#8221;&#8221;,<br \/>\n            (code, owner, destination)<br \/>\n        ).fetchone()<br \/>\n        if row:<br \/>\n            return row[0]<br \/>\n    raise RuntimeError(&#8220;allocation exhausted&#8221;)<\/p>\n<p class=\"wp-block-paragraph\">This example assumes a psycopg-style connection and a caller-managed transaction. Commit before returning the code to the client. A sample output is a seven-character string such as aB3xY9q. Production code also validates URLs, records idempotency keys and handles transient database errors separately. Random codes are not access tokens: sensitive destinations still require authorization at the destination.<\/p>\n<h2 class=\"wp-block-heading\">6. API and database design<\/h2>\n<p>Method and pathBehaviorPOST \/v1\/linksAuthenticated creation; 201, 400, 409 or 429GET \/{code}Public resolution; 302, 404 or 410DELETE \/v1\/links\/{code}Owner-only disable; 204 or 404GET \/v1\/links\/{code}\/statsOwner-only approximate analytics; 200 or 404<br \/>\nPOST \/v1\/links<br \/>\nIdempotency-Key: campaign-2026-12<br \/>\n{&#8220;destination&#8221;:&#8221;https:\/\/example.com\/sale&#8221;,&#8221;alias&#8221;:&#8221;winter-sale&#8221;}<\/p>\n<p>HTTP\/1.1 201 Created<br \/>\n{&#8220;code&#8221;:&#8221;winter-sale&#8221;,&#8221;short_url&#8221;:&#8221;https:\/\/sho.rt\/winter-sale&#8221;}<\/p>\n<p class=\"wp-block-paragraph\">Scope idempotency keys to the authenticated owner and store a request hash alongside the result. Reusing a key with different input returns a conflict. Commit the idempotency record and mapping atomically, so a timeout after commit does not create a second link when the client retries.<\/p>\n<p>CREATE TABLE links (<br \/>\n  code varchar(32) COLLATE &#8220;C&#8221; PRIMARY KEY,<br \/>\n  owner_id bigint NOT NULL,<br \/>\n  destination text NOT NULL,<br \/>\n  created_at timestamptz NOT NULL DEFAULT now(),<br \/>\n  expires_at timestamptz,<br \/>\n  disabled boolean NOT NULL DEFAULT false,<br \/>\n  version bigint NOT NULL DEFAULT 1<br \/>\n);<br \/>\nCREATE INDEX links_owner_created<br \/>\n  ON links(owner_id, created_at DESC);<\/p>\n<p class=\"wp-block-paragraph\">The primary key supports the hot redirect lookup; the composite index supports an owner\u2019s dashboard. Case-sensitive code comparison matters for Base62. Keep disabled mappings as tombstones to prevent reuse. If storage eventually demands partitioning, hash by code for even distribution, and route owner listing through a separate index or read model. Custom aliases must route to the same authoritative partition as ordinary codes.<\/p>\n<h2 class=\"wp-block-heading\">7. Caching, redirect semantics and consistency<\/h2>\n<p class=\"wp-block-paragraph\">A permanent 301 can be cached by browsers beyond your control, making edits and emergency takedowns difficult. Use 302 with explicit Cache-Control policies for mutable links; use permanent redirects only for genuinely immutable destinations. A short cache TTL bounds ordinary staleness but does not guarantee immediate revocation. For abuse takedowns, maintain a rapidly propagated denylist and check it before serving cached destinations.<\/p>\n<p class=\"wp-block-paragraph\">Cache invalidation has a subtle race: a reader can fetch an old value, then populate the cache after a writer deletes it. Use versioned entries and conditional cache updates or accept a documented short staleness window. Negative caching protects the database against random-code scans, but keep its TTL short and invalidate it after creation. Coalesce concurrent misses for a hot key to avoid a stampede.<\/p>\n<p>OptionWhen usefulTradeoffPostgreSQLModerate write volume, ownership queriesReplica lag and eventual scaling limitsDistributed key-value storeVery large code-keyed workloadSecondary indexes and global consistency complexityRedisRegional hot mappingsMemory cost, eviction and invalidationCDNImmutable or carefully controlled redirectsBrowser\/edge cache revocation complexity<\/p>\n<h2 class=\"wp-block-heading\">8. Failure handling, security and operations<\/h2>\n<p>FailureDetectionResponseCache unavailableError rate and hit ratioCircuit breaker, bounded database fallbackReplica lagReplay lag metricAuthoritative lookup on miss; alertViral linkPer-key traffic skewLocal cache, request coalescingAnalytics backlogQueue age and dropped eventsScale workers; sample without blocking redirectsPrimary outageWrite failuresFail over with fencing; preserve acknowledged mappings<\/p>\n<p class=\"wp-block-paragraph\">Validate absolute HTTP and HTTPS destinations and reject control characters, dangerous schemes and malformed hosts. A public shortener intentionally redirects off-site, so scheme validation alone does not prevent phishing. Add abuse reporting, reputation checks, rate limits and a takedown process. If a scanner fetches destinations, isolate it and block private network access to mitigate SSRF. Avoid storing full IP addresses indefinitely; define retention and access policies for analytics.<\/p>\n<p class=\"wp-block-paragraph\">Measure redirect latency by region and cache outcome, successful resolution rate, creation conflicts, replica lag and queue age. Separate expected 404 responses from infrastructure errors. Set a recovery objective explicitly: for example, a five-minute recovery time and zero acknowledged mapping loss within a synchronous replication domain. Cross-region disaster recovery may have a different recovery point; do not promise zero loss without synchronous cross-region durability. Test restores and failover fencing regularly.<\/p>\n<h2 class=\"wp-block-heading\">9. Testing the design<\/h2>\n<p class=\"wp-block-paragraph\">Unit tests cover code length, URL validation, expiry boundaries and status transitions. Integration tests force two transactions to insert the same alias and verify that exactly one wins. Contract tests verify Location, status and Cache-Control headers without following redirects. A load test should combine 3,860 peak reads per second with a highly skewed hot-key distribution and measure tail latency. Inject cache failures and replica lag to verify bounded fallback. Finally, disable a cached link during concurrent traffic and measure actual revocation delay against the stated policy.<\/p>\n<h2 class=\"wp-block-heading\">10. Interview guide and questions<\/h2>\n<p class=\"wp-block-paragraph\">In a 45-minute interview, spend five minutes clarifying scope, five on capacity, ten on architecture, fifteen on allocation and caching, and ten on failures and tradeoffs. Start with the simplest correct design. Explain why each new component exists instead of drawing a collection of fashionable technologies.<\/p>\n<h3 class=\"wp-block-heading\">Why not hash the destination directly?<\/h3>\n<p class=\"wp-block-paragraph\">Identical destinations may belong to different owners, have different expiry policies or require separate campaign analytics. Truncating a hash also introduces collisions. A random code plus a unique constraint separates identity from destination while preserving correctness.<\/p>\n<h3 class=\"wp-block-heading\">How do you prevent duplicate codes across regions?<\/h3>\n<p class=\"wp-block-paragraph\">Use one authoritative write domain or route each code to a unique owning partition with a strongly consistent conditional insert. Regional caches cannot arbitrate uniqueness. If active-active writes are required, partition the namespace or use consensus for conflicting aliases.<\/p>\n<h3 class=\"wp-block-heading\">What happens if a newly created link returns 404?<\/h3>\n<p class=\"wp-block-paragraph\">A lagging replica or stale negative cache may hide the committed mapping. Invalidate negative entries and perform a bounded authoritative lookup on misses. Document the consistency guarantee rather than treating every miss as proof that a link does not exist.<\/p>\n<h3 class=\"wp-block-heading\">How would you handle a celebrity sharing one link?<\/h3>\n<p class=\"wp-block-paragraph\">Replicate the hot mapping into regional and process-local caches, coalesce misses and avoid synchronous analytics writes. Sharding by code alone does not solve a single hot key because all requests still target the same partition.<\/p>\n<h3 class=\"wp-block-heading\">Can click analytics be exactly once?<\/h3>\n<p class=\"wp-block-paragraph\">Retries and client behavior make the definition of a click ambiguous. Use event IDs and deduplicate within a defined window if required, but distinguish delivered redirect responses from human visits. Approximate analytics is often a better tradeoff than delaying redirects for synchronous counting.<\/p>\n<h2 class=\"wp-block-heading\">Conclusion and further reading<\/h2>\n<p class=\"wp-block-paragraph\">Build the first version with an indexed mapping table and a stateless service. Add caching only after measuring read pressure, then regional reads when latency warrants them. Keep uniqueness authoritative, revocation explicit and analytics asynchronous. As an exercise, design a five-minute takedown guarantee for a link cached in three regions and explain how you would test it under network partition.<\/p>\n<p class=\"wp-block-paragraph\">Further reading: <a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc9110.html\" target=\"_blank\" rel=\"noopener\">HTTP semantics (RFC 9110)<\/a>, <a href=\"https:\/\/www.postgresql.org\/docs\/current\/sql-insert.html\" target=\"_blank\" rel=\"noopener\">PostgreSQL INSERT and conflict handling<\/a>, and <a href=\"https:\/\/redis.io\/docs\/latest\/develop\/\" target=\"_blank\" rel=\"noopener\">Redis developer documentation<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>Imagine a retailer sends a promotional SMS to millions of customers. The destination URL is long, contains campaign parameters and may change after the message is sent. A short link solves the presentation problem, but the engineering challenge begins when thousands of customers click simultaneously. A slow redirect can lose sales; a wrong redirect can [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":10766,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-10765","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news"],"_links":{"self":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10765"}],"collection":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10765"}],"version-history":[{"count":0,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/posts\/10765\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=\/wp\/v2\/media\/10766"}],"wp:attachment":[{"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10765"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10765"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cybersecurityinfocus.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10765"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}