My Solution for Designing a Simple URL Shortening Service: A TinyURL Approach with Score: 9/10

by vertex3447

System requirements


Functional:

URL Shortening:

  • This service allows user to input long URL and then generate short unique URL with optional expiration date.
  • The purpose of the service is to generate easily readable URL.

URL Redirection:

  • When a user enters any short URL, system will verify its validity.
  • System will check the expiration of the URL
  • System will find the relevant URL mapped with the short URL
  • It should handle the request effectively, and ensure low latency to avoid delays.

Error Handling:

  • If the shorten URL is invalid or expired, system will return the meaning full error message.


Non-Functional:

Availability:

  • Ensure the service is highly available, especially for URL redirection service to ensure uninterrupted service.

Scalability:

  • Design the service to efficiently handle increasing numbers of requests and data, particularly as the user base grows.

Security:

  • Implement measures to protect against unauthorized access, data breaches, and DDoS attacks.



Capacity estimation

Estimate the scale of the system you are going to design...


URL Shortening:

  • Assume 200 request per second.
  • System should generate the unique short URL ASAP, in case of delay the threshold is max 10 seconds


URL Redirection:

  • URL redirection is more usage service in the system, it should handle 2000 requests per second.
  • The delay is response is not an ideal situation, response should be return in max 10 milliseconds.


API design

Define what APIs are expected from the system...

  • API will follow the RESTful structure
  • API will follow the standard response
  • API will follow the versioning
  • API version will contain URL versioning method

Success Response: {

data: {

url: "abc.ly/xu3isf1"

},

status: 200, //status code is be according to the API response

message: "success",

error: {}

}


Error Response: {

data: {},

status: 412, //status code is be according to the API response

message: "validation failed",

error: {

code: 412,

message: "URL is invalid format"

}

}


  1. Generate URL: v1/url POST
    1. API will take 2 parameters
      1. URL (required)
      2. expiration (optional)
    2. API will validate the URL is valid URL format
    3. API will validate the URL duplication entry
    4. API will generate the unique short URL
    5. API will return the response in standard format containing shorten URL
  2. GET All URL: v1/url GET
    1. API will fetch all valid URL's from system
    2. API will contain pagination meta data
    3. API will send the response based on the pagination flow
  3. GET Single URL: v1/url/{id} GET
    1. API will fetch the URL based on the provided ID
    2. API will send standard response containing URL and its information
  4. DELETE URL: v1/url/{id} DELETE
    1. API will fetch the URL based on the provided ID
    2. API will soft delete the URL of the provided ID
    3. API will send standard success response
  5. Redirect URL: GET
    1. API will take 1 query param
      1. code
    2. API will find the corresponding long URL associated with the code
    3. API will validate its expiration
    4. API will increase the count
    5. API will return the original long URL


Database design

Tables:

  • users
    • id (unique, auto increment, primary)
    • name (string)
    • email (string, unique)
    • created_at (timestamp)
    • updated_at (timestamp)
    • deleted_at (timestamp)
  • shorten_urls
    • id (unique, auto increment, primary)
    • user_id (unique, foreign, reference users.id)
    • long_url (string)
    • short_url (string, unique)
    • code (string, unique)
    • expiry (date, nullable)
    • count (integer)
    • created_at (timestamp)
    • updated_at (timestamp)
    • deleted_at (timestamp)





High-level design

Architecture:

The URL Shortening Service is designed as a scalable, high-performance, and fault-tolerant web system that allows users to generate, resolve, and track shortened URLs.

At a high level, the system follows a modular microservice-based architecture (or optionally monolithic for MVP), consisting of stateless services behind a load balancer, with persistent storage and a caching layer to optimize performance.


Key Design Principles

  • Stateless application layer: Enables easy horizontal scaling and fault recovery.
  • Separation of concerns: Each component (e.g., URL generator, redirect handler, analytics collector) performs a single, well-defined function.
  • Read-heavy optimization: Prioritized for high-throughput read operations, since redirection is the most frequent action.

High-Level Flow

  1. URL Shortening Request:
    • The user sends a request with a long URL.
    • The system generates a unique short code (via hashing or sequence-based generation).
    • The mapping is saved to persistent storage and optionally cached.
    • The short URL is returned to the user.
  2. URL Redirection Request:
    • When a user accesses a short URL, the service looks up the corresponding long URL.
    • If found in cache, it redirects immediately.
    • If not, it retrieves from the database, caches it, then redirects.
    • Optionally, the system logs analytics data asynchronously.

Components:

  • API Gateway: handles user requests
  • URL Shorten Service: Generate short code and validate URL
  • URL Redirect Service: Search for mapped URL with code
  • Cache Layer: Save database interaction and improves performance
  • Database: Store URL, metadata and user information





Request flows

Request flow:

  • URL Shorten Service
    • User will submit long URL
    • System will validate the URL
    • System will generate unique short code against the URL
    • System will map the long URL with short code and store in database
  • URL Redirect Service
    • User will open short URL from browser
    • Client end will detect the URL and send the short code to API
    • API will find the mapped long URL with the code
    • API will return long URL to client
    • Client will redirect user to long URL






Detailed component design


Short Code Generator

Purpose:

Generates a unique, collision-free short code for each long URL.

Design Options:

  • Hashing-based (e.g., MD5, SHA-256 + Base62)
    • Truncate to 6–8 characters
    • Risk of collisions → must check DB for uniqueness
  • Counter-based (auto-increment + Base62 encoding)
    • Convert an incrementing ID to a short string using Base62
    • No collisions if atomic counter is used

Data Structure / Algorithm:

  • Use a global counter stored in Redis or DB
  • Convert numeric ID to Base62

Scalability:

  • Horizontal scale: Safe if using a distributed ID generator (like Twitter Snowflake or Redis INCR)
  • Sharding: Can shard ID ranges by machine or region


Redirect Handler

Purpose:

Redirect users from a short URL to the original long URL.

Workflow:

  1. Extract short code from the incoming URL
  2. Look up the mapping in cache
  3. If cache miss, query the database and populate cahce
  4. Redirect the user using HTTP 301 or 302

Data Access:

  • Cache: Get short code → returns long url
  • Fallback to database





Trade offs/Tech choices

Tech Choices:

  • Micro services:
    • Better for the separation of services
    • It might be a overload for MVP
  • Redis
    • Improves performance, reduces database load
    • An extra layer of implementation for the work
  • Relational Database (PgSQL)
    • Relational database provide consistency and better structure, using it with cache layer can provide a good performance while reading the data
    • DynamoDB could be the better option in terms of performance




Failure scenarios/bottlenecks


  • increase in number of requests per second by the time system grows and more users are using the system.
  • Caching service capability to handle requests, if caching service goes down the load the shift to our database
  • Generating unique codes as the number of code has been generated in our system, system will face hurdle to generate new unique codes and it will increase the write time and database hits





Future improvements


  • Implementation of the load balance will solve the request per second issue, it will direct the load towards the node with low burden
  • scale the caching mechanism to avoid downtime