TExcelTAD

Field Notes

Things that go wrong when a service like linkly meets production, collected from real incidents and reviews. Each note is short; the linked lessons have the context.

Cache: misses are where the load is

Unknown codes are never cached. linkly caches successful lookups only, so every request for a code that doesn't exist goes to PostgreSQL. A link shortener on the public internet gets a steady stream of guessed and scanned codes. The model sends a mix of real and random codes and counts database queries with and without a short negative cache (remembering "not found" for a minute):

python · try it yourself
import random

random.seed(7)
known = {f"k{i}" for i in range(50)}
requests = [random.choice(sorted(known)) if random.random() < 0.6 else f"scan{random.randrange(400)}"
            for _ in range(5000)]

def db_queries(negative_cache):
    cache, queries = {}, 0
    for code in requests:
        if code in cache:
            continue                              # hit (positive or negative)
        queries += 1
        if code in known or negative_cache:
            cache[code] = code in known           # store "found" or, optionally, "not found"
    return queries

print(f"requests: {len(requests)}, unknown: {sum(c not in known for c in requests)}")
print(f"database queries, positive cache only:   {db_queries(False)}")
print(f"database queries, with a negative cache: {db_queries(True)}")
requests: 5000, unknown: 1966
database queries, positive cache only:   2016
database queries, with a negative cache: 444

With only positive caching, about 40% of the traffic in this mix reaches the database. Negative entries need a short TTL (a code may be created a second later) and a size bound, or a scanner fills Redis with junk keys; the allkeys-lru policy on the capstone's Redis evicts them first. Rate limiting at the Gateway is the other half of the answer.

Hot keys expire all at once. When a popular code's cache entry expires, every concurrent request misses together and all of them query PostgreSQL (a cache stampede). In Go, golang.org/x/sync/singleflight collapses concurrent loads of the same key into one; the module is already in linkly's go.sum as a dependency of pgx's pool. Adding a little random jitter to CACHE_TTL spreads expiries of keys written at the same time.

Readiness, liveness, startup

  • Readiness fails only for hard dependencies. A Redis restart must not empty the Service (Running linkly).
  • Liveness depends on nothing. A liveness probe that checks the database restarts every pod during a database outage, adding cold starts to an incident.
  • No startupProbe is needed for a Go binary that starts in milliseconds; add one only if startup does real work (cache warm-up, large migrations), so liveness doesn't kill a pod that is still starting.

Shutdown

  • preStop: sleep needs Kubernetes 1.30 or later (the sleep action was beta from 1.30 and is enabled by default there). On older clusters, distroless has no sleep binary for an exec hook; instead, make the app wait itself: on SIGTERM, flip readiness to failing, sleep a few seconds, then call Shutdown.
  • Exit 0 on SIGTERM. http.ErrServerClosed from ListenAndServe after Shutdown is not an error; linkly's run returns before it can be mistaken for one.
  • Long requests need a longer grace period, not a longer SHUTDOWN_GRACE alone: the kubelet's SIGKILL at terminationGracePeriodSeconds wins.

Connections

The pool size claim from Production Hardening, checked against the pgx module itself. (The sandbox's offline proxy holds the module versions linkly's dependency graph uses, so the session pins them before tidying.)

bash · try it yourself
mkdir pool && cd pool
cat > main.go <<'GO'
package main

import (
	"fmt"
	"runtime"

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

func main() {
	for _, dsn := range []string{
		"postgres://linkly@db:5432/linkly",
		"postgres://linkly@db:5432/linkly?pool_max_conns=5&pool_max_conn_lifetime=30m",
	} {
		cfg, err := pgxpool.ParseConfig(dsn)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%-75s MaxConns=%d MaxConnLifetime=%s\n", dsn, cfg.MaxConns, cfg.MaxConnLifetime)
	}
	cfg, _ := pgxpool.ParseConfig("postgres://linkly@db:5432/linkly")
	fmt.Println("default == max(4, runtime.NumCPU()):", int(cfg.MaxConns) == max(4, runtime.NumCPU()))
}
GO
go mod init example.com/pool >/dev/null 2>&1
go get github.com/jackc/pgx/v5@v5.11.0 golang.org/x/sync@v0.23.0 github.com/stretchr/testify@v1.12.1 >/dev/null 2>&1
go mod tidy 2>/dev/null
go run . | sed -E 's/MaxConns=[0-9]+ (MaxConnLifetime=1h0m0s)$/MaxConns=<NumCPU or 4> \1/'
postgres://linkly@db:5432/linkly                                            MaxConns=<NumCPU or 4> MaxConnLifetime=1h0m0s
postgres://linkly@db:5432/linkly?pool_max_conns=5&pool_max_conn_lifetime=30m MaxConns=5 MaxConnLifetime=30m0s
default == max(4, runtime.NumCPU()): true

The default really is max(4, runtime.NumCPU()), which depends on the machine (the session masks the number because it differs between the machines that verify this course). Pool settings in the URL are pgx-specific parameters, so they live in the DATABASE_URL Secret: set them where the Secret is built (the CloudNativePG uri doesn't include them; append them in the chart or build the URL in an ExternalSecret template). pool_max_conn_lifetime makes the pool recycle connections, which spreads load back across replicas after a database failover.

Kubernetes networking

  • ndots: 5. Inside a pod, a name with fewer than five dots is tried against every search domain first. REDIS_ADDR=linkly-redis:6379 resolves on the first try (it is in the pod's namespace), but an external name such as api.example.com costs several failed lookups per new connection. Use fully qualified names with a trailing dot for external hosts, or lower ndots in the pod's dnsConfig.
  • NetworkPolicies are allow-lists once one exists. The chart's policy only restricts ingress; the first egress policy you add will block DNS unless you allow port 53 to kube-dns explicitly.
  • Static Go binaries use Go's own DNS resolver, which reads /etc/resolv.conf like glibc does; behaviour differences are rare, but they show up with exotic nsswitch.conf setups, which containers don't have.

Delivery

  • The HPA owns replicas. The chart omits replicas when autoscaling is on; otherwise every Argo CD sync resets the HPA's decision (Helm & Kustomize).
  • Deploy digests, display tags. Tags are mutable; a re-pushed v1.4.0 silently changes what new pods run.
  • Selectors in kube-prometheus-stack. A ServiceMonitor or PrometheusRule that "does nothing" usually lacks the label the operator's Prometheus selects on. Check kubectl get prometheus -A -o yaml | grep -A3 Selector before debugging anything else.
  • One change per promotion. Bundling a chart change with an image change turns a rollback into a decision.

Logs and metrics

  • Libraries log too. go-redis wrote unstructured lines to stderr until linkly routed them through slog; check every dependency's logging when you adopt JSON logs. Those messages also repeat per retry: rate-limit or demote them if they flood Loki during an outage.
  • Count probes, don't trace or log them at info. They are useful in metrics, noise everywhere else.
  • Route templates, not paths, as labels. Tested in TestMetricsUseRouteTemplates; keep the test.

Test yourself

Why should negative cache entries have a short TTL?

  1. Redis can't store empty values
  2. A code that doesn't exist now may be created moments later, and a long negative entry would hide it
  3. To save CPU
  4. They slow down positive lookups

What does singleflight prevent?

  1. Two pods using the same cache
  2. Many concurrent requests for the same expired key all querying the database at once
  3. Duplicate inserts
  4. Slow DNS lookups

A ServiceMonitor for linkly is applied, but Prometheus never scrapes it. What do you check first?

  1. The Go version
  2. Whether the ServiceMonitor has the label the Prometheus resource's serviceMonitorSelector requires
  3. The Redis TTL
  4. The image digest