Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 52 ยท Projects

Project: URL Shortener

Build a URL shortener in ASP.NET Core: base62 ids, safe redirects, custom aliases, per-client rate limiting, memory caching and click counting.

A URL shortener looks trivial: take a long address, hand back a short one, and redirect when somebody visits it. That is exactly why it makes a good project. Behind the simple idea sit real design questions: how do you generate short, unique codes? How do you stop people from creating redirects to dangerous addresses? What should happen when a million people click the same link? What stops one client from creating a million links?

You will build the service in two steps: first the pure logic (base62 codes and URL validation), then the full web app with redirects, rate limiting and caching. Everything runs in one program that starts Kestrel on loopback and drives it with HttpClient.

How it works

flowchart TD
    A["POST /api/links<br/>url + optional alias"] --> B{"Rate limit<br/>ok?"}
    B -->|"no"| X["429 Too Many Requests"]
    B -->|"yes"| C{"URL valid<br/>http or https?"}
    C -->|"no"| Y["400 problem"]
    C -->|"yes"| D["Make code<br/>base62 of counter or alias"]
    D --> E[("Link store")]
    F["GET /{code}"] --> G{"In memory<br/>cache?"}
    G -->|"yes"| H["302 redirect"]
    G -->|"no"| I["Look up in store<br/>then cache it"]
    I --> H

Creating a link passes the rate limiter and validation; following a link usually hits the cache and answers with a redirect.

The API has three parts: POST /api/links creates a link, GET /api/links/{code} shows its statistics, and GET /{code} is the redirect everybody actually uses. Reads vastly outnumber writes in a shortener, which shapes every decision below.

Step 1: base62 codes

How do you get a short unique code? One approach is random strings, which must be checked for collisions. A simpler and collision-free approach is to number the links with an increasing integer id and write that number in base 62, using the digits 0-9, a-z and A-Z. Base 62 packs more information into each character than decimal does: six characters cover about 56 billion links, and the characters are URL-safe, so no encoding is needed.

The code starts the counter at 62^5 so every generated code has at least six characters, which looks more consistent and hides how few links exist. Sequential ids are guessable (someone can walk through 100000, 100001, ...). If links must be private, add random bits or use an unguessable token instead; for public redirects that is usually fine.

Validation matters just as much. A shortener that accepts any string can be abused for phishing and for XSS through javascript: URLs. Accept only absolute http and https URLs, set a length limit, and refuse to redirect to ourselves, which could create a redirect loop.

C# Step 1: base62 ids and URL validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Encode then decode returns the original id, so the code is the id: no extra column or lookup table is needed to turn a code back into a number. Look at the validation list: javascript: and ftp: are rejected because their scheme is not http or https, and https:// fails because it is not a valid absolute URI. A check that only looked for the text http at the start would be much easier to fool.

Step 2: the web app

Four design decisions shape the service.

302, not 301. A 301 Moved Permanently lets browsers and CDNs cache the redirect forever, which means you can never count clicks, change the target or delete the link. A 302 Found (or 307 Temporary Redirect) keeps every click flowing through your server. Use 301 only when you accept those costs.

Rate limit creation, per client. Anyone can call the create endpoint, so we limit it. The built-in rate limiter middleware (see Rate Limiting, Health Checks and Resilience of the App) partitions by key, here the caller's IP address. A fixed window of 5 requests per 10 minutes is small enough to demonstrate. Reads (the redirects) are not limited; they must stay fast. Behind a reverse proxy, remember to enable forwarded headers (see Deployment), or every user shares the proxy's IP and one limit.

Cache the lookup. The same popular link is requested again and again. An IMemoryCache entry with a short expiry means the store is consulted once, then the answer comes from memory (see Caching). The catch is invalidation: when a link is deleted, remove it from the cache too, or it will keep redirecting until the entry expires.

Count clicks without locking. Each link holds a long that is increased with Interlocked.Increment, which is atomic and lock-free, so concurrent clicks never lose counts.

Now the whole service. The client at the bottom creates links, follows redirects without auto-following them (so we can see the 302 and its Location header), and runs into each failure.

C# The URL shortener service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the run in order. The generated link got the code 100000 (the first six-character code), and the alias link got docs. The duplicate alias was refused with 409 Conflict, the javascript: URL and the alias with a space with 400. Those first five attempts used up the client's five permits, so the sixth is rejected with 429 Too Many Requests and a Retry-After header that tells well-behaved clients when to come back. Note that rejected requests and invalid ones count against the limit: the limiter runs before your handler.

Following a link returns 302 with a Location header and no body: the browser does the actual navigation. The statistics call shows hits of 3 for docs. The final line counts store lookups: 5 in total (the first click on docs, 100000, the unknown nope, the stats call, and the /docs request after the delete). The two repeated clicks on docs were answered from the cache and never touched the store. After the delete, the link is gone from both the store and the cache, so /docs is 404.

A public redirector is an open redirect by nature, which phishers like. Real services add abuse controls on top of what you built here: blocklists (for example Google Safe Browsing), a warning page for unknown destinations, accounts and quotas, and reporting tools. Never redirect to a URL taken from a query string without validating it, and never skip the scheme check.

Extending the project

  • Persistence. Links vanish when the process stops. Put them in a database table with a unique index on Code, using an auto-increment id as the source of the base62 code (EF Core Overview). Click counts are better kept in a separate counters table or buffered and written in batches by a background service, so the redirect path never waits on a write.
  • Expiry. Add an optional ExpiresAt and treat expired links as 410 Gone.
  • Analytics. Record referrer, country and time of each click using a channel and a hosted service.
  • Distributed caches. With several servers, in-process memory caches become inconsistent after a delete. Use a distributed cache or short expiry times.
  • Protect management. Require an API key to delete or list links (Authentication Concepts).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the shortener answer with 302 instead of 301?

    A temporary redirect keeps every click flowing through the service, which keeps counting, editing and deleting possible.
  2. 2. Which is the main advantage of generating codes by base62-encoding an incrementing id?

    Each id maps to exactly one code, and 62 URL-safe symbols keep the code compact. The downside is that sequential ids are guessable.
  3. 3. A user shortens javascript:alert(1). What should the service do and why?

    Other schemes enable XSS and phishing. Validate with Uri.TryCreate and an explicit scheme check.
  4. 4. Why must the DELETE endpoint also remove the entry from the memory cache?

    The redirect endpoint answers from the cache first, so a stale entry would still redirect after the link was deleted.
  5. 5. What happens to the sixth creation request from one client in the 10-minute window when the limit is 5?

    The rate limiter middleware rejects it with 429 (QueueLimit is 0, so nothing waits) and the handler never runs.

Summary

  • A shortener numbers links and writes the number in base62 to get short, URL-safe, unique codes; custom aliases need a uniqueness check and a reserved-word list.
  • Validate targets strictly: absolute http and https only, with a length limit and no links to yourself.
  • Use a temporary redirect (302 or 307) so every click reaches your server.
  • Rate limit the write endpoint per client and leave the read path unrestricted; set Retry-After on rejections.
  • Cache hot lookups in memory, never cache misses blindly, and invalidate entries when links change.
  • Count clicks with Interlocked.Increment; for production, persist data and buffer the counters.

Next: Project: Notes API with Authentication