1. Why two processes are a separate problem
When we say “two processes,” it sounds a little abstract — as if we are talking about some servers with millions of users. But in practice, it can literally be you and your colleague, both launching the same CLI command at the same time, or two terminals on one laptop. The problem is insidious because the file almost always stays “beautiful and intact,” so the bug can live for a long time.
Imagine our training app — a simple task manager tasker that stores tasks in a file tasks.json. The tasker add "buy milk" command works roughly like this: read the file → parse JSON → add a task → write the file.
Now let’s run two commands almost simultaneously.
sequenceDiagram
participant A as Process A (tasker add)
participant F as tasks.json
participant B as Process B (tasker done)
A->>F: Read old version (v1)
B->>F: Read old version (v1)
A->>A: Compute v2 (task added)
B->>B: Compute v3 (marked done)
A->>F: Publish v2 (temp+rename)
B->>F: Publish v3 (temp+rename)
Both processes behaved honestly and carefully. And both used reliable writing. But the end result is this: v3 will end up in the file, and process A’s changes (the added task) may disappear, because B read the old version (v1), knew nothing about the new task, and wrote “its” v3 as a full replacement. This is called a lost update.
The main idea: temp+rename protects against a “half-file,” but not against “half-logic” , when two independent computations compete for the right to be the last one.
2. The lock-file idea: an agreement between processes
Lock-file is a very “human” solution. Instead of trying to do magic at the OS level (that is where the nuances start, with different platforms and different kinds of locking), we introduce a simple rule: if a lock file is sitting nearby, writing is already in progress, so do not touch it.
It is important to understand lock-file correctly right away: it is an agreement, not an absolute “covers everything” guarantee. If one process crashes, the lock-file may remain (we will discuss that later). But even such a simple agreement greatly reduces the chance of data loss in ordinary CLI scenarios.
The policy looks like this:
- for tasks.json we create tasks.json.lock;
- the process that wants to change tasks.json first tries to create exclusively tasks.json.lock;
- if the lock cannot be created because it already exists, that means someone else is writing right now, and we exit cleanly with the error “storage is busy”;
- if the lock is created, we proceed: read, compute, write (via temp+rename/backup);
- at the end, we delete the lock file.
The key technical trick: exclusive creation is done through os.OpenFile with flags os.O_CREATE|os.O_EXCL. The idea is that the OS must perform the operation “create the file, but only if it does not already exist” atomically, without a window where two processes can manage to “agree differently.”
3. os.O_CREATE|os.O_EXCL: what the flag combination means
Flags in os.OpenFile often look like spells: O_CREATE, O_EXCL, O_WRONLY… But here the logic is quite down to earth, and it is useful to say it out loud.
os.O_CREATE says: “if the file does not exist, create it.” But on its own, it does not stop two processes from almost simultaneously taking the same path.
os.O_EXCL adds strictness: “I want exclusivity.” And here is the important nuance: O_EXCL makes sense specifically together with O_CREATE, because “exclusivity” in this context means exclusively create a new file.
So what we need is not “exclusive open,” but “exclusive create,” so that a second process cannot quietly create the same lock.
Let’s also add os.O_WRONLY to open the file for writing. This is convenient at least because we can write useful debugging information inside the lock file (for example, the PID). But even if we do not write anything, the fact that the file is created already plays a role.
4. Implementation: AcquireLock and Release
When writing a lock file, it is especially easy to produce “almost correct code” that later leaves junk behind or does not explain why everything broke. That is why we will write it the way we are used to in Go: small functions, early returns, and clear error text.
One more thing: releasing the lock is cleanup. Here defer is a perfect fit, because it guarantees execution on any exit from the function. This is exactly the kind of case where defer helps make code safer and easier to reason about.
Mini structure Lock
To make it convenient to store both the path and the open file, let’s define a small type.
package storage
import (
"os"
)
type Lock struct {
f *os.File
path string
}
There is no “OOP magic” here. It is just a container with two fields.
Acquiring the lock file: AcquireLock
Now the most important part: acquisition. We distinguish two kinds of errors: “the lock already exists” and “something really went wrong (permissions, path, disk).”
package storage
import (
"fmt"
"os"
)
func AcquireLock(lockPath string) (*Lock, error) {
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
if os.IsExist(err) {
return nil, fmt.Errorf("storage is busy: lock exists")
}
return nil, fmt.Errorf("create lock %s: %w", lockPath, err)
}
return &Lock{f: f, path: lockPath}, nil
}
Notice: we return the error with context using fmt.Errorf(... %w ...), so that higher up it is clear “at which step” everything failed, while the root cause of the error is not lost. This is a basic and very important Go practice.
Releasing the lock file: Release
Release means “close and delete.” Usually release errors should not overshadow the main business-operation error, so in Release we often do best effort: close, delete, and do not return errors (or log them at the application boundary).
package storage
import "os"
func (l *Lock) Release() {
_ = l.f.Close()
_ = os.Remove(l.path)
}
Yes, we ignore errors here. In an ideal world, we could collect them and return them, but for the educational pattern “lock-file as an agreement” this is enough. The main thing is to always call Release via defer.
5. Where to place the lock: around writing or around the whole operation
This is where many people make an intuitive mistake: “well, the lock is needed for writing, so let’s wrap only the write.” That sounds logical, but then you can still lose updates.
Lost updates happen because both processes read the same old version. So if your goal is “only one writer,” the lock must cover the whole critical section, including reading.
The correct form is this:
AcquireLock
Read file
Compute new state
Write (temp+rename + backup)
ReleaseLock
But this is not enough:
Read file
Compute new state
AcquireLock
Write
ReleaseLock
Because by the time you call AcquireLock, you have already read the old data.
6. Integrating lock-file into the tasker storage
Imagine we have a SaveTasks function that already knows how to write a file reliably (temp+rename, backup). We will add a lock there so that the code reads top to bottom and looks like a protocol.
Let the task file be called tasks.json, and the lock be tasks.json.lock.
package storage
import (
"fmt"
)
func SaveTasks(path string, data []byte) error {
lock, err := AcquireLock(path + ".lock")
if err != nil {
return err
}
defer lock.Release()
if err := WriteWithBackup(path, data, 0644); err != nil {
return fmt.Errorf("save tasks: %w", err)
}
return nil
}
Two things are important here.
First: defer lock.Release() must be placed immediately after a successful Acquire. Then you will not forget to add it, and your future bug will be somewhere else (which, of course, is still unpleasant, but at least it is variety).
Second: we are not inventing a new way to write. A lock file is not a replacement for temp+rename, but an additional turnstile at the entrance: only one process gets through, and inside we already perform the reliable write protocol.
7. Practical nuances and limitations of lock-file
What to tell the CLI user if the lock already exists
When your user sees an error, they are usually not interested in what the O_EXCL flags are or what atomicity means. They need to understand: “Is this my fault? Is it a bug? What should I do?”
So in the “lock exists” message, it is usually useful to be friendly and brief: “Storage is busy, try again later” or “Another instance of the program is performing a write.”
At the storage level, we returned "storage is busy: lock exists". At the CLI boundary (in main) you will decide whether to print it as is or turn it into a human-friendly phrase.
And there is a subtle line here: if you always write the same thing, that is great for UX, but sometimes you want diagnostics. A good compromise is a short user-facing message and a wrapped error for logs/debugging (we do that constantly in the course).
“Stuck” lock: why it happens
A lock file is an agreement, and it has a weak point: if the process dies (panic, kill -9, power loss), defer will not run, and the lock file may remain.
As a result, the next launch will say “storage is busy,” even though in reality “nobody is writing, the key was just left in the door.”
What should we do about it? For this lecture, we will fix an important idea: lock-file solves a common problem, but it is not an ideal locking system. In mature systems, people add a “lease” (lock lifetime), write the PID and timestamp inside, check whether the process is alive, or use specialized OS mechanisms. But that is a different level of the topic.
For our training CLI, it is usually enough to agree on this: if you are sure no write is in progress, you can delete tasks.json.lock manually. And to make life easier for the user, sometimes teams add a tasker doctor or tasker unlock command — but that is a product decision, not something required to understand the O_EXCL mechanism.
Table: what each layer protects
To avoid confusion, it is useful to keep a simple responsibility map in mind:
| Mechanism | What it protects against | What it does not protect against |
|---|---|---|
|
a “half-version of the file” if a failure happens during writing | lost updates with two writers |
|
a “logically bad new version” (you can roll back) | a partial file (that is solved by temp+rename) |
|
simultaneous execution of read→compute→write by two processes | a “forever lock” after an abnormal termination |
This table matters precisely as an engineering model: each layer closes its own hole, but does not replace the others.
8. Typical mistakes with lock-file
Mistake #1: making the lock only around Rename, not around reading.
This code looks “correct” because you really do protect the publish moment. But lost updates happen earlier — when two processes read the same old version. If the goal is not to lose updates, the lock must cover the entire read→compute→write cycle.
Mistake #2: using os.O_EXCL without os.O_CREATE and expecting exclusivity.
Intuitively it may seem that O_EXCL means “I will not let anyone in.” But in this context it means “exclusive creation.” If you forget O_CREATE, the logic breaks, and you may get behavior very different from what you expect.
Mistake #3: forgetting defer Release() immediately after successfully acquiring the lock.
This is classic: you acquired the lock, then kept writing code, added two more returns, and forgot to release it in one of them. The result is that the lock remains even after normal completion, and the program starts “blocking itself.” defer exists precisely so these mistakes happen less often.
Mistake #4: returning raw system error text to the user without context.
If you simply pass through the error open tasks.json.lock: file exists, the user may not understand what is happening. In Go we usually wrap the error with operation context (create lock ... %w), and at the application boundary turn it into a short and clear message.
Mistake #5: treating lock-file as a rock-solid guarantee of correctness in all situations.
A lock file is a good practical agreement, but it does not heal crashes, does not solve the question of “how to wait for the lock,” and does not replace a reliable write protocol. If you remember the limits of its responsibility, it works great and makes CLI behavior much more predictable.
GO TO FULL VERSION