You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 7a341ca
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: docs/PLAN.md
+35-91Lines changed: 35 additions & 91 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,8 +2,7 @@
2
2
3
3
## Purpose
4
4
5
-
This project practices several ways to protect a shared rule when concurrent
6
-
Node.js operations modify the same data.
5
+
This project practices several ways to protect a shared rule when concurrent Node.js operations modify the same data.
7
6
8
7
The rule in this project is:
9
8
@@ -14,16 +13,11 @@ A naive checkout does this:
14
13
1. Read whether the locker is available.
15
14
2. If it is available, insert a checkout.
16
15
17
-
The race occurs when callers A and B both complete the read before either one
18
-
inserts. Both see an available locker, so both insert a checkout.
16
+
The race occurs when callers A and B both complete the read before either one inserts. Both see an available locker, so both insert a checkout.
19
17
20
-
The project compares ways to prevent or detect that race in Node.js, Postgres,
21
-
and Redis. Every strategy is tested with real infrastructure rather than an
22
-
in-memory database fake.
18
+
The project compares ways to prevent or detect that race in Node.js, Postgres, and Redis. Every strategy is tested with real infrastructure rather than an in-memory database fake.
23
19
24
-
A secondary goal is to practice the low-level APIs involved: `pg.Pool`, SQL
25
-
transactions, parameterized queries, and raw Redis commands without an ORM or
26
-
framework abstraction.
20
+
A secondary goal is to practice the low-level APIs involved: `pg.Pool`, SQL transactions, parameterized queries, and raw Redis commands without an ORM or framework abstraction.
27
21
28
22
## Domain and infrastructure
29
23
@@ -51,75 +45,51 @@ A inserts
51
45
B inserts
52
46
```
53
47
54
-
This test reliably demonstrates the original bug. It talks directly to
55
-
Postgres and deliberately bypasses `checkout()`, so it is not reused to test a
56
-
strategy.
48
+
This test reliably demonstrates the original bug. It talks directly to Postgres and deliberately bypasses `checkout()`, so it is not reused to test a strategy.
57
49
58
50
### Shared behavior contract
59
51
60
-
Call a strategy's real `checkout()` function many times concurrently for the
61
-
same locker. A correct strategy should return exactly one successful checkout
62
-
and leave exactly one active checkout in Postgres.
52
+
Call a strategy's real `checkout()` function many times concurrently for the same locker. A correct strategy should return exactly one successful checkout and leave exactly one active checkout in Postgres.
63
53
64
-
This is useful shared coverage, but it is not enough by itself. Node.js may
65
-
happen to run the calls one after another, allowing a broken strategy to pass
66
-
by chance.
54
+
This is useful shared coverage, but it is not enough by itself. Node.js may happen to run the calls one after another, allowing a broken strategy to pass by chance.
67
55
68
56
### Strategy-specific mechanism test
69
57
70
-
Control the point where callers contend so the test proves why a strategy
71
-
works. For example:
58
+
Control the point where callers contend so the test proves why a strategy works. For example:
72
59
73
60
- Keep caller A inside a keyed mutex and prove caller B waits.
74
-
- Under Postgres `READ COMMITTED` isolation, hold an advisory lock
75
-
and prove another connection waits.
61
+
- Under Postgres `READ COMMITTED` isolation, hold an advisory lock and prove another connection waits.
76
62
- Make two optimistic writers use the same version.
77
63
- Coordinate Redis lock holders with child-process messages.
78
64
79
65
### Process-topology test
80
66
81
-
Run two concurrent checkout attempts in two separate Node.js processes. This
82
-
reveals where each coordination mechanism lives:
67
+
Run two concurrent checkout attempts in two separate Node.js processes. This reveals where each coordination mechanism lives:
83
68
84
-
- A keyed mutex coordinates only callers in one process, so two processes can
85
-
both win.
86
-
- Postgres, Redis with stale-write protection, optimistic locking, and a
87
-
database uniqueness rule must protect the invariant across processes.
69
+
- A keyed mutex coordinates only callers in one process, so two processes can both win.
70
+
- Postgres, Redis with stale-write protection, optimistic locking, and a database uniqueness rule must protect the invariant across processes.
88
71
89
72
## Step 2 — Implement one strategy at a time
90
73
91
-
For each strategy, complete its shared contract, mechanism test, and topology
92
-
test before starting the next strategy. Then add what was learned to
93
-
[`comparison.md`](comparison.md).
74
+
For each strategy, complete its shared contract, mechanism test, and topology test before starting the next strategy. Then add what was learned to [`comparison.md`](comparison.md).
94
75
95
76
### App-level keyed mutex
96
77
97
-
Maintain a promise queue for each locker ID. A caller waits for the previous
98
-
promise before reading and writing, then releases its promise for the next
99
-
caller.
78
+
Maintain a promise queue for each locker ID. A caller waits for the previous promise before reading and writing, then releases its promise for the next caller.
100
79
101
-
The queue is ordinary JavaScript memory. It works when every caller uses the
102
-
same checkout instance in one process. Two serverless invocations or container
103
-
replicas have different queues, so the mutex cannot coordinate between them.
80
+
The queue is ordinary JavaScript memory. It works when every caller uses the same checkout instance in one process. Two serverless invocations or container replicas have different queues, so the mutex cannot coordinate between them.
104
81
105
82
### Postgres advisory lock with READ COMMITTED
106
83
107
-
Acquire `pg_advisory_xact_lock(...)` inside the transaction before checking the
108
-
locker. Every process using the same lock key asks Postgres for the same lock,
109
-
so Postgres serializes them.
84
+
Acquire `pg_advisory_xact_lock(...)` inside the transaction before checking the locker. Every process using the same lock key asks Postgres for the same lock, so Postgres serializes them.
110
85
111
-
This strategy depends on PostgreSQL `READ COMMITTED` transaction
112
-
isolation. Each statement receives a new snapshot, so a caller that waited for
113
-
the advisory lock runs its availability query against a snapshot taken after
114
-
the previous holder commits. Using `REPEATABLE READ` or `SERIALIZABLE` would require different snapshot and retry handling.
86
+
This strategy depends on PostgreSQL `READ COMMITTED` transaction isolation. Each statement receives a new snapshot, so a caller that waited for the advisory lock runs its availability query against a snapshot taken after the previous holder commits. Using `REPEATABLE READ` or `SERIALIZABLE` would require different snapshot and retry handling.
115
87
116
-
The transaction-scoped lock is automatically released on commit or rollback.
117
-
All code paths that modify this state must follow the locking convention.
88
+
The transaction-scoped lock is automatically released on commit or rollback. All code paths that modify this state must follow the locking convention.
118
89
119
90
### Optimistic locking with a version column
120
91
121
-
Optimistic locking does not make the second caller wait before reading.
122
-
Instead, it detects at write time that another caller has changed the data.
92
+
Optimistic locking does not make the second caller wait before reading. Instead, it detects at write time that another caller has changed the data.
123
93
124
94
Suppose callers A and B both read version `7`. Each tries a conditional update:
125
95
@@ -136,9 +106,7 @@ Postgres performs each update atomically:
136
106
- A updates the row, changing the version to `8`.
137
107
- B's condition no longer matches, so B updates zero rows.
138
108
139
-
The affected-row count (`result.rowCount` in `pg`) tells the application who
140
-
won. The winner inserts the checkout in the same transaction. The loser reads
141
-
the current state again and, for this domain, normally returns `unavailable`.
109
+
The affected-row count (`result.rowCount` in `pg`) tells the application who won. The winner inserts the checkout in the same transaction. The loser reads the current state again and, for this domain, normally returns `unavailable`.
142
110
143
111
This conditional update is often called **compare-and-swap**:
144
112
@@ -147,9 +115,7 @@ This conditional update is often called **compare-and-swap**:
147
115
148
116
### Database uniqueness rule
149
117
150
-
Let Postgres enforce the invariant directly. Because the `checkouts` table
151
-
keeps historical rows, `UNIQUE (locker_id)` would be too strict: it would
152
-
prevent a locker from ever being checked out again.
118
+
Let Postgres enforce the invariant directly. Because the `checkouts` table keeps historical rows, `UNIQUE (locker_id)` would be too strict: it would prevent a locker from ever being checked out again.
153
119
154
120
Use a partial unique index that applies only to active rows:
155
121
@@ -159,10 +125,7 @@ ON checkouts (locker_id)
159
125
WHERE released_at IS NULL;
160
126
```
161
127
162
-
If two processes insert concurrently, Postgres accepts one insert and rejects
163
-
the other. The application converts that expected conflict into an
164
-
`unavailable` result. This strategy is not a locking technique; it expresses
165
-
the business rule in the database.
128
+
If two processes insert concurrently, Postgres accepts one insert and rejects the other. The application converts that expected conflict into an `unavailable` result. This strategy is not a locking technique; it expresses the business rule in the database.
166
129
167
130
### Redis distributed lock and fencing
168
131
@@ -172,13 +135,9 @@ First, implement a Redis lease:
172
135
SET lock:<key> <owner-token> NX PX <ttl>
173
136
```
174
137
175
-
`NX` acquires the key only when it does not already exist. `PX` gives the lock
176
-
a time-to-live so a crashed owner cannot hold it forever. Release the lock with
177
-
an atomic Lua script that deletes the key only when its value still equals the
178
-
caller's owner token.
138
+
`NX` acquires the key only when it does not already exist. `PX` gives the lock a time-to-live so a crashed owner cannot hold it forever. Release the lock with an atomic [Lua script](/docs/lua-scripts.md) that deletes the key only when its value still equals the caller's owner token.
179
139
180
-
The owner-token check makes release safe, but it does not make an expired owner
181
-
safe. Consider this sequence:
140
+
The owner-token check makes release safe, but it does not make an expired owner safe. Consider this sequence:
182
141
183
142
```text
184
143
A acquires the lock
@@ -187,40 +146,25 @@ B acquires the lock and writes
187
146
A resumes and tries to write
188
147
```
189
148
190
-
A must not be allowed to write after B. Checking the token during release only
191
-
stops A from deleting B's lock; it does not stop A's database write.
149
+
A must not be allowed to write after B. Checking the token during release only stops A from deleting B's lock; it does not stop A's database write.
192
150
193
-
The owner token above is a random identity: it answers "is this still my
194
-
lock?" A fencing token is different. It is an increasing number that records
195
-
the order in which owners acquired the lock.
151
+
The owner token above is a random identity: it answers "is this still my lock?" A fencing token is different. It is an increasing number that records the order in which owners acquired the lock.
196
152
197
-
Postgres remembers the highest fencing token it has accepted and rejects a
198
-
write carrying an older token. A resumed owner can therefore be recognized as
199
-
stale even after its Redis lease expires.
153
+
Postgres remembers the highest fencing token it has accepted and rejects a write carrying an older token. A resumed owner can therefore be recognized as stale even after its Redis lease expires.
200
154
201
-
Fencing and optimistic locking both use conditional database writes, but their
202
-
values mean different things:
155
+
Fencing and optimistic locking both use conditional database writes, but their values mean different things:
203
156
204
-
- An optimistic-lock version is read from the database row. The write succeeds
205
-
only if that row still has the same version.
206
-
- A fencing token represents the order in which owners acquired the lock. The
207
-
database rejects an owner older than one it has already accepted.
157
+
- An optimistic-lock version is read from the database row. The write succeeds only if that row still has the same version.
158
+
- A fencing token represents the order in which owners acquired the lock. The database rejects an owner older than one it has already accepted.
208
159
209
-
Using `UPDATE ... WHERE version = $expected` alongside Redis can still be a
210
-
valid design, but it combines the Redis lease with optimistic locking. It is
211
-
not, by itself, a fencing-token implementation.
160
+
Using `UPDATE ... WHERE version = $expected` alongside Redis can still be a valid design, but it combines the Redis lease with optimistic locking. It is not, by itself, a fencing-token implementation.
212
161
213
162
## Test-harness decisions
214
163
215
-
-**Database isolation:** Give each test a separate schema. In particular, the
216
-
partial unique index must not change the behavior of other strategies.
217
-
-**Test-runner concurrency:** Run integration-test files serially or isolate
218
-
their database state. One cleanup transaction cannot include work performed
219
-
by other connections or processes.
220
-
-**Client ownership:** The process that creates a `pg.Pool` or Redis connection
221
-
must close it with `pool.end()` or `redis.quit()`/`disconnect()`.
222
-
-**Deterministic cleanup:** Release barriers and close clients in `finally`
223
-
blocks so a failed assertion does not leave a test or child process hanging.
164
+
-**Database isolation:** Give each test a separate schema. In particular, the partial unique index must not change the behavior of other strategies.
165
+
-**Test-runner concurrency:** Run integration-test files serially or isolate their database state. One cleanup transaction cannot include work performed by other connections or processes.
166
+
-**Client ownership:** The process that creates a `pg.Pool` or Redis connection must close it with `pool.end()` or `redis.quit()`/`disconnect()`.
167
+
-**Deterministic cleanup:** Release barriers and close clients in `finally` blocks so a failed assertion does not leave a test or child process hanging.
0 commit comments