Skip to content

Commit 7a341ca

Browse files
committed
feat: add Redis distributed locking with fencing
1 parent d630a75 commit 7a341ca

13 files changed

Lines changed: 624 additions & 92 deletions

File tree

‎docs/PLAN.md‎

Lines changed: 35 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22

33
## Purpose
44

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.
76

87
The rule in this project is:
98

@@ -14,16 +13,11 @@ A naive checkout does this:
1413
1. Read whether the locker is available.
1514
2. If it is available, insert a checkout.
1615

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.
1917

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.
2319

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.
2721

2822
## Domain and infrastructure
2923

@@ -51,75 +45,51 @@ A inserts
5145
B inserts
5246
```
5347

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.
5749

5850
### Shared behavior contract
5951

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.
6353

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.
6755

6856
### Strategy-specific mechanism test
6957

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:
7259

7360
- 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.
7662
- Make two optimistic writers use the same version.
7763
- Coordinate Redis lock holders with child-process messages.
7864

7965
### Process-topology test
8066

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:
8368

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.
8871

8972
## Step 2 — Implement one strategy at a time
9073

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).
9475

9576
### App-level keyed mutex
9677

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.
10079

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.
10481

10582
### Postgres advisory lock with READ COMMITTED
10683

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.
11085

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.
11587

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.
11889

11990
### Optimistic locking with a version column
12091

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.
12393

12494
Suppose callers A and B both read version `7`. Each tries a conditional update:
12595

@@ -136,9 +106,7 @@ Postgres performs each update atomically:
136106
- A updates the row, changing the version to `8`.
137107
- B's condition no longer matches, so B updates zero rows.
138108

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`.
142110

143111
This conditional update is often called **compare-and-swap**:
144112

@@ -147,9 +115,7 @@ This conditional update is often called **compare-and-swap**:
147115

148116
### Database uniqueness rule
149117

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.
153119

154120
Use a partial unique index that applies only to active rows:
155121

@@ -159,10 +125,7 @@ ON checkouts (locker_id)
159125
WHERE released_at IS NULL;
160126
```
161127

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.
166129

167130
### Redis distributed lock and fencing
168131

@@ -172,13 +135,9 @@ First, implement a Redis lease:
172135
SET lock:<key> <owner-token> NX PX <ttl>
173136
```
174137

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.
179139

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:
182141

183142
```text
184143
A acquires the lock
@@ -187,40 +146,25 @@ B acquires the lock and writes
187146
A resumes and tries to write
188147
```
189148

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.
192150

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.
196152

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.
200154

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:
203156

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.
208159

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.
212161

213162
## Test-harness decisions
214163

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.
224168

225169
## Related documents
226170

0 commit comments

Comments
 (0)