System Design

G8

Packages and modules

How Go code is cut into packages, how packages start, and how the go command picks each version of each dependency. Every output on this sheet comes from the real go command, run against a private proxy.

Not startedSaved in this browser only.
  1. 1A package is a folder and the unit of import. A module is a tree of packages and the unit of version.
  2. 2Initialization follows dependencies, not source order. Do not depend on anything else.
  3. 3Minimal version selection takes the highest version that any go.mod asks for. A new release changes nothing by itself.
  4. 4replace and exclude work only in the main module. A library cannot force them on you.
G8
    A

    The trap

    main imports alpha first, and beta runs first
    main.gogo
    package main
    
    import (
    	"fmt"
    
    	"example.com/shop/alpha"1
    	"example.com/shop/beta"
    )
    
    func init() { fmt.Println("main init") }
    
    func main() {
    	fmt.Println("main", alpha.Name, beta.Name)
    }
    1. 1Listed first, and it does not run first.
    recorded outputstdout
    $ go run .
    beta init: beta
    zeta init: zeta
    alpha init: alpha+zeta
    main init
    main alpha+zeta beta
    alpha/alpha.gogo
    package alpha
    
    import (
    	"fmt"
    
    	"example.com/shop/zeta"1
    )
    
    var Name = "alpha+" + zeta.Name
    
    func init() { fmt.Println("alpha init:", Name) }
    1. 1alpha must wait for zeta.
    beta/beta.gogo
    package beta
    
    import "fmt"
    
    var Name = "beta"1
    
    func init() { fmt.Println("beta init:", Name) }
    1. 1beta imports only fmt, so it is ready first. zeta has the same shape as beta.
    • Since 1.21 the go tool sorts packages by import path. It then takes the first package whose imports are done.
    • alpha sorts first but is not ready. beta is ready, so beta runs. Then zeta, then alpha, then main.

    Initialization order follows the import graph. If two packages have no link, sorted import path decides, so I never rely on it.

    B

    The model: module, package, file

    three layers, three jobs
    module example.com/shop: go.mod, go.sumcmd/apipackage mainmain.goorderspackage ordersorders.goorders_test.goorders/internal/taxpackage taxtax.gotax_linux.goModuleThe unit of version anddownload. Holds one tree.PackageOne folder. The unit ofimport, compile and scope.FileBuild constraints decideif the compiler sees it.

    I version a module, I import a package, and I select a file with build constraints.

    C

    The rules: package design and naming

    the name is part of every call
    ruleexamplestatus
    Short, lower case, one word, no underscoreorders, tax, httpApproved
    Name it for what it providescache.Get, not data.GetCacheApproved
    Do not repeat the package name in exportshttp.Server, not http.HTTPServerApproved
    Keep main small: parse flags, wire, runcmd/api/main.goApproved
    Start with internal/, and export only on demandinternal/storeApproved
    Define an interface in the package that consumes itorders.StoreApproved
    Split a package when two parts change for different reasonsorders, billingNot by type
    A package that names nothingutil, common, helpersNot approved
    One package per type, in the Java stylemodels, servicesNot approved
    An import cycle; the compiler refuses ita imports b imports aMove the shared part

    A package name is a word that reads well before the dot. If the best name is util, the package has no single job.

    D

    internal/

    recorded: the go command enforces this
    another module imports itterminal
    $ go build -o /dev/null .
    package example.com/shop
    	main.go:6:2: use of internal package example.com/secure/internal/pay not allowed
    a sibling folder imports itterminal
    $ go build ./orders/...
    $ go build ./billing
    package example.com/shop/billing
    	billing/billing.go:3:8: use of internal package example.com/shop/orders/internal/tax not allowed
    • orders/internal/tax is open to orders and to orders/api. billing is a sibling, so the build fails.
    • Use it to keep a public API small: you can change internal code with no major version.

    A package under internal is importable only from the tree rooted at the parent of internal. The go command enforces it, also inside one module.

    E

    Initialization rules

    the Go spec, and recorded in the drill
    steprulestatus
    1Each package initializes once, after all of its imports, however many packages import it.Approved
    2Package variables start in declaration order. A variable waits for each variable that it refers to, also through a function.Approved
    3Then init functions run. A package can have many, and no code can call them.Approved
    4All of this runs in one goroutine. main.main starts after every init returns.Approved
    useRegister a driver or a codec in init, through a blank import.Standard pattern only
    useA dependency hidden by an interface call. The spec leaves that order open.Not approved
    useI/O, flags or network calls in init. A test cannot skip them, and a failure can only panic.Not approved

    Each package initializes once: imports first, then variables by dependency, then each init. I keep init small and free of I/O.

    F

    See it: minimal version selection

    step through it; the result is go list -m all from a real run
    shopmain modulea v1.2.0b v1.2.0c v1.3.0not readc v1.4.0c v1.5.0publishedd v1.1.0d v1.2.0d v1.3.0published

    Step 1: Main module

    • Start at the main module, which has no version.
    • Each require line is a minimum: a v1.2.0 or higher, b v1.2.0 or higher.

    If it fails

    A go.sum entry that is missing stops the command. The go command does not add one in a read-only build.

    MVS walks the graph and keeps the highest version that anyone required. There is no solver and no lock file, so the build list is the same tomorrow.

    G

    What each change does to the build list

    recorded: go list -m all after each change
    changeabcdwhy
    Nothingv1.2.0v1.2.0v1.4.0v1.2.0The highest that any go.mod asks for.
    go get [email protected]v1.2.0v1.2.0v1.5.0v1.3.0c v1.5.0 needs d v1.3.0, so d moves too.
    go get [email protected]v1.2.0v1.1.0v1.3.0v1.2.0b v1.2.0 needs c v1.4.0, so b moves down.
    exclude c v1.4.0v1.2.0v1.2.0v1.3.0v1.2.0The requirement is ignored, so b runs below what it asked for.
    replace c => ./forks/cv1.2.0v1.2.0v1.4.0 => ./forks/cv1.2.0The version stays. The code comes from the folder.
    a replace in a dependency has no effectterminal
    $ go list -m all
    example.com/shop
    example.com/c v1.3.0
    example.com/d v1.1.0
    example.com/e v1.0.0
    $ go run .
    e v1.0.0 > c v1.3.0 > d v1.1.0
    a replace in the main moduleterminal
    $ go list -m all
    example.com/shop
    example.com/a v1.2.0
    example.com/b v1.2.0
    example.com/c v1.4.0 => ./forks/c
    example.com/d v1.2.0
    $ go run .
    a v1.2.0 > c forked > d v1.2.0
    b v1.2.0 > c forked > d v1.2.0

    Upgrades move one path and what it needs. exclude and replace change the graph, and they apply only in the main module.

    H

    MVS in one function

    tested: it matches go list -m all
    BuildListgo
    // Version is one release of a module, such as {"C", 3} for C v1.3.0.
    type Version struct {
      Path  string
      Minor int
    }
    
    // Graph maps each module version to the versions it requires.
    type Graph map[Version][]Version
    
    // BuildList walks everything reachable from main, and keeps the highest
    // version it sees of each path. No solver runs, and no choice is made.
    func BuildList(g Graph, main Version) []Version {
      best := map[string]int{}
      seen := map[Version]bool{}
      var walk func(v Version)
      walk = func(v Version) {
        if seen[v]2 {
          return
        }
        seen[v] = true
        best[v.Path] = max(best[v.Path], v.Minor)1
        for _, dep := range g[v] {
          walk(dep)
        }
      }
      walk(main)
      delete(best, main.Path)3
    
      list := make([]Version, 0, len(best))
      for _, path := range slices.Sorted(maps.Keys(best)) {
        list = append(list, Version{path, best[path]})
      }
      return list
    }
    1. 1The only decision: keep the highest version seen for each path.
    2. 2The graph can contain cycles, so stop at a version already visited.
    3. 3The main module has no version, and it is not in the list.

    The whole algorithm is a graph walk with a max per path. I can write it on a whiteboard.

    I

    go.mod, after go mod tidy

    recorded
    go.modgo.mod
    module example.com/shop1
    
    go 1.272
    
    require (
    	example.com/a v1.2.0
    	example.com/b v1.2.0
    )
    
    require (
    	example.com/c v1.4.0 // indirect3
    	example.com/d v1.2.0 // indirect
    )
    1. 1The import path prefix of each package here.
    2. 2The language version, and the minimum toolchain.
    3. 3No package here imports c directly. This line lets the go command skip deeper go.mod files.
    go mod graph: c v1.3.0 has no outgoing edgesterminal
    example.com/shop example.com/[email protected]
    example.com/shop example.com/[email protected]
    example.com/shop example.com/[email protected]
    example.com/shop example.com/[email protected]
    example.com/shop [email protected]
    example.com/[email protected] example.com/[email protected]
    example.com/[email protected] example.com/[email protected]
    example.com/[email protected] [email protected]
    example.com/[email protected] example.com/[email protected]
    example.com/[email protected] example.com/[email protected]
    example.com/[email protected] [email protected]
    example.com/[email protected] example.com/[email protected]
    example.com/[email protected] [email protected]
    example.com/[email protected] [email protected]
    [email protected] [email protected]

    Direct and indirect requirements sit in two blocks. The indirect block is what makes graph pruning work.

    J

    go.mod directives

    go.dev/ref/mod; each one checked against a run or the reference
    directivewhat it doesapplies insince
    moduleThe path of this module.Every module
    goLanguage version and minimum toolchain. A strict minimum since 1.21.Every module1.21
    toolchainA suggested toolchain, not below the go line.Main module1.21
    godebugGODEBUG defaults for this build.Main module1.23
    requireA minimum version of a dependency.Every module
    toolA package to run with go tool. Needs a require line.Main module1.24
    ignoreFolders that package patterns skip. They stay in the module zip.This module1.25
    excludeA version that must not load.Main module only
    replaceOther code for a version: a fork, or a local path.Main module only
    retractMarks your own bad releases, so go get avoids them.The latest version of that module

    require is a minimum. replace and exclude are local to the main module. tool and ignore are newer, and they remove old workarounds.

    K

    go.sum

    recorded
    two lines per module: code, and go.modterminal
    $ cat go.sum
    example.com/a v1.2.0 h1:YSwjZ5JwWj2yBGTNtMwdfAYUu4yZIINu5/wQIz0nRrE=
    example.com/a v1.2.0/go.mod h1:daNonZL2PaAIl/yidmaNSrA/6BPWJsETeMBiOnsWQ8M=
    example.com/b v1.2.0 h1:iNVB2uf7L3pGDab8VKaHJPboZFFbXB0mkHOukwUIBeg=
    example.com/b v1.2.0/go.mod h1:MQw/MJYoqpiCbgkCcl+gAoFRuNP8wzTwEeYmbdRvLfQ=
    example.com/c v1.4.0 h1:0CprvYQtt0CBtZc2K7L3S02DhJMrgwjogjcyWFJbDI8=
    example.com/c v1.4.0/go.mod h1:Ag7GF220kK80oroB+j27GMiNDuNUVuX4lEt3XUw4NFo=
    example.com/d v1.2.0 h1:pNf5YhI8SI0DxS2MPYemzyRWSrW4+KL5t71yWWBOiKw=
    example.com/d v1.2.0/go.mod h1:ChwSNrGUE67ZT+15RcIKm3aoo8UU74op9eTKN5AqaoY=
    the proxy now serves other bytes for c v1.4.0terminal
    $ go build -o /dev/null .
    go: downloading example.com/a v1.2.0
    go: downloading example.com/b v1.2.0
    go: downloading example.com/c v1.4.0
    verifying example.com/[email protected]: checksum mismatch
    	downloaded: h1:rqPegbOuaEtqhObzlzcrWotGgajm+kiFiP7GS8X8euk=
    	go.sum:     h1:0CprvYQtt0CBtZc2K7L3S02DhJMrgwjogjcyWFJbDI8=
    
    SECURITY ERROR
    This download does NOT match an earlier download recorded in go.sum.
    The bits may have been replaced on the origin server, or an attacker may
    have intercepted the download attempt.
    
    For more information, see 'go help module-auth'.
    • A version is immutable. The same module and version must have the same hash on every machine.
    • Commit go.sum. It can hold more lines than the build list, and go mod tidy removes the extra ones.

    go.sum is not a lock file. It holds hashes of what I already trust, so a changed release stops the build.

    L

    Tool directives

    since 1.24, recorded
    add and run a toolterminal
    $ go get -tool example.com/hello/cmd/hello
    go: downloading example.com/hello v1.0.0
    go: added example.com/hello v1.0.0
    $ cat go.mod
    module example.com/shop
    
    go 1.27
    
    tool example.com/hello/cmd/hello
    
    require example.com/hello v1.0.0 // indirect
    $ go tool hello
    hello from a tool

    A build tool is now a dependency in go.mod, so each developer and CI run the same version. The tools.go file can go.

    M

    Workspaces

    recorded
    go.workterminal
    $ (in svc) go run .
    lib published v1.0.0
    $ go work init ./svc ./lib
    $ cat go.work
    go 1.27.3
    
    use (
    	./lib
    	./svc
    )
    $ (in svc) go run .
    lib local edit
    $ (in svc) go run .
    lib published v1.0.0

    The last run sets GOWORK=off. The go.mod files never change.

    A workspace lets me change a library and a service together with no replace line. I do not commit go.work for a library.

    N

    Build tags and file suffixes

    recorded: go list on each configuration
    filelinux/amd64linux/arm64darwin/arm64windows/amd64linux/amd64 -tags prowhy
    app.goInInInInInNo constraint.
    linux.goInInInInInA name with no underscore has no constraint.
    app_unix.goInInInInInunix is not a file suffix, so this has no constraint.
    app_linux.goInInOutOutInSuffix _GOOS.
    app_windows.goOutOutOutInOutSuffix _GOOS.
    app_amd64.goInOutOutInInSuffix _GOARCH.
    app_linux_arm64.goOutInOutOutOutSuffix _GOOS_GOARCH.
    tag_unix.goInInInOutIn//go:build unix: the unix tag does exist.
    pro.goOutOutOutOutIn//go:build pro, set with -tags pro.
    free.goInInInInOut//go:build !pro.
    future.goOutOutOutOutOut//go:build go1.99: newer than this toolchain.
    gen.goOutOutOutOutOut//go:build ignore: only go run gen.go uses it.
    app_test.goOutOutOutOutOutOnly go test compiles it.

    A _linux or _amd64 suffix is a build constraint. There is no _unix suffix, so for that I use a //go:build unix line.

    O

    go generate

    recorded
    the build needs a generated fileterminal
    $ go build -o /dev/null .
    # example.com/shop
    ./main.go:7:27: undefined: generated
    $ go generate -x
    go run gen.go
    $ cat names_gen.go
    // Code generated by gen.go; DO NOT EDIT.
    
    package main
    
    const generated = "made by go generate"
    $ go run .
    made by go generate
    • The go tool scans source for //go:generate lines and runs each one. It does no dependency analysis.
    • go build ignores these lines, so the first build fails.
    • The line "Code generated ... DO NOT EDIT." marks a file as generated for tools.
    • The generator here has //go:build ignore, so it stays out of the package.
    • Pin a generator with a tool directive: //go:generate go tool stringer.

    go generate is a command I run by hand, and go build never runs it. I commit the output, so users need no generator.

    P

    Vendoring

    recorded with the proxy off and an empty module cache
    vendorterminal
    $ go mod vendor
    $ cat vendor/modules.txt
    # example.com/a v1.2.0
    ## explicit; go 1.27
    example.com/a
    # example.com/b v1.2.0
    ## explicit; go 1.27
    example.com/b
    # example.com/c v1.4.0
    ## explicit; go 1.27
    example.com/c
    # example.com/d v1.2.0
    ## explicit; go 1.27
    example.com/d
    $ go run .
    a v1.2.0 > c v1.4.0 > d v1.2.0
    b v1.2.0 > c v1.4.0 > d v1.2.0
    $ go run .
    go: inconsistent vendoring in .:
    	example.com/[email protected]: is explicitly required in go.mod, but not marked as explicit in vendor/modules.txt
    	example.com/[email protected]: is marked as explicit in vendor/modules.txt, but not explicitly required in go.mod
    
    	To ignore the vendor directory, use -mod=readonly or -mod=mod.
    	To sync the vendor directory, run:
    		go mod vendor
    situationstatus
    Builds with no network, or a rule that all source sits in the repositoryApproved
    A vendor folder at the module root, with a go line of 1.14 or laterUsed automatically
    A normal service that reaches a proxyNot needed
    A vendor folder inside a dependencyIgnored

    I vendor when a build must run with no network. If go.mod and vendor disagree, the go command stops.

    Q

    The proxy and the checksum database

    go.dev/ref/mod; defaults from go env
    go commandmodule cache firstmodule proxyGOPROXYversion controldirectchecksum databaseGOSUMDBgo.sumyour repository1 get .zip, .modfills2 new version?look up its hash3 record
    settingdefaultwhat it does
    GOPROXYhttps://proxy.golang.org,directTries each entry in turn. direct means the version control server.
    GOSUMDBsum.golang.orgA transparent log of go.sum lines. Auditors can check that it does not change.
    GOPRIVATEemptyGlob patterns of private paths. The default for GONOPROXY and GONOSUMDB.
    GONOPROXYGOPRIVATEPaths that skip the proxy.
    GONOSUMDBGOPRIVATEPaths that skip the public checksum database, so their names stay private.
    GOAUTHnetrcHow private fetches authenticate, since 1.24.

    The proxy serves bytes and the checksum database proves them, so a proxy cannot change code unnoticed. For private code I set GOPRIVATE.

    R

    Toolchains

    recorded with GOTOOLCHAIN set per row
    go.modGOTOOLCHAINrecorded resultstatus
    go 1.21.0localgo1.27.3A newer toolchain runs older code
    go 1.99.0localgo: go.mod requires go >= 1.99.0 (running go 1.27.3; GOTOOLCHAIN=local)A strict minimum
    go 1.27.0, toolchain go1.99.0localgo1.27.3The line is only a suggestion
    go 1.27.0, toolchain go1.99.0autogo: download go1.99.0 for darwin/amd64: toolchain not availableTries to download it
    go 1.27.0, godebug asynctimerchan=1localgo.mod:5: removed GODEBUG "asynctimerchan" set to old value "1" (https://go.dev/doc/godebug#go-127)Support removed in 1.27
    • Our own lab module has the line go 1.27.3 and no toolchain line. Inside it, a go 1.26.2 command downloads 1.27.3 and runs it, with GOTOOLCHAIN=auto, the default.
    • Selection order with auto: a newer toolchain line, then a newer go line, then the bundled toolchain.
    • go get [email protected] raises the go line, and go get toolchain@patch raises only the suggestion.
    • Since 1.25, a go line update no longer adds a toolchain line.
    • GODEBUG=toolchaintrace=1 prints the steps of the selection, since 1.24.

    The go line is a minimum, and the toolchain line is a suggestion for the main module. With GOTOOLCHAIN=auto the go command switches for me.

    S

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.21The go line is a strict minimum. New toolchain line, with toolchain download. Package initialization order is specified.An older toolchain refuses the module and does not guess.
    1.22go work vendor. go mod init no longer reads config files of older vendoring tools.A workspace can build with no network.
    1.23godebug block in go.mod and go.work. go mod tidy -diff. go vet stdversion.Use tidy -diff in CI: it exits non-zero when go.mod needs a change.
    1.24tool directive, go get -tool, tool pattern. GOAUTH. The main module version comes from the VCS tag. toolchaintrace=1.Delete tools.go.
    1.25ignore directive. work package pattern. A module root can be a subfolder of a repository. No automatic toolchain line.go.mod diffs get smaller.
    1.26go mod init writes a go line one release behind the toolchain.New modules work on supported versions by default.
    1.27go mod tidy keeps two require blocks. A removed GODEBUG setting with an old value is an error.Resolve an old setting before you move to 1.27.
    T

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildStarting from an empty folder.Run go mod init, then write one package main. Split only when a second concept appears.
    buildHandler, service and store in 45 minutes.Use a few files in one package, or three short packages under internal/. Do not design a tree.
    buildA global map set up at start.Build it in a constructor in main, not in init. Tests can then make their own.
    talk"Why does Go have no lock file?"MVS is deterministic: the build list comes from go.mod files, and they do not change when a new release appears.
    talk"A dependency has a security fix."Run go get on that module at the fixed version, then go mod tidy. Check that go list -m all shows it.
    talk"A library breaks in a new version."Stay at the old version, or use replace with a fork. A library cannot pass a replace to its users.
    talk"How do you make builds reproducible?"Commit go.mod and go.sum, set the go line, and pin tools with tool directives. Vendor if the build has no network.
    talk"How do you use private modules?"Set GOPRIVATE, so that the paths skip the proxy and the checksum database. Authenticate through Git or GOAUTH.
    talk"When is a monorepo one module?"One module gives one version of each dependency. Use a workspace when teams need separate modules.

    I keep the build flat and simple, and I can explain each line of go.mod when asked.

    U

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. Predict the output.

      package main
      
      import "fmt"
      
      var a = trace("a", b+1)
      var b = trace("b", c+1)
      var c = trace("c", 1)
      
      func trace(name string, v int) int {
        fmt.Println(name, v)
        return v
      }
      
      func main() {
        fmt.Println("main", a)
      }
    2. Predict the output.

      package main
      
      import "fmt"
      
      var total = sum()
      var prices = load()
      
      func load() []int {
        fmt.Println("load")
        return []int{2, 3}
      }
      
      func sum() int {
        fmt.Println("sum")
        n := 0
        for _, p := range prices {
          n += p
        }
        return n
      }
      
      func main() {
        fmt.Println(total)
      }
    3. Predict the output. Compare it with the question before.

      package main
      
      import "fmt"
      
      type Getter interface{ Get() int }
      
      type source struct{}
      
      func (source) Get() int { return v }
      
      var g Getter = source{}
      var x = trace("x", g.Get())
      var v = trace("v", 7)
      
      func trace(name string, n int) int {
        fmt.Println(name, n)
        return n
      }
      
      func main() {
        fmt.Println(x, v)
      }
    4. Predict the output.

      package main
      
      import "fmt"
      
      var ready = announce()
      
      func announce() bool {
        fmt.Println("var")
        return true
      }
      
      func init() {
        fmt.Println("init 1", ready)
      }
      
      func init() {
        fmt.Println("init 2")
      }
      
      func main() {
        fmt.Println("main")
      }
    5. Predict the output.

      package main
      
      import "fmt"
      
      func init() {
        fmt.Println("start")
        panic("boot failed")
      }
      
      func main() {
        fmt.Println("main")
      }
    6. Predict the output. Compare it with the G1 drill on panic(nil).

      //go:debug panicnil=1
      package main
      
      import "fmt"
      
      func main() {
        defer func() {
          fmt.Println(recover())
        }()
        panic(nil)
      }
    7. You run go get example.com/[email protected]. Predict the new build list.

      shop needs a v1.2.0, b v1.2.0
      a v1.2.0 needs c v1.3.0
      b v1.2.0 needs c v1.4.0
      c v1.4.0 needs d v1.2.0
      published: c v1.5.0 (needs d v1.3.0)
    8. You run go get example.com/[email protected], below what b v1.2.0 needs. Predict the result.

      shop needs a v1.2.0, b v1.2.0
      a v1.2.0 needs c v1.3.0
      b v1.2.0 needs c v1.4.0
      c v1.4.0 needs d v1.2.0
      published: c v1.5.0 (needs d v1.3.0)
      b v1.1.0 needs c v1.2.0
    9. You add exclude example.com/c v1.4.0, then run go mod tidy. Predict the build list.

      shop needs a v1.2.0, b v1.2.0
      a v1.2.0 needs c v1.3.0
      b v1.2.0 needs c v1.4.0
      c v1.4.0 needs d v1.2.0
      published: c v1.5.0 (needs d v1.3.0)
    10. Module e has its own line: replace example.com/c => example.com/c v1.5.0. Your module requires e, and e requires c v1.3.0. Predict the build list.

      require example.com/e v1.0.0