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.
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.
"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/linksreturns the code, andGET /{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."
| 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 |
| 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 |
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
| 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 |
| 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 |
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.
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
Red flags
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.
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.
| 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.
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.
CloudFront for the edge, ElastiCache or MemoryDB for Redis, DynamoDB (partition key = code) or Aurora for storage, Kinesis for click events.
Decode(Encode(n)) == n for random 64-bit values.k6 or bombardier at 5,000 req/s; watch dotnet-counters monitor -n <process> System.Runtime Microsoft.AspNetCore.Hosting.sys.dm_exec_query_stats).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
);
Cache-Control.UPDATE ... OUTPUT, so the row is touched once per block and the default READ COMMITTED isolation is enough.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.
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.
I pick by read/write ratio, how much staleness is acceptable, and whether losing a write is ever acceptable.
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.
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.
Last updated 23 Nov 2026.