The moment a user pastes a 2,000‑character link into a chat, the next step is to shrink it.
In a world where URLs are shared on social media, printed flyers, and QR codes, a shortener must be fast, reliable, and, most importantly, collision‑free.
Below is a practical guide to building a Go‑based URL shortener that scales to millions of requests while keeping the codebase simple enough to understand in a single read.
TL;DR
- Use a base62 encoder on a counter that starts from a high random offset to generate compact, human‑readable IDs.
- Store mappings in an in‑memory
map[string]Recordfor the demo; switch to Redis or PostgreSQL for production. - Expose
POST /shortenfor creation andGET /{id}for redirection; validate JSON and handle 404s. - Detect and resolve collisions by incrementing the counter and retrying, with exponential backoff.
- Scale by sharding the counter across stateless workers and caching hot redirects in an LRU store.
Problem Definition & Goals
A URL shortener must map an arbitrary long URL to a unique, short identifier that can be used as a path segment in a domain.
The core functional requirements are straightforward:
- Create – Accept a long URL, return a short URL.
- Redirect – Resolve the short URL to the original long URL and issue an HTTP redirect.
Non‑functional goals drive the architecture:
- Uniqueness – No two different long URLs should share the same short ID.
- Low latency – Creation and redirection should complete in < 10 ms for most traffic.
- Durability – Mappings must survive restarts; in‑memory storage is only a prototype.
- Extensibility – Adding features (analytics, custom aliases, expiration) should be plug‑and‑play.
Choosing the Identifier Strategy
Base62 vs UUID vs Auto‑Increment
| Strategy | Size | Readability | Collision Risk | Typical Use |
|---|---|---|---|---|
| Base62 | ~6 chars for 62^6 ≈ 56 billion IDs | Good | Low if counter is seeded correctly | URL shorteners, slugs |
| UUID | 36 chars | Poor | Zero | Session tokens, database keys |
| Auto‑Increment | Variable | Good | None | Relational primary keys |
Base62 is ideal for shorteners because it produces the smallest human‑readable string for a given numeric counter. UUIDs are too long to be useful in a URL path, and a simple auto‑increment counter can lead to predictable IDs that expose the number of created links.
Deterministic Base62 Encoder
The encoder converts a uint64 counter into a string composed of [0‑9a‑zA‑Z]. The implementation is straightforward:
// base62.go
package main
import "math"
const base62Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// encode converts a positive integer to a base62 string.
func encode(num uint64) string {
if num == 0 {
return string(base62Chars[0])
}
var encoded []byte
base := uint64(len(base62Chars))
for num > 0 {
rem := num % base
encoded = append(encoded, base62Chars[rem])
num /= base
}
// Reverse the slice.
for i, j := 0, len(encoded)-1; i < j; i, j = i+1, j-1 {
encoded[i], encoded[j] = encoded[j], encoded[i]
}
return string(encoded)
}
Explanation
The algorithm repeatedly divides the number by 62, collecting remainders that map to characters. The slice is reversed because the least significant digit is computed first. The function is deterministic: the same input always produces the same output, which is essential for collision detection.
Random Offset for the Counter
If the counter starts at 1, an attacker can guess how many URLs have been created. By initializing the counter with a large random value (e.g., a random 48‑bit integer), the first few IDs appear random and the mapping between ID and creation order is obscured. The counter can be persisted in a distributed store (Redis INCR) to avoid split‑brain.
Data Model & Persistence
In‑Memory Map (Prototype)
// record.go
package main
import "time"
type Record struct {
OriginalURL string
CreatedAt time.Time
ExpiresAt *time.Time // nil means no expiration
}
var (
// shortID -> Record
store = make(map[string]Record)
)
This simple map satisfies the prototype. All data is lost on restart, so the service is stateful and unsuitable for production.
Production‑Ready Persistence
| Store | Pros | Cons |
|---|---|---|
| Redis | Fast, TTL support, INCR atomic counter |
Single point of failure unless replicated |
| PostgreSQL | Strong consistency, ACID, mature tooling | Slightly higher latency, requires migrations |
A typical schema in PostgreSQL:
CREATE TABLE url_mappings (
short_id TEXT PRIMARY KEY,
original_url TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now(),
expires_at TIMESTAMP NULL
);
In Redis, you can use SETEX key seconds value for TTL or store the expiration timestamp separately.
API Design & Routing
Endpoints
| Method | Path | Purpose |
|---|---|---|
| POST | /shorten |
Create a new short URL |
| GET | /{id} |
Resolve and redirect |
Request & Response
POST /shorten
Content-Type: application/json
{
"url": "https://example.com/some/very/long/path"
}
Response (201 Created):
{
"short_url": "https://short.ly/4f9G"
}
If the ID already exists (collision), the server returns a 409 Conflict and retries internally.
Implementation with net/http and gorilla/mux
// server.go
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"sync"
"time"
"github.com/gorilla/mux"
)
var (
counter uint64
mu sync.Mutex // protects counter and store
)
func init() {
// Seed counter with a high random offset.
rand.Seed(time.Now().UnixNano())
counter = uint64(rand.Int63n(1<<48))
}
type shortenRequest struct {
URL string `json:"url"`
}
func shortenHandler(w http.ResponseWriter, r *http.Request) {
var req shortenRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.URL == "" {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
// Basic URL validation (placeholder).
if !isValidURL(req.URL) {
http.Error(w, "invalid URL", http.StatusBadRequest)
return
}
var id string
mu.Lock()
defer mu.Unlock()
for {
id = encode(counter)
counter++
if _, exists := store[id]; !exists {
// No collision.
store[id] = Record{
OriginalURL: req.URL,
CreatedAt: time.Now(),
}
break
}
// Collision detected: retry with next counter value.
}
shortURL := "https://short.ly/" + id
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"short_url": shortURL})
}
func redirectHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
mu.Lock()
record, exists := store[id]
mu.Unlock()
if !exists {
http.NotFound(w, r)
return
}
// Optional: remove expired entries.
if record.ExpiresAt != nil && time.Now().After(*record.ExpiresAt) {
mu.Lock()
delete(store, id)
mu.Unlock()
http.NotFound(w, r)
return
}
http.Redirect(w, r, record.OriginalURL, http.StatusFound)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/shorten", shortenHandler).Methods("POST")
r.HandleFunc("/{id}", redirectHandler).Methods("GET")
srv := &http.Server{
Addr: ":8080",
Handler: r,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
log.Println("Server listening on :8080")
if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
Explanation
- A global
counteris protected by a mutex to avoid race conditions. - On each
POST /shorten, the counter is encoded to base62. If the ID already exists, the loop increments the counter until an unused ID is found. - The
GET /{id}handler looks up the map and redirects. - Basic URL validation is left as a placeholder (
isValidURL); in production you would use a proper parser. - Timeouts protect against slow clients.
Handling Collisions & Expiration
Collision Detection
Because the counter is deterministic, a collision can only occur if a previous ID was manually overridden or if the counter wraps around. The retry loop in the handler guarantees uniqueness.
Exponential Backoff
Under high load, many requests may hit the same counter value simultaneously. A naive loop could cause contention. A simple backoff strategy:
for i := 0; i < 5; i++ {
id = encode(counter)
counter++
if _, exists := store[id]; !exists {
// success
break
}
time.Sleep(time.Duration(i) * 10 * time.Millisecond)
}
If after 5 attempts a unique ID is still not found, the service can return a 429 Too Many Requests.
Expiration
An optional expires_at timestamp allows short URLs to be short‑lived (e.g., for marketing campaigns). The redirectHandler removes expired entries on access, preventing stale redirects. In Redis, TTL can be set automatically; in PostgreSQL, a scheduled job can purge expired rows.
Scaling & Performance Optimizations
Counter Sharding
Running a single counter across many workers leads to a bottleneck. Split the ID space:
- Range Sharding: Worker 1 owns IDs 0–1 billion, Worker 2 owns 1 billion–2 billion, etc.
- Hash Sharding: Hash the original URL and modulo by the number of workers.
Each worker maintains its own counter and persists it to a distributed store (Redis SET with NX to avoid duplicates).
Caching Hot Redirects
Most traffic will hit a small subset of URLs repeatedly. An in‑memory LRU cache (e.g., github.com/hashicorp/golang-lru) can store the mapping from ID to original URL, bypassing the map/DB for hot keys. Cache entries can be evicted after a configurable TTL.
Load Balancer & Stateless Workers
Deploy the service behind a load balancer (NGINX, HAProxy) to distribute traffic. Because each worker owns a disjoint ID range, they can operate statelessly except for the counter persistence. This design simplifies horizontal scaling.
Distributed Counter Store
To avoid split‑brain, store the counter in a single source of truth (Redis INCR). Workers fetch the next counter value atomically. If a worker crashes, the counter value is still available to others.
Common Mistakes & Trade‑offs
| Mistake | Why It Matters | Mitigation |
|---|---|---|
| Using only an in‑memory map | Data lost on restart, no multi‑node support | Persist to Redis/PostgreSQL; implement graceful shutdown with state dump |
| Skipping input validation | Open‑redirect attacks, malformed URLs | Validate URL scheme, length, and domain whitelist |
| Choosing a too‑small ID space | Rapid collisions, forced retries | Use 6‑char base62 (~56 billion IDs) or increase length; seed counter high |
| Prioritizing speed over durability | Data loss, inconsistent state | Use write‑through cache; log each creation to a durable store |
| Hard‑coding domain | Inflexible deployments | Inject domain via environment variable or configuration file |
| Ignoring expiration cleanup | Memory bloat, stale redirects | Implement TTL in Redis or scheduled cleanup jobs |
Trade‑offs often involve latency vs durability. A write‑through cache gives near‑instant writes but duplicates effort; a read‑through cache can hide database latency but may serve stale data if not refreshed.
Key takeaways
- Base62 on a high random counter gives compact, collision‑resistant IDs suitable for URL shorteners.
- In‑memory maps are fine for demos; for production, use Redis or PostgreSQL with TTL support.
- Deterministic retry loops and exponential backoff keep uniqueness guarantees while handling contention.
- Sharding the counter and caching hot redirects are essential for scaling to millions of requests.
- Validate inputs and implement expiration to keep the service secure and manageable.
- Always balance speed against durability; a write‑through cache protects against data loss without sacrificing performance.
By following these guidelines, you can build a Go‑based URL shortener that is both efficient and ready for real‑world traffic.
FAQ
How does the base62 encoder work?
It repeatedly divides the counter by 62, mapping remainders to digits 0‑9, a‑z, A‑Z, and reverses the result to form the ID.
What storage options are recommended for production?
Redis is fast and supports TTL with INCR; PostgreSQL offers strong consistency and ACID guarantees, ideal for durable mappings.
How are collisions detected and resolved?
After generating an ID, the server checks if it exists in the store; on collision it increments the counter and retries with exponential backoff.
Can I add custom aliases to the shortener?
Yes, by allowing clients to specify an ID and validating its uniqueness before insertion, you can plug in custom alias support.