linkly: The Source
linkly is deliberately small (three files, about 460 lines of Go) but written the way a production service should be: configuration from the environment, structured logs, metrics and traces from the first commit, timeouts on every dependency, a cache that can fail without taking the service down, and a clean shutdown. Everything the later sections build (probes, alerts, dashboards, the chart's settings) points back at something in this code, so this lesson goes through it carefully.
What it does
| Endpoint | Does | Status codes |
|---|---|---|
POST /links |
stores {"url": …} under a random 7-character code, or under {"code": …} if given |
201, 400 (bad input), 409 (code taken) |
GET /{code} |
redirects to the stored URL; Redis is a read-through cache in front of PostgreSQL | 302, 404 |
GET /healthz |
liveness: the process is running | 200 |
GET /readyz |
readiness: PostgreSQL answers (Redis is reported but optional) | 200, 503 |
GET /metrics |
Prometheus metrics | 200 |
Configuration, twelve-factor style, all from environment variables:
| Variable | Default | Meaning |
|---|---|---|
DATABASE_URL |
(required) | PostgreSQL connection string |
REDIS_ADDR |
localhost:6379 |
host:port, or a redis:// / rediss:// (TLS) URL |
LISTEN_ADDR |
:8080 |
where the HTTP server listens |
BASE_URL |
http://localhost:8080 |
prefix for the short_url in responses |
LOG_LEVEL |
info |
debug, info, warn, error |
CACHE_TTL |
1h |
how long Redis keeps a code |
SHUTDOWN_GRACE |
10s |
how long in-flight requests get after SIGTERM |
OTEL_TRACES_EXPORTER |
none |
console prints spans as JSON on stderr |
The source
The session writes the three files, creates the module, resolves the dependencies from the sandbox's offline module proxy, builds, vets and checks formatting. This exact block opens every later session that runs the app.
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}
linkly: The Source - 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
go mod tidy 2>/dev/null
echo "--- direct dependencies:"
go list -m -f '{{if not .Indirect}}{{.Path}} {{.Version}}{{end}}' all | grep -v '^github.com/acme/linkly'
go build -ldflags "-X main.version=1.4.0" -o linkly .
go vet ./... && echo "go vet: ok"
test -z "$(gofmt -l .)" && echo "gofmt: ok"
go version -m linkly | grep -E 'path|-ldflags|CGO_ENABLED'go: creating new go.mod: module github.com/acme/linkly
go: to add module requirements and sums:
go mod tidy
--- direct dependencies:
github.com/jackc/pgx/v5 v5.11.0
github.com/prometheus/client_golang v1.25.0
github.com/redis/go-redis/v9 v9.23.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0
go.opentelemetry.io/otel v1.47.0
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.47.0
go.opentelemetry.io/otel/sdk v1.47.0
go.opentelemetry.io/otel/trace v1.47.0
go vet: ok
gofmt: ok
path github.com/acme/linkly
build -ldflags="-X main.version=1.4.0"
build CGO_ENABLED=1
The eight direct requirements come from five projects (pgx, go-redis, the Prometheus client and OpenTelemetry's core and contrib repositories); go mod tidy added about twenty indirect ones, and go.sum pins every one of them by hash. CGO_ENABLED=1 in the build information matters in the next section: it means this binary may link against the system's C library. go version -m reads the build information Go embeds in every binary: you will use it again to check what CI actually built.
Walkthrough: main.go
Configuration fails fast. loadConfig reads every variable once at startup and returns an error for a missing DATABASE_URL or an unparsable duration. A service that starts with bad configuration and fails on the first request is much harder to debug than one that refuses to start: Kubernetes shows the crash loop and the log line right away.
Logs are JSON from the first line. slog.NewJSONHandler(os.Stdout, …) writes one JSON object per line to stdout, where the container runtime collects it (Structured Logging). Even a configuration error is logged through it, so log pipelines never see a half-structured stream.
run owns the lifecycle, in order:
signal.NotifyContextturns SIGINT and SIGTERM into a cancelled context. Kubernetes sends SIGTERM when it stops a pod.- The OpenTelemetry SDK is installed (
setupTracing). The default exporter isnone, which still creates trace IDs for the logs;consoleprints spans, and a production build swaps in the OTLP exporter (see Metrics, Logs & Traces). - A
pgxpoolconnection pool opens andmigratecreates the table if it doesn't exist. - The Redis client is created by
newRedis, with short timeouts and one retry: a read times out after 300 ms instead of go-redis's default 3 s, so a sick cache can't make every redirect slow. - The server starts with explicit timeouts (
ReadHeaderTimeoutprotects against slow-header attacks; the zero-valuehttp.Serverhas none). - On SIGTERM: mark the app as draining (readiness now fails), then
srv.Shutdownstops accepting connections and waits up toSHUTDOWN_GRACEfor in-flight requests.
redisLogger is a small adapter: go-redis logs connection problems with the standard log package on stderr, which would break a JSON log stream. redis.SetLogger sends those messages through slog instead.
Walkthrough: store.go
Store is an interface with three methods. Production uses pgStore on top of pgx; the unit tests use an in-memory fake. That single seam is what makes the handlers testable without a database (Unit & Integration Tests).
Duplicate codes are detected by the database, not by a "check, then insert" in Go: the PRIMARY KEY rejects the second insert with SQLSTATE 23505 (unique_violation), which Create maps to ErrExists. A check-then-insert has a race window between two pods; the constraint has none.
Walkthrough: app.go
Routing uses the Go 1.22+ ServeMux patterns: POST /links, GET /{code}, GET /healthz. The method is part of the pattern, so DELETE /links gets a 405 for free, and r.PathValue("code") reads the wildcard.
observe wraps the whole mux and does three jobs per request, all keyed by the route template: it counts the request in http_requests_total{route, code} and times it in the http_request_duration_seconds histogram, names the trace span (GET /{code}), and writes one log line. After the mux has matched, r.Pattern holds the pattern, so the label is /{code}, never /docs or /x7Kp2Qa. Requests that match nothing get route="unmatched". Raw paths as labels would create one time series per short link and eventually take Prometheus down (Labels & Cardinality).
createLink limits the body to 4 KiB (http.MaxBytesReader), validates the URL (absolute, http or https, at most 2048 bytes) and the optional custom code (^[A-Za-z0-9_-]{3,32}$). Random codes come from crypto/rand, so they can't be predicted: 7 characters from a 64-letter alphabet, so b&63 maps each random byte to a letter without modulo bias. A collision just draws again, up to three times.
redirect is the read-through cache:
GET /docs ─► Redis GET link:docs ──hit──► 302
│ miss (redis.Nil) or error
▼
PostgreSQL SELECT ──none──► 404
│
├─► Redis SET link:docs (TTL = CACHE_TTL) errors only logged
└─► 302Every lookup increments linkly_cache_requests_total{result="hit"|"miss"|"error"} and tags the trace span with linkly.cache. A Redis error is not a failed request: the code logs a warning, falls through to PostgreSQL and still answers. That decision (the cache is an optimisation, not a dependency) runs through the whole course: it is why /readyz doesn't fail without Redis, and why the cache alert in SLO Alerts & Dashboards is a ticket, not a page.
readyz answers 503 when draining or when PostgreSQL doesn't respond within a second; it reports Redis as "down" but stays ready. The response deliberately contains no error text: readiness endpoints are often reachable from outside, and connection errors leak hostnames. The details go to the log.
linkly_build_info is a gauge that is always 1, with the version and Go version as labels: the standard trick for "which version runs where" queries (Aggregation).
What is not here (yet)
Authentication for POST /links, rate limiting, link expiry, and a proper migration tool are missing on purpose. The Production Hardening lesson discusses each one and where it belongs (in the app, at the Gateway, or in a separate job). The Exercises add some of them.
Test yourself
Why does linkly label its HTTP metrics with r.Pattern ("/{code}") instead of the request path?
- Prometheus forbids slashes in labels
- Each distinct path would create new time series: one per short link
- The path is not available in Go
- It makes the histogram faster
How does linkly detect that a custom code is already taken?
- It SELECTs first and inserts if nothing was found
- It asks Redis
- The PRIMARY KEY rejects the insert with SQLSTATE 23505, mapped to ErrExists
- It keeps a map of codes in memory
What happens to a redirect when Redis is unreachable?
- linkly returns 503
- linkly returns 500
- The lookup is counted as a cache error, PostgreSQL answers, and the client still gets a 302
- The pod restarts