Posted in Engineering

Go’s Error Handling Explained: Why Go Rejected Exceptions and What’s Changing

Ask a Go developer what they’d change about the language, and “error handling” shows up near the top more often than almost anything else. The repetitive if err != nil { return err } pattern is the most-mocked feature of Go’s syntax — and also a direct, deliberate consequence of a design decision the Go team made at the language’s birth and has, after years of public debate, formally decided not to revisit.

At a Glance

QuestionAnswer
Does Go have exceptions?No. Go has panic/recover for truly exceptional, non-recoverable situations, but idiomatic error handling uses ordinary return values
What is an error in Go?Any value implementing the built-in error interface: a single method, Error() string
Standard library helperserrors.New, errors.Is, errors.As (both since Go 1.13), errors.Unwrap (Go 1.13), errors.Join (Go 1.20)
Was a “try” shorthand added?No — the built-in try proposal (#32437) was proposed and then withdrawn by its own authors in 2019 after strong public pushback
Current official stanceThe Go team has stopped pursuing syntactic changes to error handling “for the foreseeable future” and is closing related proposals

Short Verdict

Go treats errors as values, not control flow. That’s a feature, not an oversight: the official Go blog argues explicit error checks keep failure handling visible at the call site rather than hidden behind a try/catch block that can silently skip over code. The cost is verbosity. After nearly a decade of proposals to fix that verbosity with new syntax — including a built-in try function and a ?-operator idea — the Go team has formally given up on a syntactic fix and instead keeps investing in library-level tools: errors.Is, errors.As, and errors.Join.

Why Go Doesn’t Use Exceptions

The error type is just a built-in interface:

type error interface {
    Error() string
}

Any type that implements that one method satisfies it, which is why Go functions that can fail conventionally return an error as their last value, and callers are expected to check it immediately:

f, err := os.Open("config.json")
if err != nil {
    return fmt.Errorf("loading config: %w", err)
}
defer f.Close()

The official Go blog’s rationale is that this keeps the failure path visible at the exact place it can occur, instead of letting it propagate silently up through a call stack the way a thrown exception can. The trade-off the language accepts in exchange is the repetition critics point to — the same three lines, over and over, in almost every function that does I/O.

The Toolkit: Is, As, and Join

Rather than adding new syntax, the standard library has grown targeted helpers for the hard parts of value-based error handling:

  • errors.Is(err, target) (Go 1.13) — reports whether a specific sentinel error (like io.EOF) appears anywhere in err’s wrapped chain, even through multiple layers of fmt.Errorf("...: %w", err) wrapping.
  • errors.As(err, &target) (Go 1.13) — finds the first error in the chain matching a specific type and, if found, assigns it into target so you can read fields or call methods on it.
  • errors.Join(err1, err2, ...) (Go 1.20) — combines multiple errors into one, useful when a function needs to report that several independent operations failed rather than just the first one. It discards nil values and returns nil if everything passed in is nil.
var ErrNotFound = errors.New("not found")

func lookup(id string) error {
    return fmt.Errorf("lookup %s: %w", id, ErrNotFound)
}

err := lookup("42")
if errors.Is(err, ErrNotFound) {
    // handle the specific case, even though err's message
    // is "lookup 42: not found", not the sentinel itself
}

Why “try” Didn’t Survive

In 2019, the Go team formally proposed a built-in try function (Go issue #32437) that would let a call like try(f()) return early from the enclosing function automatically on error, cutting the three-line pattern down to one. The proposal arrived close to a finished design with an aggressive rollout timeline, and the community reaction was strongly negative — critics argued it hid control flow (an early return) inside what looked like a normal expression, buried arbitrarily deep in a line of code. The Go team withdrew it within weeks.

That wasn’t the end of the conversation — a later community proposal for a ? operator (similar to Rust’s) got the same scrutiny. In the Go blog’s own account, neither that nor any other syntactic proposal reached anything resembling consensus, which under Go’s proposal process means decline. The Go team’s current, explicit position: it is done pursuing syntax changes for error handling “for the foreseeable future” and is closing related proposals, while acknowledging that the verbosity complaint remains one of the most common pieces of Go feedback.

Pros and Cons of Go’s Approach

  • Pros: Every point where a function can fail is visible and explicit in the code; no hidden stack unwinding; errors can carry structured data via custom types, not just a message string; errors.Is/errors.As/errors.Join handle the common wrapping and multi-error cases without new syntax
  • Cons: Genuinely more boilerplate than exception-based languages for functions with several fallible calls in a row; no built-in shorthand, and the Go team has ruled one out for now; easy to accidentally ignore an error by not checking it (though linters like errcheck catch this)

Bottom Line

Go’s error handling isn’t an unfinished feature waiting for new syntax — it’s a settled design position, reaffirmed after years of public proposals that never reached consensus. If you’re coming from an exception-based language, the repetition is real, but the standard library’s errors.Is, errors.As, and errors.Join cover the cases that actually trip people up (wrapped sentinel errors, typed errors, multiple simultaneous failures) without requiring a language change.

FAQ

Does Go have any exception-like mechanism at all?
Yes — panic and recover — but idiomatic Go reserves these for truly unrecoverable programmer errors (like an out-of-bounds slice access), not for ordinary, expected failure conditions like a missing file or a failed network call.

Is the “try” proposal completely dead?
As of the Go team’s own blog post on the subject, yes — they’ve stated they’re not pursuing error-handling syntax changes for the foreseeable future and are closing related proposals, including follow-ons like the “?” operator idea.

What’s the difference between errors.Is and errors.As?
errors.Is checks whether a specific known error value appears in the chain (useful for sentinel errors like io.EOF). errors.As checks whether an error of a specific type appears in the chain and extracts it so you can access its fields.

Sources

Posted in Engineering

Go 1.26 Explained: Green Tea GC, Self-Referential Generics, and What Changed in Go’s Toolchain

This site has already covered Go’s concurrency model in depth — goroutines, channels, and the scheduler — and separately compared garbage collection across Java, Go, and Python at a conceptual level. Neither piece is about a specific Go release. Go 1.26, which shipped in February 2026, is worth its own look: it changes the garbage collector’s default behavior, adds two small but genuinely new language capabilities, rewrites a core toolchain command, and quietly ships post-quantum-ready TLS defaults. This piece sticks to what actually shipped in Go 1.26 itself, per the official release notes.

At a Glance

FactDetail
ReleaseGo 1.26, released February 2026, six months after Go 1.25
Headline runtime changeGreen Tea GC (experimental in Go 1.25) is now the default garbage collector
Claimed GC improvement10–40% reduction in GC overhead for GC-heavy programs; a further ~10% on newer amd64 CPUs (Intel Ice Lake / AMD Zen 4+) via vector instructions
Language changesnew(expr) now accepts an initializing expression; generic types can now refer to themselves in their own type-parameter list
Toolchain changego fix rewritten into a “modernizers” framework built on go vet‘s analysis engine; cmd/doc removed in favor of go doc
Bootstrap requirementBuilding Go 1.26 from source requires Go 1.24.6 or later

Short Verdict

Go 1.26 is a solid, unglamorous point release in the best Go tradition — no breaking changes to the language’s compatibility promise, but a default garbage-collector swap that should measurably help GC-heavy services with zero code changes, plus a handful of small ergonomic wins (initializing new(), self-referential generics) that Go developers have quietly wanted for years. The most consequential change for infrastructure teams specifically may be the least flashy one: Go’s TLS stack now defaults to hybrid post-quantum key exchange, which is a meaningful, no-effort step toward the same quantum-safe migration enterprises like IBM are pushing at the hardware and software layer (covered separately on this site).

Green Tea GC Becomes the Default

The biggest runtime change in Go 1.26 is that Green Tea, an experimental garbage-collector redesign introduced in Go 1.25, is now the default collector for every Go 1.26 program. Per the official release notes, the Go team expects a 10% to 40% reduction in GC overhead for real-world, GC-heavy programs. On newer amd64 hardware specifically — Intel Ice Lake or AMD Zen 4 and later — Green Tea gets a further roughly 10% reduction on top of that, because it uses vector instructions to scan small objects faster. Teams that need to roll back to the old collector can still do so by building with GOEXPERIMENT=nogreenteagc, but that escape hatch is expected to be removed entirely in Go 1.27, so Green Tea is clearly intended as permanent, not a toggle. Notably, Go 1.26 does not change the tuning knobs around the collector — GOGC and GOMEMLIMIT work exactly as before; it’s the collector’s internal algorithm that changed, not the controls you use to steer it.

Two Small Language Changes

Go 1.26 adds two language capabilities, both small in scope but each closing a long-standing gap. First, the built-in new function now accepts an expression specifying the variable’s initial value, not just a type. The release notes specifically call out optional pointer fields in serialization code as the motivating case:

type Person struct {
    Name string `json:"name"`
    Age  *int   `json:"age"` // age if known; nil otherwise
}

func personJSON(name string, born time.Time) ([]byte, error) {
    return json.Marshal(Person{
        Name: name,
        Age:  new(yearsSince(born)),
    })
}

Before Go 1.26, getting a pointer to a computed value like this required an intermediate variable and a helper function; new(expr) collapses that into one line. Second, generic types can now refer to themselves within their own type-parameter list, which was previously disallowed:

type Adder[A Adder[A]] interface {
    Add(A) A
}

func algo[A Adder[A]](x, y A) A {
    return x.Add(y)
}

This pattern — a type constraint that references the type parameter it’s constraining — comes up in generic algorithms that need to guarantee a type can operate on itself (an Add method that takes and returns the same type, for example), and Go’s type checker previously rejected it outright.

Toolchain and Module Changes

  • go fix was rewritten and is now the home for “modernizers” — a suite of fixers that update code to current Go idioms and library APIs, built on the same analysis framework as go vet. It also includes a source-level inliner that honors //go:fix inline directives. The old, historical fixers that previously lived in go fix were removed.
  • go mod init now defaults to an older go directive version than the toolchain running it: a toolchain numbered 1.N.X writes go 1.(N-1).0 into go.mod, and a pre-release toolchain writes go 1.(N-2).0. In practice, Go 1.26 writes go 1.25.0 by default; running go get go@version after init changes it.
  • cmd/doc and go tool doc were deleted. go doc remains and takes the same flags and arguments.
  • pprof‘s web UI now defaults to the flame-graph view instead of the graph view, which is still available under View → Graph.

Security and Runtime Details Worth Knowing

  • Hybrid post-quantum TLS key exchange is now on by default. The SecP256r1MLKEM768 and SecP384r1MLKEM1024 hybrid key exchanges — combining classical elliptic-curve key exchange with the NIST-standardized ML-KEM post-quantum algorithm — are enabled by default in Go’s TLS stack, with no configuration required.
  • A new crypto/hpke package implements RFC 9180 Hybrid Public Key Encryption, including post-quantum hybrid key-encapsulation mechanisms.
  • Faster cgo calls: baseline call overhead is reduced by roughly 30%.
  • Heap base address randomization on 64-bit platforms, a security hardening measure specifically for programs using cgo.
  • An experimental goroutine leak profile (GOEXPERIMENT=goroutineleakprofile), served at /debug/pprof/goroutineleak, which the Go team intends to enable by default in Go 1.27.
  • io.ReadAll is about twice as fast and uses roughly half the memory in typical cases.
  • New errors.AsType, a generic, type-safe version of errors.As, and a new log/slog.NewMultiHandler that invokes multiple handlers at once.

Go 1.25 vs. Go 1.26 at a Glance

AreaGo 1.25Go 1.26
Garbage collectorGreen Tea GC available as an opt-in experimentGreen Tea GC is the default; opt-out removed in Go 1.27
new()Type only — no initializing expressionAccepts an initializing expression
GenericsA type could not reference itself in its own type-parameter listSelf-referential generic type parameters are allowed
TLS defaultsClassical key exchange by defaultHybrid post-quantum key exchange (ML-KEM-based) enabled by default
go fixLimited set of historical, hardcoded fixersRewritten “modernizers” framework plus a source-level inliner

Trade-offs

ProsCons
Green Tea GC’s 10–40% overhead reduction is essentially free performance for any GC-heavy service that upgradesThe Go team’s own 10–40% GC figure is a general expectation across “real-world” programs, not a guaranteed result for any specific workload
Post-quantum TLS defaults require no code or configuration changes to adoptGo 1.26 is the last release supporting macOS 12 Monterey and the ELFv1 ABI on linux/ppc64, so some older deployment targets need planning before the next upgrade
Self-referential generics and initializing new() are small but genuinely useful ergonomic fixes with no downside for existing codeBuilding Go 1.26 from source requires a relatively recent bootstrap toolchain (Go 1.24.6+), which can matter for older build pipelines

Who It’s Relevant For

Any team running Go services in production, particularly latency- or throughput-sensitive ones where GC pause time matters, should treat the Green Tea GC default as reason enough to test an upgrade. Teams writing generic library code that previously hit Go’s self-referential-generics restriction, and anyone maintaining code with a lot of optional pointer fields (common in JSON-heavy APIs), will get immediate, direct benefit from the two language changes.

Who Should Look Elsewhere (or Wait)

Teams still deploying to macOS 12 Monterey or relying on the ELFv1 ABI on linux/ppc64 should treat Go 1.26 as their last release on those targets and plan the migration before moving to Go 1.27. Anyone depending on cmd/doc directly (rather than go doc) or on one of the historical go fix fixers that got removed will need to adjust tooling before upgrading.

Bottom Line

Go 1.26 doesn’t change the language in any way that breaks Go’s compatibility promise, but it’s a meaningfully useful release: a default GC that should reduce overhead for most programs with zero code changes, two small language features that close real gaps, a rewritten go fix aimed at keeping codebases current, and post-quantum-ready TLS defaults that quietly move the entire Go ecosystem a step closer to the same quantum-safe posture enterprises are being pushed toward at the hardware level. For most teams, it’s a low-risk, genuinely worthwhile upgrade.

FAQ

Do I need to change any code to benefit from Green Tea GC? No. It’s the new default garbage collector in Go 1.26; existing programs get it automatically on upgrade, with no code changes required. It can be disabled with a build flag if needed, though that option is expected to disappear in Go 1.27.

Does Go 1.26 change how GOGC or GOMEMLIMIT work? No. The official release notes describe no changes to those tuning variables; what changed is the garbage collector’s internal scanning algorithm, not the controls used to configure it.

What’s “self-referential generics” in plain terms? It means a generic type’s type parameter can now be constrained by a type that itself references that same type parameter — useful for patterns like an interface requiring a method that both takes and returns the implementing type. Go 1.25 and earlier rejected this at compile time; Go 1.26 allows it.

Is Go 1.26’s post-quantum TLS support related to IBM’s quantum-safe cryptography work? They’re separate efforts solving the same underlying problem. Go 1.26 enables hybrid post-quantum key exchange (based on the NIST-standardized ML-KEM algorithm) by default in its TLS stack; IBM’s Guardium Cryptography Manager and its z17/LinuxONE hardware, covered separately on this site, address quantum-safe migration at the enterprise cryptographic-inventory and mainframe-hardware level. Both ultimately rely on the same NIST-standardized algorithms.

Sources

  • The Go Blog — Go 1.26 Release Notes (go.dev/doc/go1.26)
  • The Go Blog — Go 1.26 announcement (go.dev/blog/go1.26)

Related reading on this site: Go’s Concurrency Model Explained (Goroutines, Channels, and the Go Scheduler), Garbage Collection Explained (Java, Go, and Python), The Go Programming Language in 2026, and IBM’s Quantum-Safe Cryptography Push.

Posted in Engineering

Go’s Concurrency Model Explained: How Goroutines, Channels, and the Go Scheduler Actually Work

Our earlier piece on the Go programming language introduced goroutines and channels and showed a basic worker-pool pattern. This one goes a level deeper: how does the Go runtime actually schedule hundreds of thousands of goroutines onto a handful of OS threads, what guarantees do channels really give you when goroutines run concurrently, and how does select let a goroutine wait on several channels at once? These mechanics are what make Go’s concurrency model more than just “lightweight threads with a nicer syntax” — and they’re also where the model’s real sharp edges live.

At a Glance

ConceptWhat it is
Goroutine (G)A function running concurrently, with its own small, growable stack — not an OS thread
OS thread (M)What the Go runtime calls a “machine” — the real kernel thread that actually executes instructions
Processor (P)A runtime-managed context, up to GOMAXPROCS of them, that holds a local run queue of goroutines ready to execute
Work stealingWhen a P’s local queue is empty, it steals goroutines from another P’s queue instead of going idle
Async preemptionSince Go 1.14, the runtime can interrupt a long-running goroutine mid-loop, not just at function calls
Memory modelDefines exactly which operations are guaranteed to be visible across goroutines (“happens before”)

Short Verdict

Go’s concurrency model earns its reputation by combining three things that are each unremarkable alone but genuinely useful together: goroutines that cost a few kilobytes instead of a full OS thread stack, a scheduler that multiplexes them with work-stealing so idle cores don’t sit idle, and a small set of channel operations with memory-model guarantees precise enough to build correct synchronization without a mutex. None of it is magic — the Go FAQ is upfront that the scheduler “is not perfect,” and the memory model’s own advice is “if you must read the rest of this document to understand the behavior of your program, you are being too clever.” The mechanics are worth knowing specifically because they explain where things break: goroutine leaks, GOMAXPROCS misconfiguration in containers, and data races on plain variables that look fine until they aren’t.

Why Goroutines Are Cheap: the Short Version

Go’s own FAQ describes a goroutine as a coroutine multiplexed onto a set of OS threads: “When a coroutine blocks, such as by calling a blocking system call, the run-time automatically moves other coroutines on the same operating system thread to a different, runnable thread so they won’t be blocked. The programmer sees none of this, which is the point.” The cost structure is what makes this practical at scale — a new goroutine starts with just a few kilobytes of stack, which the runtime grows and shrinks automatically, and Go’s own documentation states the CPU overhead per function call averages about three cheap instructions. The FAQ’s own conclusion: “It is practical to create hundreds of thousands of goroutines in the same address space. If goroutines were just threads, system resources would run out at a much smaller number.”

The Scheduler: G, M, and P

The Go runtime’s scheduler implementation is commonly described using three letters — G, M, and P — a shorthand that comes from the runtime’s own source code and the engineering writeups around it, rather than a term you’ll find spelled out in the beginner-level Go docs. It’s worth understanding because it explains exactly how “multiplexed onto OS threads” actually happens:

LetterStands forRole
GGoroutineA single concurrent function call and its stack — the unit of work being scheduled
MMachineAn actual OS thread that executes code; the runtime creates and parks these as needed
PProcessor (context)A scheduling context, capped at GOMAXPROCS, that must be held by an M before it can run a G; each P keeps a local run queue

An M can only execute Go code while holding a P, and the number of Ps — not the number of Ms — determines how many goroutines can run truly in parallel at once. When a goroutine makes a blocking system call, the runtime detaches the P from that M so another M can pick it up and keep making progress, which lines up with the FAQ’s description of moving blocked coroutines aside automatically. When a P’s own local run queue runs dry, it doesn’t go idle — it steals goroutines from another P’s queue, a technique generally known as work-stealing scheduling, so work spreads across available cores instead of piling up behind one busy P.

GOMAXPROCS: Controlling How Many Ps Exist

Go’s FAQ states that “the number of CPUs available simultaneously to executing goroutines is controlled by the GOMAXPROCS shell environment variable, whose default value is the number of CPU cores available.” You can also set it from code:

package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Println("default GOMAXPROCS:", runtime.GOMAXPROCS(0))

	// Limit parallel execution to 4 OS threads.
	runtime.GOMAXPROCS(4)
	fmt.Println("updated GOMAXPROCS:", runtime.GOMAXPROCS(0))
}

The FAQ is also clear that this setting only governs parallelism, not concurrency: “GOMAXPROCS only affects how many goroutines can actually execute at once; arbitrarily more may be blocked in system calls.” Setting it to 1 doesn’t stop you from spawning goroutines — it just forces them to take turns on a single OS thread instead of running simultaneously. This matters more than it sounds: older Go runtimes sometimes read a container’s host CPU count instead of its actual CPU limit/cgroup quota, over-provisioning Ps relative to the CPU the container was actually allowed to use — a real-world reason this setting shows up in production tuning discussions rather than just scheduler theory.

Preemption: Stopping a Goroutine That Won’t Yield

For its first several years, Go’s scheduler could only preempt a goroutine at specific safe points, mostly function calls — a tight loop with no function calls inside it could starve the scheduler or stall garbage collection. Go 1.14’s release notes record the fix: “Goroutines are now asynchronously preemptible. As a result, loops without function calls no longer potentially deadlock the scheduler or significantly delay garbage collection.” The same release notes flag a side effect worth knowing if you’re doing low-level systems work in Go: “on Unix systems, including Linux and macOS systems, programs built with Go 1.14 will receive more signals than programs built with earlier releases,” which can surface as more EINTR failures from slow system calls that code using syscall or golang.org/x/sys/unix needs to handle by retrying.

select: Waiting on Multiple Channels at Once

A single channel receive blocks until something arrives. select is how a goroutine waits on several channel operations simultaneously and reacts to whichever one is ready first. Per the Go language specification, if more than one case could proceed, one is chosen by uniform pseudo-random selection — not source order — and a default case runs only when nothing else is ready, making the whole statement non-blocking:

package main

import (
	"context"
	"fmt"
	"time"
)

func fetch(ctx context.Context, results chan<- string) {
	select {
	case <-time.After(200 * time.Millisecond):
		results <- "data fetched"
	case <-ctx.Done():
		// The caller cancelled or the deadline passed first.
		return
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	results := make(chan string, 1)
	go fetch(ctx, results)

	select {
	case r := <-results:
		fmt.Println(r)
	case <-ctx.Done():
		fmt.Println("timed out:", ctx.Err())
	}
}

This pattern — racing a real result against a timeout or cancellation signal through select — is the standard way Go code bounds how long it waits on a concurrent operation, and it’s the same mechanism the standard library’s own context package is built around.

The Memory Model: What Channels Actually Guarantee

Goroutines running concurrently can each see a different, stale view of shared memory unless something establishes an explicit ordering between them — what the Go memory model calls “happens before.” The model spells out specific channel guarantees: a send is synchronized before the corresponding receive completes; on an unbuffered channel, a receive is synchronized before the corresponding send completes; closing a channel is synchronized before a receive that returns because the channel is closed; and for a channel with capacity C, the kth receive is synchronized before the (k+C)th send completes. That last rule is exactly what makes a buffered channel usable as a counting semaphore:

package main

import "sync"

// limit caps how many goroutines run concurrently.
var limit = make(chan struct{}, 3)

func process(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	limit <- struct{}{} // acquire a slot
	defer func() { <-limit }() // release it

	// ... do work with at most 3 goroutines active at once ...
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go process(i, &wg)
	}
	wg.Wait()
}

The memory model is equally specific about what doesn’t give you a guarantee: checking a plain boolean variable in a busy-wait loop has no happens-before edge at all, so the compiler and runtime are free to never let the reading goroutine observe the write. The memory model’s own busy-wait example using a plain bool is documented as broken for exactly this reason — it “may print the empty string… or never terminate” — and its closing advice is blunt: “If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don’t be clever.”

Trade-offs

  • Cheap goroutines are still not free — spawning millions without a bound (a worker pool, a semaphore channel like the one above) can exhaust memory even though each one is individually tiny.
  • A goroutine blocked forever on a channel that nothing will ever write to or read from is a classic leak; select with a cancellation case (as shown above) is the usual fix, not a substitute for actually closing channels when producers finish.
  • Work-stealing and async preemption make the scheduler good at avoiding starvation in the common case, but Go’s own FAQ concedes it “is not perfect,” and GOMAXPROCS tuning is a real, occasionally necessary escape hatch — especially in containers with CPU limits below the host’s full core count.
  • The memory model’s guarantees are specific to the operations it documents (channels, sync.Mutex, sync/atomic, sync.Once); reasoning about anything outside those primitives from first principles is how subtle data races get introduced.

Bottom Line

Goroutines, channels, and select are the parts of Go’s concurrency model every tutorial shows. The GMP scheduler, work-stealing, async preemption, and the memory model’s happens-before rules are the parts that explain why those primitives behave the way they do under load — and they’re exactly what you need once you’re debugging a goroutine leak, a CPU-throttled container, or a data race that only shows up under go test -race. None of it replaces careful design, but it does explain which shortcuts are actually safe.

FAQ

What do G, M, and P stand for in the Go scheduler?
Goroutine, Machine (an OS thread), and Processor (a scheduling context capped at GOMAXPROCS that holds a local run queue). This terminology comes from the Go runtime’s own implementation and the engineering writing around it, not from a single official beginner-facing document.

Does raising GOMAXPROCS always make my program faster?
No. It only raises the ceiling on how many goroutines can run in true parallel; a program that isn’t actually parallelizable, or that spends more time synchronizing than computing, won’t benefit and can even slow down from added context-switching overhead.

When did Go gain asynchronous goroutine preemption?
Go 1.14, released in February 2020. Before that, a tight loop with no function calls could block the scheduler or delay garbage collection indefinitely.

Does an unbuffered channel guarantee the receiver sees the sender’s writes?
Yes, per the Go memory model: a send on a channel is synchronized before the corresponding receive completes, and for an unbuffered channel, the receive is also synchronized before the send completes — so any plain variable written before the send is guaranteed visible after the receive.

Sources

Posted in Engineering

The Go Programming Language in 2026: Concurrency, Generics, and Why Cloud Infrastructure Runs On It

Go doesn’t get the kind of chip-launch coverage that Nvidia or AWS silicon gets, but it quietly underpins a huge share of the infrastructure those chips run on. Kubernetes, Docker, Terraform, Prometheus, and etcd are all written in Go, and that’s not a coincidence — the language was designed from the start around two things cloud infrastructure needs constantly: handling many things happening at once, and staying simple enough for large teams to maintain. Here’s what’s actually in the language, including the 2022 addition of generics, and why so much of the infrastructure layer keeps choosing it.

At a Glance

FeatureWhat It DoesAdded
GoroutinesLightweight concurrent functions multiplexed onto OS threadsGo 1.0 (2012)
ChannelsTyped pipes for goroutines to communicate and synchronizeGo 1.0 (2012)
Generics (type parameters)Functions/types that work across multiple types without losing type safetyGo 1.18 (March 2022)
Built-in fuzzingAutomated test-input generation via go test -fuzzGo 1.18 (March 2022)

Goroutines: Concurrency Without the Thread Management

A goroutine is, in Go’s own documentation, “a function executing concurrently with other goroutines in the same address space.” The Go team deliberately avoided calling them threads, because goroutines are much cheaper: each one starts with a small stack that grows and shrinks as needed, and the Go runtime multiplexes many goroutines onto a much smaller number of OS threads. Starting one is as simple as putting the keyword go in front of a function call — the goroutine runs independently, and the caller doesn’t wait for it to finish. That cost difference is a big part of why Go code can comfortably run tens of thousands of concurrent operations — incoming requests, open connections, background jobs — that would be expensive to run as that many OS threads in other languages.

Channels: How Goroutines Actually Talk to Each Other

Goroutines aren’t very useful on their own if they can’t coordinate, and that’s what channels are for. A channel, created with make(chan T), is a typed conduit that one goroutine can send values into and another can receive values from. An unbuffered channel blocks the sender until a receiver is ready, which gives you communication and synchronization in a single operation; a buffered channel (make(chan T, N)) lets a sender proceed until the buffer fills. Go’s own documentation sums up the resulting style this way: “Do not communicate by sharing memory; instead, share memory by communicating.” Rather than multiple goroutines fighting over a shared variable with locks, they pass values through channels instead.

A simple worker-pool pattern, a staple of Go network and infrastructure code, looks like this:

package main

import "fmt"

func worker(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		results <- j * 2
	}
}

func main() {
	jobs := make(chan int, 5)
	results := make(chan int, 5)

	for w := 1; w <= 3; w++ {
		go worker(w, jobs, results)
	}

	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)

	for a := 1; a <= 5; a++ {
		fmt.Println(<-results)
	}
}

Here, three worker goroutines all read from the same jobs channel; whichever one is free next picks up the next job, and each result is sent back on a separate channel for the main goroutine to collect. Patterns like this — a fixed pool of goroutines draining a shared channel — show up constantly in Go services that need to process many requests concurrently without spawning an unbounded number of goroutines.

Generics: Go 1.18’s Biggest Change

For its first decade, Go had no way to write a function or type that worked across multiple types without either duplicating code or falling back to interface{} and losing type safety. Go 1.18, released in March 2022, fixed that by adding type parameters. A function or type declaration can now take type parameters in square brackets, and interfaces can define “type constraints” — sets of types a type parameter is allowed to be, rather than just sets of methods. Go 1.18 also introduced two new predeclared identifiers: any, an alias for interface{}, and comparable, the set of types that support == and !=. The change was designed to be fully backward-compatible — existing Go code didn’t need to change — though the Go team cautioned at the time that generic code “has not had much production testing” and recommended appropriate caution deploying it. The same release shipped Go’s built-in fuzz testing support (go test -fuzz), a register-based calling convention extended to more CPU architectures for a roughly 10% performance gain on some platforms, and a revised append growth strategy, among other runtime changes.

Why Cloud Infrastructure Keeps Choosing Go

None of this explains, by itself, why Go became the default language for so much cloud-native tooling — Kubernetes, Docker, Terraform, Prometheus, and etcd are all implemented in Go. But the companies that have published their own reasons for adopting it, via Go’s official case studies, point to a consistent pattern. Dropbox moved performance-critical backends off Python for, in its words, “better concurrency support and faster execution speed.” Monzo called Go “a perfect language for creating microservice architectures.” Stream said Go’s “fast performance, solid support for concurrency” helped it power real-time feeds and chat for more than 500 million users. CockroachDB’s team cited “performance benefits, garbage collection, and low barrier to entry.” Netflix picked Go in part because it offers lower latency than Java while being more approachable than C, and because it can comfortably handle tens of thousands of simultaneous connections — precisely the shape of problem infrastructure tools like a container orchestrator or a reverse proxy have to solve. Compiled, statically-linked Go binaries also deploy as a single file with no separate runtime to install, which matters a great deal for software that has to run identically across thousands of servers or inside minimal containers.

Trade-offs

  • Goroutines are cheap, but cheap doesn’t mean free — spawning millions of them without a limiting pattern like a worker pool or semaphore can still exhaust memory.
  • Generics closed a real gap, but Go’s own 1.18 release notes flagged real limitations (no type declarations inside generic functions, no field access on type-parameter values) that shaped how cautiously teams adopted them early on.
  • Go’s simplicity is also a constraint: the language and standard library deliberately omit features, like exceptions or certain forms of operator overloading, that some teams coming from other languages miss.
  • Being the language cloud-native tooling is written in doesn’t mean every team building on Kubernetes or Terraform needs to write Go themselves — most only interact with those tools’ APIs or CLIs.

Bottom Line

Go’s core pitch hasn’t changed much since 2012 — goroutines and channels make concurrency manageable, and the language stays deliberately small — but generics in 2022 closed one of its longest-standing gaps without breaking that simplicity. Combined with fast compilation and single-binary deployment, that combination is why so much of the software managing cloud infrastructure itself, rather than running on top of it, continues to be written in Go.

FAQ

What’s the difference between a goroutine and a thread?
A goroutine is managed entirely by the Go runtime, not the operating system. It starts with a small, growable stack, and many goroutines are multiplexed onto a much smaller number of OS threads, which makes goroutines far cheaper to create than OS threads.

Do I need a channel every time I use a goroutine?
No, but without some way to communicate or synchronize — a channel, a sync.WaitGroup, or similar — there’s no way to know when a goroutine has finished or to safely exchange data with it.

When were generics added to Go?
Go 1.18, released in March 2022, added type parameters (generics) to the language, along with the any and comparable predeclared identifiers.

Why are so many cloud infrastructure tools written in Go?
Companies that have published their reasoning cite Go’s concurrency model, fast execution, and simple deployment as a single static binary as recurring reasons, according to Go’s own published case studies.

Sources

Posted in Engineering

Garbage Collection Explained: How Java, Go, and Python Manage Memory Without Leaks

Every long-running program allocates memory it eventually stops using, and someone has to reclaim that memory or the process eventually runs out. In languages like C, that someone is the programmer, and getting it wrong produces leaks, double-frees, and use-after-free bugs. Java, Go, and Python all take that job away from the programmer, but they do it with genuinely different mechanisms, tuned for different trade-offs between pause time, throughput, and memory overhead. This explainer sticks to what each language’s own official documentation and engineering blogs say about how their collectors actually work.

At a Glance

RuntimePrimary StrategyPause BehaviorTypical Use Case
JVM (HotSpot) — G1Generational, mostly-concurrent tracing collectorTargets a pause-time goal “with high probability”, default on most hardwareGeneral-purpose server applications where response time matters more than raw throughput
JVM (HotSpot) — ZGCFully concurrent, generational tracing collectorMax pauses under one millisecond, independent of heap sizeLow-latency applications with heaps from a few hundred MB up to 16 TB
Go runtimeConcurrent tracing mark-sweep collector, parallelized across coresRuns concurrently with your goroutines; short stop-the-world phases for setupGeneral-purpose networked/cloud services
CPythonReference counting, backed by a generational cyclic collectorRefcounting frees objects immediately; the cyclic collector runs periodically and can be tuned or disabledGeneral-purpose scripting; the cyclic collector exists specifically to catch reference cycles

Why Automatic Memory Management Exists

In a language with manual memory management, every allocation needs a matching, correctly-timed deallocation. Free too early and you get a use-after-free; never free and you get a leak; free twice and you get undefined behavior. Garbage collectors exist to make these bugs structurally impossible (or at least much rarer) by having the runtime itself figure out when memory is no longer reachable and reclaiming it automatically. The three ecosystems covered here solve that problem with different core techniques: tracing (follow references from a set of roots and reclaim what you don’t reach) and reference counting (track how many references point at an object and reclaim it when that count hits zero). Java and Go use tracing; Python uses reference counting as its primary mechanism, with a tracing collector as a backstop.

The JVM’s Collectors: G1 and ZGC

Oracle’s HotSpot documentation describes several collectors, but two matter most for modern server workloads. G1 (Garbage-First), enabled with -XX:+UseG1GC and the default on most hardware and OS configurations, is described by Oracle as “mostly concurrent”: it performs some of its most expensive work concurrently with the running application, and is designed to meet a pause-time goal with high probability while still achieving high throughput. It scales from small machines up to large multiprocessors with lots of memory, and Oracle recommends it when response time matters more than peak throughput.

ZGC, enabled with -XX:+UseZGC -XX:+ZGenerational for its generational mode, is fully concurrent rather than mostly concurrent. Oracle’s documentation states ZGC keeps maximum pause times under one millisecond, independent of heap size, and that it’s designed for low-latency applications with heap sizes ranging from a few hundred megabytes up to 16 terabytes — at some cost in throughput compared to G1. Oracle’s general tuning principle applies to both: throughput is inversely proportional to how much memory is available, because collections happen when a generation fills up, so total heap size is the single most important factor in GC performance. Oracle’s own starting-point guidance is straightforward: if peak throughput matters most and pauses of a second or more are tolerable, use the Parallel collector; if response time matters more than throughput, use G1; if response time is a high priority, use ZGC.

Go’s Concurrent Mark-Sweep Collector

Go’s runtime uses a tracing mark-sweep collector. According to the Go team’s own blog, the mark phase walks the object graph starting from roots (global and local variables) and marks every object it reaches; the sweep phase then frees everything that was never marked. Critically, this runs concurrently with your regular Go code and is parallelized across CPU cores, rather than stopping your whole program for the full collection the way older or simpler collectors do. The Go team’s own analysis found that marking accounts for roughly 90% of total GC cost, with sweeping making up the rest, and that the graph walk’s unpredictable jumps between objects and memory pages hurt CPU cache performance — a cost that’s grown worse as hardware trends (NUMA, lower per-core memory bandwidth, more cores contending on shared work queues) have progressed. Some Go programs reportedly spend 20% or more of their total CPU time in the garbage collector as a result.

To address this, the Go team has been developing “Green Tea GC,” an experimental redesign whose core idea, per the Go blog, is to “work with pages, not objects” — tracking whole memory pages on the work list instead of individual objects, with per-object “seen” and “scanned” bits on each page so the collector can scan a page’s pending objects in one in-memory-order pass. In Google’s internal benchmark suite, this cut GC CPU time by 10% to 40% (about 10% typical), though some workloads saw no benefit or slightly regressed. Green Tea GC is experimental in Go 1.25 (opt-in via GOEXPERIMENT=greenteagc) with plans to make it the default in Go 1.26.

CPython: Reference Counting Plus a Generational Cyclic Collector

Python’s approach is structurally different from Java’s and Go’s. CPython’s primary mechanism is reference counting: every object tracks how many references point at it, and when that count reaches zero, CPython frees the object immediately, with no separate “sweep” pass required. The problem reference counting cannot solve on its own is a reference cycle — two or more objects that reference each other (directly or indirectly) so their counts never reach zero, even after nothing outside the cycle can reach them. This is where CPython’s gc module comes in: Python’s own documentation describes it as an “optional cyclic garbage collector” that supplements reference counting specifically to catch these cycles.

A minimal example of the problem the cyclic collector exists to solve:

import gc

class Node:
    def __init__(self):
        self.other = None

a = Node()
b = Node()
a.other = b
b.other = a   # a reference cycle: a -> b -> a

del a, b      # reference counts never reach zero on their own
print(gc.collect())  # the cyclic collector finds and frees them

Per the official docs, the cyclic collector sorts tracked objects into three generations: new objects start in generation 0, and any object that survives a collection is promoted to the next older generation, with generation 2 being the oldest. A collection is triggered once the count of allocations minus deallocations exceeds threshold0; generation 1 is examined once generation 0 has been checked more than threshold1 times since generation 1 was last checked, with generation 2 following its own, more involved rules. The thresholds are tunable via gc.set_threshold(), and automatic collection can be disabled entirely by setting threshold0 to 0 — something the docs note is reasonable only if you’re confident your program creates no reference cycles. Unreachable objects that still can’t be freed (typically from C extension types with certain finalizer slots) land in the gc.garbage list rather than silently leaking without a trace.

Comparing the Mechanisms

MechanismCore TechniqueConcurrent With App?Generational?Handles Reference Cycles?
JVM G1Tracing (mark-and-reclaim)Mostly — some work runs concurrentlyYesYes, inherently (tracing collectors don’t rely on counts)
JVM ZGCTracing (mark-and-reclaim)Fully concurrentYes (generational mode)Yes, inherently
Go runtimeTracing mark-sweepYes, concurrent and parallel across coresNo (Go’s collector is not generational)Yes, inherently
CPythonReference counting + tracing backstopRefcounting: immediate, synchronous; cyclic GC: runs periodically, not continuously concurrentYes, for the cyclic collector (3 generations)Only via the separate cyclic collector — refcounting alone cannot

Trade-offs

  • Pause time vs. throughput: ZGC buys sub-millisecond pauses at some throughput cost versus G1; Oracle’s own guidance frames this explicitly as a trade a team should choose deliberately, not a free upgrade.
  • Cache behavior vs. simplicity: Go’s object-by-object mark phase is conceptually simple but, per the Go team’s own analysis, jumps unpredictably through memory in ways that hurt CPU cache performance — which is exactly the problem the experimental Green Tea redesign targets by working in whole pages instead.
  • Immediacy vs. completeness: CPython’s reference counting frees most objects the instant they become unreachable, which is great for predictability and for releasing OS resources (file handles, sockets) promptly — but it cannot, by itself, free a reference cycle, which is why the generational cyclic collector exists as a second, separate mechanism layered on top.

If you’re interested in other core engineering mechanisms we’ve covered in depth, see our explainers on Unicode for developers and CRDTs, both of which deal with a similar theme: a runtime or protocol doing complex bookkeeping so application code doesn’t have to.

The Bottom Line

There’s no single “best” garbage collector, only a best fit for a workload’s latency and throughput requirements. The JVM gives you an explicit choice (G1 for balanced throughput and response time, ZGC when sub-millisecond pauses matter more than raw speed). Go gives you one well-tuned, concurrent mark-sweep collector with no manual collector selection, and active engineering work (Green Tea) aimed at reducing its CPU overhead without changing its external behavior. Python gives you fast, deterministic reference counting for the common case, with a separate, tunable cyclic collector that exists solely to catch the one class of object that counting can’t: reference cycles. Understanding which mechanism your runtime uses — and what it’s bad at — is usually more useful for diagnosing a memory problem than reaching for a tuning flag first.

FAQ

Which Java garbage collector is the default?
G1 is the default on most hardware and OS configurations in modern HotSpot JVMs; Serial is the default only on certain limited configurations.

Does Go have generational garbage collection like Java?
No. Go’s collector is a concurrent, parallelized mark-sweep collector, but per the Go team’s own description it is not generational the way G1 or ZGC are.

Can I turn off Python’s garbage collector?
You can disable the cyclic collector with gc.disable() or by setting threshold0 to 0. Reference counting itself cannot be disabled — it’s built into how CPython manages every object.

Why does a reference cycle leak memory in Python if nothing can reach it?
Because reference counting only looks at each object’s own count of incoming references. Two objects referencing each other keep each other’s count above zero even when nothing outside the cycle can reach either one — which is exactly the gap the generational cyclic collector is designed to close.

Is ZGC always better than G1 because its pauses are shorter?
No. Oracle’s own documentation frames this as a trade-off, not a strict upgrade: ZGC’s sub-millisecond pauses come at some cost to overall throughput compared to G1, so the right choice depends on whether your application cares more about response time or total work done per second.

Sources

Posted in software online review

Chromium

https://en.wikipedia.org/wiki/Chromium_(web_browser)

The One Investment Rule

https://youtu.be/IBD_AdM3WNI?si=xORYvpzXfwyYxO-a

Chromium org

https://www.chromium.org/chromium-projects/

browsing history

https://interestingengineering.com/culture/chatgpt-to-absorb-users-life-history

ghat gpt – gemini – missing personality

https://www.tomsguide.com/ai/i-switched-from-chatgpt-to-gemini-for-one-week-and-heres-why-im-going-back-to-chatgpt

Chromium base

https://www.pcmag.com/comparisons/chatgpt-vs-gemini-which-ai-chatbot-is-actually-smarter

Gemini

https://gemini.google.com/app/download

https://gemini.google/subscriptions/

Chat Gpt – Open AI

https://chatgpt.com/

https://openai.com/

https://en.wikipedia.org/wiki/OpenAI