This resume is also available in English.

5. Going live and operating1 / 7 · All columns

Columns › 5. Going live and operating › Part 21

Versioning with Git: Branches, Tags and Rolling Back

Git 版本管理:分支、打 tag 與退版

Knowing what runs in production, rebuilding it and rolling it back all depend on versioning. With diagrams, this article explains commits, branches and tags, Semantic Versioning and Go module rules, how to choose a branching strategy, how to create and push tags and embed the version in the binary, how CI turns a tag into immutable images, and finally reset, revert, production rollback and hotfixes.

  • Git
  • Go
  • CI/CD
  • DevOps
In this article
  1. What this article solves
  2. Step 1: Commits, branches, HEAD and tags
  3. Step 2: Choosing version numbers with Semantic Versioning
  4. Step 3: Go module version rules
  5. Step 4: Choosing a branching strategy
  6. Step 5: Creating, pushing and deleting tags
  7. Step 6: Release notes from the range between two tags
  8. Step 7: Embedding the version in the Go binary
  9. Step 8: CI builds immutable images when a tag is pushed
  10. Step 9: Rolling back code with reset, reflog and revert
  11. Step 10: Rolling back production
  12. Step 11: Hotfixes from the tag, without extra changes
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

“Distributed Transactions: Sagas and the Outbox Pattern” kept the ordering flow consistent even when parts of it fail, the previous article, “Event-Driven Go with Watermill: What It Is, What It Solves, and Wiring It to an Outbox”, turned event handling into shared components, and by now we have covered most of "is the code correct". This article opens the "running in production" part of the series with the most basic question, and one that goes wrong surprisingly often: how code becomes a "version" and reaches production, and how to get back when something breaks.

What this article solves

Picture a Friday evening. The payment service has just shipped a new version, and ten minutes later support reports that some customers have been charged twice. Three questions must be answered within minutes:

  • Which version is running in production right now? Which commit was it built from? What changed since the previous version?
  • Can we go straight back to the last good version? Does the previous image still exist? What is its tag? Is the database schema still compatible with it?
  • Once it is fixed, how do we ship it again? main already contains features meant for next week, and they must not ride along.

None of these answers live in the code. They live in version management: how commits are organised into branches, which commit is marked as a release, how that mark maps all the way to the binary and the image, and which kind of "rollback" suits which situation. If any link in that chain depends on memory or a verbal agreement, an incident turns into panic.

This article covers, in order:

  1. How commits, branches, HEAD and tags relate: understand the picture first and the commands stop being things to memorise.
  2. Choosing version numbers: Semantic Versioning, and what counts as "incompatible" for an HTTP/gRPC API versus a Go library.
  3. Go module version rules: vX.Y.Z, /v2, tags for submodules, and why the module proxy will not let you move a tag.
  4. Branching strategies: trunk-based development, Git Flow and release branches, and which kind of project each one fits.
  5. Tagging: lightweight and annotated tags, signing, pushing, sorting, and deleting a wrong tag.
  6. Producing release notes from the range between two tags.
  7. Embedding the version and commit into the Go binary.
  8. CI: build when a tag is pushed, tag the image with the git tag plus the commit SHA, and never overwrite it.
  9. Rolling back code: reset, reflog, revert, and the trap in reverting a merge commit.
  10. Rolling back production: redeploying the previous version, why database migrations make it hard, and feature flags.
  11. Hotfixes: branch from the tag, fix, tag v1.4.1, and cherry-pick back to main.
QuestionTool in this article
Which version is liveAnnotated tags, version embedded in the binary, image tag = tag + SHA
Can we rebuild exactly that versionTags never move, images are never overwritten, build from a clean tree
How do we go backRedeploy the previous tag; use revert in git history
How do we ship a fix without extra changesHotfix branch from the tag, then cherry-pick the fix back to main

Step 1: Commits, branches, HEAD and tags

Git's version management rests on a very simple graph. Each commit is a complete snapshot carrying an author, a time, a message and a link to its parent commit(s). A commit's ID (its SHA) is computed from its content; change one bit and the ID changes, so a commit never changes once created.

There are three kinds of "pointer" on this graph:

  • A branch is a name that moves. Commit on main and main moves forward to the new commit.
  • HEAD points to "where you are now", usually to a branch, meaning new commits will be added to that branch.
  • A tag is a name that does not move: it is fixed to one commit. Whatever commit v1.4.0 points to today, it should still point to a year from now.
c1 c2 c3 c4 c5 f1 f2 tag v1.4.0 main HEAD feature/refund never moves moves on each commit where you are Arrows point from a commit to its parent; branches and HEAD move, a tag stays on the released commit

Figure: commits point to their parents and form a graph; main and feature/refund are branches that move with new commits, HEAD marks the current branch, and the tag v1.4.0 stays fixed on the commit that was released.

Keep this picture in mind; every operation that follows either moves a pointer or adds commits:

OperationWhat happens on the graphRewrites history?
git commitAdds a commit; the current branch moves forwardNo
git tag -a v1.4.0Adds a fixed pointerNo
git reset --hard XPulls the current branch back to X; later commits drop off itYes
git revert XAdds a commit that cancels XNo
git cherry-pick XCopies X's change as a new commit on the current branchNo
git push --force a branchMakes the remote branch point at your version; others' commits may vanishYes

Why be so careful about versions? Because production needs three abilities: to know which commit is running, to rebuild a version with exactly the same bytes (or at least exactly the same source), and to return to the last known good version. All three rely on a name mapping to exactly one commit. Branch names move, so they cannot represent a version; a commit SHA is unique but meaningless to humans; a tag sits in between, fixed yet meaningful. That is why releases use tags.

Step 2: Choosing version numbers with Semantic Versioning

A tag can be named anything, but teams and tools need a shared rule. The most widespread is Semantic Versioning (SemVer): MAJOR.MINOR.PATCH.

PartWhen to incrementExample
MAJORAn incompatible change; consumers may need to change codev1.9.3 → v2.0.0
MINORNew functionality, backwards compatiblev1.4.2 → v1.5.0
PATCHBug fixes only, backwards compatiblev1.4.0 → v1.4.1
Pre-releaseA test version before the final releasev1.5.0-rc.1, which sorts before v1.5.0

When a part is incremented, the parts to its right reset to zero. 0.y.z means "still in development, may break at any time"; declaring 1.0.0 is a promise to follow these rules from then on.

The heart of SemVer is the definition of "incompatible", and that depends on who uses your thing.

For an HTTP/gRPC API, an incompatible change is one that breaks an existing client:

  • Removing or renaming an endpoint, field or enum value; changing a field's type or unit (for example an amount going from whole currency units to minor units).
  • Making a previously optional request field required; tightening validation so that previously valid requests now get a 400.
  • Changing semantics, for example POST /orders used to be idempotent and no longer is.
  • In Protocol Buffers, changing a field number or type, or reusing a deleted number (“gRPC and Protocol Buffers in Go” explained that deleted fields should be reserved).

Adding an optional field, adding an endpoint, or adding a field to a response (clients must ignore unknown fields) is normally compatible.

For a Go library, an incompatible change is one that makes dependent code fail to compile or behave differently:

  • Removing or renaming an exported identifier; changing a function signature, including adding a parameter.
  • Adding a method to an exported interface: every external implementation stops compiling because it lacks the method.
  • Changing the type of an exported struct field.

Adding a field to a struct, or adding new functions and types, is generally treated as compatible. If you want a tool to check, golang.org/x/exp/cmd/gorelease compares the API of two versions and suggests what the next version number should be.

A service's version and its API's version are two different things. This is easy to confuse with microservices. The order service is a continuously deployed application; nobody runs go get on it, so its v1.4.0 is mainly a "release identity" that tells people and tools which release is live. What actually promises compatibility to the outside world is the API contract, such as the /v1/orders path or the protobuf package shop.order.v1. The service jumping from v1.4.0 to v2.0.0 does not mean the API moves to /v2; conversely, when the API gains a /v2, the service usually keeps serving /v1 for a while. So a service's tags can follow SemVer (MINOR for features, PATCH for fixes, which helps communication), or simply be an increasing number or a date; what matters is that every release has a unique, unchanging name.

Step 3: Go module version rules

If what you publish is a Go module (a shared library or an SDK), the git tag is the version source that the Go toolchain reads, and the rules are enforced rather than conventions.

  • Tags must be semantic versions prefixed with v: v1.4.0, v1.5.0-rc.1. 1.4.0 (no v) or release-1.4 is not treated as a module version. An untagged commit gets a pseudo-version such as v1.4.1-0.20261120013647-290aa47f407d, built from the previous tag, a timestamp and the commit SHA.
  • v2 and above change the module path: the module line in go.mod must end with /v2, for example module example.com/shopkit/v2, and consumers import example.com/shopkit/v2/.... This is semantic import versioning: to Go, different major versions are different modules, and they can coexist in one program. Tag v2.0.0 without changing the module path and go get rejects it.
  • With several modules in one repository, tags carry a directory prefix. Suppose the shop extracts its money handling into a separate module under pkg/money/ with its own go.mod (module example.com/shop/pkg/money). Its version tags are pkg/money/v1.2.0, not v1.2.0; the latter belongs to the module at the repository root.
  • go get ...@latest prefers releases: once v1.4.0 exists, v1.5.0-rc.1 is not treated as latest; consumers must ask for @v1.5.0-rc.1 explicitly. That makes it safe to publish a release candidate for a few consumers to try.

The most important rule: never move or reuse a published tag. The first time a public module version is downloaded, the module proxy (proxy.golang.org by default) caches its content and the checksum database (sum.golang.org) records its hash. Even if you later move v1.4.0 to another commit, people downloading through the proxy still get the old content, and people fetching directly from the repository hit a checksum mismatch that the go command refuses to accept. The result is different people getting different code under the same version number, or not being able to build at all.

When a version turns out to be broken, the right move is:

  1. Fix it and publish a new version, for example v1.4.1.
  2. In the new version's go.mod, mark the broken version with retract so that go get and go list -m -u warn consumers away from it:
// go.mod (excerpt)
module example.com/shop/pkg/money

go 1.24

retract v1.4.0 // allocation may lose one minor unit; upgrade to v1.4.1

Private modules do not go through the public proxy, but the same principle holds: build caches, other people's go.sum files and already-built images all remember the old content. And it applies to every tag, not just Go modules: a version number is a promise; once it is out you cannot take it back, only move forward with a new number.

Step 4: Choosing a branching strategy

A branching strategy answers: where everyday work happens, when it is merged, and where releases are cut from. There are three common ones:

Trunk-based main v1.4.0 v1.4.1 Short branches merge within a day or two; tags go on main Git Flow main hotfix/* release/* develop feature/* v1.4.0 v1.4.1 Release branches main release/1.4 v1.4.0 v1.4.1 fix on main cherry-pick

Figure: trunk-based development has only main plus branches that live a day or two, and tags go straight onto main; Git Flow has main, develop, feature, release and hotfix branches; with release branches, release/1.4 is cut from main and fixes land on main first, then get cherry-picked across.

Trunk-based development: everyone merges into main; branches live a day or two and are merged as soon as they pass review and CI; main is always deployable, and a release is a tag on some commit of main. Unfinished features are hidden behind feature flags rather than kept on long-lived branches.

  • Fits: continuously deployed services such as the shop's order and payment, which may ship several times a day and only ever need to maintain "the version that is live now".
  • Why: the shorter the branches, the smaller the merge conflicts and the earlier integration problems surface; the release cadence can be driven entirely by automation.
  • Does not fit: teams without enough automated tests. Trunk-based development assumes CI stops broken merges; without that, main breaks often.

Git Flow: main holds only released versions and daily work happens on develop. Features branch from develop as feature/*; to prepare a release, a release/* branch is cut from develop for testing and fixes, then merged into main and tagged, and merged back into develop; urgent production fixes branch from main as hotfix/*.

  • Fits: products with a fixed release cycle and a testing period before each release, such as a monthly release that needs manual acceptance.
  • Why: code in development and released code are clearly separated, and the stabilisation period before a release is not disturbed by new features.
  • Does not fit: continuously deployed services. Two long-lived branches plus several merge directions bring a lot of merging and a lot of tracking of "which branches has this fix reached". The author of Git Flow also added a note in 2020 that continuously delivered web applications can use a simpler workflow.

Release branches: day to day it works like trunk-based development on main; when it is time to release, release/1.4 is cut from main, and every later v1.4.x is tagged on that branch. Fixes always land on main first and are then cherry-picked to the release branches that need them.

  • Fits: products with several versions under support at the same time, such as software customers install themselves, mobile apps, SDKs or libraries (where both v1.4.x and v1.5.x are still in use).
  • Why: each supported version has a stable branch to ship patch releases from, without dragging new features into old versions.
  • Does not fit: a service with a single live version; nobody needs the extra branches.
StrategyLong-lived branchesWhere releases are taggedFitsMain cost
Trunk-basedOnly mainmainContinuously deployed servicesNeeds good CI and feature flags
Git Flowmain, developmainFixed cycles with a test periodLots of merging, heavy process
Release branchesmain, release/x.yrelease/x.yProducts and libraries with several supported versionsSomeone must track cherry-picks

The shop's four services live in one repository and are built together, so it uses trunk-based development: a release is one v1.4.0 tag on main, and all four images use that tag. If the services later release independently, switch to prefixed tags such as order/v1.4.0 so that each service has its own version sequence.

Step 5: Creating, pushing and deleting tags

Git has two kinds of tag:

KindHow to createWhat it storesFits
Lightweightgit tag v1.4.0Just a name pointing at a commitTemporary local markers
Annotatedgit tag -a v1.4.0 -m "…"A separate tag object: who tagged, when, a message; can be signedReleases
c1 c2 c3 c4 c5 annotated tag object v1.4.0 tagger: dev <dev@example.com> date: 2026-11-20 message: Release v1.4.0 v1.3.0 (lightweight) main later commits move main A lightweight tag points straight at a commit; an annotated tag adds an object with tagger, date and message; neither moves

Figure: an annotated tag is a separate object recording the tagger, the time and a message, and it points at a commit; a lightweight tag points at the commit directly. main keeps moving forward while both tags stay where they are.

Always release with annotated tags. They record who released, when and why; git describe considers only annotated tags by default, and git push --follow-tags pushes only annotated tags. In a test repository the difference is easy to see:

$ git tag v1.3.0                         # lightweight
$ git tag -a v1.4.0 -m "Release v1.4.0"  # annotated
$ git cat-file -t v1.3.0
commit
$ git cat-file -t v1.4.0
tag
$ git show v1.4.0 --no-patch
tag v1.4.0
Tagger: dev <dev@example.com>

Release v1.4.0
…

Signing lets others verify that the tag really came from you, and not from whoever obtained push access. -s creates a signed annotated tag; the key can be GPG or an SSH key:

git config gpg.format ssh
git config user.signingkey ~/.ssh/release_ed25519.pub
git tag -s v1.4.0 -m "Release v1.4.0"
git tag -v v1.4.0   # verify; SSH keys need gpg.ssh.allowedSignersFile set

Pushing: git push does not push tags by default, which is the most common reason a freshly created tag "did not trigger CI". Name the tag explicitly when pushing:

git push origin v1.4.0

Or let git push also push annotated tags that point at the commits being pushed:

git push --follow-tags origin main
# to make it the default: git config --global push.followTags true

Avoid git push --tags: it pushes every local tag, including lightweight temporary markers and old tags that others deleted long ago but that still linger in your clone.

Listing and sorting: the default order is lexical, so v1.10.0 sorts before v1.9.0. Sort by version instead:

$ git tag --sort=-v:refname        # newest first
v1.10.0
v1.9.0
v1.4.0
v1.3.0
$ git tag -l 'v1.4*'               # only the v1.4 series
v1.4.0

Deleting a wrong tag: if a tag is wrong and nobody has used it yet (CI has not built it, nobody has fetched it), delete it locally and on the remote:

git tag -d v1.4.2                    # delete locally
git push origin --delete v1.4.2      # delete on the remote (same as git push origin :refs/tags/v1.4.2)

But once a tag has gone out, do not reuse the name for another commit. Git itself pushes back: move a tag and push it, and the remote refuses; anyone who already has the old tag will not have it overwritten by git fetch either:

$ git tag -f -a v1.4.1 -m moved HEAD
$ git push origin v1.4.1
 ! [rejected]        v1.4.1 -> v1.4.1 (already exists)
hint: Updates were rejected because the tag already exists in the remote.

# Even if a forced push succeeds, anyone who already fetched it sees:
$ git fetch --tags
 ! [rejected] v1.4.1     -> v1.4.1  (would clobber existing tag)

You end up with the same v1.4.1 meaning different code for different people, different CI caches and different images. If you got it wrong, release v1.4.2. Version numbers are cheap; trust is expensive.

Step 6: Release notes from the range between two tags

With tags in place, "what changed in this release" is a range query:

$ git log v1.3.0..v1.4.0 --oneline
cabdd98 fix(payment): retry on timeout
979cd19 feat(order): add refund API

A..B means "commits reachable from B but not from A", that is, the changes added after v1.3.0 up to v1.4.0. In projects with many merges, add --no-merges to filter out merge commits, or --first-parent to see only the merges on the trunk (one line per PR).

If the team is willing to follow Conventional Commits (feat:, fix:, feat!: for incompatible changes), release notes can be grouped automatically and even the next version number can be derived: feat! or BREAKING CHANGE bumps MAJOR, feat bumps MINOR, only fix bumps PATCH. This is optional:

  • Fits: libraries or products that release often and whose release notes are read by outside users.
  • Not needed: internal services read only by your own team. Clear PR titles plus git log --first-parent are usually enough; forcing a format just adds another check.

With or without tooling, release notes should at least state three things: incompatible changes and how to migrate, required database migrations, and known issues. The second one matters in Step 10: it decides whether this release can be rolled back directly.

Step 7: Embedding the version in the Go binary

With the tag in place, the running program needs to know which version it is: in every log line, on a /version endpoint and as a metric label, so nobody has to guess during an incident. Go has two complementary mechanisms:

  • -ldflags "-X main.version=...": overwrites a string variable with the given value at link time. The build pipeline decides the version string; it is the most direct way.
  • runtime/debug.ReadBuildInfo: when building inside a version-controlled directory, the toolchain automatically embeds vcs.revision (the commit SHA), vcs.time and vcs.modified (whether there were uncommitted changes). Since Go 1.24, the main module's version is also derived from git tags: exactly on a tag it is v1.4.0, uncommitted changes add +dirty, and after a tag it is a pseudo-version.

“Go Project Layout and Go Modules” showed ReadBuildInfo; here the two are combined: prefer the version given via -ldflags, fall back to the version the toolchain derived, and always take the commit from the VCS information.

package main

import (
	"flag"
	"fmt"
	"log/slog"
	"os"
	"runtime/debug"
)

// version is overridden by the build with -ldflags "-X main.version=..."; it stays dev otherwise
var version = "dev"

// BuildInfo answers "which version is this binary, and which commit was it built from"
type BuildInfo struct {
	Version  string // release version, e.g. v1.4.0
	Revision string // full commit SHA
	Time     string // commit time
	Modified bool   // whether the working tree had uncommitted changes at build time
}

func readBuildInfo() BuildInfo {
	bi := BuildInfo{Version: version, Revision: "unknown"}
	info, ok := debug.ReadBuildInfo()
	if !ok {
		return bi
	}
	// Without -ldflags, fall back to the module version the toolchain derived from git tags
	if bi.Version == "dev" && info.Main.Version != "" && info.Main.Version != "(devel)" {
		bi.Version = info.Main.Version
	}
	for _, s := range info.Settings {
		switch s.Key {
		case "vcs.revision":
			bi.Revision = s.Value
		case "vcs.time":
			bi.Time = s.Value
		case "vcs.modified":
			bi.Modified = s.Value == "true"
		}
	}
	return bi
}

func main() {
	showVersion := flag.Bool("version", false, "print the version and exit")
	flag.Parse()

	bi := readBuildInfo()
	if *showVersion {
		fmt.Printf("order %s (%s, modified=%t)\n", bi.Version, bi.Revision, bi.Modified)
		return
	}
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With(
		"service", "order", "version", bi.Version, "revision", bi.Revision,
	)
	logger.Info("starting")
}

Built in a repository tagged v1.4.0 (Go 1.27), the three cases print:

$ go build -o order ./cmd/order && ./order -version
order v1.4.0 (3f29a65df9a0632b954cb6d75a5ab9bca14a168c, modified=false)

$ echo "// x" >> cmd/order/main.go     # make the working tree dirty
$ go build -o order ./cmd/order && ./order -version
order v1.4.0+dirty (3f29a65df9a0632b954cb6d75a5ab9bca14a168c, modified=true)

$ go build -ldflags "-X main.version=$(git describe --tags --always --dirty)" \
    -o order ./cmd/order && ./order -version
order v1.4.0-dirty (3f29a65df9a0632b954cb6d75a5ab9bca14a168c, modified=true)

git describe --tags --always --dirty is a handy way to produce the version string: exactly on a tag it prints v1.4.0; one commit after the tag it prints v1.4.0-1-g290aa47 (distance and SHA); with a modified working tree it appends -dirty; with no tags at all, --always falls back to the commit SHA. --tags makes it consider lightweight tags as well.

go version -m reads the embedded information from any Go binary without running it:

$ go version -m order | grep -E 'mod|vcs'
	mod	example.com/shop	v1.4.0
	build	vcs=git
	build	vcs.revision=3f29a65df9a0632b954cb6d75a5ab9bca14a168c
	build	vcs.time=2026-11-20T01:36:42Z
	build	vcs.modified=false

Two things to watch:

  • vcs.modified counts untracked files too. If build output lands inside the repository and is not in .gitignore, the second build reports modified=true. git describe --dirty only looks at tracked files, so the two can disagree.
  • Without .git in a Docker build, the VCS information is simply missing. The Dockerfile in “Deploying One Go Service with Docker and Kubernetes” passes the version in with ARG VERSION and -ldflags precisely so it does not depend on .git; to carry the commit too, add another -X main.revision=..., or keep .git in the build stage.

A unit test confirms that -ldflags really overrides the variable (the test actually compiles the binary once and runs it):

package main

import (
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

func TestVersionFromLdflags(t *testing.T) {
	bin := filepath.Join(t.TempDir(), "order")
	build := exec.Command("go", "build", "-buildvcs=false",
		"-ldflags", "-X main.version=v1.4.0", "-o", bin, ".")
	if out, err := build.CombinedOutput(); err != nil {
		t.Fatalf("build: %v\n%s", err, out)
	}
	out, err := exec.Command(bin, "-version").Output()
	if err != nil {
		t.Fatal(err)
	}
	if got := string(out); !strings.HasPrefix(got, "order v1.4.0 (unknown") {
		t.Fatalf("got %q", got)
	}
}

func TestDefaultVersion(t *testing.T) {
	if bi := readBuildInfo(); bi.Version != "dev" && !strings.HasPrefix(bi.Version, "v") {
		t.Fatalf("unexpected version %q", bi.Version)
	}
}

-X can only set package-level string variables, and the name must be the full package path (main.version for the main package, example.com/shop/internal/buildinfo.Version for another package). If the name is wrong, the linker does not complain; the variable simply keeps its original value. This test is there to catch exactly that.

Step 8: CI builds immutable images when a tag is pushed

The full path of a release now looks like this:

1. Push the tag git tag -a v1.4.0 git push origin v1.4.0 2. CI (on: push: tags) go vet / go test -ldflags -X main.version 3. Image registry shop/order:v1.4.0 shop/order:sha-3f29a65df9a0 4. Config repo PR newTag: v1.4.0 merged after approval 5. Argo CD syncs cluster pulls v1.4.0 rolling update 6. Service reports version=v1.4.0 revision=3f29a65… immutable Three answers that must agree: newTag in the config repo, the Pod image tag, and the version the service reports

Figure: pushing the tag v1.4.0 triggers CI; CI tests, embeds the version with -ldflags and builds images tagged v1.4.0 and sha-3f29a65df9a0, neither of which can be overwritten; the deployment side changes the tag to v1.4.0 in the config repository, the cluster pulls it, and the service reports itself as v1.4.0.

The GitHub Actions configuration follows. on.push.tags filters tags with a glob, so only tags starting with v trigger it:

# .github/workflows/release.yml
name: release

on:
  push:
    tags: ['v*']

permissions:
  contents: read

jobs:
  image:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        service: [api-gateway, order, payment, inventory]
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
      - run: go vet ./... && go test ./...
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: registry.example.com
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
      - name: build and push
        env:
          SERVICE: ${{ matrix.service }}
        run: |
          VERSION="${GITHUB_REF_NAME}"
          SHA="$(git rev-parse --short=12 HEAD)"
          IMAGE="registry.example.com/shop/${SERVICE}"
          if docker buildx imagetools inspect "${IMAGE}:${VERSION}" >/dev/null 2>&1; then
            echo "${IMAGE}:${VERSION} already exists; refusing to overwrite" >&2
            exit 1
          fi
          docker buildx build \
            --build-arg SERVICE="${SERVICE}" \
            --build-arg VERSION="${VERSION}" \
            -f deploy/docker/Dockerfile \
            -t "${IMAGE}:${VERSION}" \
            -t "${IMAGE}:sha-${SHA}" \
            --push .

Some design choices:

  • GITHUB_REF_NAME is the tag name (v1.4.0) when a tag triggers the run, so it serves directly as the version string. fetch-depth: 0 fetches full history and tags so that commands such as git describe work.
  • Two tags per image: v1.4.0 for people and for the deployment config to reference; sha-3f29a65df9a0 lets you trace an image straight back to its commit, even if the tag name is misunderstood.
  • No overwriting: before building, check whether an image with that tag already exists and fail if it does. More reliable still is to turn on tag immutability in the registry (most registries offer such a setting) so the server refuses overwrites. Referencing the digest (@sha256:...) at deploy time goes further and guarantees the exact bytes.
  • No latest. latest is overwritten by every build; it tells you nothing about the version and leaves no "previous version" to go back to.
  • The * wildcard in tag filters does not match /, so 'v*' does not fire for directory-prefixed tags such as order/v1.4.0; if you move to per-service tags, add a filter such as 'order/v*'.

The deployment side follows “GitOps with Argo CD: Let the Cluster Follow git on Its Own”: production image tags live in the config repository shop-deploy, and changing a tag is a PR:

# apps/overlays/prod/kustomization.yaml (excerpt)
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - ../../base
images:
  - name: registry.example.com/shop/order
    newTag: v1.4.0
  - name: registry.example.com/shop/payment
    newTag: v1.4.0

Now "which version is live" has three answers that confirm each other: newTag in the config repository, the image tag of the Pods in the cluster, and the version and commit the service itself reports in its logs and on /version. If they disagree, someone bypassed the process.

Step 9: Rolling back code with reset, reflog and revert

"Rolling back" has two completely different meanings in git, and picking the wrong one hurts other people:

git reset --hard C rewrites history git revert D adds a cancelling commit before after before after A B C D A B C D main ← main A B C D A B C D D' main ← main D drops off the branch; only reflog finds it a pushed branch needs a force push D' exactly cancels D's change history only grows; others just pull

Figure: reset pulls the branch pointer back so commit D disappears from the branch, which rewrites history and, for a pushed branch, needs a force push to update the remote; revert adds a commit D' that cancels D, so history only grows and everyone can keep pulling normally.

Commits not yet pushed: use reset. It only affects your local branch, nobody depends on these commits, and rewriting history is safe. The three modes differ in whether the working tree and the staging area are rolled back too:

CommandBranch pointerStaging area (index)Working treeWhen
git reset --soft HEAD~1Back oneKeptKeptRewrite the last commit's message, or squash commits
git reset HEAD~1 (--mixed, default)Back oneReset to that commitKeptChoose again which files to commit
git reset --hard HEAD~1Back oneReset to that commitReset to that commitYou are sure the commit and its changes must go

Running it in the test repository:

$ git log --oneline -3
863cad3 wip: two
19599b9 wip: one
cecf8aa chore: bump deps
$ git reset --soft HEAD~1
$ git status --short
M  app.txt               # the change is still there, and staged
$ git reset --mixed HEAD~1
Unstaged changes after reset:
M	app.txt               # the change is still there, but unstaged
$ git reset --hard HEAD
HEAD is now at cecf8aa chore: bump deps

If a reset was a mistake, recover with reflog. Git records every movement of HEAD in the local reflog; commits removed by a reset do not vanish at once, they are just no longer pointed to by a branch:

$ git reflog -5
cecf8aa HEAD@{0}: reset: moving to HEAD
cecf8aa HEAD@{1}: reset: moving to HEAD~1
19599b9 HEAD@{2}: reset: moving to HEAD~1
863cad3 HEAD@{3}: commit: wip: two
19599b9 HEAD@{4}: commit: wip: one
$ git reset --hard 863cad3      # or: git branch rescue 863cad3

The reflog has three limits: it is local only (someone else's reflog cannot save your commits); entries expire (by default, entries no longer reachable from a branch are kept for 30 days); and it only remembers commits. Uncommitted changes thrown away by reset --hard were never in a commit, so the reflog cannot bring them back; glance at git status before running --hard.

Commits already pushed to a shared branch: use revert. Others may have pulled them and branched from them, and CI may already have built images from them. Rewriting history at this point (reset plus git push --force) makes everyone else's history diverge from the remote, and can even wipe out commits someone just pushed. revert instead adds a new commit whose content exactly cancels the target:

$ git revert --no-edit HEAD
[main 15ea309] Revert "feat: discount v1"
$ git log --oneline -2
15ea309 Revert "feat: discount v1"
3f76210 feat: discount v1

History only grows, and "when and why it was undone" stays on record. Shared branches should be protected on the server so that force pushes are refused, rather than relying on discipline.

Reverting a merge commit needs -m 1. When a PR entered main as a merge commit and you want to undo all of it, git needs to know which parent to diff against:

$ git revert --no-edit HEAD
error: commit ec1b2d2… is a merge but no -m option was given.
$ git revert -m 1 --no-edit HEAD
[main 42b24ee] Revert "Merge branch 'feature/refund'"
 2 files changed, 2 deletions(-)

-m 1 takes the first parent (the branch you were on when merging, that is, main) as the mainline and undoes "everything the other side brought in".

There is a trap here that people fall into often: after reverting a merge, merging the same branch again does not bring the earlier changes back.

m0 M W M2 R A B C merges A, B reverts M brings only C revert W A, B return main feature/refund revert undoes the content, not the fact that the merge happened; revert W before merging again

Figure: merge M brings in A and B; W reverts M. Later feature/refund is fixed with C and merged again as M2, but git considers A and B already merged and brings in only C; W must be reverted first for A and B to come back.

The reason is that revert undoes the content, not the fact that the merge happened. As far as git is concerned, A and B are already ancestors of main, so the second merge only brings in the newer C. In the test repository, after the second merge only refund_fix.txt came back, while refund_table.txt and refund_api.txt were still missing. The fix is to revert the revert before (or after) merging again:

$ git revert --no-edit 42b24ee
[main 2560d1d] Reapply "Merge branch 'feature/refund'"
 2 files changed, 2 insertions(+)

This is also why trunk-based development favours small, quick merges: the smaller the PR, the simpler it is to revert and reapply.

Step 10: Rolling back production

When production breaks, the first question is not "which line is wrong" but "what stops the bleeding fastest". The answer is usually not to rewrite git history but to redeploy the last known good version. This is the payoff for insisting that tags never move and images are never overwritten: the v1.3.2 image sits untouched in the registry, and rolling back is just pointing back at it.

Production incident Can a feature flag turn it off? behavioural changes Switch the flag off seconds, no deploy Incompatible schema change? check the release notes Roll forward: hotfix v1.4.1 expand–contract avoids this Redeploy the previous image rollout undo, set image or git revert Make git match the cluster revert in the config repo yes no yes no

Figure: after an incident, first check whether a feature flag can be switched off; if not, check whether this release contains incompatible database changes; if it does not, redeploy the previous image, and if it does, roll forward with a hotfix release.

Depending on how you deploy, there are three routes:

# 1. Fastest: send the Deployment back to the previous ReplicaSet (emergency stop)
kubectl -n shop rollout history deployment/payment
kubectl -n shop rollout undo deployment/payment
kubectl -n shop rollout undo deployment/payment --to-revision=3
kubectl -n shop rollout status deployment/payment

# 2. Name the previous tag explicitly
kubectl -n shop set image deployment/payment payment=registry.example.com/shop/payment:v1.3.2

# 3. GitOps: revert the commit that changed the tag in the config repo; Argo CD syncs back
cd shop-deploy
git log --oneline -3 -- apps/overlays/prod
git revert --no-edit <the commit that set v1.4.0>
git push origin main
ApproachSpeedRecord leftWatch out for
kubectl rollout undoFastestOnly in the clusterCluster and git disagree; Argo CD with auto-sync and self-heal changes it back
kubectl set imageFastOnly in the clusterSame as above, and you must know the exact previous tag
git revert in the config repoOne sync cyclegit history and PRThe proper way under GitOps; also needed after a rollout undo

“Deploying One Go Service with Docker and Kubernetes” introduced rollout undo, and “GitOps with Argo CD: Let the Cluster Follow git on Its Own” explained why git revert is the main tool under GitOps. The principle is the same: you may take a shortcut to stop the bleeding, but in the end git and the cluster must agree, or the next release brings the broken version back.

Note that the revert here is in the config repository, not the code repository. The faulty commit on the code's main can stay; once fixed, you move forward with v1.4.1. Reverting the code's main as well is only needed when the change will not be fixed soon and is blocking other people's releases.

Database migrations are the biggest obstacle to rolling back. Code can be rolled back in seconds; a schema cannot. Suppose v1.4.0 renamed orders.total to total_minor. After rolling back to v1.3.2, the old code cannot find the total column, and the rollback itself becomes a second incident. And "down migrations" are often not viable in production: data the new version has already written may not fit the old schema.

The answer is to make every schema change backwards compatible using expand–contract, splitting one incompatible change into several releases that can each be rolled back:

ReleaseDatabaseCodeCan roll back to the previous release?
v1.4.0Add total_minor (nullable)Write both total and total_minor, read the old columnYes: old code ignores the new column
Background jobBackfill old rows into total_minorUnchangedNo code involved
v1.5.0UnchangedRead total_minor, still write bothYes: the old column is still kept up to date
v1.6.0Drop total (contract)Use only total_minorYes, back to v1.5.0

Each step only changes things in a direction the old code can still live with, so a rollback is always safe. The price is that one rename takes three releases. Migrations such as adding an index to a large table carry their own locking risks; “Adding Indexes Safely: Indexing Large Tables Without an Outage” covers how to do that. Release notes state "which migrations this release contains and whether it can be rolled back directly" precisely so that nobody has to read code to decide during an incident.

Feature flags are another kind of rollback. Wrap the new feature in a flag; when v1.4.0 ships, the flag is off by default and is then turned on for internal accounts and a small share of users. If something goes wrong, switch the flag off; there is no redeploy, and it takes effect in seconds.

  • Fits: behavioural changes such as a new discount calculation or new routing between payment providers; features that need a gradual rollout or an A/B comparison. Trunk-based development also relies on flags to hide unfinished features merged into main.
  • Why: it separates "deploy" from "enable", so deployments carry on as usual while enabling and disabling become operations that need no build.
  • Does not fit: schema changes, dependency upgrades, or changes that fail at start-up; a runtime flag cannot route around those. Flags are also a liability: each one doubles the combinations to test, so once the feature is stable, delete the flag along with the old code path.

Step 11: Hotfixes from the tag, without extra changes

Back to the opening scenario: payment v1.4.0 charges some customers twice, but main already contains features meant for next week. Tagging v1.4.1 straight from main would ship those unready features too. The right move is to branch from the tag that has the problem:

c1 c2 c3 c4 c5 F' v1.4.0 next week's features F v1.4.1 deploy v1.4.1 cherry-pick -x main hotfix/1.4.1 Branch from the faulty tag and ship only this fix; then copy the same fix back to main

Figure: hotfix/1.4.1 is branched from the tag v1.4.0, the fix is tagged v1.4.1 on that branch and deployed; the same fix is then copied back to main with cherry-pick -x so the next release does not bring the bug back.

$ git switch -c hotfix/1.4.1 v1.4.0
Switched to a new branch 'hotfix/1.4.1'
# fix, add tests, commit
$ git commit -am "fix(payment): double charge on retry"
$ git tag -a v1.4.1 -m "Release v1.4.1"
$ git push origin hotfix/1.4.1 v1.4.1
 * [new branch]      hotfix/1.4.1 -> hotfix/1.4.1
 * [new tag]         v1.4.1 -> v1.4.1

# bring the fix back to main
$ git switch main
$ git cherry-pick -x 4d09112
$ git log -1 --format=%B
fix(payment): double charge on retry

(cherry picked from commit 4d091129b6080a2ac7d6e3d333088cc90c8a23fc)

Pushing v1.4.1 triggers the CI from Step 8, which builds new images, and the normal deployment follows. A few details:

  • -x records the original commit in the message, so "which branches has this fix reached" can be traced later.
  • Do not forget the cherry-pick back to main. Otherwise the next release, v1.5.0 from main, brings the same bug back to production, and "a fixed bug came back" is the hardest thing to explain to users. You can also do it the other way round: merge the fix into main first, then cherry-pick it to the hotfix branch; teams using release branches usually require "fixes always land on main first" so nothing is missed.
  • Hotfixes go through full CI and review too. The more urgent it is, the more tempting it is to skip tests, but a double-charge fix that introduces a new bug costs even more.
  • The hotfix branch can be deleted once it is merged back and no longer needed. The tag stays, and you can branch from v1.4.1 again at any time.

If the fix is not ready yet, stop the bleeding with Step 10 first by going back to v1.3.2, and ship the hotfix when it is done properly. Rolling back and hotfixing are not alternatives; they often come one after the other.

Common pitfalls

  • Force-pushing shared branches. git push --force makes the remote branch point at your version, wiping out commits others just pushed and making the history of anyone who already pulled diverge. Use revert on shared branches and refuse force pushes on the server; when you must rewrite your own branch, use --force-with-lease, which refuses if the remote has commits you have not seen.
  • Moving or reusing a published tag. The module proxy, the checksum database, other people's clones and images all remember the old content, and git fetch will not overwrite an existing tag. If you got it wrong, release the next version number.
  • Deploying with the latest tag. You cannot tell which version is live and there is no previous version to go back to; the latest cached on different nodes may even come from different builds.
  • Building a release from a dirty working tree. The binary reports v1.4.0 but contains uncommitted changes, and nobody can rebuild it. Always build releases in CI from a clean checkout, and fail the build if the version string contains dirty or vcs.modified=true.
  • Forgetting to push the tag. git push does not push tags by default, CI never runs, and everyone thinks the release went out. Push with git push origin v1.4.0 explicitly, or set push.followTags.
  • Pushing junk with git push --tags. Local lightweight markers and old tags deleted long ago all get pushed.
  • Releasing with lightweight tags. There is no tagger, time or message, they cannot be signed, and git describe ignores them by default.
  • Tagging v2 without changing the module path. A Go module's v2.0.0 must come with a /v2 module path, or go get rejects it.
  • Merging again right after reverting a merge. The earlier changes do not come back; revert the revert first.
  • Running reset --hard without checking git status. Uncommitted changes are not in the reflog; once lost, they are gone.
  • Calling it done after rollout undo. The cluster and git disagree, and the next sync or release brings the broken version back; follow up with a revert in the config repository.
  • Shipping an irreversible schema change in one release. Code can roll back, the database cannot; split it into several reversible releases with expand–contract.
  • Forgetting to bring a hotfix back to main. The next release ships the bug to production all over again.

Key takeaways

  • A branch is a moving pointer and a tag is a fixed one; release with annotated tags so that a version name maps to exactly one commit.
  • The heart of Semantic Versioning MAJOR.MINOR.PATCH is the definition of "incompatible": for an API, whether existing clients break; for a Go library, whether consumers fail to compile. A service's release version and its API contract version are two different things.
  • Go module tags start with v, v2 and above change the module path, and submodule tags carry a directory prefix; published versions cannot move, so release a new one and mark the bad one with retract.
  • Continuously deployed services use trunk-based development; products with a fixed release cycle may consider Git Flow; products and libraries supporting several versions use release branches.
  • Push tags explicitly or with --follow-tags, not --tags; git tag --sort=-v:refname sorts by version; a wrong tag may be deleted only if nobody has used it.
  • Use -ldflags "-X main.version=..." and runtime/debug.ReadBuildInfo so the binary reports its own version and commit; since Go 1.24 the toolchain also derives the version from tags and marks +dirty.
  • CI builds when a tag is pushed, tags images with the tag and the commit SHA, never overwrites them and never uses latest.
  • Use reset for commits not yet pushed and reflog to recover from mistakes; use revert for pushed ones, with -m 1 for merge commits, and revert the revert before merging again.
  • Rolling back production means redeploying the previous image; under GitOps, revert in the config repository. Keep schema changes reversible with expand–contract; feature flags separate deploying from enabling.
  • A hotfix branches from the tag with the problem, is tagged v1.4.1, and is cherry-picked back to main.

References

  • Semantic Versioning 2.0.0: the rules of MAJOR.MINOR.PATCH and how pre-release versions sort, used in step 2.
  • Go Modules Reference (official Go documentation): version tags, pseudo-versions, major version suffixes, tag prefixes for modules in subdirectories and retract, used in step 3.
  • git-tag (Git documentation): lightweight and annotated tags, signing, and what goes wrong when a tag is re-tagged, used in step 5.
  • git-revert (Git documentation): choosing the mainline with -m and what reverting a merge means for later merges, used in step 9.
  • git-reflog (Git documentation): what the reflog records and the 30-day default expiry for unreachable entries, used in step 9.
  • Go 1.24 Release Notes (official Go documentation): go build sets the main module version from VCS tags and appends +dirty, used in step 7.
  • Workflow syntax for GitHub Actions (GitHub documentation): on.push.tags filters and the fact that * does not match /, used in step 8.
  • A successful Git branching model (Vincent Driessen): the original Git Flow write-up and the author's 2020 note of reflection, used in step 4.

Next

We can now say which version is live and get back to the previous one within minutes. But deciding whether to roll back first requires noticing that something is wrong, and telling whether this release caused it: did the error rate start climbing the moment v1.4.0 went live? The next article, “Observability in Go: Logs, Metrics and Tracing”, carries the version embedded here into every log line and every metric, so "which version started being slow" can be read straight off a chart.