1. Why do we need .bak and what is its policy?
初めて「ファイルの横にバックアップを置きます」と聞くと、頭の中では正直こう問い返します。「でも、もう“half-file” は書いていないのに、なぜさらに複雑にするの?」――それはもっともな疑問です。
temp + rename は、書き込み途中の障害で ファイルが部分的に上書きされる という、非常に具体的な問題からは守ってくれます。ですが、盲点があります。temp + rename は「新しい版が正しくないのに、完璧に書けてしまった」という状況は救えません。
たとえば、アプリのデータをファイルに保存しているとします。タスク一覧、設定、ミニデータベース――何でもよいです。データを誤って計算したり(ロジックエラー)、違う形式でシリアライズしたり(フォーマットエラー)、突然空の結果を受け取ったり(予期しない入力)しても、そのまま一時ファイルに書き込み、最後にリネームしてしまうことはあります。プロトコル上はすべて「成功」です。ファイルは「完全」です。でも、データの意味は壊れています。
そんなとき、少なくとも すべてを失わずに済む よう、直前の版を手元に持っておけるととても安心です。
だからこそ .bak は「別の書き込み方法」ではなく、方針なのです。「その横に前の版を置いておく」という方針です。
- temp + rename — 書き込みの整合性を守るためのものです(“ファイルの半分” を作らない)。
- .bak — ロールバック可能性のためのものです(新しい版が悪かったときに前の版へ戻る)。
.bak policy
コードを書く前に、少し立ち止まって、開発者がよく忘れることをしておくと役立ちます。それは 決定すること です。.bak は魔法ではなく、合意です。方針を固定しないと、プログラムは「たまたまそう動く」だけになります。
.bak の方針には、避けられない問いがいくつかあります。いつバックアップを作るのか、バックアップがすでに存在していたらどうするのか、そして復元時にどう振る舞うのか。以下は、学習用プロジェクト(そして多くの実務プロジェクト)でよく必要になる、コンパクトな判断表です。
| Situation | Default decision | Why this is convenient |
|---|---|---|
| Target file does not exist yet | Do not create .bak | Nothing to back up — this is the first version |
| Target file exists | Create .bak before writing | The backup reflects the previous version |
| .bak already exists | Overwrite it (remove the old .bak and create a new one) | The “keep only one step back” policy is simple and predictable |
| Restoration | If the main file is missing but .bak exists, restore it | After a failure, you can recover without manual intervention |
Yes, you can keep multiple generations (for example, .bak1, .bak2), you can keep them in a separate folder, and you can make archives. But here we stay focused: we need a reliable and understandable protocol, not a homegrown version-control system.
2. Write protocol: temp + rename + .bak
Now we will carefully “insert” .bak into the already familiar temp + rename protocol. It is important not to mix up the order of steps: the backup is made before publishing the new version, otherwise you back up the new one already (and that would be a very sad backup).
If we draw the protocol as a diagram, it looks roughly like this:
flowchart TD
A[Prepare new version in temp] --> B{Does target file exist?}
B -- no --> E[Publish: rename temp -> target]
B -- yes --> C[Create .bak: rename target -> target.bak]
C --> E[Publish: rename temp -> target]
E --> F{Publish successful?}
F -- yes --> G[Done: target = new version, .bak = previous one]
F -- no --> H[Try to roll back: rename .bak -> target]
Pay attention to an important idea: .bak by itself does not guarantee that “you can always roll back.” It guarantees that you have a rollback attempt and that the previous version is usually close at hand.
Why “usually”? Because file operations can fail: no permissions, strange file system, file locked, disk space suddenly ran out, and so on. In the real world, “reliability” does not mean “never breaks”; it means “breaks predictably and leaves traces.”
One more nuance: when you do Rename(target, target + ".bak"), the main file disappears (its name changes). Between this step and publishing the temp file, there is a gap when target may not exist. If the process crashes exactly at that moment, on the next run the application will see that target is missing, but .bak is present. That is why we want to know how to restore.
3. Implementation in Go
Before the code, let us take a small architectural pause. Even in a learning project, it is useful to separate:
- storage functions perform file operations and return error;
- the user interface (CLI) prints messages.
This reduces confusion and makes the code testable: tests do not like it when they are spammed into stdout.
Below there will be three building blocks: checking whether a file exists, writing with backup, and restoring from backup.
Check “does the file exist?”
This part looks boring, but in practice this is exactly where “weird bugs” begin, when people confuse “the file does not exist” with “no permission to read Stat”. So it is useful to keep the distinction in mind: os.Stat can return an error for different reasons.
import "os"
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
Here is an important habit: not exist is a normal logic branch, while “some other error” is already a reason to stop and return it upward.
Writing: WriteWithBackup
The idea is simple: writing data should look to the application code like one operation — “here is the path, here are the bytes, here are the permissions: do it reliably.” Internally we use the familiar technique: prepare temp, then make .bak (if needed), then publish.
To keep the example shorter, we will assume that we already have a helper from the previous lecture:
writeTempFile(dir, data, perm) (tmpName string, err error)
It creates a temp file, writes data into it, closes it, and sets permissions. Here we focus specifically on .bak.
import (
"fmt"
"os"
"path/filepath"
)
func WriteWithBackup(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmpName, err := writeTempFile(dir, data, perm)
if err != nil {
return err
}
bakPath := path + ".bak"
if err := rotateBackup(path, bakPath); err != nil {
_ = os.Remove(tmpName)
return err
}
if err := os.Rename(tmpName, path); err != nil {
_ = os.Rename(bakPath, path) // attempt rollback
_ = os.Remove(tmpName)
return fmt.Errorf("publish %s: %w", path, err)
}
return nil
}
There are several “grown-up” points here, even though the code is still short:
- we clean up tmpName if something goes wrong: temporary files should not clutter the directory;
- on publication error we try to put .bak back in place;
- we add context via fmt.Errorf("...: %w", err), so the error is readable and suitable for further handling.
Now we only need to explain what rotateBackup is.
Updating .bak: rotateBackup
The name “rotate” sounds like logging, but the meaning is simple: “update the backup so that the previous version is in .bak.” We chose the “one step back” policy, so we do not need the old .bak — we overwrite it.
import (
"fmt"
"os"
)
func rotateBackup(path, bakPath string) error {
exists, err := fileExists(path)
if err != nil {
return fmt.Errorf("stat target: %w", err)
}
if !exists {
return nil
}
_ = os.Remove(bakPath) // policy: overwrite .bak
if err := os.Rename(path, bakPath); err != nil {
return fmt.Errorf("make backup: %w", err)
}
return nil
}
Here we intentionally have _ = os.Remove(bakPath): we remove the old .bak in advance, because the behavior of Rename when the destination file already exists differs depending on the OS and file system. For a learning project, predictability is more important.
And once again: the backup is made with Rename, not by “reading and writing a copy.” For large files this is faster, and we do not add another long copy operation that itself can fail halfway through.
Restoration: RestoreFromBackup
Here people often want to write, “if the main file cannot be opened, restore .bak.” But it is safer and more precise to say this: if the main file does not exist, and .bak exists, then you can put .bak back in place. If the main file exists, do not touch it, because “DIY restoration” can be worse than the failure.
import (
"fmt"
"os"
)
func RestoreFromBackup(path string) error {
if _, err := os.Stat(path); err == nil {
return nil // main file is in place
}
bakPath := path + ".bak"
if err := os.Rename(bakPath, path); err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("restore backup: %w", err)
}
return nil
}
The same general principle applies here: some errors are “expected” (file missing) and some are “unexpected” (no permissions, broken FS). Expected ones should not crash the program; unexpected ones should be visible.
4. Using it in a learning application
Let us imagine a very simple CLI task manager that stores data in a file "tasks.txt". The format is primitive: one line is one task. We care about the storage mechanics, not the format.
Before reading the file, we try to restore from .bak, and when saving, we write through WriteWithBackup.
import (
"os"
"strings"
)
func LoadTasks(path string) ([]string, error) {
if err := RestoreFromBackup(path); err != nil {
return nil, err
}
b, err := os.ReadFile(path)
if os.IsNotExist(err) {
return []string{}, nil
}
if err != nil {
return nil, err
}
return strings.Split(strings.TrimSpace(string(b)), "\n"), nil
}
Notice the logic: if the file does not exist yet, that is a normal situation, so we return an empty list. If it exists, we read it.
Saving is just assembling lines and writing with backup:
import "strings"
func SaveTasks(path string, tasks []string) error {
data := []byte(strings.Join(tasks, "\n") + "\n")
return WriteWithBackup(path, data, 0644)
}
For the rest of the application, this looks like an ordinary Save, but inside there is already a safety net: the previous version is stored in .bak.
5. Typical mistakes when working with .bak
Mistake #1: create .bak after publishing the new version.
This seems logical only for the first five seconds: “first save it, then make a copy.” But then .bak will not contain the previous version, it will contain the new one. The moment you urgently need a rollback, you will discover that there is nowhere to roll back to. The backup is made before publication — that is the key order.
Mistake #2: not agreeing on what to do with the old .bak.
If one developer expects .bak to be overwritten, and another expects it to be “eternal,” in production you will get either a rename error or mysterious old data that suddenly appears during recovery. The policy must be single and obvious: in the learning version, it is usually simpler to overwrite .bak.
Mistake #3: trying to restore over an existing main file without an explicit rule.
Sometimes restoration is written like this: “if .bak exists, always restore.” That is dangerous: you can destroy the current file just because .bak remained from an old run. The basic strategy is safer: restore only when the main file is missing, and do not touch it if it exists.
Mistake #4: forgetting that .bak is not a “magic pill,” but just another file.
It can also fail to be created (no permissions), it can also fail to be renamed (file locked), and it can also be deleted by accident. That is why good code does two things: returns errors with context and does not hide the fact that “the backup was not updated.”
Mistake #5: leaving junk temp files on errors.
When you add .bak, the number of steps increases, and the temptation to forget os.Remove(tmpName) grows. And then the directory turns into a “graveyard of temporary files.” Every early return after creating a temp file should have clear cleanup (via defer or careful Remove calls in error branches).
GO TO FULL VERSION