ALL INTELLIGENCE
Hacker News AIT2·Tools

Go Engineering Conventions for AI Inference Gateways

Original title: Go Conventions That Clicked Too Late for an AI Engineer
45AI Score

This article outlines critical Go engineering conventions learned through production failures in AI inference gateways. It highlights that issues like misusing `context`, leaking error wrapping, and improper goroutine management are not just syntax errors but vital stability patterns, offering lessons to prevent costly debugging cycles.

Full Report

Contents14 sections

The ones that only make sense after you’ve been burned by them

Image 1: Cheikh seck

8 min read

2 days ago

I spent three years writing Go for inference gateways before I realized I was fighting the language instead of using it.

I’d write a handler, ship it, and six months later someone would point out that I’d used context wrong, or that my error wrapping was leaking, or that my goroutine was going to take down the pod. Each time I'd think: why didn't anyone tell me this in week one?

These aren’t rules you learn in a tutorial. They’re conventions that only click when you’ve been burned by their absence. Here are the ten that hit me hardest.

Press enter or click to view image in full size

Image 2

1. context Is Not a Request Bag — It's a Cancellation Contract

Everyone’s first instinct is to stuff values into context.WithValue. I did this for two years. Then a timeout propagated through my gateway and took down a model swap because the value was still there.

The convention that clicked: context is for cancellation, deadlines, and tracing — not for passing data your handler needs.

func handler(ctx context.Context) { userID, _ := ctx.Value("user_id").(string) } func handler(ctx context.Context, userID string) { }

What’s happening here: The first version hides a dependency. You don’t know userID exists unless you read the caller. The type assertion silently fails if the value is missing — you get an empty string and no error. The second version makes the dependency visible in the signature. No magic. No surprises.

Full example:01-context-not-a-bag.go

2. errors.Wrap Changes the Error — But errors.Is Walks the Chain

I used to do if err.Error() == "something" and wonder why tests broke when someone refactored a string. The convention that clicked: wrap errors with context, check them witherrors.Is/errors.As, never match strings.

func find(err error) bool { return strings.Contains(err.Error(), "not found") } var ErrNotFound = errors.New("not found")

func find(err error) bool { return errors.Is(err, ErrNotFound) }

What’s happening here: The first version breaks if someone changes the error message. The second version survives refactoring because it checks identity, not text. errors.Is walks the wrap chain — it knows ErrNotFound is inside even if it's wrapped three times.

Full example:02-errors-is-not-strings.go

3. sync.Mutex for Single Values Is a Code Smell — Use atomic or a Channel

I once wrapped a counter in a mutex and spent an hour debugging a deadlock in a hot path. The convention that clicked: if you’re protecting a single value,atomicis faster and simpler. If you're coordinating goroutines, use a channel.

type Counter struct { mu sync.Mutex n int } type Counter struct { n atomic.Int32 }

What’s happening here: A mutex is a general-purpose lock. It’s overkill for a single integer. atomic.Int32 is lock-free, faster, and impossible to deadlock. Save mutexes for protecting maps, slices, or multiple fields that must change together.

Full example:03-atomic-not-mutex.go

4. defer in a Loop Is a Memory Leak — Unless You Scope It

I had a function that deferred cleanup inside a loop processing 10,000 files. The defers stacked up until the function returned. The convention that clicked: defer only defers until the function returns. Inside a loop, use a scoped function or explicit cleanup.

func process(files []string) { for _, f := range files { file, _ := os.Open(f) defer file.Close() } } func process(files []string) { for _, f := range files { func() { file, _ := os.Open(f) defer file.Close() }() } }

What’s happening here: In the first version, every defer waits until the function returns — not the loop iteration. If you process 10,000 files, all 10,000 file handles stay open until the function exits. The second version wraps each iteration in a closure, so defer fires when the closure returns — which is every iteration.

Full example:04-defer-in-loop.go

5. interface for Configuration Is a Trap — Use Struct Tags

I defined a Config interface and spent weeks debugging why a field was nil. The convention that clicked: use structs with tags. Interfaces for behavior, structs for data.

type Config interface { GetTimeout() time.Duration GetRetries() int } type Config struct { Timeout time.Duration default:"30s" Retries int default:"3" }

What’s happening here: An interface for config means every consumer must implement methods. You can’t easily serialize it, validate it, or set defaults. A struct with tags works with encoding/json, yaml, and any validator you want. Data is data — interfaces are for behavior.

The field tags in this example are purely visual and serve no actual functionality.

Full example:05-struct-not-interface.go

6. log Is for Humans — slog Is for Machines

I used log.Printf for years and then tried to parse my logs with grep. The convention that clicked: structured logging withslogmakes logs queryable. Your gateway's access logs should be JSON.

log.Printf("request for model=%s tokens=%d", model, tokens) slog.Info("request completed", "model", model, "tokens", tokens, )

What’s happening here: The first version produces a string that needs regex to parse. The second version produces JSON with named fields. Your log aggregator can query by model or tokens without writing parsers. In production, this is the difference between "I don't know why latency spiked" and "latency spiked for model X with token count > 1000."

Full example:06-slog-not-log.go

7. panic Is a Bug — Not a Feature

I once used panic to enforce an invariant in a config parser. The convention that clicked: panic only for truly unrecoverable situations (likeruntimeerrors). Useerrorreturns for everything else.

func parse(data []byte) { if len(data) == 0 { panic("empty config") } } func parse(data []byte) error { if len(data) == 0 { return fmt.Errorf("empty config") } return nil }

What’s happening here:panic crashes the entire process. There's no recovery unless you explicitly add recover() — and even then, it's messy. An error return lets the caller decide: retry, fall back, or exit cleanly. In a gateway, a panic takes down all active connections. An error doesn't.

Full example:07-panic-not-control.go

8. time.Now in Tests Is a Recipe for Flaky Tests

I had a test that compared timestamps and it failed randomly. The convention that clicked: usetime.Datefor fixed times, orclockpackage for injectable time. Tests should be deterministic.

func age(birthDate time.Time) int { return int(time.Since(birthDate).Hours() / 24 / 365) } func age(birthDate, now time.Time) int { return int(now.Sub(birthDate).Hours() / 24 / 365) }

What’s happening here: The first version depends on when the test runs. Run it at midnight and the age changes. The second version takes now as a parameter — in tests, you pass a fixed time. In production, you pass time.Now(). Same function, deterministic tests.

Full example:08-fixed-time-not-now.go

9. http.Client Timeout Is Not Enough — Set Timeout on the Transport Too

I had a gateway that hung for minutes because the client had a timeout but the transport didn’t. The convention that clicked: setTimeoutonhttp.ClientANDIdleConnTimeouton theTransport. A timeout on the client doesn't close idle connections.

client := &http.Client{ Timeout: 30 * time.Second, } client := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ IdleConnTimeout: 90 * time.Second, }, }

What’s happening here:http.Client.Timeout covers the entire request lifecycle — DNS, connect, send, receive. But it doesn't close idle connections sitting in the pool. IdleConnTimeout on the Transport does that. Without it, your gateway leaks connections until the process runs out of file descriptors. Both settings are needed.

Full example:09-transport-not-client.go

10. go.mod``// indirect Is a Warning — Not a Comment

I ignored // indirect for months and wondered why my build was slow. The convention that clicked: // indirectmeans the dependency isn't imported directly. It's a signal to rungo mod tidyand check your dependency graph.

require ( my-app v1.0.0 golang.org/x/exp/slog v0.0.0-20240123 ) What’s happening here: The // indirect comment means slog is needed by another dependency, not by your code directly. But it's also a signal: if you see this and you are importing slog, run go mod tidy. If you see it and you're not importing it, someone's dependency is leaking into your binary. Either way, it's information, not decoration.

Full example:10-indirect-not-comment.go

Conclusion: Why These Conventions Matter

These ten conventions aren’t about writing correct Go. They’re about writing Go that survives contact with production.

Each one of them bit me in a way that took months to diagnose. A context value that survived a timeout and corrupted a model swap. A string match that broke when someone refactored an error message. A mutex that deadlocked in a hot path. A defer that leaked file handles until the pod ran out of memory.

These aren’t academic concerns. They’re the difference between a gateway that runs quietly for months and one that wakes you up at 3am.

The deeper pattern is this: Go is a language that rewards explicitness. Every time I tried to be clever — hiding a dependency in context, matching strings instead of errors, panicking instead of returning — I paid for it later. The conventions that clicked were the ones that made the code more honest about what it was doing.

The Takeaway

Press enter or click to view image in full size

Image 3

Pick one. Don’t rewrite your codebase. Find the convention that bit you last week. Fix it. The rest will click when you need them to.

What to Ignore

  • Don’t memorize these. They’re conventions, not rules. They’ll click when you hit the pain they solve.
  • Don’t argue about style. These are production-proven, not opinion. If you have a better pattern, great — but show me the outage it prevented.
  • Don’t rungo mod tidyin production. The // indirect warning is for your local checkout, not your deployed binary.