Case study: URL shortener end to end

The most common HLD warm-up: create a short code, redirect fast, count clicks without slowing redirects.

Time O(1) redirectSpace O(n) linksCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Reads outnumber writes by a hundred to one, so design for redirects. Generate a unique id without a central counter, encode it in base 62 to get a short code, and store code → URL. Redirects check the cache first and publish click events to a queue so analytics never slow the redirect.

Code

// Create: id from a distributed generator, encoded in base 62 (0-9, a-z, A-Z).
string Create(string longUrl)
{
    long id = _ids.Next();                         // unique, no central lock
    string code = Base62(id);
    _db.Insert(code, longUrl);
    return $"https://sho.rt/{code}";
}
// Redirect: cache first, then database. 302 so every click reaches us.
IResult Go(string code)
{
    var url = _cache.Get(code) ?? _db.Find(code);
    _clicks.Publish(new Click(code, DateTime.UtcNow)); // async, not in the hot path
    return Results.Redirect(url);
}

Tips

In the .NET library

The full version with deep dives is in the System design course; here the point is the request flow.