TExcelTAD
Home › DevOps Capstone: Ship a Production Service › Running linkly Locally

Running linkly Locally

Reading code is half of knowing it. In this lesson linkly runs for real against PostgreSQL and Redis, and you poke at every endpoint the way the cluster, the monitoring stack and its users will later: create links, follow redirects, read the metrics, break the cache, and stop the process with the same signal Kubernetes sends.

On your machine

The sandbox below starts PostgreSQL and Redis as plain processes. On your own machine the quickest equivalent is two containers (the Docker Compose course shows the same pattern with health checks):

bash
docker run -d --name linkly-pg -e POSTGRES_USER=linkly -e POSTGRES_PASSWORD=linkly -p 5432:5432 postgres:16
docker run -d --name linkly-redis -p 6379:6379 redis:7
export DATABASE_URL='postgres://linkly:linkly@localhost:5432/linkly?sslmode=disable'
export REDIS_ADDR=localhost:6379
go run .

The session

The first part recreates linkly (the same heredocs as linkly: The Source) and starts the two servers; DATABASE_URL points pgx at PostgreSQL's Unix socket in the session. Then linkly starts in the background with stdout and stderr going to linkly.log, and a bounded wait loop polls /healthz until the server answers:

bash · try it yourself
initdb -D pgdata -U linkly --auth=trust >/dev/null
mkdir -p pgrun
pg_ctl -D pgdata -o "-k /home/learner/pgrun -c listen_addresses=" -l pg.log start >/dev/null
createdb linkly
redis-server --port 6379 --bind 127.0.0.1 --daemonize yes --dir /home/learner
mkdir linkly && cd linkly
cat > main.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

// version is stamped at build time: go build -ldflags "-X main.version=1.4.0"
var version = "dev"

type config struct {
	Addr, DatabaseURL, RedisAddr, BaseURL, LogLevel, Traces string
	CacheTTL, ShutdownGrace                                 time.Duration
}

func env(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

// loadConfig reads the twelve-factor configuration from the environment.
func loadConfig() (config, error) {
	c := config{
		Addr:        env("LISTEN_ADDR", ":8080"),
		DatabaseURL: env("DATABASE_URL", ""),
		RedisAddr:   env("REDIS_ADDR", "localhost:6379"),
		BaseURL:     env("BASE_URL", "http://localhost:8080"),
		LogLevel:    env("LOG_LEVEL", "info"),
		Traces:      env("OTEL_TRACES_EXPORTER", "none"),
	}
	var err error
	if c.CacheTTL, err = time.ParseDuration(env("CACHE_TTL", "1h")); err != nil {
		return c, fmt.Errorf("CACHE_TTL: %w", err)
	}
	if c.ShutdownGrace, err = time.ParseDuration(env("SHUTDOWN_GRACE", "10s")); err != nil {
		return c, fmt.Errorf("SHUTDOWN_GRACE: %w", err)
	}
	if c.DatabaseURL == "" {
		return c, errors.New("DATABASE_URL is required")
	}
	return c, nil
}

func main() {
	cfg, err := loadConfig()
	var level slog.Level
	if err == nil {
		err = level.UnmarshalText([]byte(cfg.LogLevel))
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
	if err == nil {
		err = run(cfg, log)
	}
	if err != nil {
		log.Error("linkly stopped", "err", err)
		os.Exit(1)
	}
}

func run(cfg config, log *slog.Logger) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	shutdownTracing, err := setupTracing(cfg.Traces, os.Stderr)
	if err != nil {
		return err
	}
	defer shutdownTracing(context.Background())

	db, err := pgxpool.New(ctx, cfg.DatabaseURL)
	if err != nil {
		return fmt.Errorf("database: %w", err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		return fmt.Errorf("migrate: %w", err)
	}
	redis.SetLogger(redisLogger{log})
	rdb := newRedis(cfg.RedisAddr)
	defer rdb.Close()

	app := newApp(pgStore{db}, rdb, cfg, log, prometheus.DefaultRegisterer, prometheus.DefaultGatherer)
	srv := &http.Server{Addr: cfg.Addr, Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
	errc := make(chan error, 1)
	go func() {
		log.Info("listening", "addr", cfg.Addr, "version", version)
		errc <- srv.ListenAndServe()
	}()
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	log.Info("shutting down", "grace", cfg.ShutdownGrace.String())
	app.draining.Store(true) // /readyz now answers 503
	sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return err
	}
	log.Info("stopped")
	return nil
}

// newRedis takes host:port or a redis:// or rediss:// (TLS) URL. The short timeouts keep
// the cache from slowing requests down when Redis is unwell.
func newRedis(addr string) *redis.Client {
	opt, err := redis.ParseURL(addr)
	if err != nil {
		opt = &redis.Options{Addr: addr}
	}
	opt.DialTimeout, opt.DialerRetries, opt.MaxRetries = time.Second, 1, 1
	opt.ReadTimeout, opt.WriteTimeout = 300*time.Millisecond, 300*time.Millisecond
	return redis.NewClient(opt)
}

// redisLogger sends go-redis's own messages to the JSON log instead of plain stderr.
type redisLogger struct{ log *slog.Logger }

func (r redisLogger) Printf(ctx context.Context, format string, v ...any) {
	r.log.WarnContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis")
}

// setupTracing installs the OpenTelemetry SDK; "console" writes spans as JSON to w.
func setupTracing(exporter string, w io.Writer) (func(context.Context) error, error) {
	res := resource.NewSchemaless(semconv.ServiceName("linkly"), semconv.ServiceVersion(version))
	opts := []sdktrace.TracerProviderOption{sdktrace.WithResource(res)}
	switch exporter {
	case "none":
	case "console":
		exp, err := stdouttrace.New(stdouttrace.WithWriter(w))
		if err != nil {
			return nil, err
		}
		opts = append(opts, sdktrace.WithSyncer(exp))
	default:
		return nil, fmt.Errorf("OTEL_TRACES_EXPORTER=%q: this build supports none and console", exporter)
	}
	tp := sdktrace.NewTracerProvider(opts...)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp.Shutdown, nil
}
EOF
cat > app.go <<'EOF'
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/url"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/attribute"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
)

type App struct {
	store    Store
	cache    *redis.Client
	ttl      time.Duration
	baseURL  string
	log      *slog.Logger
	newCode  func() string
	draining atomic.Bool
	metrics  http.Handler

	requests  *prometheus.CounterVec
	duration  *prometheus.HistogramVec
	cacheReqs *prometheus.CounterVec
	created   prometheus.Counter
}

func newApp(store Store, cache *redis.Client, cfg config, log *slog.Logger,
	reg prometheus.Registerer, g prometheus.Gatherer) *App {
	f := promauto.With(reg)
	a := &App{store: store, cache: cache, ttl: cfg.CacheTTL, baseURL: cfg.BaseURL, log: log,
		newCode: randomCode, metrics: promhttp.HandlerFor(g, promhttp.HandlerOpts{}),
		requests: f.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",
			Help: "HTTP requests by route and status code."}, []string{"route", "code"}),
		duration: f.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds",
			Help:    "Time to handle a request, by route.",
			Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5}}, []string{"route"}),
		cacheReqs: f.NewCounterVec(prometheus.CounterOpts{Name: "linkly_cache_requests_total",
			Help: "Redis lookups for redirects, by result (hit, miss, error)."}, []string{"result"}),
		created: f.NewCounter(prometheus.CounterOpts{Name: "linkly_links_created_total",
			Help: "Short links created."}),
	}
	f.NewGaugeVec(prometheus.GaugeOpts{Name: "linkly_build_info", Help: "Always 1; labels describe the build."},
		[]string{"version", "goversion"}).WithLabelValues(version, runtime.Version()).Set(1)
	return a
}

func (a *App) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /{code}", a.redirect)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) })
	mux.HandleFunc("GET /readyz", a.readyz)
	mux.Handle("GET /metrics", a.metrics)
	notProbe := func(r *http.Request) bool { return !quiet(r.URL.Path) }
	return otelhttp.NewHandler(a.observe(mux), "linkly", otelhttp.WithFilter(notProbe))
}

func quiet(route string) bool {
	return route == "/healthz" || route == "/readyz" || route == "/metrics"
}

// observe records metrics, names the trace span and logs every request, all by route template.
func (a *App) observe(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		route := "unmatched" // r.Pattern is "GET /{code}" once the mux has matched, "" otherwise
		if _, p, ok := strings.Cut(r.Pattern, " "); ok {
			route = p
		}
		a.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
		a.duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
		span := trace.SpanFromContext(r.Context())
		span.SetName(r.Method + " " + route)
		span.SetAttributes(semconv.HTTPRoute(route))
		level := slog.LevelInfo
		if quiet(route) {
			level = slog.LevelDebug
		} else if rec.status >= 500 {
			level = slog.LevelError
		}
		a.log.LogAttrs(r.Context(), level, "request", slog.String("method", r.Method),
			slog.String("route", route), slog.Int("status", rec.status),
			slog.String("trace_id", span.SpanContext().TraceID().String()))
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

var codeRE = regexp.MustCompile(`^[A-Za-z0-9_-]{3,32}

  
    
    
    Running linkly Locally - DevOps Capstone: Ship a Production Service · ExcelTAD
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    )

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

// randomCode returns 7 random characters from a 64-letter alphabet (b&63 has no modulo bias).
// They come from crypto/rand, so codes can't be predicted.
func randomCode() string {
	b := make([]byte, 7)
	if _, err := rand.Read(b); err != nil {
		panic(err) // the OS random source failed: nothing sensible is left to do
	}
	for i := range b {
		b[i] = alphabet[b[i]&63]
	}
	return string(b)
}

func validateURL(raw string) error {
	if len(raw) > 2048 {
		return errors.New("url is longer than 2048 bytes")
	}
	u, err := url.Parse(raw)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return errors.New("url must be an absolute http or https URL")
	}
	return nil
}

func (a *App) createLink(w http.ResponseWriter, r *http.Request) {
	var req struct{ URL, Code string }
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": `body must be JSON like {"url": "https://..."}`})
		return
	}
	if err := validateURL(req.URL); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	if req.Code != "" && !codeRE.MatchString(req.Code) {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "code must be 3-32 of A-Z a-z 0-9 _ -"})
		return
	}
	code := req.Code
	for attempt := 1; ; attempt++ {
		if req.Code == "" {
			code = a.newCode()
		}
		err := a.store.Create(r.Context(), code, req.URL)
		if err == nil {
			break
		}
		if errors.Is(err, ErrExists) && req.Code == "" && attempt < 3 {
			continue // a random code collided: draw again
		}
		if errors.Is(err, ErrExists) {
			writeJSON(w, http.StatusConflict, map[string]string{"error": "code already taken"})
			return
		}
		a.fail(w, r, err)
		return
	}
	a.created.Inc()
	writeJSON(w, http.StatusCreated, map[string]string{"code": code, "short_url": a.baseURL + "/" + code, "url": req.URL})
}

// redirect reads through the cache: Redis first, PostgreSQL on a miss (or when Redis is down).
func (a *App) redirect(w http.ResponseWriter, r *http.Request) {
	code, ctx := r.PathValue("code"), r.Context()
	if !codeRE.MatchString(code) {
		http.NotFound(w, r)
		return
	}
	key := "link:" + code
	target, err := a.cache.Get(ctx, key).Result()
	result := "hit"
	if errors.Is(err, redis.Nil) {
		result = "miss"
	} else if err != nil {
		result = "error"
		a.log.WarnContext(ctx, "cache read failed", "err", err)
	}
	a.cacheReqs.WithLabelValues(result).Inc()
	trace.SpanFromContext(ctx).SetAttributes(attribute.String("linkly.cache", result))
	if result != "hit" {
		if target, err = a.store.Get(ctx, code); errors.Is(err, ErrNotFound) {
			http.NotFound(w, r)
			return
		} else if err != nil {
			a.fail(w, r, err)
			return
		}
		if err := a.cache.Set(ctx, key, target, a.ttl).Err(); err != nil {
			a.log.WarnContext(ctx, "cache write failed", "err", err)
		}
	}
	http.Redirect(w, r, target, http.StatusFound)
}

// readyz fails only on the database: without Redis, linkly is slower but still correct.
func (a *App) readyz(w http.ResponseWriter, r *http.Request) {
	if a.draining.Load() {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "draining"})
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), time.Second)
	defer cancel()
	res, code := map[string]string{"status": "ready", "database": "up", "cache": "up"}, http.StatusOK
	if err := a.store.Ping(ctx); err != nil {
		a.log.WarnContext(ctx, "readiness: database", "err", err)
		res["status"], res["database"], code = "unavailable", "down", http.StatusServiceUnavailable
	}
	if err := a.cache.Ping(ctx).Err(); err != nil {
		a.log.WarnContext(ctx, "readiness: cache", "err", err)
		res["cache"] = "down"
	}
	writeJSON(w, code, res)
}

func (a *App) fail(w http.ResponseWriter, r *http.Request, err error) {
	a.log.ErrorContext(r.Context(), "request failed", "err", err)
	writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(v)
}
EOF
cat > store.go <<'EOF'
package main

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

var (
	ErrNotFound = errors.New("link not found")
	ErrExists   = errors.New("code already exists")
)

// Store is where links live; pgStore in production, an in-memory fake in unit tests.
type Store interface {
	Create(ctx context.Context, code, url string) error
	Get(ctx context.Context, code string) (string, error)
	Ping(ctx context.Context) error
}

const schema = `CREATE TABLE IF NOT EXISTS links (
  code       text PRIMARY KEY,
  url        text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now())`

func migrate(ctx context.Context, db *pgxpool.Pool) error {
	_, err := db.Exec(ctx, schema)
	return err
}

type pgStore struct{ db *pgxpool.Pool }

func (s pgStore) Create(ctx context.Context, code, url string) error {
	_, err := s.db.Exec(ctx, `INSERT INTO links (code, url) VALUES ($1, $2)`, code, url)
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
		return ErrExists
	}
	return err
}

func (s pgStore) Get(ctx context.Context, code string) (string, error) {
	var url string
	err := s.db.QueryRow(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&url)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", ErrNotFound
	}
	return url, err
}

func (s pgStore) Ping(ctx context.Context) error { return s.db.Ping(ctx) }
EOF
go mod init github.com/acme/linkly >/dev/null 2>&1 && go mod tidy 2>/dev/null
go build -ldflags "-X main.version=1.4.0" -o linkly . && cd ..

echo "== 1. configuration fails fast"
./linkly/linkly; echo "exit code: $?"

echo "== 2. start"
export DATABASE_URL="postgres:///linkly?host=/home/learner/pgrun" REDIS_ADDR=127.0.0.1:6379
./linkly/linkly > linkly.log 2>&1 &
for i in $(seq 50); do curl -sf localhost:8080/healthz >/dev/null && break; sleep 0.1; done
curl -s localhost:8080/readyz

echo "== 3. create links"
curl -s -X POST localhost:8080/links -d '{"url": "https://go.dev/doc/", "code": "docs"}'
curl -s -X POST localhost:8080/links -d '{"url": "https://example.com/a/long/path?q=1"}' | jq -c '{code_length: (.code | length), url}'
curl -s -X POST localhost:8080/links -d '{"url": "https://example.org", "code": "docs"}'
curl -s -X POST localhost:8080/links -d '{"url": "javascript:alert(1)"}'

echo "== 4. follow redirects (miss, then hit)"
for i in 1 2; do curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' localhost:8080/docs; done
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/unknown

echo "== 5. look behind the API"
psql -c "SELECT code, url FROM links WHERE code = 'docs'"
psql -tAc "SELECT count(*) || ' links stored' FROM links"
echo "redis TTL of link:docs: $(redis-cli ttl link:docs)s"

echo "== 6. metrics"
curl -s localhost:8080/metrics | grep -E '^(http_requests_total|linkly_)'
== 1. configuration fails fast
{"time":"2026-10-28T04:26:59.668559626Z","level":"ERROR","msg":"linkly stopped","err":"DATABASE_URL is required"}
exit code: 1
== 2. start
{"cache":"up","database":"up","status":"ready"}
== 3. create links
{"code":"docs","short_url":"http://localhost:8080/docs","url":"https://go.dev/doc/"}
{"code_length":7,"url":"https://example.com/a/long/path?q=1"}
{"error":"code already taken"}
{"error":"url must be an absolute http or https URL"}
== 4. follow redirects (miss, then hit)
302 -> https://go.dev/doc/
302 -> https://go.dev/doc/
404
== 5. look behind the API
 code |         url
------+---------------------
 docs | https://go.dev/doc/
(1 row)

2 links stored
redis TTL of link:docs: 3600s
== 6. metrics
http_requests_total{code="200",route="/healthz"} 1
http_requests_total{code="200",route="/readyz"} 1
http_requests_total{code="201",route="/links"} 2
http_requests_total{code="302",route="/{code}"} 2
http_requests_total{code="400",route="/links"} 1
http_requests_total{code="404",route="/{code}"} 1
http_requests_total{code="409",route="/links"} 1
linkly_build_info{goversion="go1.27.3",version="1.4.0"} 1
linkly_cache_requests_total{result="hit"} 1
linkly_cache_requests_total{result="miss"} 2
linkly_links_created_total 2

Reading the output top to bottom:

  1. Without DATABASE_URL, linkly logs one JSON error line and exits with status 1 before opening a port. In Kubernetes this shows up as CrashLoopBackOff with the reason in kubectl logs: much better than a pod that runs and fails every request.
  2. /readyz reports both dependencies up. The keys come out sorted because Go's JSON encoder sorts map keys.
  3. The custom code docs is stored; the random code is 7 characters long (its value changes every run, so the session prints only its length). The second docs gets 409, and a javascript: URL gets 400: a link shortener that redirects to arbitrary schemes is an attack tool.
  4. Both redirects return 302. The first was a cache miss (read from PostgreSQL, then written to Redis), the second a hit: see linkly_cache_requests_total in part 6. The unknown code is a 404 and counts as a second miss: codes that don't exist are never cached, so every request for one reaches PostgreSQL (the Field Notes discuss when that matters).
  5. The row is in PostgreSQL, and Redis holds the key with the one-hour TTL (CACHE_TTL).
  6. The metrics use route templates (/{code}, /links), never paths. /healthz and /readyz are counted too: probes are traffic, and a dashboard that ignores them hides a crashing pod's health checks. linkly_build_info carries the version stamped with -ldflags.

Breaking the cache, then stopping

Now the session shuts Redis down while linkly keeps running, follows a link, checks readiness, then sends SIGTERM, the signal the kubelet sends when it stops a pod, and prints the log the process wrote. jq drops the timestamp and trace ID fields to keep the output short:

bash · try it yourself
initdb -D pgdata -U linkly --auth=trust >/dev/null
mkdir -p pgrun
pg_ctl -D pgdata -o "-k /home/learner/pgrun -c listen_addresses=" -l pg.log start >/dev/null
createdb linkly
redis-server --port 6379 --bind 127.0.0.1 --daemonize yes --dir /home/learner
mkdir linkly && cd linkly
cat > main.go <<'EOF'
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

// version is stamped at build time: go build -ldflags "-X main.version=1.4.0"
var version = "dev"

type config struct {
	Addr, DatabaseURL, RedisAddr, BaseURL, LogLevel, Traces string
	CacheTTL, ShutdownGrace                                 time.Duration
}

func env(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

// loadConfig reads the twelve-factor configuration from the environment.
func loadConfig() (config, error) {
	c := config{
		Addr:        env("LISTEN_ADDR", ":8080"),
		DatabaseURL: env("DATABASE_URL", ""),
		RedisAddr:   env("REDIS_ADDR", "localhost:6379"),
		BaseURL:     env("BASE_URL", "http://localhost:8080"),
		LogLevel:    env("LOG_LEVEL", "info"),
		Traces:      env("OTEL_TRACES_EXPORTER", "none"),
	}
	var err error
	if c.CacheTTL, err = time.ParseDuration(env("CACHE_TTL", "1h")); err != nil {
		return c, fmt.Errorf("CACHE_TTL: %w", err)
	}
	if c.ShutdownGrace, err = time.ParseDuration(env("SHUTDOWN_GRACE", "10s")); err != nil {
		return c, fmt.Errorf("SHUTDOWN_GRACE: %w", err)
	}
	if c.DatabaseURL == "" {
		return c, errors.New("DATABASE_URL is required")
	}
	return c, nil
}

func main() {
	cfg, err := loadConfig()
	var level slog.Level
	if err == nil {
		err = level.UnmarshalText([]byte(cfg.LogLevel))
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
	if err == nil {
		err = run(cfg, log)
	}
	if err != nil {
		log.Error("linkly stopped", "err", err)
		os.Exit(1)
	}
}

func run(cfg config, log *slog.Logger) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	shutdownTracing, err := setupTracing(cfg.Traces, os.Stderr)
	if err != nil {
		return err
	}
	defer shutdownTracing(context.Background())

	db, err := pgxpool.New(ctx, cfg.DatabaseURL)
	if err != nil {
		return fmt.Errorf("database: %w", err)
	}
	defer db.Close()
	if err := migrate(ctx, db); err != nil {
		return fmt.Errorf("migrate: %w", err)
	}
	redis.SetLogger(redisLogger{log})
	rdb := newRedis(cfg.RedisAddr)
	defer rdb.Close()

	app := newApp(pgStore{db}, rdb, cfg, log, prometheus.DefaultRegisterer, prometheus.DefaultGatherer)
	srv := &http.Server{Addr: cfg.Addr, Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
	errc := make(chan error, 1)
	go func() {
		log.Info("listening", "addr", cfg.Addr, "version", version)
		errc <- srv.ListenAndServe()
	}()
	select {
	case err := <-errc:
		return err
	case <-ctx.Done():
	}
	log.Info("shutting down", "grace", cfg.ShutdownGrace.String())
	app.draining.Store(true) // /readyz now answers 503
	sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		return err
	}
	log.Info("stopped")
	return nil
}

// newRedis takes host:port or a redis:// or rediss:// (TLS) URL. The short timeouts keep
// the cache from slowing requests down when Redis is unwell.
func newRedis(addr string) *redis.Client {
	opt, err := redis.ParseURL(addr)
	if err != nil {
		opt = &redis.Options{Addr: addr}
	}
	opt.DialTimeout, opt.DialerRetries, opt.MaxRetries = time.Second, 1, 1
	opt.ReadTimeout, opt.WriteTimeout = 300*time.Millisecond, 300*time.Millisecond
	return redis.NewClient(opt)
}

// redisLogger sends go-redis's own messages to the JSON log instead of plain stderr.
type redisLogger struct{ log *slog.Logger }

func (r redisLogger) Printf(ctx context.Context, format string, v ...any) {
	r.log.WarnContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis")
}

// setupTracing installs the OpenTelemetry SDK; "console" writes spans as JSON to w.
func setupTracing(exporter string, w io.Writer) (func(context.Context) error, error) {
	res := resource.NewSchemaless(semconv.ServiceName("linkly"), semconv.ServiceVersion(version))
	opts := []sdktrace.TracerProviderOption{sdktrace.WithResource(res)}
	switch exporter {
	case "none":
	case "console":
		exp, err := stdouttrace.New(stdouttrace.WithWriter(w))
		if err != nil {
			return nil, err
		}
		opts = append(opts, sdktrace.WithSyncer(exp))
	default:
		return nil, fmt.Errorf("OTEL_TRACES_EXPORTER=%q: this build supports none and console", exporter)
	}
	tp := sdktrace.NewTracerProvider(opts...)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp.Shutdown, nil
}
EOF
cat > app.go <<'EOF'
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/url"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/redis/go-redis/v9"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/attribute"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
)

type App struct {
	store    Store
	cache    *redis.Client
	ttl      time.Duration
	baseURL  string
	log      *slog.Logger
	newCode  func() string
	draining atomic.Bool
	metrics  http.Handler

	requests  *prometheus.CounterVec
	duration  *prometheus.HistogramVec
	cacheReqs *prometheus.CounterVec
	created   prometheus.Counter
}

func newApp(store Store, cache *redis.Client, cfg config, log *slog.Logger,
	reg prometheus.Registerer, g prometheus.Gatherer) *App {
	f := promauto.With(reg)
	a := &App{store: store, cache: cache, ttl: cfg.CacheTTL, baseURL: cfg.BaseURL, log: log,
		newCode: randomCode, metrics: promhttp.HandlerFor(g, promhttp.HandlerOpts{}),
		requests: f.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",
			Help: "HTTP requests by route and status code."}, []string{"route", "code"}),
		duration: f.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds",
			Help:    "Time to handle a request, by route.",
			Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5}}, []string{"route"}),
		cacheReqs: f.NewCounterVec(prometheus.CounterOpts{Name: "linkly_cache_requests_total",
			Help: "Redis lookups for redirects, by result (hit, miss, error)."}, []string{"result"}),
		created: f.NewCounter(prometheus.CounterOpts{Name: "linkly_links_created_total",
			Help: "Short links created."}),
	}
	f.NewGaugeVec(prometheus.GaugeOpts{Name: "linkly_build_info", Help: "Always 1; labels describe the build."},
		[]string{"version", "goversion"}).WithLabelValues(version, runtime.Version()).Set(1)
	return a
}

func (a *App) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /links", a.createLink)
	mux.HandleFunc("GET /{code}", a.redirect)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) })
	mux.HandleFunc("GET /readyz", a.readyz)
	mux.Handle("GET /metrics", a.metrics)
	notProbe := func(r *http.Request) bool { return !quiet(r.URL.Path) }
	return otelhttp.NewHandler(a.observe(mux), "linkly", otelhttp.WithFilter(notProbe))
}

func quiet(route string) bool {
	return route == "/healthz" || route == "/readyz" || route == "/metrics"
}

// observe records metrics, names the trace span and logs every request, all by route template.
func (a *App) observe(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		route := "unmatched" // r.Pattern is "GET /{code}" once the mux has matched, "" otherwise
		if _, p, ok := strings.Cut(r.Pattern, " "); ok {
			route = p
		}
		a.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
		a.duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
		span := trace.SpanFromContext(r.Context())
		span.SetName(r.Method + " " + route)
		span.SetAttributes(semconv.HTTPRoute(route))
		level := slog.LevelInfo
		if quiet(route) {
			level = slog.LevelDebug
		} else if rec.status >= 500 {
			level = slog.LevelError
		}
		a.log.LogAttrs(r.Context(), level, "request", slog.String("method", r.Method),
			slog.String("route", route), slog.Int("status", rec.status),
			slog.String("trace_id", span.SpanContext().TraceID().String()))
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

var codeRE = regexp.MustCompile(`^[A-Za-z0-9_-]{3,32}

  
    
    
    Running linkly Locally - DevOps Capstone: Ship a Production Service · ExcelTAD
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    )

const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

// randomCode returns 7 random characters from a 64-letter alphabet (b&63 has no modulo bias).
// They come from crypto/rand, so codes can't be predicted.
func randomCode() string {
	b := make([]byte, 7)
	if _, err := rand.Read(b); err != nil {
		panic(err) // the OS random source failed: nothing sensible is left to do
	}
	for i := range b {
		b[i] = alphabet[b[i]&63]
	}
	return string(b)
}

func validateURL(raw string) error {
	if len(raw) > 2048 {
		return errors.New("url is longer than 2048 bytes")
	}
	u, err := url.Parse(raw)
	if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return errors.New("url must be an absolute http or https URL")
	}
	return nil
}

func (a *App) createLink(w http.ResponseWriter, r *http.Request) {
	var req struct{ URL, Code string }
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": `body must be JSON like {"url": "https://..."}`})
		return
	}
	if err := validateURL(req.URL); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}
	if req.Code != "" && !codeRE.MatchString(req.Code) {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "code must be 3-32 of A-Z a-z 0-9 _ -"})
		return
	}
	code := req.Code
	for attempt := 1; ; attempt++ {
		if req.Code == "" {
			code = a.newCode()
		}
		err := a.store.Create(r.Context(), code, req.URL)
		if err == nil {
			break
		}
		if errors.Is(err, ErrExists) && req.Code == "" && attempt < 3 {
			continue // a random code collided: draw again
		}
		if errors.Is(err, ErrExists) {
			writeJSON(w, http.StatusConflict, map[string]string{"error": "code already taken"})
			return
		}
		a.fail(w, r, err)
		return
	}
	a.created.Inc()
	writeJSON(w, http.StatusCreated, map[string]string{"code": code, "short_url": a.baseURL + "/" + code, "url": req.URL})
}

// redirect reads through the cache: Redis first, PostgreSQL on a miss (or when Redis is down).
func (a *App) redirect(w http.ResponseWriter, r *http.Request) {
	code, ctx := r.PathValue("code"), r.Context()
	if !codeRE.MatchString(code) {
		http.NotFound(w, r)
		return
	}
	key := "link:" + code
	target, err := a.cache.Get(ctx, key).Result()
	result := "hit"
	if errors.Is(err, redis.Nil) {
		result = "miss"
	} else if err != nil {
		result = "error"
		a.log.WarnContext(ctx, "cache read failed", "err", err)
	}
	a.cacheReqs.WithLabelValues(result).Inc()
	trace.SpanFromContext(ctx).SetAttributes(attribute.String("linkly.cache", result))
	if result != "hit" {
		if target, err = a.store.Get(ctx, code); errors.Is(err, ErrNotFound) {
			http.NotFound(w, r)
			return
		} else if err != nil {
			a.fail(w, r, err)
			return
		}
		if err := a.cache.Set(ctx, key, target, a.ttl).Err(); err != nil {
			a.log.WarnContext(ctx, "cache write failed", "err", err)
		}
	}
	http.Redirect(w, r, target, http.StatusFound)
}

// readyz fails only on the database: without Redis, linkly is slower but still correct.
func (a *App) readyz(w http.ResponseWriter, r *http.Request) {
	if a.draining.Load() {
		writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "draining"})
		return
	}
	ctx, cancel := context.WithTimeout(r.Context(), time.Second)
	defer cancel()
	res, code := map[string]string{"status": "ready", "database": "up", "cache": "up"}, http.StatusOK
	if err := a.store.Ping(ctx); err != nil {
		a.log.WarnContext(ctx, "readiness: database", "err", err)
		res["status"], res["database"], code = "unavailable", "down", http.StatusServiceUnavailable
	}
	if err := a.cache.Ping(ctx).Err(); err != nil {
		a.log.WarnContext(ctx, "readiness: cache", "err", err)
		res["cache"] = "down"
	}
	writeJSON(w, code, res)
}

func (a *App) fail(w http.ResponseWriter, r *http.Request, err error) {
	a.log.ErrorContext(r.Context(), "request failed", "err", err)
	writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}

func writeJSON(w http.ResponseWriter, code int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(v)
}
EOF
cat > store.go <<'EOF'
package main

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

var (
	ErrNotFound = errors.New("link not found")
	ErrExists   = errors.New("code already exists")
)

// Store is where links live; pgStore in production, an in-memory fake in unit tests.
type Store interface {
	Create(ctx context.Context, code, url string) error
	Get(ctx context.Context, code string) (string, error)
	Ping(ctx context.Context) error
}

const schema = `CREATE TABLE IF NOT EXISTS links (
  code       text PRIMARY KEY,
  url        text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now())`

func migrate(ctx context.Context, db *pgxpool.Pool) error {
	_, err := db.Exec(ctx, schema)
	return err
}

type pgStore struct{ db *pgxpool.Pool }

func (s pgStore) Create(ctx context.Context, code, url string) error {
	_, err := s.db.Exec(ctx, `INSERT INTO links (code, url) VALUES ($1, $2)`, code, url)
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
		return ErrExists
	}
	return err
}

func (s pgStore) Get(ctx context.Context, code string) (string, error) {
	var url string
	err := s.db.QueryRow(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&url)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", ErrNotFound
	}
	return url, err
}

func (s pgStore) Ping(ctx context.Context) error { return s.db.Ping(ctx) }
EOF
go mod init github.com/acme/linkly >/dev/null 2>&1 && go mod tidy 2>/dev/null
go build -ldflags "-X main.version=1.4.0" -o linkly . && cd ..
export DATABASE_URL="postgres:///linkly?host=/home/learner/pgrun" REDIS_ADDR=127.0.0.1:6379
./linkly/linkly > linkly.log 2>&1 &
for i in $(seq 50); do curl -sf localhost:8080/healthz >/dev/null && break; sleep 0.1; done
curl -s -o /dev/null -X POST localhost:8080/links -d '{"url": "https://go.dev/doc/", "code": "docs"}'

redis-cli shutdown nosave
echo "redirect without Redis: $(curl -s -o /dev/null -w '%{http_code}' localhost:8080/docs)"
echo "readiness without Redis: $(curl -s localhost:8080/readyz)"
curl -s localhost:8080/metrics | grep 'linkly_cache_requests_total{'

kill -TERM %1; wait %1; echo "linkly exit code: $?"
echo "--- linkly.log (go-redis lines counted, not shown):"
jq -c 'select(.component != "go-redis") | del(.time, .trace_id)' linkly.log
echo "go-redis warnings: $(grep -c '"component":"go-redis"' linkly.log)"
redirect without Redis: 302
readiness without Redis: {"cache":"down","database":"up","status":"ready"}
linkly_cache_requests_total{result="error"} 1
linkly exit code: 0
--- linkly.log (go-redis lines counted, not shown):
{"level":"INFO","msg":"listening","addr":":8080","version":"1.4.0"}
{"level":"INFO","msg":"request","method":"POST","route":"/links","status":201}
{"level":"WARN","msg":"cache read failed","err":"dial tcp 127.0.0.1:6379: connect: connection refused"}
{"level":"WARN","msg":"cache write failed","err":"dial tcp 127.0.0.1:6379: connect: connection refused"}
{"level":"INFO","msg":"request","method":"GET","route":"/{code}","status":302}
{"level":"WARN","msg":"readiness: cache","err":"dial tcp 127.0.0.1:6379: connect: connection refused"}
{"level":"INFO","msg":"shutting down","grace":"10s"}
{"level":"INFO","msg":"stopped"}
go-redis warnings: 6

What happened:

  • With Redis gone, the redirect still returned 302. The cache lookup failed fast (the 300 ms timeouts and single retry from newRedis), was counted as result="error", and PostgreSQL answered. The attempt to re-cache the link failed too and was only logged.
  • /readyz still says "status":"ready" with "cache":"down". If readiness failed whenever Redis did, a Redis restart would pull every linkly pod out of the Service at once, turning a slower service into an outage.
  • kill -TERM made linkly log shutting down, finish in-flight work, log stopped and exit with 0. A process that exits non-zero on SIGTERM looks like a crash to Kubernetes and to your alerts.
  • The go-redis lines are now JSON warnings with "component":"go-redis" (thanks to redisLogger), so the log stays machine-readable. There are several per failed operation (one per attempt); the Field Notes come back to noisy dependency logs.

Note: The trace_id field that jq removed links each request log line to its trace. Metrics, Logs & Traces uses it.

Test yourself

Why does linkly exit immediately when DATABASE_URL is missing, instead of starting and failing requests?

  1. Go requires it
  2. A failed start shows up at once (CrashLoopBackOff plus the log line), instead of a running pod that fails every request
  3. To save memory
  4. Kubernetes sets DATABASE_URL automatically

Redis was shut down. What did /readyz report, and why?

  1. 503, because a dependency is down
  2. 200 with cache "down": without Redis linkly is slower but still correct, and failing readiness would remove every pod at once
  3. It timed out
  4. 200 with cache "up"

Why does it matter that linkly exits with status 0 after SIGTERM?

  1. It doesn't matter
  2. Kubernetes and alerting treat a non-zero exit during a normal stop as a crash
  3. Exit codes are only used by Docker
  4. It makes the image smaller