Short Link Implementation: Core Algorithms, Base62 Encoding, and 302 Redirection
This article details the architecture of short link systems, covering short domain selection, unique ID generation strategies (auto-increment, Redis, Snowflake), Base62 and custom encoding, mapping storage with Redis and databases, 302 redirection flow, cache optimization, anti-enumeration, idempotency, expiration handling, multi-data-center deployment, and click tracking.
Core Idea
A short link is not a compression algorithm but a high-speed mapping table plus a short, usable key. When a user clicks https://3.cn/011HqOh0x, the browser does not decompress the short code. Instead, the request hits the short domain 3.cn, the redirect service extracts the short code 011HqOh0x, looks up the pre-stored long URL, and returns a 302/301 redirect with the Location header pointing to the real address.
User clicks https://3.cn/011HqOh0x
│
▼
DNS resolves 3.cn to short-link redirect service
│
▼
Service extracts short code from path: 011HqOh0x
│
▼
Query mapping table: short code → original long URL (also validate expiry and status)
│
▼
Return 302/301, Location = real address
│
▼
Browser requests long URL, opens target pageThe system typically consists of four parts:
Short domain : e.g., 3.cn, t.cn — short, brand-trusted, stable resolution.
Unique ID : Guarantees each short code maps to a unique record, avoiding collisions.
Encoding : Converts integer ID into a shorter readable string (commonly Base62 or custom charset).
Storage and redirect : DB/cache stores mappings; redirect service performs 302 and asynchronously logs clicks.
Business requests short link
│
▼
Generate unique ID → encode to short code → write "short code ↔ long URL" mapping
│
▼
Return https://short-domain/short-code
User visits short link
│
▼
Short domain service resolves short code → query cache/DB → 302 to long URLShort Domain
Short domains solve the "long prefix" problem. Even with an 8–10 character code, a long marketing domain keeps the SMS link long. Selection criteria:
As short as possible : Second-level or even top-level short domains like 3.cn.
ICP-licensed and HTTPS-capable : Hard requirement for domestic Chinese businesses.
Independent deployment : Redirect cluster decoupled from main site for separate scaling, rate limiting, and risk control.
Credibility : In SMS, whether carriers/users recognize the domain as legitimate directly affects click-through rates.
Two common path forms:
Pure short code : /011HqOh0x — shortest, most common.
Prefixed : /a/011HqOh0x — distinguishes business lines, algorithm versions, or canary releases.
Unique ID Generation
Behind every short code is almost always a globally unique integer (or equivalent). Generating an ID first, then encoding, is more controllable than random strings.
Common generation methods:
Database auto-increment / number segments : Simple, ordered; segments can be pre-allocated in batches. Suitable for small to large scale.
Redis INCR : Fast implementation, high throughput. Suitable for single data center or clear sharding strategy.
Snowflake-like algorithms : Local ID generation without central counter. Suitable for multi-data-center, high-concurrency writes.
Business gene IDs : Embed shard, business, and other info into the ID. Suitable for massive sharding scenarios.
Generation pseudo-flow:
id = nextId() // globally unique
code = encode(id) // Base62 / custom encoding
save(code, longUrl, meta)
return "https://3.cn/" + codeSequential auto-increment IDs cause short codes to appear consecutive, making them easy to enumerate. Production systems often combine "shuffled charset / salting / random bits" to reduce predictability.
Base62 and Custom Encoding
Integers directly in URLs are neither short nor "code-like". The common approach is to use a larger base.
Base62 uses 62 URL-friendly characters: 0-9, a-z, A-Z.
Approximate capacity:
6 chars: 62^6 ≈ 56.8 billion
7 chars: 62^7 ≈ 3.5 trillion
8 chars: 62^8 ≈ 218 trillion
For most businesses, 6–8 characters are sufficient.
Why not Base64? Because + and / appear in the output, requiring extra encoding when placed in path or query, hurting compatibility and UX.
Custom encoding adjusts Base62 for engineering needs:
Shuffle charset order to weaken "sequential ID → sequential short code".
Remove confusing characters ( 0/O, 1/l/I) to reduce manual transcription errors.
Add checksum digits to detect tampering or input errors.
Fixed-length padding for consistent display.
Encoding is usually reversible (ID ↔ short code). Security must not rely on algorithm obscurity but on unguessable design, rate limiting, target domain validation, and access control.
Mapping Storage and Redirection
5.1 What to Store
A mapping record minimally contains:
short_code : Short code, unique key.
long_url : Original destination address.
status : Active / disabled / deleted.
expire_at : Expiration timestamp (nullable).
biz_id / creator : Ownership and audit trail.
created_at : Creation timestamp.
5.2 Redirect Flow
Redirect is read-heavy, write-light; the path must be extremely short:
Receive /{code}
→ Check local cache / Redis
→ On miss, query DB and backfill cache
→ Validate status and expiry
→ Return 302, Location = long_url
→ Async write click log (Kafka, etc.)Redirect status code choice:
302 : Temporary redirect; allows target changes, ensures every click hits origin for stats; common in marketing SMS.
301 : Permanent redirect; intermediate layers may cache aggressively, making later target changes difficult; use with caution.
5.3 Generation API Side
POST /shorten { longUrl, expireAt, bizId }
→ Validate protocol, domain whitelist, length
→ Decide whether to reuse existing short code per business rules (idempotency)
→ Generate ID + encode
→ Write DB, write cache
→ Return full short linkOther Key Technologies
1. Hash Truncation (Alternative to ID Generation)
Hash the long URL, take first N characters as short code; on collision, re-hash with salt.
Pros: Same long URL easily yields same short code.
Cons: Collision handling and length planning more complex.
Suitable for small-to-medium scale with strong reuse needs; large-scale systems prefer "generate ID + encode".
2. Caching and Hotspots
Promotional SMS can drive extreme QPS on a few short links. Common stack:
Redis caches hot mappings.
In-process local cache (e.g., Caffeine) shields hottest keys.
Bloom filter quickly rejects obviously non-existent short codes, reducing enumeration pressure.
3. Anti-Enumeration and Abuse Prevention
Add randomness to short codes to prevent sequential guessing.
Rate limit redirect endpoint; detect anomalous UA/IP.
Authenticate generation API to prevent misuse as public short-link platform.
Long URL domain whitelist/blacklist to reduce phishing redirect risk.
4. Idempotency: Same Link → Same Code
Business often requires: same business party, same long URL, within validity period → return same short code. Achieved by unique constraint on (biz_id, url_hash) or "check-then-insert".
5. Expiration and Recycling
Redis TTL for cache; DB uses scheduled jobs to mark expired or archive.
Recycling short codes is risky: old SMS may persist, causing "old link jumps to new business".
Most production systems avoid recycling or enforce very long cool-down periods.
6. Multi-Data-Center
Write: Pre-allocate number segments per data center, generate locally, reduce cross-region coordination.
Read: Replicate mapping data / active-active; redirect serves from nearest location.
Degradation: Cache-first; on storage failure, return error page for cache misses to avoid avalanche.
7. Click Statistics and Attribution
Synchronous path only does "lookup + 302". Channel, device, time, etc., are collected asynchronously to avoid slowing redirect latency.
8. Relation to QR Codes and App Launch
SMS: Prioritize extreme brevity and domain trust.
QR codes: Slightly more length tolerance, but short links still benefit layout.
App: May go through Universal Link / App Link first, then decide to open app or H5; short link can still serve as unified entry point.
Solution Selection
Comparison of three mainstream approaches:
Generate ID + Base62 : Uniqueness guaranteed by ID generation; compact controllable length; same-link reuse needs extra logic; anti-enumeration needs extra handling; very suitable for large scale.
Hash truncation : Requires collision handling; length depends on truncation bits; reuse relatively natural; anti-enumeration relatively better; moderate for large scale.
Pure random string : Uniqueness by length and probability; usually longer; reuse needs extra logic; best anti-enumeration; suitable for large scale (security-oriented).
The mainstream combination for internet SMS/message short links can be summarized as:
Short domain + distributed ID generation + Base62 (or shuffled charset) + DB/Redis mapping + 302 redirect + async statistics.
Back to the Opening Example
For https://3.cn/011HqOh0x: 3.cn is the short domain entry point. 011HqOh0x is the short code encoded from a unique ID via Base62/custom charset.
JD's short-link service uses that code to look up the real long URL.
Browser receives 302/301 and redirects to product page, campaign page, etc.
Click counts, channel attribution, risk control, expiry enforcement — all hang on this mapping and redirect chain.
In one sentence: Short link = short domain entry + globally unique short code + fast redirect on server-side mapping table.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
