Nov 23, 20266 min read

Build a URL Shortener Backend with Postgres and Click Analytics

Short code generation, 301 vs 302 redirects, caching the hot path, counting clicks without slowing redirects and blocking abuse, with a Go service on Encore using Postgres, a Redis cache and Pub/Sub.

Illustration for Build a URL Shortener Backend with Postgres and Click Analytics

A URL shortener is a common system design exercise because its core is tiny: store a code and a URL, look it up, redirect. The production work sits around that core, from code generation and fast redirects under load to click counting and abuse prevention.

This guide works through each of those and builds a shortener in Go with Postgres, a cache for redirects and a queue for click analytics.

How should short codes be generated?

Random base62 strings (a-z, A-Z, 0-9) are the usual choice. Seven characters give 62^7, about 3.5 trillion codes, so collisions are rare, and when one happens the unique constraint rejects the insert and you retry with a new code. Codes from an incrementing counter are shorter at first but leak how many links exist and let anyone walk through every link by counting, which matters when people shorten private document links. Custom aliases ("/launch") go through the same unique constraint with a reserved-word check.

Should redirects be 301 or 302?

A 301 Moved Permanently is cached by browsers, so the second visit from the same browser never reaches your server and your click counts stay low. It also means a destination you later fix or disable keeps working for everyone who cached it. A 302 Found is the right default for a shortener that counts clicks or lets users edit links, at the cost of one extra request per visit.

How do you keep the redirect path fast?

Redirects are read-heavy and dominated by a few popular links, which makes them ideal for a cache. Look the code up in Redis first, fall back to Postgres on a miss and write the result back with a TTL of an hour or so. A deleted or disabled link should also overwrite its cache entry with a disabled marker so it stops working immediately rather than when the TTL runs out, and so a lookup that read the old row cannot write it back.

How do you count clicks?

Writing an UPDATE links SET clicks = clicks + 1 on every redirect makes the hottest link the most contended row in the database. Publish a click event instead and return the redirect right away, then let a subscriber roll events up into a (code, day) table with an upsert. You lose nothing if the subscriber falls behind for a few minutes, and the redirect latency stays the cost of one cache read.

How do you stop a shortener from being abused?

Open shorteners get used to hide phishing and malware URLs, which can get your domain blocked by browsers and mail filters. Accept only http and https targets, reject links that point back at your own domain to avoid redirect loops, rate limit link creation per account, and check new targets against a reputation list such as the Google Safe Browsing API before activating them. OWASP's guidance on unvalidated redirects applies directly, since a shortener is a redirect service by design.

URL shortener with Encore

Encore

Encore is a backend framework with built-in infrastructure, and all three pieces of this design are declared in the Go service: links in a Postgres database, lookups in a cache keyspace backed by Redis, and click events on a Pub/Sub topic. In your AWS or GCP account these become RDS or Cloud SQL, ElastiCache or Memorystore and SNS/SQS or Pub/Sub, and encore run provides local versions of all three.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- shortener/migrations/1_create_links.up.sql CREATE TABLE links ( code TEXT PRIMARY KEY, target_url TEXT NOT NULL, owner_id TEXT NOT NULL, disabled BOOLEAN NOT NULL DEFAULT false, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE link_clicks_daily ( code TEXT NOT NULL REFERENCES links (code), day DATE NOT NULL, clicks BIGINT NOT NULL, PRIMARY KEY (code, day) );
// shortener/shortener.go package shortener import ( "context" "crypto/rand" "errors" "math/big" "net/http" "net/url" "time" "encore.dev" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/rlog" "encore.dev/storage/cache" "encore.dev/storage/sqldb" "encore.dev/storage/sqldb/sqlerr" ) var db = sqldb.NewDatabase("shortener", sqldb.DatabaseConfig{Migrations: "./migrations"}) var cluster = cache.NewCluster("shortener", cache.ClusterConfig{ EvictionPolicy: cache.AllKeysLRU, }) var targets = cache.NewStringKeyspace[string](cluster, cache.KeyspaceConfig{ KeyPattern: "link/:key", DefaultExpiry: cache.ExpireIn(time.Hour), }) type Click struct { Code string At time.Time } var Clicks = pubsub.NewTopic[*Click]("link-clicks", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func newCode(n int) (string, error) { b := make([]byte, n) for i := range b { idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet)))) if err != nil { return "", err } b[i] = alphabet[idx.Int64()] } return string(b), nil } type CreateParams struct { URL string OwnerID string } type CreateResponse struct { Code string } //encore:api private method=POST path=/links func Create(ctx context.Context, p *CreateParams) (*CreateResponse, error) { u, err := url.Parse(p.URL) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "only absolute http and https URLs are allowed"} } for attempt := 0; attempt < 5; attempt++ { code, err := newCode(7) if err != nil { return nil, err } _, err = db.Exec(ctx, `INSERT INTO links (code, target_url, owner_id) VALUES ($1, $2, $3)`, code, u.String(), p.OwnerID) if err == nil { return &CreateResponse{Code: code}, nil } if sqldb.ErrCode(err) != sqlerr.UniqueViolation { return nil, err } } return nil, errors.New("could not allocate a unique code") } func lookup(ctx context.Context, code string) (string, error) { if target, err := targets.Get(ctx, code); err == nil { if target == "" { return "", sqldb.ErrNoRows // the disabled marker written by Disable } return target, nil } else if !errors.Is(err, cache.Miss) { rlog.Warn("cache read failed", "err", err) } var target string err := db.QueryRow(ctx, `SELECT target_url FROM links WHERE code = $1 AND NOT disabled`, code).Scan(&target) if err != nil { return "", err } // SetIfNotExists never overwrites the disabled marker, even if Disable ran after the read above. if err := targets.SetIfNotExists(ctx, code, target); err != nil && !errors.Is(err, cache.KeyExists) { rlog.Warn("cache write failed", "err", err) } return target, nil } //encore:api public raw method=GET path=/r/:code func Redirect(w http.ResponseWriter, req *http.Request) { code := encore.CurrentRequest().PathParams.Get("code") target, err := lookup(req.Context(), code) if errors.Is(err, sqldb.ErrNoRows) { http.NotFound(w, req) return } else if err != nil { http.Error(w, "temporarily unavailable", http.StatusServiceUnavailable) return } if _, err := Clicks.Publish(req.Context(), &Click{Code: code, At: time.Now()}); err != nil { rlog.Warn("click not recorded", "code", code, "err", err) } http.Redirect(w, req, target, http.StatusFound) } type DisableParams struct { Code string } //encore:api private method=POST path=/links/disable func Disable(ctx context.Context, p *DisableParams) error { if _, err := db.Exec(ctx, `UPDATE links SET disabled = true WHERE code = $1`, p.Code); err != nil { return err } // An empty value marks the link disabled until the entry expires. return targets.Set(ctx, p.Code, "") } var _ = pubsub.NewSubscription(Clicks, "count-clicks", pubsub.SubscriptionConfig[*Click]{ Handler: func(ctx context.Context, c *Click) error { _, err := db.Exec(ctx, ` INSERT INTO link_clicks_daily (code, day, clicks) VALUES ($1, $2::date, 1) ON CONFLICT (code, day) DO UPDATE SET clicks = link_clicks_daily.clicks + 1`, c.Code, c.At.UTC().Format("2006-01-02")) return err }, })

encore run starts Postgres, a local cache and local Pub/Sub together, so you can create a link, open /r/<code> a few times and watch the cache miss, the cache hit and the click subscriber in the local trace. A failed cache read or publish only logs a warning, so Redis or the queue having a bad minute never breaks redirects. Delivery is at least once, so a redelivered event can count a click twice; for billing-grade counts, add an event ID and deduplicate in the subscriber.

The redirect path, the cache and the analytics queue are all in this one file, so an agent asked to add per-link expiry can update the table, the lookup query and the cache invalidation together and click through the result locally.

Best fit: Teams building link tracking, campaign links or a branded shortener who want links, cache and click analytics running in their own cloud account.

Frequently asked questions

How do URL shorteners generate short codes?

Most use either random base62 strings, retried on the rare collision, or a counter encoded in base62. Random codes do not reveal how many links exist and cannot be enumerated, and seven base62 characters give about 3.5 trillion combinations.

Should a URL shortener use a 301 or a 302 redirect?

Use 302 (or 307) when you count clicks or might change the destination. Browsers cache a 301 permanently, so repeat visits skip your server and never show up in analytics, and a changed target never reaches people who already followed the link.

How do you count clicks without slowing down redirects?

Publish a small click event to a queue and return the redirect right away. A subscriber aggregates the events into daily counts per link, so the redirect path does one cache read and one publish and never waits on an analytics write.

How do I build a URL shortener with Encore?

Store links in an Encore Postgres database, cache lookups in an Encore cache keyspace, serve redirects from a raw endpoint and publish click events to a Pub/Sub topic that a subscriber rolls up into daily counts. encore run starts the database, cache and queue locally.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders