Concurrency and races · Chapter 4 of 15
Check-then-act across two servers
Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Two requests at once
- 3 tasks
- JavaScript
- In the all labs plan
The first 2 chapters of Concurrency and races are free. This one comes with the all labs plan.
Why you need this
A promise-chain lock makes one server's bookings wait for each other. Here is one, on rider slots, with a stand-in database:
// One booking at a time, inside this server.
function createServer(name) {
let queue = Promise.resolve();
return {
book(slot) {
const turn = queue.then(async () => {
const free = await db.free(slot);
if (free < 1) return `${name}: full`;
await db.save(slot, free - 1);
return `${name}: booked`;
});
queue = turn;
return turn;
},
};
}
const one = createServer('server 1');
console.log(await Promise.all([one.book('6pm'), one.book('6pm')]));
slots.set('6pm', 1);
const two = createServer('server 2');
console.log(await Promise.all([one.book('6pm'), two.book('6pm')]));
[ 'server 1: booked', 'server 1: full' ]
[ 'server 1: booked', 'server 2: booked' ]
Inside server 1 the lock works: the second booking waited, saw the slot taken and said full. Across two servers, both booked the one slot. Each server has its own queue. The lock works inside one process and means nothing to the other one. The only thing both servers share is the database, so that is where the check and the act must happen together.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
repro.js: sell the last box twice on purpose
Write reproduce() in repro.js. Make one stock table with createStockDb from stock-db.js, with 1 box left (any sku, say { 'diwali-box': 1 }). Make two shops with createShop({ db }) from shop.js, one per API server, both on that one table. Let each shop buy 1 box at the same time, wait for both, and resolve to how many of the two buys resolved to 'sold'.
The check runs your reproduce() twice: beside the original shop.js it must resolve to 2 (one box, two sales), and beside a fixed shop.js it must resolve to 1. Buys made one after another never race, so start both before waiting for either. No real waiting: the stand-in answers on the next turn of the event loop, and reproduce() must finish within 2 seconds.
- Task 2
shop.js: never sell what is not there
Fix createShop({ db }) in shop.js so that buy(sku, qty) checks the stock and takes it in one step in the database, with db.takeIf(sku, qty), which takes qty only if at least qty is left and resolves to true, or takes nothing and resolves to false. When it took the stock, buy logs <sku>: sold <qty> and resolves to 'sold'; when not, it logs <sku>: sold out and resolves to 'sold out'. Keep both log lines as they are.
However many shops (servers) buy at once on one table, exactly the stock is sold and it never goes below zero. Buying 2 with 1 left is sold out and takes nothing. The check uses its own table and items, and races two shops, then ten shops for three items.
- Task 3
shop.test.js: a test that would have caught it
Write a vitest test file, shop.test.js, that would have caught the oversold boxes. The check runs your file three times: beside the original shop.js, where at least one test must fail; beside the fixed shop.js, where every test must pass; and beside a wrong fix with a lock in JavaScript inside each shop, where at least one test must fail.
So make one stock table from stock-db.js with 1 item left and two shops on it, buy one on each at the same time, and expect exactly one 'sold' and one 'sold out', and 0 left. No real waiting: each test must finish within 3 seconds.
What you will learn
- repro.js: sell the last box twice on purpose
- shop.js: never sell what is not there
- shop.test.js: a test that would have caught it
More in Two requests at once
Build "Check-then-act across two servers" yourself
Tapri's backend grew busy, and Kabir keeps handing you incidents that only happen when two things run at once. Each is a race interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Concurrency and races are free. This one comes with the all labs plan.