Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 15

    Module 1 · Start Here: Two Classic Cases · Lesson 1 of 15

    Case: URL Shortener with Base62 Codes, Snowflake IDs and Collision Math

    A URL shortener scales with unique short codes, durable mappings and cached redirects. The C# example below encodes counters with a 62-symbol alphabet and builds IDs from timestamp, worker and sequence fields.

    The design below starts with SQL, separates code generation from uniqueness enforcement, and keeps analytics off the redirect path. We will use collision math to choose codes without confusing available capacity with resistance to guessing.

    How much traffic and storage does a URL shortener need?

    Assume 100 million new links per month, 100 redirect requests per creation, and peak traffic three times the average. Using a 30-day month:

    EstimateCalculationResult
    Average creates100 million / 2,592,000 secondsAbout 39/s
    Peak createsAverage × 3About 116/s
    Peak redirectsPeak creates × 100About 11,600/s
    Five-year row count100 million × 60 months6 billion
    Mapping storage6 billion × 500 bytes3 TB, using decimal TB

    The method behind these numbers is in back-of-the-envelope estimation and the system design interview method.

    That storage figure excludes indexes, replicas, backups, idempotency records and click events: the write rate is modest, but retained data and redirect traffic are not. Reads are indexed key-value lookups by code, so SQL is a reasonable start at 116 peak writes/s; test storage and read performance before adding shards.

    Store Code, Destination, OwnerId, CreatedAt, ExpiresAt, DisabledAt and a version for updates. Make Code unique and compare it case-sensitively: Ab9 and ab9 must remain different throughout routing, caching and storage. In SQL Server and Azure SQL the default collation ignores case, so give the column a binary collation, for example Code varchar(16) COLLATE Latin1_General_100_BIN2; otherwise the unique index treats Ab9 and ab9 as one code and a lookup for one can return the other.

    An alternative is Azure Cosmos DB for NoSQL with the code as both item ID and partition key: knowing the code is enough for an efficient point read, and traffic spreads across codes. Listing one owner's links then searches across partitions, so add a second container or index keyed by owner. See Microsoft's partition-key guidance.

    How should create, redirect and disable APIs work?

    Use a small API surface:

    OperationExampleBehaviour
    CreatePOST /linksAccept destination, optional alias and optional expiry; return the code and short URL
    RedirectGET /{code}Resolve an active mapping and return a redirect
    DisableDELETE /links/{code}Authorize the owner, mark disabled and invalidate cached mappings

    An alias is a caller-selected code, such as summer-sale. Give aliases an allowed alphabet and length, reserve paths such as health, and return a conflict when an alias is taken; never silently choose another. Missing, expired and disabled codes return 404, and disabled codes stay reserved so an old bookmark never leads somewhere new.

    Require an Idempotency-Key on creates: save the caller-scoped key, the request and the response in the same transaction as the mapping, under a unique constraint, so a retry gets the same link (idempotency and the outbox pattern). Reusing the key with a different payload returns 422; a retry that arrives while the first request is still running gets 409. These are the codes in the IETF Idempotency-Key draft, which is not yet an RFC. Code uniqueness is separate: it stops two mappings claiming one code, not one caller creating two links.

    How do you generate unique short codes across servers?

    Use the fixed alphabet 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz for base62. In the example below, counter values 60, 61, 62 and 63 encode as y, z, 10 and 11.

    There are four useful choices:

    GeneratorCoordination and uniquenessLength and predictability
    Counter ranges + base62Allocate disjoint ranges; never reuse issued numbersCompact, but easy to enumerate
    Snowflake + base62Give each generator an exclusive worker identityUp to 11 characters for a 63-bit ID; exposes ordering information
    Cryptographically random codeAtomically insert; retry collisionsFixed chosen length; harder to predict
    Truncated URL hashAtomically insert; resolve collisionsFixed chosen length; predictable for known inputs

    A hash is a fixed-size fingerprint calculated from input, so the same URL always gets the same code. That deduplicates links, but two owners may need different expiry or disable settings for the same destination, so URL-based deduplication is a product choice, not an automatic benefit.

    For counter ranges, a central allocator gives each server a block, such as 1–10,000 and 10,001–20,000; a crash wastes numbers, which is safer than reissuing them. SQL Server's sp_sequence_get_range can hand out blocks, but a sequence does not enforce table uniqueness, so keep a unique constraint and prevent cycling. See SQL Server sequence numbers.

    A common Snowflake layout uses:

    • 41 timestamp bits: milliseconds since a chosen starting instant, called the epoch. This lasts about 69.7 years.
    • 10 worker bits: 1,024 worker identities.
    • 12 sequence bits: 4,096 IDs per millisecond per worker.

    The fields form a 63-bit nonnegative integer.

    When the sequence is exhausted, wait for another millisecond or reject generation. Never wrap within the same millisecond. When the clock moves backward, stop or wait according to a defined policy; do not silently reuse earlier timestamp-and-sequence combinations.

    Worker ownership must be exclusive: a paused former owner can resume after its lease expires, so stop it publishing IDs before reassigning its worker identity. After a restart the sequence starts again at 0, so persist the last timestamp used and wait until the clock passes it.

    For random codes, use a cryptographically secure generator, such as RandomNumberGenerator.GetString. Correct creation still requires:

    1. Generate a candidate.
    2. Attempt an atomic insert protected by code uniqueness.
    3. On a code conflict, generate a fresh candidate and retry, perhaps at most five attempts.
    4. After the bound, return a retryable failure and alert on an unexpected conflict rate.

    Do not retry storage outages as though they were code collisions. Caller-selected aliases return a conflict rather than following this random retry loop.

    The mistake to avoid. Do not use a separate existence check as the uniqueness decision. Require the insert to enforce the code's unique constraint.

    How long should a base62 code be?

    Six base62 characters provide about 56.8 billion values. The program below calculates the seven-character space as 62^7: 3,521,614,606,208, or about 3.52 trillion.

    That is capacity. A collision is different: a random candidate repeats an earlier one, and for a single new insert its chance is the fraction of the space already used, a/N. With 6 billion of 3.52 trillion codes taken, that is about 0.17%. With a secure random generator, where every code is equally likely and draws are independent, five attempts almost never all collide.

    The birthday effect makes repeats likely well before a space is full. The program below calculates the approximate 50% collision threshold as Math.Sqrt(2 * space * Math.Log(2)): for seven characters, 2,209,524 draws, about 2.2 million, while the space is still mostly empty. A collision means a retry, not an exhausted space or an accepted duplicate.

    Guessing resistance is a third question. With all 6 billion links live, about 1/587 of the seven-character space is taken, so a random guess hits some live link about once in 587 tries. Codes are not secrets: rate-limit lookups, remember that counter codes are easy to enumerate, and never treat a short code as an authorization check.

    Compare counters, Snowflake and random draws in C#

    Predict whether the counter and Snowflake examples repeat, then count the duplicates among random draws from a deliberately small three-character space.

    C#Runs
    using System;
    using System.Collections.Generic;
    using System.Security.Cryptography;
    
    const string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    
    string Base62(ulong value)
    {
        string text = "";
        do
        {
            text = alphabet[(int)(value % 62)] + text;
            value /= 62;
        } while (value != 0);
        return text;
    }
    
    for (ulong id = 60; id < 64; id++)
        Console.WriteLine($"counter {id}: {Base62(id)}");
    
    double space = Math.Pow(62, 7);
    double halfway = Math.Sqrt(2 * space * Math.Log(2));
    Console.WriteLine($"Seven-character space: {space:F0}");
    double occupiedFraction = 6_000_000_000d / space;
    Console.WriteLine($"Used fraction: {occupiedFraction:P2}");
    Console.WriteLine($"One occupied code per approximately {1 / occupiedFraction:F0} guesses");
    Console.WriteLine($"Five independent collisions: {Math.Pow(occupiedFraction, 5):E2}");
    Console.WriteLine($"Approximate 50% collision threshold: {halfway:F0} draws");
    Console.WriteLine($"Timestamp lifetime: {Math.Pow(2, 41) / 1000 / 60 / 60 / 24 / 365.25:F1} years");
    Console.WriteLine($"Maximum 63-bit base62 length: {Base62((1UL << 63) - 1).Length}");
    
    var snowflake = new SnowflakeModel(7);
    long fakeMilliseconds = 1000;
    ulong first = snowflake.Next(fakeMilliseconds);
    ulong second = snowflake.Next(fakeMilliseconds);
    Console.WriteLine($"Same-millisecond IDs differ: {first != second}");
    for (int i = 2; i < 4096; i++)
        snowflake.Next(fakeMilliseconds);
    try
    {
        snowflake.Next(fakeMilliseconds);
    }
    catch (InvalidOperationException error)
    {
        Console.WriteLine(error.Message);
    }
    fakeMilliseconds++;
    Console.WriteLine($"Next millisecond advances ID: {snowflake.Next(fakeMilliseconds) > second}");
    try
    {
        snowflake.Next(fakeMilliseconds - 1);
    }
    catch (InvalidOperationException error)
    {
        Console.WriteLine(error.Message);
    }
    
    var seen = new HashSet<string>(StringComparer.Ordinal);
    int duplicates = 0;
    for (int i = 0; i < 5000; i++)
    {
        string candidate = RandomNumberGenerator.GetString(alphabet, 3);
        if (!seen.Add(candidate)) duplicates++;
    }
    Console.WriteLine($"Random duplicate draws: {duplicates}");
    Console.WriteLine($"Space occupied: {100.0 * seen.Count / Math.Pow(62, 3):F2}%");
    
    public sealed class SnowflakeModel
    {
        private readonly int worker;
        private long lastMilliseconds = -1;
        private int sequence;
    
        public SnowflakeModel(int worker)
        {
            if (worker < 0 || worker >= 1024)
                throw new ArgumentOutOfRangeException(nameof(worker));
            this.worker = worker;
        }
    
        public ulong Next(long milliseconds)
        {
            if (milliseconds < 0 || milliseconds >= (1L << 41))
                throw new ArgumentOutOfRangeException(nameof(milliseconds));
            if (milliseconds < lastMilliseconds)
                throw new InvalidOperationException("Clock rollback rejected");
            if (milliseconds == lastMilliseconds)
            {
                if (sequence == 4095)
                    throw new InvalidOperationException("Sequence exhausted");
                sequence++;
            }
            else
            {
                lastMilliseconds = milliseconds;
                sequence = 0;
            }
            return ((ulong)milliseconds << 22) | ((ulong)worker << 12) | (uint)sequence;
        }
    }
    Output
    counter 60: y
    counter 61: z
    counter 62: 10
    counter 63: 11
    Seven-character space: 3521614606208
    Used fraction: 0.17 %
    One occupied code per approximately 587 guesses
    Five independent collisions: 1.44E-014
    Approximate 50% collision threshold: 2209524 draws
    Timestamp lifetime: 69.7 years
    Maximum 63-bit base62 length: 11
    Same-millisecond IDs differ: True
    Sequence exhausted
    Next millisecond advances ID: True
    Clock rollback rejected
    Random duplicate draws: 59
    Space occupied: 2.07%

    The counter crosses from z to 10: consecutive numbers, not random codes. Your random duplicate count will vary: with 5,000 draws, at most about 2.1% of this three-character space is occupied, yet repeats are overwhelmingly likely.

    This single-threaded model has no worker allocator, restart persistence or ownership enforcement, and its HashSet does not replace an atomic database insert.

    How do HybridCache and Redis keep redirects fast?

    Keep SQL authoritative and put caches in front of its lookup.

    HybridCache keeps a local copy on each server and can use Redis as a shared second level. Within one server, only one caller loads a missing key while the others wait; caching strategies with HybridCache and Redis explains both levels, stampede protection and invalidation.

    flowchart TD
        R["Redirect request"] -->|"looks up code"| L["HybridCache: local memory (L1)"]
        L -->|"on local miss"| S["HybridCache: Redis secondary cache (L2)"]
        S -->|"on shared miss"| D["Authoritative database"]

    Cache a small mapping containing destination, disabled state, expiry and a freshness deadline: the latest time the entry may be used without reloading authoritative state. When a server copies an entry from Redis into local memory, keep the original deadline rather than starting a new full lifetime. A mapping expiring in ten seconds must not get a fresh 60-second life, so cap cache lifetimes at expiry and check the stored expiry before redirecting.

    A minimal API with HybridCache

    This complete ASP.NET Core example uses an in-memory dictionary as sample database data. The database is read only when the cache misses. The cached copy carries the link's expiry, so the handler checks it after every lookup and never redirects an expired or disabled link.

    C#
    using Microsoft.Extensions.Caching.Hybrid;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddHybridCache();
    var app = builder.Build();
    
    // Sample data standing in for the database table.
    var links = new Dictionary<string, Link>(StringComparer.Ordinal)
    {
        ["demo"] = new Link("https://example.com/", DateTimeOffset.UtcNow.AddHours(1), false)
    };
    
    app.MapGet("/{code}", async Task<IResult> (
        string code,
        HybridCache cache,
        HttpContext context,
        CancellationToken cancellationToken) =>
    {
        context.Response.Headers["Cache-Control"] = "no-store";
    
        // The database is read only when the cache misses.
        var link = await cache.GetOrCreateAsync<Link?>(
            $"link:{code}",
            _ => ValueTask.FromResult(links.GetValueOrDefault(code)),
            options: new HybridCacheEntryOptions
            {
                Expiration = TimeSpan.FromSeconds(30),
                LocalCacheExpiration = TimeSpan.FromSeconds(30)
            },
            cancellationToken: cancellationToken);
    
        // The cached copy carries its own expiry, so an expired link is never redirected.
        if (link is null || link.Disabled || link.ExpiresAt <= DateTimeOffset.UtcNow)
            return Results.NotFound();
    
        return Results.Redirect(link.Destination);
    });
    
    app.Run();
    
    public sealed record Link(string Destination, DateTimeOffset ExpiresAt, bool Disabled);

    Needs ASP.NET Core (a web project) and the package Microsoft.Extensions.Caching.Hybrid 10.0.0. Built with them, and checked on the in-memory TestServer: three requests to /demo read the data once.

    Request /demo and it returns a 302 redirect with Cache-Control: no-store. This sample configures only local caching; the diagram's shared layer requires a Redis cache registration. It caches a missing code for the same 30 seconds; the next paragraph gives these “not found” entries a shorter life.

    For this design, cache a “not found” result, called a negative entry, for two seconds and bound how many you keep. Successful creates must invalidate any negative entry for their code.

    Removing a key does not clear other servers' local copies, so keep local lifetimes short; immediate revocation needs an authoritative check.

    A link receiving 50,000 requests/s is a hot key: unusually high traffic targets one code. Ordinary sharding still sends that code to one shard. If you shard by code, route with a stable hash such as SHA-256, never string.GetHashCode(): .NET randomizes it per process, so two servers would send the same code to different shards (sharding and consistent hashing). Local caches spread its reads across application instances, and read replicas or a CDN add capacity, though CDN-cached redirects hide clicks and delay revocation.

    Should a URL shortener return 301 or 302?

    A 301 (or 308) says the move is permanent: browsers may cache it with no expiry, so later clicks skip your service and you cannot change or disable the link for those users. Use it only for links that never change and whose clicks you do not need to count. 302 and 307 differ only for non-GET requests (307 keeps the method and body), so for these GET redirects either works. See the .NET HTTP status definitions and ASP.NET Core response-caching guidance.

    For mutable links, prefer 302 or 307 with Cache-Control: no-store, which tells compliant caches not to store the response; your application can still cache the internal mapping. If the product accepts delayed revocation and fewer observed clicks, permit bounded shared caching instead and document the freshness window.

    How do you limit abuse?

    Authorize creation, destination changes and disabling by owner. Public redirects may be anonymous, but private destinations still need their own authorization. Restrict destination schemes to HTTP and HTTPS, apply creation and lookup rate limits, and provide abuse reporting and malicious-destination review. If a preview service fetches destinations, separately protect it from access to internal network addresses.

    For algorithm choices behind these limits, see rate limiter algorithms.

    How do you count clicks without slowing redirects?

    Emit a redirect event on both mapping-cache hits and misses, then aggregate asynchronously. Record an event ID, code, timestamp and only the metadata the product needs.

    For the baseline, choose best-effort analytics: put the event into a bounded in-process queue, return the redirect, and let a background sender publish batches. A crash can lose queued events, and a full queue drops events and counts the loss rather than growing memory. If loss is unacceptable, await a durable enqueue before redirecting; that adds latency and a dependency, so decide whether an enqueue failure fails the request or allows an uncounted redirect.

    Delivery can duplicate events, so deduplicate by event ID within a retention window or accept approximate totals. Redirect requests also include bots, link previews and retries, and browser- or CDN-cached redirects never reach the service, so name the metric “observed redirect requests”, not human clicks.

    The mistake to avoid. Updating a SQL click counter synchronously on every redirect makes analytics part of redirect latency and concentrates writes on popular links.

    Your interview answer

    In an interview, say: “At about 116 peak creates and 11,600 peak redirects a second, I start with case-sensitive code lookups in SQL and measure before sharding. Codes come from non-reused counter ranges, Snowflake IDs with exclusive workers, or random draws with an atomic unique insert and bounded retries. Seven base62 characters give about 3.52 trillion values, but random draws reach a 50% collision chance near 2.2 million. Redirects read through HybridCache and Redis with bounded freshness, and local caches, replicas or a CDN spread a viral link. For mutable links I return a 302 or 307 with no-store, because browsers may keep a 301 for good, which hides clicks and blocks changes. Click events go to an asynchronous pipeline with an explicit loss policy.”

    Check yourself

    A seven-character base62 space has about 3.52 trillion values. What follows for random code generation?

    A Repeats become likely early, so inserts still need uniqueness and retries.
    B Collisions cannot occur until every value has been used.
    C Base62 codes are safe to share because nobody can guess them.
    D Checking for absence before insertion guarantees uniqueness across servers.
    Show answer

    Correct answer: A

    Birthday collisions become likely while the space is mostly empty. Atomic uniqueness enforcement prevents a repeated candidate from becoming a duplicate mapping.

    A mutable link must be disabled quickly, and every request reaching the application should produce an analytics event. Which baseline fits best?

    A A permanent redirect that browsers may cache with no expiry.
    B A temporary redirect, counting clicks only on cache misses.
    C A 302 or 307 with no-store, with events on hits and misses.
    D A synchronous SQL click-counter update before every redirect.
    Show answer

    Correct answer: C

    Explicit response cache controls keep compliant HTTP caches from storing the redirect. Internal cache freshness still needs a revocation policy, and analytics emission must cover both lookup outcomes.

    Going deeper

    Cosmos DB changes the idempotency transaction. A Cosmos DB transaction covers only one logical partition (one partition-key value), so a code-partitioned mapping and a caller-partitioned idempotency record cannot commit together. Colocate them with a lookup route to that partition, or use a recoverable reservation workflow whose stored states let a retry finish an interrupted creation.

    Snowflake ownership needs enforcement. A fencing token, an ownership version that a downstream system checks to reject stale owners, helps only where publication checks it. Explore these failure cases in distributed job scheduling with leases and idempotency.

    Recovery is part of uniqueness. Restoring an allocator from an old backup must not reissue counter ranges. Restoring mappings without their idempotency records can turn retried creates into new links. Design backup, restore and failover tests around both pieces of state, not just the URL table.

    Sources

    Practice

    Practice test: Practice: Case: URL Shortener with Base62 Codes, Snowflake IDs and Collision Math7 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·