📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Design a URL shortener like the ones used in marketing emails and SMS. Clarify the requirements, estimate the scale, then walk me through the API, how you generate short codes, the data model, how redirects stay fast at peak, and what fails first.

A full URL shortener design: requirements, capacity estimate, API, short-code generation (counter + Base62 vs hashing vs random), data model, read-heavy caching with a CDN and Redis, 301 vs 302 redirects, abuse and failure modes, mapped to Azure and .NET 10.

Mid-Level SystemDesign Intermediate azure-front-door base62 caching capacity-estimation system-design url-shortener

๐ŸŽฏ Key points

  • Clarify: custom aliases, expiry, analytics, 100:1 read-to-write ratio
  • Estimate: ~40 writes/s, ~4,000 reads/s average (×3 peak); ~600 GB/year at ~500 B/row including indexes (URLs vary, average ~100–200 B)
  • Short code from leased ID ranges encoded in Base62: 7 chars ≈ 3.5 trillion codes; one allocator update per block, so no contention
  • Hashing needs collision handling; random codes need a uniqueness check (unique index, retry on violation)
  • Create is idempotent: client idempotency key or unique index on (OwnerId, Target) so retries don't create duplicates
  • Read path: CDN/Front Door → Redis (HybridCache) → database; cache hit rate > 95%
  • 302 keeps analytics and lets you change targets; 301 is cached by browsers indefinitely
  • Abuse and failure: URL scanning, per-key create limits, takedown purge, stampedes, allocator and database outages

โฑ 30-second answer

A URL shortener is a read-heavy key-value lookup: write once, redirect thousands of times. I clarify scope (custom aliases, expiry, click analytics), then estimate: 100 million new links a month is about 40 writes/s and 4,000 redirects/s, three times that at peak, and roughly 600 GB a year. Codes come from a distributed counter encoded in Base62: each API instance leases a block of IDs, so codes are unique without coordination per request, and 7 characters give about 3.5 trillion codes. The redirect path is CDN โ†’ Redis โ†’ database, so the database sees only cache misses. I return 302 so clicks are counted and targets can change. The main trade-off: sequential codes are cheap and collision-free but guessable, so I add a shuffle or a random suffix when links must not be enumerable.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd start by pinning down the requirements. Functionally: create a short link for a long URL, optionally with a custom alias and an expiry, redirect anyone who opens it, and count clicks. Non-functionally: redirects must be fast, say p99 under 50 ms at the edge, highly available because a broken link in a sent SMS can't be recalled, and links must not be enumerable if they point at private documents. Then the numbers: 100 million new links a month is about 40 writes a second, and with a 100-to-1 read ratio about 4,000 redirects a second, maybe 12,000 at a campaign peak. At 500 bytes a row that's roughly 600 GB a year, so storage is not the hard part; the read path is.

The API is two calls: POST /api/links returns the code, and GET /{code} returns a redirect. For codes I use a counter, not a hash: each ASP.NET Core instance leases a range of a million IDs from a small allocator table, hands them out from memory, and encodes them in Base62. Seven characters cover 3.5 trillion links, there are no collisions to check, and the allocator is touched once per million writes. If links must not be guessable I run the ID through a reversible shuffle before encoding. The data model is a single table keyed by code, in Azure SQL or Cosmos DB with the code as partition key. The redirect path is Azure Front Door, then a HybridCache backed by Redis, then the database, so 95% of redirects never reach storage.

The mistake I see is returning 301 because it sounds 'correct': browsers cache it forever, so you lose click analytics and can never fix a wrong target. What fails first is a viral link and a cold cache, so I protect against stampedes and keep the database out of the hot path. A URL shortener is a caching problem wearing a code-generation costume."


Requirements I write on the board

Type Requirement Assumption
Functional Create link, optional custom alias, optional expiry Aliases 4โ€“30 chars, unique
Functional Redirect GET /{code} Expired โ†’ 410 Gone
Functional Click counts per link Eventually consistent, minutes old is fine
Non-functional Redirect p99 < 50 ms at edge Users in Australia first, global later
Non-functional Availability 99.95% for redirects Creates may degrade first
Non-functional Not enumerable for private links Abuse scanning on create

Capacity estimate (arithmetic shown)

Quantity Arithmetic Result
Writes (avg) 100M รท 2.6M s/month โ‰ˆ 40/s
Writes (peak ร—3) 40 ร— 3 โ‰ˆ 120/s
Redirects (avg) 40 ร— 100 โ‰ˆ 4,000/s
Redirects (peak ร—3) 4,000 ร— 3 โ‰ˆ 12,000/s
Storage per year 100M ร— 12 ร— 500 B โ‰ˆ 600 GB
Keyspace 62^7 โ‰ˆ 3.5 ร— 10^12 codes
Hot set in cache 20M links ร— 500 B โ‰ˆ 10 GB

High-level design

Client โ”€โ”€โ–บ Azure Front Door (CDN + WAF, caches 302 for 60 s)
              โ”‚ miss
              โ–ผ
        ASP.NET Core redirect API (AKS / Container Apps, 3+ replicas, zone-redundant)
              โ”‚                     โ”‚
              โ–ผ                     โ–ผ
     HybridCache (L1 memory    Click events โ”€โ”€โ–บ Event Hubs โ”€โ”€โ–บ aggregator โ”€โ”€โ–บ analytics store
      + L2 Azure Managed Redis)
              โ”‚ miss
              โ–ผ
     Azure SQL (Links table, PK = Code)   โ—„โ”€โ”€ ID range allocator table

Code generation options

Option How Pros Cons
Counter + Base62 Leased ID ranges per instance No collisions, cheap, short Sequential โ†’ guessable unless shuffled
Hash (SHA-256, take 7 chars) Hash the long URL Same URL โ†’ same code (dedup) Collisions need retry; dedup leaks that a URL exists
Random 7โ€“8 chars RandomNumberGenerator Not guessable Uniqueness check on every insert; rare retries

When to use what for storage

Store Fits when Watch out for
Azure SQL You also need admin queries, reporting, joins to users Single writer; scale reads with replicas and cache
Cosmos DB (partition key = code) Global multi-region reads and point lookups only RU cost of analytics queries; design for point reads

Production example

A link service like this handles a 12,000 redirects/s SMS campaign peak with about 98% served from Front Door and HybridCache, so Azure SQL sees under 250 lookups a second. Redirect p99 stays around 20 ms from Sydney, and the ID allocator is called roughly once a day per instance.

๐Ÿ” What the interviewer is checking

Checks that the candidate can run a full, structured design on a small problem: numbers first, then a simple design that puts effort where the load is.

Green flags

  • Does the capacity arithmetic and concludes the read path is the hard part
  • Explains code generation trade-offs (counter vs hash vs random) with collision and enumeration risks
  • Chooses 302 and explains why
  • Mentions abuse, takedown and cache invalidation

Red flags

  • Jumps straight to microservices, Kafka and sharding for 600 GB
  • Hash truncation with no collision story
  • Updates a counter row per click
  • No numbers at all

๐Ÿ“š Learn in depth

1. Why it is a read path problem

Writes are 40/s; any database handles that. Redirects are 100ร— more and arrive in bursts tied to campaigns. So the design effort goes into keeping redirects out of the database: an edge cache, an in-process L1, a shared L2 and only then storage.

Request โ”€โ”€โ–บ Edge (Front Door) โ”€โ”€โ–บ L1 MemoryCache โ”€โ”€โ–บ L2 Redis โ”€โ”€โ–บ Azure SQL
 hit rate      ~60โ€“80%              ~10โ€“20%          ~5โ€“15%       < 2%

Each layer has a different invalidation cost: edge entries live until TTL, L1 lives per pod, L2 can be removed by tag. That is why the edge TTL is short (60 s) when links can be edited or disabled.

2. Counter-based IDs without a single bottleneck

A single global IDENTITY column works up to thousands of writes a second, but it couples every write to one database. The leased-range pattern (sometimes called hi/lo) removes that:

Allocator row: NextBlock = 42
Instance A: UPDATE ... SET NextBlock = NextBlock + 1 OUTPUT deleted.NextBlock โ†’ 42 โ†’ owns IDs 42,000,000โ€“42,999,999
Instance B: โ†’ 43 โ†’ owns 43,000,000โ€“43,999,999

IDs are handed out with Interlocked.Increment in memory. A crash wastes the rest of a block, which is fine: 3.5 trillion codes is far more than you'll use. Base62 (0โ€“9, aโ€“z, Aโ€“Z) turns a 64-bit integer into at most 11 characters; 7 characters suffice until 3.5 trillion.

To stop enumeration, apply a reversible permutation before encoding, for example a Feistel network or multiply by a large odd constant modulo 62^7. It keeps uniqueness and length but breaks the obvious sequence. It is obfuscation, not security: private links still need authorisation or long random tokens.

3. 301 vs 302 vs 307

Status Browser caches Analytics Can change target
301 Moved Permanently Yes, indefinitely Lost after first visit No (cached clients ignore you)
302 Found No (unless headers say so) Every click Yes
307/308 307 like 302, 308 like 301 โ€” Preserve method; rarely matters for GET

You control caching explicitly with Cache-Control: private, max-age=60 on the 302.

4. Click analytics without slowing redirects

Never update a counter row per click: 12,000 updates a second on hot rows causes lock contention. Instead write a click event to a Channel<T> in memory, batch to Event Hubs, and aggregate per minute into a table or Azure Data Explorer. Counts are eventually consistent, which the requirement allows. Avoid storing IP addresses beyond what you need: under the Privacy Act 1988 an IP address combined with other data can be personal information.

5. Failure modes

  • Viral link + cold cache: many concurrent misses for one key โ†’ HybridCache coalesces concurrent fetches for the same key in a process; the edge absorbs the rest.
  • Redis down: fall back to L1 and the database with a circuit breaker; capacity-test that the database survives the miss rate.
  • Allocator unavailable: instances keep serving from their current block; only new blocks fail. Alert when a pod has less than 10% of its block left.
  • Abuse: phishing links damage your domain's reputation. Scan on create (Google Safe Browsing or Microsoft Defender threat intelligence), rate-limit creates per API key, and support takedown that purges edge and cache.
  • Region loss: redirects matter more than creates, so replicate data to Australia Southeast (geo-replica or Cosmos DB multi-region reads) and let Front Door fail over.

6. AWS mapping

CloudFront for the edge, ElastiCache or MemoryDB for Redis, DynamoDB (partition key = code) or Aurora for storage, Kinesis for click events.

Try it yourself

  1. Implement Base62 encode/decode and a property test (FsCheck or a loop) that Decode(Encode(n)) == n for random 64-bit values.
  2. Build the redirect endpoint below and load-test it with k6 or bombardier at 5,000 req/s; watch dotnet-counters monitor -n <process> System.Runtime Microsoft.AspNetCore.Hosting.
  3. Kill Redis during the test and measure how many requests reach SQL Server (Query Store or sys.dm_exec_query_stats).
  4. Compare p99 latency with HybridCache L1 enabled and disabled.
  5. Calculate how many years until 7-character codes run out at 100M links a month.

๐Ÿ’ป Code

A Base62 encoder, a leased ID range, and the redirect endpoint with HybridCache (Microsoft.Extensions.Caching.Hybrid).

namespace Shortener;

public static class Base62
{
    private const string Alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static string Encode(long value)
    {
        ArgumentOutOfRangeException.ThrowIfNegative(value);
        if (value == 0) return "0";
        Span<char> buffer = stackalloc char[11]; // long.MaxValue needs 11 chars in base 62
        var i = buffer.Length;
        while (value > 0)
        {
            buffer[--i] = Alphabet[(int)(value % 62)];
            value /= 62;
        }
        return new string(buffer[i..]);
    }

    public static long Decode(string code)
    {
        long result = 0;
        foreach (var c in code)
        {
            var digit = Alphabet.IndexOf(c);
            if (digit < 0) throw new FormatException($"Invalid character '{c}'.");
            result = checked(result * 62 + digit);
        }
        return result;
    }
}

// Hands out IDs from a block leased from the database; only one DB call per BlockSize IDs.
public sealed class IdRangeAllocator(IBlockStore store)
{
    private const long BlockSize = 1_000_000;
    private readonly SemaphoreSlim _gate = new(1, 1);
    private long _next;
    private long _end;

    public async Task<long> NextAsync(CancellationToken ct)
    {
        await _gate.WaitAsync(ct);
        try
        {
            if (_next >= _end)
            {
                var block = await store.LeaseNextBlockAsync(ct); // UPDATE ... OUTPUT, atomic in SQL
                _next = block * BlockSize;
                _end = _next + BlockSize;
            }
            return _next++;
        }
        finally { _gate.Release(); }
    }
}

public interface IBlockStore { Task<long> LeaseNextBlockAsync(CancellationToken ct); }
public interface ILinkStore { Task<string?> FindTargetAsync(string code, CancellationToken ct); }
// Program.cs
using Microsoft.Extensions.Caching.Hybrid;
using Shortener;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHybridCache(o => o.DefaultEntryOptions = new HybridCacheEntryOptions
{
    Expiration = TimeSpan.FromMinutes(30),        // L2 (Redis, if registered)
    LocalCacheExpiration = TimeSpan.FromMinutes(1) // L1 short, so disabled links stop quickly
});
builder.Services.AddSingleton<ILinkStore, SqlLinkStore>();
var app = builder.Build();

app.MapGet("/{code:regex(^[0-9a-zA-Z]{{4,30}}$)}", async (string code, HybridCache cache, ILinkStore links, HttpContext http, CancellationToken ct) =>
{
    // GetOrCreateAsync coalesces concurrent misses for the same key: protects the DB from a viral link.
    var target = await cache.GetOrCreateAsync($"link:{code}",
        async token => await links.FindTargetAsync(code, token), cancellationToken: ct);

    if (target is null) return Results.NotFound();
    http.Response.Headers.CacheControl = "private, max-age=60";
    return Results.Redirect(target, permanent: false); // 302: keeps analytics, target can change
});

app.Run();

sealed class SqlLinkStore : ILinkStore
{
    public Task<string?> FindTargetAsync(string code, CancellationToken ct) =>
        Task.FromResult<string?>(null); // SELECT Target FROM Links WHERE Code = @code AND (ExpiresAt IS NULL OR ExpiresAt > SYSUTCDATETIME())
}
CREATE TABLE dbo.Links (
    Code       varchar(30)    NOT NULL CONSTRAINT PK_Links PRIMARY KEY,
    Target     nvarchar(2048) NOT NULL,
    OwnerId    int            NOT NULL,
    CreatedAt  datetime2(0)   NOT NULL DEFAULT SYSUTCDATETIME(),
    ExpiresAt  datetime2(0)   NULL,
    IsDisabled bit            NOT NULL DEFAULT 0
);

โš  Common mistakes

  • Mistake: Returning 301 for every redirect. Why it is wrong: browsers cache it indefinitely, so click analytics stop after the first visit and you can never change or disable the target. Instead: return 302 with an explicit short Cache-Control.
  • Mistake: Hashing the URL and taking 7 characters without collision handling. Why it is wrong: by the birthday bound, collisions become likely long before the keyspace is full, and two URLs share a code. Instead: use a counter, or check uniqueness and retry with a salt.
  • Mistake: Incrementing a click counter row on every redirect. Why it is wrong: thousands of updates per second on the same row cause lock waits and slow the redirect path. Instead: emit events and aggregate asynchronously.
  • Mistake: Calling the ID allocator for every new link. Why it is wrong: every create then updates the same allocator row, which serialises writes under row locks at high rates. Instead: lease large blocks (e.g. 1 million IDs) with a single atomic UPDATE ... OUTPUT, so the row is touched once per block and the default READ COMMITTED isolation is enough.
  • Mistake: Treating sequential Base62 codes as private. Why it is wrong: anyone can enumerate the neighbours of their own link. Instead: shuffle IDs for cosmetics, and use long random tokens plus authorisation for genuinely private content.
  • Mistake: Skipping the capacity estimate. Why it is wrong: you over-engineer storage (sharding 600 GB) and under-engineer the 12,000/s read path. Instead: do the arithmetic first and let it decide where effort goes.
  • Mistake: Long edge TTLs with no purge. Why it is wrong: a phishing link keeps redirecting after takedown. Instead: short TTLs plus a purge call to Front Door and cache removal on disable.
  • Mistake: No abuse controls or abuse monitoring. Why it is wrong: phishing links get the domain blocklisted by mail providers, breaking every legitimate link, and without signals you find out from customers. Instead: scan targets on create, rate-limit creates per key, log creates and redirects per key and target domain, and alert on spikes (e.g. one new key creating thousands of links, or links to newly registered domains).

๐Ÿ› Senior insight: trade-offs

The senior move is to notice the asymmetry early: writes are trivial, reads are bursty, and the domain's reputation is the asset at risk. So I spend the time on the cache hierarchy, takedown and abuse, not on exotic ID schemes. I also say what I would not build: no sharding at 600 GB a year, no Cosmos DB multi-region writes when creates can tolerate a regional outage.

Decision When it fits Cost When not to
Counter + Base62 Most shorteners; need short codes One allocator table Codes must be unguessable on their own
Random 8-char code Private links, low write rate Uniqueness check per insert Very high write rate with tiny keyspace
Azure SQL + cache Need admin queries and reporting Single-region writer Global writes required
Cosmos DB Global reads, point lookups only RU cost, design discipline Ad hoc reporting on the same store

I measure success by edge + cache hit rate (target > 95%), redirect p99 at the edge, and database lookups per second during a campaign test.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate quotes requests per second without showing how they got there Why: Checks that the candidate can do the capacity arithmetic from users to requests, storage and bandwidth
    How to answer

    A capacity estimate turns user numbers into load. Start with daily active users ร— actions per user to get requests per day, divide by ~86,400 s (round to 10^5) for average requests/s, then multiply by a peak factor (2โ€“10ร—, often 3ร—). For storage, multiply writes per day by record size and 365, then add indexes and replicas. For bandwidth, multiply requests/s by payload size.

    Example: 10M DAU ร— 20 reads = 200M reads/day โ‰ˆ 2,300/s average, ~7,000/s peak.

    The point is not precision โ€” it's deciding whether one database and a cache are enough or you need partitioning. The trade-off is speed versus accuracy: round hard, but state every assumption.

  2. When: Candidate says 'put Redis in front of it' Why: Checks cache-aside vs write-through and how disabled links get invalidated
    How to answer
    • Cache-aside (lazy loading): the app checks the cache, loads from the database on a miss and populates it; on a write it updates the database, then deletes the key. Simple and the default, but the first read after a change is slow and a failed delete leaves stale data until the TTL.
    • Write-through: every write goes to the database and the cache together, so reads are warm and consistent, at the cost of slower writes and caching data nobody reads.
    • Write-behind (write-back): writes land in the cache and are flushed to the database later, giving very fast writes but eventual consistency and a data-loss window if the cache fails.

    I pick by read/write ratio, how much staleness is acceptable, and whether losing a write is ever acceptable.

  3. When: Candidate proposes an IDENTITY column or a global counter Why: Checks knowledge of leased ID ranges, Snowflake-style IDs and their trade-offs
    How to answer

    Three options. Leased ID ranges: each instance reserves a block (say 10,000 IDs) from an allocator table in one call and hands them out from memory โ€” shortest codes, one database call per block, gaps on crash. Snowflake-style IDs: 64-bit timestamp + worker id + sequence, no per-ID coordination and time-ordered, but each worker id must be unique and a node whose clock jumps backwards must stop issuing. UUIDv7 / random: zero coordination, but 128 bits is ~22 Base62 characters โ€” too long for short links. Then Base62-encode. The trade-off is length versus coordination versus ordering: for a URL shortener I pick leased ranges; for internal event ids, UUIDv7.

๐Ÿ›  Real-world problems: how you handle them

Viral SMS campaign link overloads a cold link service
Situation
A link shortener for [a retailer's] SMS and email campaigns, running on [AKS in Australia East] with Azure SQL. A [national sale] SMS went to [2 million] customers at 9 am.
Signals
Redirect p99 jumped from [25 ms] to [4 s]; Azure SQL DTU at 100%; Application Insights showed thousands of identical `SELECT ... WHERE Code = @code` dependency calls per second; customers reported links timing out.
Investigation
Application Insights application map showed nearly every redirect missing cache. The cache had been flushed by a deployment ten minutes earlier and the hand-written cache-aside code let every concurrent miss query the database (a stampede). Query Store confirmed one query plan at [9,000] executions a second.
Resolution
Immediate: scaled the database up and set a 60 s Front Door cache on the 302 responses for the campaign code. Long term: replaced the hand-written cache code with HybridCache (which coalesces concurrent misses), added cache warming for scheduled campaign codes, and moved click counting to Event Hubs.
Prevention
Load test with a cold cache in the pipeline before each campaign season, an alert on cache hit rate below [90%], and a campaign checklist that registers codes for pre-warming. ADR recording the 302 + short edge TTL decision.

How to tell it (STAR)

**S:** At [company] I owned the link service behind our SMS campaigns, about [2 million] messages per send. **T:** A deployment had flushed the cache just before a 9 am send, and redirects were timing out with the database at 100%. **A:** I traced it in Application Insights to a cache stampede on one code, put a 60-second edge cache on that link to stop the bleeding, then replaced our cache-aside code with HybridCache and added pre-warming for scheduled campaigns and a cold-cache load test. **R:** The next campaign peaked at [12,000] redirects a second with [98%] cache hits and database load under [10%], and we haven't had a campaign incident since.

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me