1. Why two processes are a separate problem
When we say “two processes,” it sounds a bit abstract — as if we were talking about some servers with millions of users. But in practice, it can be literally you and your colleague, both launching the same CLI command at the same time, or two terminals on one laptop. The problem is tricky because the file almost always remains “pretty and intact,” so the bug can live for a long time.
Let’s 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 (added task)
B->>B: Compute v3 (marked done)
A->>F: Publish v2 (temp+rename)
B->>F: Publish v3 (temp+rename)
Both processes acted honestly and carefully. And both used reliable writing. But the final result is this: the file will contain v3, and A’s changes (the added task) may disappear, because B read the old version (v1), did not know 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 it does not protect against “half-logic” , when two independent computations compete for the right to be last.
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, different platforms, different kinds of locks), we introduce a simple rule: if a lock file is present nearby, writing is already in progress, do not touch it.
It is important to understand lock-file correctly right away: it is an agreement, not an absolute “protects from everything” guarantee. If one process crashes, the lock-file may remain (we will discuss that later). But even such a simple agreement sharply 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 modify tasks.json first tries to create exclusively tasks.json.lock;
- if the lock cannot be created because it already exists — then someone else is writing right now, and we exit cleanly with the error “storage is busy”;
- if the lock is created — we work: read, compute, write (via temp+rename/backup);
- at the end, remove the lock file.
The key technical trick: exclusive creation is done via os.OpenFile with the 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 could 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 by itself, it does not prevent two processes from almost simultaneously going through 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 create a new file exclusively.
So what matters to us is not “open exclusively,” but “create exclusively,” so that a second process cannot quietly create the same lock.
Let’s add os.O_WRONLY to open the file for writing. This is useful at least because we can write helpful debugging information inside the lock file (for example, the PID). But even if we write nothing, 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 make “almost correct code” that then leaves junk behind or fails to explain why everything broke. That is why we will write the way we are used to in Go: small functions, early returns, and clear error text.
Separately: 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 case where defer helps make code safer and easier for the brain.
Mini structure Lock
To make it convenient to store both the path and the open file, let’s create 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 types 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 that we return the error with context via fmt.Errorf(... %w ...), so that higher up it is visible “at which step” everything failed, while the underlying cause is not lost. This is a basic and very important Go practice.
Releasing the lock file: Release
Releasing means “close and delete.” Usually release errors should not overshadow the main business-logic error, so in Release people often do best-effort: closed, removed, errors are not returned (or are logged at the application boundary).
package storage
import "os"
func (l *Lock) Release() {
_ = l.f.Close()
_ = os.Remove(l.path)
}
Yes, here we ignore errors. In an ideal world, we could collect 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 entire operation
At this point 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.
A lost update happens because both processes read the same old version. So if your goal is “only one writer,” the lock must cover the entire critical section, including reading.
So the correct form is:
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
Let’s imagine we have a SaveTasks function that already knows how to write a file reliably (temp+rename, backup). We will add the lock there so that the code reads from top to bottom and looks like a protocol.
Suppose the task file is called tasks.json, and the lock is 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
}
There are two important things 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 also unpleasant, but at least it is variety).
Second: we are not inventing a new way to write. Lock-file is not a replacement for temp+rename, but an additional “turnstile” at the entrance: only one process gets inside, and once inside we execute a reliable writing 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 usually do not care about flags like O_EXCL and what atomicity is. They need to understand: “Is this my fault? Is this a bug? What should I do?”
That is why, in the message for “lock exists,” it is usually useful to be friendly and short: “Storage is busy, try again later” or “Another instance of the program is writing.”
At the storage layer we returned "storage is busy: lock exists". At the CLI boundary (in main) you can 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 print the same thing, that is great for UX, but sometimes you want diagnostics. A good compromise is a short message for the user and a wrapped error for logs/debugging (we deal with this constantly in the course).
“Stuck” lock: why it happens
Lock-file is an agreement, and it has a weak spot: if the process dies (panic, kill -9, power goes out), defer will not run, and the lock file may remain.
As a result, the next run will say “storage is busy,” even though in reality “nobody is writing, the key was just left in the door.”
What do we do about that? In this lecture we establish 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 PID and timestamp inside, check whether the process is alive, or use specialized OS mechanisms. But that is a different depth of the topic.
For our training CLI, most of the time it is enough to agree on this: if you are sure that no writing is happening, you can remove tasks.json.lock manually. And to make it easier for the user, sometimes people add a tasker doctor or tasker unlock command — but these are product decisions, not mandatory for understanding the O_EXCL mechanics.
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 |
|---|---|---|
|
“half-version of a file” when a write fails | lost updates with two writers |
|
“logically bad new version” (you can roll back) | 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: putting the lock only around Rename, not around reading.
That code looks “correct,” because you really are protecting the publication moment. But the lost update happens 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 seems that O_EXCL means “I won’t let anyone in.” But in this context it is “exclusive creation.” If you forget O_CREATE, the logic breaks, and you may get behavior that is completely different from what you expect.
Mistake #3: forgetting defer Release() right after successfully acquiring the lock.
This is classic: you acquired the lock, then started writing code, added two more returns, and in one of them forgot to release it. The result is that the lock remains even after normal completion, and the program starts “blocking itself.” defer was created exactly to make such mistakes happen less often.
Mistake #4: returning the “raw” system error text to the user without context.
If you simply propagate the error open tasks.json.lock: file exists, the user may not understand what is happening. In Go we usually wrap errors with operation context (create lock ... %w), and at the application boundary turn it into a short and understandable message.
Mistake #5: treating lock-file as a rock-solid guarantee of correctness in every case.
Lock-file is a good practical agreement, but it does not cure crashes, does not solve “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