Go
Zero Values Are Useful
In most languages, a freshly declared variable is either uninitialized garbage you can’t touch safely, or it needs a constructor call before it …
Value vs Pointer Receivers
Value vs pointer receivers is one of those topics that seems like a style preference until it silently breaks your program. The tell is a method that …
Production Concurrency Architecture
This is the lesson I wish existed when I started. Not “here’s how channels work” or “here’s a simple worker pool” …
Testing with Real Databases
For years, the standard advice for testing Go database code was to use sqlmock — a library that intercepts database calls and lets you assert which …
Table-Driven Tests
Most engineers know to write tests. Fewer think about how the test code itself should scale. When you need to cover thirty input variations of a …
Idempotency in Concurrent Systems
Every distributed system I’ve worked on eventually ran something twice. A retry after a timeout. A duplicate webhook delivery. A job that got …
Migrations Without Downtime
The first time I caused a production outage with a database migration, I was adding a NOT NULL column to a table. The migration looked innocent. It …
Small Packages Win
There is a particular kind of Go codebase that’s immediately recognizable as written by someone still thinking in another language. It has a …
Safe Background Jobs in Web Servers
The first time I saw go func() inside an HTTP handler, I thought it was clever. Fire off the slow work in the background, respond to the client fast, …
Observability for Concurrency
The goroutine leak doesn’t announce itself. It just slowly inflates your memory graph — 50MB, 80MB, 150MB — until either your alerting fires or …
Slices Are Views, Not Arrays
If you’re coming from Python, JavaScript, or Java, slices look familiar enough that you’ll assume you understand them. That assumption …
Testing Concurrent Code
A flaky test is a lie your codebase tells you. It says “this sometimes works and sometimes doesn’t” and if you’re honest with …
Simplicity Is a Language Feature
Every Go design decision that looks like a missing feature is actually a deliberate choice to remove cognitive overhead. No method overloading. No …
The N+1 Problem
The N+1 problem is the most common database performance issue I find when reviewing Go code, and it’s especially sneaky because it looks totally …
Distributed vs Local Concurrency
There’s a particular kind of confidence that comes after you’ve spent a few months writing Go. You’ve learned channels, you …
select Is Elegant
Every non-trivial concurrent program eventually needs to wait on more than one thing at a time. Maybe you’re waiting on a job channel but also …
Rate Limiting and Load Shedding
The most honest thing a server can do is say “no.” Not crash, not time out after 30 seconds, not queue work indefinitely until memory …
Context with Database Queries
We once had a query that ran for 47 minutes. I’m not joking. A reporting query that worked fine on the test dataset decided to do a full …
range Gotchas
range looks harmless. Index and value, loop over a slice — what could go wrong? Quite a bit, it turns out. Some of the most insidious bugs I’ve …
Supervisor Patterns
Erlang got famous for the “let it crash” philosophy. The idea is that trying to handle every possible error in every possible place …
Prefer Plain Structs
There is a particular brand of cleverness that feels deeply satisfying to write and deeply painful to maintain. The AbstractServiceProviderFactory. …
Profiling Contention
You’ve added goroutines, you’ve got worker pools, you’ve written careful concurrent code — and the service is still slower than …
Nil Slice vs Empty Slice
Go has two ways to have a slice with zero elements, and they are not the same thing. Developers coming from Python, Ruby, or JavaScript expect an …
Ordering vs Throughput
Here’s a tension that comes up in almost every real concurrent system: you want to process things fast, which means doing them in parallel, but …
sqlc vs ORM vs Raw SQL
Every time someone asks “should I use GORM or raw SQL?” a flame war breaks out. I’ve been on both sides of that argument, and …
sync.Mutex Is Often Simpler
After you absorb the Go concurrency philosophy — share memory by communicating — there’s a temptation to reach for channels every time two …
Backpressure Design
Every system has a throughput ceiling. The question isn’t whether your service can be overwhelmed — it can. The question is what happens when it …
Go Scheduler Behavior
Most Go developers write concurrent code for years without thinking about the scheduler. That’s by design — the scheduler is supposed to be …
Multiple Return Values
In most languages, a function returns one thing and communicates failure through a side channel — an exception, a null, a magic sentinel value. …
The Repository Pattern
The repository pattern is one of those ideas that sounds great in an architecture talk and causes real pain when applied indiscriminately to a Go …
sync.Cond
Every Go concurrency course covers goroutines, channels, mutexes, WaitGroups, and maybe semaphores. Very few touch sync.Cond. It’s either …
Atomic Operations
The first time I looked at sync/atomic, it felt like a niche tool for systems programmers writing lock-free data structures. Turns out it’s one …
iota for Enums
Go doesn’t have a built-in enum keyword. What it has is iota, a constant counter that resets to zero at the start of each const block and …
Semaphores for Concurrency Limits
There’s a class of production bugs I see over and over — and the cause is almost always the same: nothing is telling the program to slow down. A …
internal Package Is Underrated
Go has two visibility levels: exported (starts with a capital letter) and unexported (doesn’t). Most engineers use only these two. But …
Transactions That Don't Bite
Transactions are the part of database programming where “it’s fine most of the time” really isn’t good enough. A buggy SELECT …
errgroup for Structured Concurrency
There’s a pattern that comes up constantly in backend services: make N concurrent calls, collect all their results, and if any one of them …
Timeouts Everywhere
I have a strongly held opinion about timeouts: if you’re making a network call, a database query, or waiting on any external resource without a …
Implicit Interfaces
In Java or C#, you declare that a class implements an interface. You write implements Runnable, and the compiler ties that class to that interface …
Leak Prevention
Goroutine leaks are the memory leaks of concurrent Go. They’re slow, invisible, and tend to surface only under load — or worse, only after days …
Goroutines Are Cheap, Not Free
“Goroutines are cheap” is something you read in every Go introduction. It’s true. A goroutine starts with a 2KB stack and the …
Connection Pool Tuning
Here’s a scenario that played out for me once: service is running fine for weeks, then we double traffic, and suddenly requests start timing …
Graceful Shutdown
Most Go services handle startup carefully and shutdown carelessly. The startup code has retries, health checks, dependency validation. The shutdown …
Error Values, Not Exceptions
In most languages, errors are events — they get thrown, they propagate up the call stack, and you catch them somewhere above. Go rejects this model …
Pipelines and Stage Isolation
A pipeline is how you turn a stream of work into a sequence of transformations without writing a single monolithic function that does everything. Each …
Error Handling
If you’re coming from Python, Java, or JavaScript, Go’s error handling will feel strange at first. There’s no try/catch. No …
Worker Pools
Production Go codebases that run fine in staging will sometimes crater under real traffic. More often than not, the cause is unbounded goroutine …
Agent Architectures
An agent is a loop: observe, think, act, repeat. The LLM is the “think” step — it decides what to do next given the current state. Your Go …
database/sql Done Right
I spent a long time reaching for third-party database libraries in Go before I actually read the database/sql docs. When I finally did, I was …
strings and bytes Builders
String concatenation with + is one of the most common performance bugs I see in Go code reviews. Not because developers are careless, but because the …
Over-Engineering CRUD
There is a category of service that I have built many times and will build many more times: an API that creates, reads, updates, and deletes records …
defer for Cleanup
Every time you open a file, acquire a lock, or start a database transaction, you’ve created a resource that needs to be released when …
Fan-Out / Fan-In
There’s a moment in every Go developer’s journey where the serial loop stops being acceptable. You’ve got 200 URLs to fetch, 500 …
The Complete Go Service
Every lesson in this series has been a piece of a puzzle. HTTP routing, middleware, validation, error responses, pagination, idempotency, timeouts, …
API Gateway Patterns
The first time I connected a mobile frontend directly to 11 microservices, I created 11 places for the mobile team to integrate, 11 different auth …
context.Context
Without context.Context, a function that makes a database call, fires an HTTP request, or runs a long computation has no way to be told to stop. The …
Zero-Downtime Deploys
The first rolling deployment I did without graceful shutdown handling produced about 200 errors for in-flight requests. Kubernetes sent SIGTERM to the …
Production Error Architecture
This is the lesson where everything comes together. Over the previous seven lessons we’ve looked at sentinels and typed errors, wrapping …
Race Conditions and the Go Memory Model
Race conditions are the category of bug that makes senior engineers paranoid and junior engineers dismissive. They don’t reproduce consistently. …
go:generate and Code Generation
go:generate is Go’s mechanism for attaching arbitrary code generation commands to your source files. It is not magic — it is a convention that …
Packaging and Distributing
Building a great CLI tool is half the job. The other half is getting it to users without making them compile it from source, navigate a GitHub …
Composition Over Inheritance
If you’ve come from Java or C++, you’re probably waiting for Go to show you its inheritance model. Where’s the extends keyword? …
Linting with golangci-lint
I made a rule for myself a few years ago: if I leave a code review comment about something a tool could have caught, I’ve wasted both the …
Mutexes Done Right
Channels get the spotlight in Go talks and blog posts — they’re the shiny, idiomatic, philosophically interesting tool. Mutexes feel like the C …
context Internals
context.Context is the most important type in Go’s standard library that most people use by convention without fully understanding. You pass it …
sync.WaitGroup
sync.WaitGroup is one of the first concurrency primitives you reach for in Go, and also one of the first you misuse. The API looks deceptively simple …
Fake Clean Architecture
I cloned a Go repository that was described to me as a “clean architecture” implementation. It had six layers: handler, usecase, service, …
The comma ok Idiom
There are three places in Go where a missing second return value means your program either silently does the wrong thing or blows up entirely: reading …
Embedding and Vector Search
For a long time, embedding-based semantic search felt like Python territory. The tutorials all pointed to LangChain, FAISS, and numpy. But the actual …
gRPC Basics and Streaming
My team migrated a set of internal service APIs from JSON over HTTP/1.1 to gRPC roughly two years ago. The motivating factors were type safety across …
Panic, Recover, and When They're Actually Justified
I’ve seen panic(err) used as error handling more times than I’d like to admit — including in codebases I helped build. The reasoning …
Buffered vs Unbuffered Channels
The first time someone tells you that buffered channels are faster, you believe them — and you spend the next year throwing make(chan T, 100) at every …
Config Management
I have seen configuration managed in at least ten different ways across the Go projects I have worked on: hardcoded constants, config structs passed …
Designing Interfaces for Libraries
Writing a library for other Go developers is a fundamentally different design problem than writing application code. In an application, you control …
Dependency Scanning
The security posture of your Go application is not just about the code you write — it is also about the code you import. A typical Go microservice …
Channels Are for Coordination
Channels are Go’s most recognizable concurrency feature, and also one of the most misused. The moment engineers learn about them, there’s …
Channel Ownership Rules
At some point, you’re going to close a channel twice and the runtime is going to panic with close of closed channel. Or you’re going to …
Capacity Matters
There’s a one-line fix that will make your hot paths faster, use less memory, and reduce GC pressure. It costs you nothing in readability. Most …
Error Boundaries Across Layers
One of the most subtle security issues I’ve encountered in Go APIs isn’t an authentication bug or a missing authorization check — …
Saga Pattern
Two-phase commit is theoretically elegant and operationally painful. I’ve seen it cause system-wide deadlocks during network partitions, …
String Internals
I used to reach for []byte over string in performance-sensitive code, assuming strings were somehow more expensive because “immutability must …
Cancellation with context.Context
Without context.Context, you have goroutines running long after the user who triggered them gave up, HTTP connections burning server resources for …
Profiling in Containers
The first time I needed to profile a Go service in production, I assumed I’d have to deploy a special build, reproduce the problem locally, or …
Avoiding Premature Optimization
I’ve spent time in this series showing you how to make Go programs faster — escape analysis, stack allocation, pre-sizing data structures, …
Avoiding Reflection
After spending several lessons on what reflection can do, it is worth turning the question around: when should you specifically choose not to use …
Accept Interfaces, Return Structs
Here’s a mistake I see in almost every Go codebase written by people coming from Java or C#: they accept concrete types everywhere and return …
Goroutine Lifecycle Management
Nobody tells you that the first goroutine you “fire and forget” in production is the one that eventually takes down your service at 3 AM. …
Build Flags and ldflags
A CLI tool that cannot tell you what version it is running is a frustrating tool to operate. When something breaks, the first question is “which …
Premature Abstraction
There is a principle in software development — “Don’t Repeat Yourself” — that is so widely known it gets abbreviated to DRY and …
Kill the Utils Package
Every Go codebase I’ve worked on for more than a year has a util package. Some have a helpers package. Some have both. I’ve seen common, …
Test Architecture
Every test suite starts clean. Then the codebase grows, the team grows, deadlines hit, and gradually the tests become the thing you dread touching. …
sync Package Complete Guide
The sync package is where Go’s concurrency tools live when channels aren’t the right answer. sync.Mutex, sync.RWMutex, sync.WaitGroup, …
Outbox Pattern
Here’s a bug that’s bitten almost every distributed system I’ve worked on: a service saves a record to the database and then …
Logging vs Returning
There’s a smell I encounter in almost every codebase I’ve reviewed — including ones I wrote early in my Go career. Someone discovers that …
Rate Limiting
A service I was running had no rate limiting. One night, a script that a client was testing started sending requests in a tight loop — about 4,000 …
Tool Calling Patterns
Tool calling is where LLM integrations get genuinely powerful. Without tool calling, you’re limited to asking the model to generate text. With …
Secure HTTP Defaults
When I run the Go HTTP server in the standard library with no configuration, it does a lot of things right — it is fast, it handles HTTP/2, it is …
The io.Reader/Writer Ecosystem
If you want to understand what makes Go interfaces powerful, do not start with your own code. Start with io.Reader. It is one method — Read(p []byte) …
The Complete Observability Stack
We have covered each signal in isolation — structured logs, Prometheus metrics, OpenTelemetry traces, correlation IDs, pprof profiles, and latency …
What's New in Go 1.25–1.26
Every major Go release follows a rhythm: one or two headline language features, a handful of standard library additions, and a runtime improvement you …
Values Copy vs Share
Early in my Go career I had a bug where I modified a slice inside a function expecting the caller’s slice to remain unchanged — and it did. Then …
Operational vs Domain Errors
One of the more expensive lessons I learned was treating all errors the same. When a database connection drops, you retry. When a user sends an …
go.work and Workspace Mode
Before go.work existed, developing across multiple local Go modules was genuinely painful. You were working on a library in one directory and an …
CPU vs Memory Tradeoffs
Every performance optimization ultimately makes the same trade: you’re giving up memory to gain CPU time, or giving up CPU time to reduce memory …
Panic as Error Handling
I have reviewed Go code from developers who learned other languages where exceptions are the primary error handling mechanism. In Ruby, Python, or …
Flaky Test Control
A flaky test is a test that sometimes passes and sometimes fails with no code change in between. It sounds like a minor annoyance. It’s actually …
Race Detector in CI
A data race is a memory safety bug. Two goroutines access the same variable without synchronization, at least one is writing, and the Go memory model …
Validation Frameworks
Input validation is one of those problems that looks solved until you realize you are writing the same type of check — not nil, min length, valid …
Package Cohesion
Go packages are the primary unit of code organization. They determine what’s visible to whom, what gets compiled together, and — most …
Embedding Assets
Before Go 1.16, embedding static assets in a Go binary required either a code generation tool that converted files to byte arrays, a third-party …
Wrapping Strategy
There’s a certain kind of error message I’ve come to dread in production logs: auth: db: sql: connection refused. Technically, it contains …
Timeouts and Retries
I once watched a service die in slow motion. An upstream dependency started responding slowly — not failing, just slow. Within minutes, all request …
Distributed Tracing
Debugging a microservices system with only logs is like debugging a multi-threaded program with only print statements — possible, but painful in ways …
Eventual Consistency
I used to believe that eventual consistency was an exotic property of distributed databases that I’d only encounter at Google scale. Then I …
os and filepath
Go’s os and path/filepath packages are among the most underappreciated in the standard library. Most developers know os.Open, os.Create, and …
Race-Aware Tests
A test suite that passes without -race is not a clean bill of health. It’s a test suite that hasn’t checked one of the most insidious …
JWT Caveats
JWT has become the default answer to “how should I handle authentication tokens?” in the Go community. I have shipped JWTs in production …
Debugging Latency and Leaks
We had a service whose p99 latency was 800ms. The p50 was 12ms. The SLA was 200ms at p99. All our dashboards showed the p99 breaching during peak …
Swallowing Errors
We had a deployment where user preferences stopped being saved. New preferences were accepted by the API — the endpoint returned 200 — but nothing was …
errors.Is and errors.As
Go 1.13 shipped what I consider the most important error-handling improvement the language has had: errors.Is, errors.As, and the %w verb. Before …
Memory Alignment and Struct Padding
I once reviewed a PR where someone had defined a struct with a bool field between two int64 fields, resulting in a 24-byte struct instead of the 17 …
Testability Without Over-Mocking
Mock frameworks are a seductive solution to a real problem. You have a dependency — a database, an email service, an HTTP client — and you need your …
pprof Deep Dive
When I first learned about pprof, I thought it was a single tool that told you “what’s slow.” It took me an embarrassingly long time …
Dependency Direction
We fixed cycles in lesson 2. But removing cycles is a necessary condition for good architecture, not a sufficient one. You can have a perfectly …
Streaming Responses
If you’ve ever used a non-streaming LLM endpoint in a user-facing feature, you know the experience it creates: the user submits a question, …
CI/CD for Go
I’ve set up CI pipelines for Go services about a dozen times, and every iteration taught me something about what the pipeline should actually …
Sentinel vs Typed Errors
When I first started writing Go seriously, I treated errors like fire: try to avoid them, and when you can’t, put them out as fast as possible …
Structured Logging with slog
I have switched logging libraries in Go more times than I care to admit. Started with the standard log package — fine for scripts, useless in …
Cross-Compilation
One of Go’s most practical superpowers is that cross-compilation is a first-class feature, not an afterthought. Two environment variables — GOOS …
Idempotency in APIs
A client sends a payment request. The network times out. The client does not know if the payment was processed. Should it retry? If it retries and the …
Small Functions Win
There is a simple test I apply to any function I’m about to merge: can I name it clearly without using “and”? If the most honest …
Golden File Testing
Some functions produce output that’s too large or too structured to assert inline. A template renderer, a code generator, a JSON serializer for …
Password Hashing
Password hashing is one of those topics where the correct answer is short and clear, the wrong answers are numerous and subtle, and developers who …
Profiling in Production
I used to think profiling was something you did when you had a performance problem: reproduce it locally, run pprof, stare at the flame graph, fix the …
Building a Serializer
encoding/json is Go’s most-used package and one of its most instructive implementations. Under the hood it is almost entirely reflection: it …
Ignoring Context
I spent a Tuesday afternoon tracking down why our service continued doing expensive database work after clients had long since disconnected. An HTTP …
gRPC-Based Plugin Architecture
After I understood how hashicorp/go-plugin worked with net/rpc, the next question was obvious: how does Terraform manage hundreds of …
Message Queues in Go
I’ve integrated all three of these systems in production Go services, and the question I get most often is: “Which one should I …
time Package Gotchas
The time package looks straightforward right up until the moment a bug report arrives saying “the nightly job didn’t run last …
When Duplication Is Better Than Abstraction
I want to end this course with the idea I wish I’d understood at the start — not just intellectually, but in my gut. It’s this: …
GC Behavior and Tuning
For years, tuning Go’s GC meant tweaking GOGC and hoping for the best. I operated on vibes and guesswork. Then Go 1.19 introduced GOMEMLIMIT — a …
Composition with Embedding
One of the things that surprised me most about Go when I came from Python was that Go has no inheritance. No base classes, no method overriding, no …
Benchmarking Done Right
Writing a Go benchmark feels simple. You drop Benchmark in front of a function name, loop from 0 to b.N, run go test -bench=., and get a number. The …
Monolith vs Multi-Module
When I first started structuring larger Go projects, I defaulted to what felt natural: one repository, one go.mod. It worked for a long time. Then I …
Service Discovery
When I first started building Go microservices, every service had a config file with a list of URLs. order-service-url: http://10.0.1.42:8080. That …
Mocking Alternatives
Mocking has a bad reputation in the Go community, and some of it is deserved. Not because mocks are inherently wrong, but because the way most people …
Config Injection
Configuration management is one of those topics that seems solved until you maintain a service that runs in four different environments, has twenty …
Signal Handling
Most CLI tools work perfectly on the happy path and fail silently on the unhappy one. The user presses Ctrl-C, the OS sends SIGINT, and the process …
Pagination Done Right
I have shipped offset-based pagination more times than I would like to admit. It looks clean, it is trivially easy to implement, and it works …
Refactoring Concrete to Generic
The advice “start concrete, extract when proven” is easy to say and surprisingly hard to follow when you’re in the middle of writing …
CGo Performance and Pitfalls
When I profiled a service that was spending 40% of its time in cgo calls, I thought I was measuring the C library. I was not. I was measuring the …
Auth Middleware
A few years ago I audited a Go API where every endpoint was protected by an authentication middleware. The middleware checked for a valid JWT, …
Code Review Heuristics
A good code review is not a diff-reading exercise. It’s a transfer of understanding — the reviewer asks “do I understand what this code …
Correlation IDs
A support ticket lands: “User 8842 says their order failed at 2:47 PM yesterday.” You open your log aggregator. You search for user_id = …
Channel Misuse
Go’s channels are genuinely great. They make certain concurrent programming patterns — pipelines, fan-out, fan-in, worker pools — natural and …
Loop Variable Fix
If you have written Go for more than a few weeks, you have hit this bug. Or you have reviewed code that had it and caught it. Or — if you were unlucky …
Connection Pooling
The first time I benchmarked a Go service against a database, the numbers were embarrassing. Five hundred requests per second, each one taking 30 …
Database Testing with Testcontainers
I used to mock databases. I had a clean Store interface, a MockStore implementation for tests, and 100% coverage on my service layer. I felt good …
Struct Tags
Struct tags are one of Go’s most practically useful metaprogramming tools and one of its least formally documented features. The syntax is …
LLM API Clients
Most Go developers approach LLM APIs the same way they approach any REST API — write an HTTP client, handle errors, parse JSON. That instinct is …
Escape Analysis Deep Dive
I used to assume that every time I wrote &someStruct{} or returned a pointer from a function, I was creating a heap allocation. I was wrong — and …
Real-World Examples
Lessons 1 through 5 were mostly about principles. This one is about code. Specifically, the five generic implementations I’ve used in real …
Returning Concrete Types
There is a piece of Go advice that sounds almost too obvious to state, and yet I see it violated in production codebases every week: return concrete …
encoding/json Beyond Basics
encoding/json is one of the first packages every Go developer uses and one of the last they fully understand. The basic json.Marshal / json.Unmarshal …
Interface Placement
This is the Go idiom that surprises people coming from Java or C# the most. In those languages, you define an interface in the same place as (or even …
String and Byte Conversions
Go strings are immutable. Byte slices are mutable. Converting between them requires copying the data — every time, without exception, unless you use …
Health Checks
I’ve seen two types of health check implementations in production: the ones that always return 200 OK, and the ones that actually check …
Error Responses
I once integrated with an API that returned HTTP 200 for everything — successes and failures alike. The actual outcome was buried in a status field …
SSRF and Injection
I reviewed a Go service that let users provide a “webhook URL” — we would call that URL when their account had a notification. The service …
Distributed Tracing with OpenTelemetry
We had an incident where checkout was timing out intermittently. The logs showed the API gateway receiving the request and returning a 504 after 30 …
File I/O Patterns
CLI tools spend most of their life doing file I/O. Reading config files, processing log dumps, writing output, transforming data from stdin to stdout …
Inter-Service Communication
Every time I’ve seen a team choose their inter-service communication protocol by default — “we’ll use REST for everything” or …
Anti-Patterns
Every powerful tool has a failure mode that looks like success. With generics, the failure mode is this: you write something that compiles, works …
Global Mutable State
There was a test suite I worked on where tests passed individually but failed when run together. The failure pattern was non-deterministic — sometimes …
Idiomatic Naming
When I review Go code, naming problems tell me more about the author’s understanding of the codebase than almost anything else. A function …
HTTP Handler Testing
Every Go HTTP handler is just a function that takes a ResponseWriter and a *Request. That’s the entire contract. The fact that the standard …
Circuit Breaking
There’s a particular kind of production incident that goes like this: Service A calls Service B. Service B starts responding slowly because its …
Go Plugins and hashicorp/go-plugin
The first time I needed a plugin system in Go, I went straight to plugin.Open in the standard library. Ten minutes later I was reading about RTLD …
Method Sets and Addressability
I spent a solid twenty minutes staring at a compilation error that read “does not implement interface (Write method has pointer receiver)” …
Interface Pollution
Interface pollution is not a hypothetical risk. I have walked into codebases where more than half the types in the package are interfaces, where every …
Slice and Map Performance
Slices and maps are so convenient in Go that it’s easy to forget they’re not free. They have hidden costs — in allocations, in CPU cache …
internal/ Usage Patterns
Go does not have access modifiers in the Java or Kotlin sense. There is no protected, no package-private, no friend classes. You get exactly two …
io Patterns
The io package is three hundred lines of interface definitions and a handful of utility functions. It is also the spine of the entire Go standard …
Performance Costs
Every time I see reflection in a hot path, I know there is a performance conversation waiting to happen. Reflection in Go is not arbitrarily slow — it …
Interfaces vs Generics
One of the most common mistakes I see in Go codebases post-1.18 is people reaching for generics when interfaces were already the right tool — and vice …
TLS Configuration
When I started writing Go HTTP servers, I thought TLS was someone else’s problem. A load balancer in front of my service handled HTTPS …
Enhanced HTTP Routing
For most of my Go career, the standard library’s net/http.ServeMux was something I used for toy services and immediately replaced with …
Docker for Go
The first Dockerfile I wrote for a Go service produced a 1.2 GB image. It was based on golang:1.22, which includes the full Go toolchain, build cache, …
Request Validation
I once shipped an endpoint that accepted a limit query parameter for pagination. The valid range was 1–100. I did not validate it. Someone called it …
Config and Env Handling
Configuration is one of those problems that looks trivial until it is not. A single environment variable is three lines of code. A configuration file …
Integration Tests
Unit tests feel productive. You write a function, you write a test, everything goes green, and you merge. But unit tests exist in a bubble — a bubble …
Building MCP Servers in Go
When Claude or another AI assistant needs to look up a database record, call an internal API, or read a file from your filesystem, it can’t do …
Metrics That Matter
The first metrics dashboard I built for a Go service had forty-two graphs. CPU, memory, goroutine count, heap allocations, GC pause duration, request …
Giant God Structs
I inherited a Go service where the primary domain object was a struct with 47 fields. Some were database columns, some were computed from other …
Spotting Over-Abstraction
There’s a version of Go code I see in almost every codebase that’s been touched by developers who came from Java or C# — it’s …
Good Patterns
The best generic code I’ve ever written looks like the worst. No clever type wizardry, no five-level constraint hierarchies — just a function …
CGo Basics
There is a saying in the Go community: “cgo is not Go.” It is not an insult. It is a warning. The moment you add import "C" to a …
Retries with Exponential Backoff
I once worked on a service that retried failed HTTP requests in a tight loop with no backoff and no jitter. When our upstream had a brief outage, …
Nil Interface Gotchas
A few months into my first production Go service, I had a bug that cost me two hours. A function returned an error, I checked if err != nil and it …
Stack vs Heap Intuition
There’s a class of performance bugs in Go that doesn’t show up in code review, doesn’t trigger the race detector, and doesn’t …
Consumer-Side Interfaces
There is a convention I spent a long time following without questioning it: put the interface in the same package as the type that implements it. If I …
Avoiding Cyclic Dependencies
The Go compiler refuses to build a program with a cyclic import. It is not a warning. It is not a lint violation. It is a hard failure. I used to find …
Fuzzing in Go
There’s a class of bugs that you will never find by thinking about edge cases. You’ll think about empty strings, about zero values, about …
Secret Handling
I once found database credentials committed directly in a Go source file — not in a toy project, in a staging environment of a real product. The …
Service Boundaries
The most expensive architectural mistake I’ve seen teams make with microservices is splitting by technical layer instead of by business …
Middleware Patterns
The first time I wrote authentication logic, I put it directly inside each handler. Copy-paste, then copy-paste again. By handler number five I had …
net/http Deep Dive
Every Go web service I’ve reviewed starts with net/http. Most of them use it correctly for the obvious parts and incorrectly for the subtle …
Type Parameters and Constraints
The hardest part of learning Go generics isn’t the concept — it’s the syntax. The first time I read a function signature like func Keys[K …
Static Binaries
The first time I deployed a Go binary to a production server, I was braced for the usual ceremony: SSH in, install the right runtime version, copy …
When Reflection Is Justified
Go’s reflect package carries a reputation: “don’t use it unless you have to.” That advice is correct but incomplete. …
Structured Logging with slog
I spent two years writing Go services that logged like this: log.Printf("processing order %s for user %d, amount %.2f", orderID, userID, …
Building CLIs with Cobra
Every Go project that grows into something useful eventually needs a command-line interface. Maybe it starts as a quick main.go with os.Args[1] checks …
Escape Analysis
I spent the first two years of writing Go completely unaware that the compiler was making decisions about my code that I never asked for — and that …
Interface Everywhere Syndrome
When I came to Go from a Java background, I brought some habits with me that made my code worse, not better. The most persistent one was defining an …
Refactoring Go Code Safely
Refactoring is the one activity that makes codebases better without adding features — and it’s also the activity most likely to introduce bugs …
Subtests and t.Run
I used to write tests the way I wrote the first functions I ever wrote in Go — flat, repetitive, and with names so generic that when they failed, I …
HTTP Client Internals
The first production Go service I wrote hammered our database proxy with thousands of new TCP connections every minute. The proxy started refusing …
Designing HTTP APIs in Go
I spent the first few months of writing Go services reaching straight for a framework. Chi, Gorilla, Echo — I cycled through them trying to find the …
Interface Representation
I remember the first time I hit a bug where err != nil returned true even though the function clearly returned nil. I spent forty minutes staring at …
When NOT to Use Interfaces
The first time I saw Go interfaces click in a codebase, I made the same mistake every developer makes: I started reaching for them everywhere. If I …
What Generics Solve in Go
I spent two years writing Go before generics shipped in 1.18, and I’ll be honest — I didn’t miss them at first. Go’s simplicity felt …
Input Validation
The first production security incident I dealt with involved a simple integer field in a JSON body. The client sent a negative number where we …
Range Over Integers and Iterators
I have written for i := 0; i < n; i++ so many times that my fingers type it on autopilot. The three-clause for loop is fine — it works, everyone …
Package Boundaries
I have refactored a lot of Go codebases — my own included. And the single most common structural mistake I see is the utils package. Or helpers. Or …
What's Next
You made it. Twenty-five lessons ago you didn’t know what package main meant. Now you understand variables, types, functions, error handling, …
The Go Toolchain
One of the things that drew me to Go was that the toolchain ships with the language. You don’t need to choose a build tool, a formatter, or a …
The Type System
When I first came to Go from Python, the type system felt like a lot of ceremony. Why can’t I just use an int where a float64 is expected? Why …
File I/O
At some point every program needs to persist something — a config file, a log, a data export. File I/O is one of those topics that sounds tedious but …
JSON and HTTP
Almost every program I write these days talks to something over HTTP — a third-party API, a database service, a webhook. And almost everything speaks …
Testing in Go
I used to think testing was something you did after you finished writing code — a checkbox you ticked before committing. Go changed that attitude for …
Context
There’s a moment in every Go developer’s journey when they realize that starting an operation isn’t the hard part — stopping it …
The sync Package
Goroutines make concurrency easy to start, but easy to start isn’t the same as easy to get right. The first time I ran multiple goroutines that …
Go Modules
Before Go modules existed, managing dependencies was genuinely painful. People used all sorts of third-party tools with their own conventions, and …
Packages and Imports
Every Go program I’ve written has taught me the same lesson over and over: good code isn’t just about what you write inside functions — …
Select
By now you know how to create goroutines and how to communicate between them using channels. But what happens when a goroutine needs to listen to two …
Channels
In the last lesson, I showed you how to run code concurrently with goroutines. But goroutines that can’t talk to each other aren’t very …
Goroutines
One of the first things people told me about Go was “it makes concurrency easy.” I was sceptical — concurrency is never easy. But the more …
Error Handling
The first time I wrote Go after years of Python and JavaScript, I kept waiting for the try/catch block. It never came. Instead, almost every function …
Interfaces
When I first learned about interfaces in Go, I expected something complicated — annotations, implements keywords, class hierarchies. Instead, Go just …
Pointers
Pointers have a reputation for being scary. In C, they’re the source of buffer overflows, dangling references, and cryptic crashes. In Go, …
Methods
In the last lesson we defined a User struct. We could pass it to functions — birthday(u), sendEmail(u), formatName(u). That works, but there’s a …
Structs
So far we’ve been working with Go’s built-in types: strings, ints, booleans, slices, maps. Those are great, but real programs deal with …
Strings, Runes, and Bytes
Strings look simple. You write "hello", you print it, done. But when I first started working with non-ASCII text in Go — names with accents, …
Maps
Every language has some version of the dictionary or hash map. Python calls it a dict, JavaScript calls it an Object or Map, Ruby calls it a Hash. In …
Arrays and Slices
Go has two sequence types: arrays and slices. I’ll tell you upfront — arrays are rarely used directly. They exist, they matter for understanding …
Functions
If there’s one thing experienced Go programmers agree on, it’s this: write small functions. Not tiny, cryptic one-liners, but focused …
Control Flow
Every program you’ll ever write needs to make decisions and repeat actions. “If this condition is true, do that. Otherwise, do something …
Variables and Types
If you’re coming from Python or JavaScript, Go’s type system might feel like extra work at first. Why should you have to tell the compiler …
Your First Go Program
I remember the first time I ran a Go program. The compiler yelled at me for an unused import, and I thought, “Okay, this language has …