Skip to content
Derar Sattouf

Go 1.26 for Backend Engineers: new(expr), Green Tea GC, and go fix Modernizers

Updated Backend & databases

Go 1.26 for Backend Engineers: new(expr), Green Tea GC, and go fix Modernizers

Go releases twice a year and almost never breaks anything. That predictability is the point of the language. But "boring" releases can still change your production behavior in ways that matter: latency tails, memory footprint, and the idioms your team writes every day.

Go 1.26 (released February 2026) is one of those releases. It ships two language-level refinements, makes the Green Tea garbage collector the default, rewrites go fix around the analysis framework, and continues the steady march of standard-library additions.

The built-in new now accepts an expression, so new(30) or new(time.Now()) gives you a pointer to an initialized value. That removes a whole category of tiny helper functions (ptr[T any](v T) *T). The Green Tea GC, an experiment in 1.25, is now on by default. It improves locality when scanning small objects, which typically lowers GC CPU overhead for allocation-heavy services. Measure it; don't assume.

go fix is a real modernizer now. Built on go/analysis, it ships a couple dozen "modernizers" that rewrite old idioms into current ones, plus //go:fix inline for API migrations.

For the upgrade itself, bump the toolchain in CI first, run go vet and race tests, compare p99 latency and RSS in a canary, then roll out.

A newer Go release may exist by the time you read this, since Go ships twice a year. The official Go 1.26 release notes are the source of truth; this post summarizes them and adds opinionated guidance.

new(expr): killing the pointer helper

If you have written a Go API client or a service that talks to JSON, you have written this function at least once:

func ptr[T any](v T) *T { return &v }

Optional fields in structs are modeled as pointers, because the zero value and "absent" need to be distinguishable:

type CreateUserRequest struct {
    Name     string  `json:"name"`
    Nickname *string `json:"nickname,omitempty"`
    Age      *int    `json:"age,omitempty"`
}

Before 1.26, building one inline required either a helper or temporary variables:

nick := "dz"
age := 30
req := CreateUserRequest{Name: "Derar", Nickname: &nick, Age: &age}

In Go 1.26, new takes an expression:

req := CreateUserRequest{
    Name:     "Derar",
    Nickname: new("dz"),
    Age:      new(30),
}

This works with any expression, not just constants:

type Job struct {
    StartedAt *time.Time
    Retries   *int
}

j := Job{StartedAt: new(time.Now()), Retries: new(len(attempts))}

Where this matters in backend code

  1. Request/response DTOs with optional fields (very common with OpenAPI-generated code).
  2. Test fixtures, where every test file used to declare its own ptr helper.
  3. Database models using pointer fields for nullable columns.
  4. Protobuf and cloud SDK structs, where AWS/GCP SDKs historically forced you to use aws.String(...)-style helpers.

You do not need to rip out existing helpers on day one, but go fix can do it for you (see the go fix section below).

The Green Tea garbage collector

Go's GC is concurrent, non-generational, and non-compacting. For most services it is invisible. Where it hurts is allocation-heavy workloads with many small objects: JSON decoding, ORM row scanning, protobuf unmarshalling, in-memory caches with lots of small entries.

The classic GC marks by chasing pointers across the heap. The CPU spends much of its time waiting on cache misses because objects that are logically related live far apart in memory. Green Tea changes the work unit: instead of tracking individual objects, it scans memory in larger spans, which improves cache locality and lets the marking loop do more useful work per memory fetch.

What to expect

  • The Go team reports meaningful reductions in GC CPU cost for many workloads. The exact win depends heavily on object size and pointer density.
  • Services dominated by large byte slices (file proxies, streaming) will see little change, since that memory is not pointer-dense.
  • Services dominated by tiny linked structures (trees, graphs, map-of-struct-pointers) are the most likely to benefit.

How to measure it properly

Do not trust a microbenchmark. Run a canary with production-shaped traffic and compare:

# Capture GC and memory behavior from a running service
GODEBUG=gctrace=1 ./server 2> gc.log

# Or use runtime metrics exported through Prometheus
# go_gc_duration_seconds, go_memstats_heap_inuse_bytes, process_cpu_seconds_total

Track these four numbers before and after:

MetricWhy it matters
p99 / p999 request latencyGC assist can add tail latency
CPU seconds per 1000 requestsThe real efficiency number
RSS / heap in useThroughput gains sometimes trade against memory
GC CPU fractionDirect measure of GC cost

If something regresses, the toolchain has an escape hatch for the duration of the transition. Check the release notes for the current GOEXPERIMENT setting that disables the new collector and keep it in your back pocket for rollback, but file a bug upstream with a reproducer if you need it.

Tuning knobs that still apply

Nothing about Green Tea removes the two knobs you should already know:

import "runtime/debug"

func init() {
    // Soft memory limit: GC works harder as you approach it.
    debug.SetMemoryLimit(1800 << 20) // ~1.8 GiB in a 2 GiB container

    // GOGC controls how much heap growth triggers a cycle (default 100).
    debug.SetGCPercent(100)
}

For containers, set the memory limit to roughly 85-90 percent of the cgroup limit so the runtime reacts before the kernel OOM-killer does. This single setting prevents more production incidents than any GC algorithm change.

go fix as a modernizer

For years go fix was a mostly-dormant tool for ancient API migrations. Go 1.26 rewrites it on top of the go/analysis framework (the same one go vet uses) and ships a set of modernizers: analyzers that propose safe rewrites from older idioms to newer ones.

Typical modernizers include:

  • Replacing manual loops with slices and maps package calls (slices.Contains, slices.Sort, maps.Keys).
  • Using min / max built-ins instead of hand-written helpers.
  • Using for i := range n instead of three-clause loops where appropriate.
  • Replacing interface{} with any.
  • Dropping the loop-variable copy (x := x) that has been unnecessary since 1.22 per-iteration semantics.

Run it like this:

# Preview what would change
go fix -diff ./...

# Apply
go fix ./...

# Always follow with tests
go vet ./... && go test -race ./...

//go:fix inline for your own APIs

The inliner is the interesting part for library authors and platform teams. You can mark a deprecated function so that go fix rewrites call sites automatically:

// Deprecated: use NewClient.
//
//go:fix inline
func Dial(addr string) *Client {
    return NewClient(WithAddr(addr))
}

Now every caller in every dependent module can be migrated with a single go fix run instead of a Slack announcement and six months of grep. For a platform team maintaining internal Go libraries, this is the biggest productivity feature in the release.

Other changes worth knowing

Without reproducing the whole release notes, here are the items most relevant to servers:

  • Reduced cgo overhead: reports indicate roughly 30 percent lower per-call cost. If you wrap C libraries (SQLite drivers, image processing, crypto), re-benchmark.
  • New crypto packages: crypto/hpke and crypto/mlkem testing support reflect the continuing move to post-quantum key exchange. If you terminate TLS in Go, you are likely already benefiting from hybrid key exchange via the standard library defaults.
  • Experimental items (SIMD package, runtime/secret, a goroutine leak detector): treat as experiments. The leak detector in particular is worth trying in staging, because goroutine leaks are the most common slow-burn production bug in Go services.
  • Platform notes: this is the last release supporting macOS 12; the 32-bit Windows ARM port is gone. Check your CI runners and developer laptops.

A safe upgrade checklist

Treat a Go upgrade like any dependency change with a large blast radius.

  1. Pin the toolchain in go.mod:

    go 1.26
    toolchain go1.26.0
  2. Update CI to build and test with the new toolchain before production changes. Run go vet, staticcheck, and go test -race ./....

  3. Run go fix -diff and review the proposed modernizations as a separate PR. Never mix toolchain bumps with mechanical rewrites in one diff.

  4. Rebuild container images from a pinned base (for example golang:1.26 builder, distroless or scratch runtime) and verify the image digest changes.

  5. Canary 5-10 percent of traffic for at least one full traffic cycle. Compare p99, CPU per request, RSS, and error rate against the baseline.

  6. Check for unsafe and cgo: anything touching memory layout deserves explicit attention.

  7. Roll forward, document the before/after numbers in the PR, and delete the rollback flag after a week of stability.

A minimal Dockerfile

FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server

FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/server /server
USER nonroot
ENTRYPOINT ["/server"]

Idioms to adopt this quarter

If you only change a few habits, change these:

// 1. Optional pointers
cfg := Config{Timeout: new(30 * time.Second)}

// 2. Prefer slices/maps packages over hand-rolled loops
if slices.Contains(allowedRoles, role) { ... }

// 3. Structured logging with slog everywhere
slog.Info("request", "method", r.Method, "path", r.URL.Path, "dur", time.Since(start))

// 4. Context-aware everything
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()

// 5. errors.Join for fan-out error aggregation
err := errors.Join(errs...)

What not to do

  • Don't tune GC knobs blindly because a blog post said Green Tea is faster. Baseline first.
  • Don't bulk-apply go fix to a huge monorepo in one commit. Split by directory so reviewers can actually read the diffs.
  • Don't rely on experimental features (SIMD, runtime/secret) in code paths that must remain stable across upgrades. Experiments can change or disappear.

A runnable lab: measure GC behaviour before and after

Claims about garbage collection are only useful if you measure them on your own workload. This lab builds a small allocation-heavy HTTP service you can run under two toolchains and compare. It needs Go 1.25 and Go 1.26 (install the second with go install golang.org/dl/go1.26.0@latest && go1.26.0 download; verify the exact download path in the Go docs).

// main.go
package main

import (
	"encoding/json"
	"log/slog"
	"net/http"
	_ "net/http/pprof"
	"os"
	"strconv"
)

type Item struct {
	ID    int      `json:"id"`
	Name  string   `json:"name"`
	Tags  []string `json:"tags"`
	Price *float64 `json:"price,omitempty"`
}

func handler(w http.ResponseWriter, r *http.Request) {
	n, _ := strconv.Atoi(r.URL.Query().Get("n"))
	if n <= 0 || n > 5000 {
		n = 500
	}
	items := make([]*Item, 0, n)
	for i := 0; i < n; i++ {
		items = append(items, &Item{
			ID:    i,
			Name:  "item-" + strconv.Itoa(i),
			Tags:  []string{"a", "b", "c"},
			Price: new(float64(i) * 1.5), // new(expr), Go 1.26+
		})
	}
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(items); err != nil {
		slog.Error("encode", "err", err)
	}
}

func main() {
	http.HandleFunc("/items", handler)
	slog.Info("listening", "addr", ":8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		slog.Error("server", "err", err)
		os.Exit(1)
	}
}

The line using new(float64(i) * 1.5) requires Go 1.26. To compare with 1.25, replace it with a small local helper, or build the same file with each toolchain after swapping that line.

Run the server and drive load with a tool such as oha or hey:

# Terminal 1: run with GC tracing so you can see GC cycles
GODEBUG=gctrace=1 go run . 2> gc-$(go version | awk '{print $3}').log

# Terminal 2: drive 30 seconds of load at 64 concurrent connections
oha -z 30s -c 64 'http://localhost:8080/items?n=2000'

# Collect a CPU profile during load (pprof is on the default mux)
go tool pprof -top -seconds 20 http://localhost:8080/debug/pprof/profile

What to compare between the two toolchain runs:

ObservationWhere to look
Share of CPU in runtime.gcBgMarkWorker, scanobject, greyobject and related functionspprof -top output
Number of GC cycles and pause or assist timegctrace lines
Throughput and tail latencyload tool report
Resident memoryps, container metrics

Note that net/http/pprof exposes sensitive endpoints; never register it on a public port in production. Bind it to localhost or an admin listener. Your numbers will not match anyone else's; that is the point.

Production habits that matter more than the release

A new toolchain is a small lever compared with these.

Container-aware runtime settings. Go 1.25 made GOMAXPROCS respect cgroup CPU limits by default, which removes a classic source of CPU throttling in Kubernetes. If you set GOMAXPROCS manually or via automaxprocs, re-check whether you still need it, and verify the behaviour in the release notes for your version.

A memory limit that matches the container. Set GOMEMLIMIT (or debug.SetMemoryLimit) to about 85 to 90 percent of the container limit, as shown earlier. It does not replace sizing the container correctly.

Graceful shutdown. Handle SIGTERM, stop accepting new connections, and drain in-flight requests:

package main

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			slog.Error("server failed", "err", err)
			os.Exit(1)
		}
	}()

	<-ctx.Done()
	slog.Info("shutting down")
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		slog.Error("shutdown", "err", err)
	}
}

The pattern routing in http.NewServeMux ("GET /healthz") has been standard since Go 1.22. Always set server timeouts; the zero values mean "no timeout", which invites slow-client resource exhaustion.

Timeouts on every outbound call. http.Client has no timeout by default. Use a client with Timeout set and contexts with deadlines. See the same principle for Rust services in production Rust services with Axum and Tokio.

Race detector in CI. go test -race ./... catches data races that only appear under production load.

Deterministic concurrency tests. testing/synctest (stable since Go 1.25) lets you test time-dependent concurrent code with a fake clock, which removes sleeps and flakiness from tests of retry loops, timeouts and tickers.

Structured logging with log/slog, with consistent keys and a request ID, and export traces and metrics through OpenTelemetry; see OpenTelemetry for LLM apps for the instrumentation approach that applies to any service.

Build hygiene. go mod tidy, go vet, govulncheck ./... for known vulnerabilities in your dependency graph, and reproducible builds with -trimpath. See software supply chain, SLSA, Sigstore and SBOM.

Other 1.26 library and tooling items to check

The release notes are long. Without reproducing them, here are categories worth scanning for backend work. Each bullet is a reminder to read the matching section, not a guarantee of exact behaviour:

  • errors and slog: new helpers for typed error matching and for fanning logs out to several handlers were part of the cycle. Check the notes for the exact names and signatures.
  • net/http and net/url: stricter parsing and new knobs appear most releases. Re-run your integration tests, especially if you parse unusual URLs.
  • crypto/*: post-quantum and hybrid key-exchange work continues. Confirm TLS behaviour with the clients and middleboxes you actually use.
  • Profiling and diagnostics: new or experimental profile types (including goroutine-leak detection) are worth trialling in staging.
  • The go command: defaults for go mod init and the toolchain directive can change what version a new module requires. Review go.mod diffs after upgrades.
  • Experimental features (SIMD, secret-handling helpers): treat as unstable.

When in doubt, search the release notes for packages you import and read only those sections.

Troubleshooting table

SymptomLikely causeWhat to do
p99 latency worse after upgradeGC behaviour change or your own code pathCompare gctrace and CPU profiles; try the documented opt-out experiment flag to isolate; file an upstream issue with a reproducer
RSS higher than beforeCollector trade-offs or a changed memory limitSet GOMEMLIMIT, check heap profile, compare against baseline
go fix changes hundreds of filesLarge legacy codebaseApply per directory, review separately, keep rewrite PRs apart from the toolchain bump
go fix rewrites break testsSemantic edge cases (for example loop variable capture assumptions)Review diffs; revert the specific rewrite and add a test
Build error on new(...) with an older toolchainModule's go directive below 1.26Raise the go line in go.mod or avoid the syntax
CI fails with "toolchain not found"Toolchain download blockedPre-install the toolchain or allow GOTOOLCHAIN downloads deliberately
cgo build slower or faster than expectedRuntime changes in cgo call pathRe-benchmark the specific call pattern
OOMKilled podsMemory limit not set below the cgroup limitSet GOMEMLIMIT to about 90 percent of the limit
CPU throttling in KubernetesOld GOMAXPROCS behaviour or CPU limits too lowUpgrade, verify GOMAXPROCS, review CPU requests and limits
Goroutine count keeps risingGoroutine leak (blocked channel, missing cancel)Use pprof goroutine profile; try the leak detector in staging

Where this usually goes wrong

  1. Upgrading and changing GC settings at the same time, so you can't attribute the effect.
  2. Trusting benchmarks from blog posts (including this one) instead of your own canary.
  3. Mixing toolchain bumps with mechanical rewrites in a single diff.
  4. Leaving http.Server and http.Client timeouts at zero.
  5. Exposing net/http/pprof publicly.
  6. Using new(expr) to avoid thinking about nullability. Pointers for optional fields are an API decision; consider whether a zero value or a dedicated type expresses intent better.
  7. Ignoring govulncheck, so a toolchain upgrade is the only security update you ever do. Standard library vulnerabilities are fixed in point releases, so keep up with patch versions.
  8. Skipping the race detector and load tests.
  9. Relying on experiments (GOEXPERIMENT flags) in long-lived production configuration.
  10. Not pinning the toolchain in go.mod and CI, leading to "works on my machine" differences.

When Go is, and is not, the right choice

Go excels at network services, CLIs, infrastructure tooling and anything that benefits from simple concurrency, fast builds and static binaries. Consider alternatives when you need maximum raw performance with fine-grained memory control, rich type-level modelling, or a mature ecosystem for a specific domain. For a structured comparison see Rust vs Go vs Zig: a backend decision guide and Node vs Bun vs Deno. If you are weighing a migration from a PHP framework, replacing Laravel with Rust covers the cost-benefit method, which applies to Go too.

Where to start

Bump CI to 1.26 this week, run go fix -diff ./... on one service, and set up a canary dashboard comparing p99 latency and CPU per request.

Questions that come up

Do I have to use new(expr)? No. It is optional syntax that replaces a helper function. Existing code keeps working.

Will Green Tea make my service faster? It might reduce GC CPU cost, especially for workloads with many small, pointer-rich objects, but results vary. Measure with a canary.

Is go fix safe to run? It aims for behaviour-preserving rewrites, but you should review diffs and run the tests, like any automated refactor.

How do I roll back if something regresses? Keep the previous toolchain version available in CI, deploy the old binary, and consult the release notes for any documented opt-out flag for the new collector. File an issue upstream with a reproducer.

Does this affect my Docker images? Only through the builder toolchain version and base images. Distroless images are now published on newer Debian bases; verify the tags you use and pin by digest.

What should I learn next in Go for backend work? Contexts and cancellation, log/slog, the net/http mux patterns, testing/synctest, pprof, and good error handling with errors.Is, errors.As and errors.Join.

Sources and docs