NOTE

Designing a Short URL System

A historical note on mapping long URLs to short codes with Redis and Base62.

System DesignCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is a Short URL?

Convert a normal URL into a shorter URL.

2. Why Do We Need Short URLs?

They are short and convenient to publish.

3. Short URL System Design

Assume the URI of the short URL system is http://t.cn.

3.1. Write Process

  1. Enter the long URL to convert: http://www.example.com.
  2. Query Redis to see whether a short URL corresponding to www.example.com already exists. If it does, return it.
  3. If not, use Redis auto-increment to generate an ID.
  4. Convert the incremented value to Base62. Assume the resulting Base62 value is RlB2PdD.
    • When converting from a lower base to a higher base, the number of characters decreases.
  5. Store the mapping between RlB2PdD and www.example.com in Redis.

3.2. Query Process

  1. Enter http://t.cn/RlB2PdD in the browser.
  2. DNS first resolves the IP address of http://t.cn.
  3. After DNS gets the IP address, for example 74.125.225.72, it sends an HTTP GET request to that address to query the short code RlB2PdD.
  4. The http://t.cn server gets the corresponding long URL through the short code RlB2PdD.
  5. The request is redirected with HTTP 301 to the corresponding long URL http://www.example.com (this uses the browser mechanism; if there is front-end cooperation, returning http://www.example.com is enough and the front end can redirect by itself).
    • 301 is a permanent redirect because a short address does not change once generated, and it also reduces server pressure.

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub