Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Lose a Ticket to a Race

In this lesson, you sent two tickets to the repair café’s API at the same moment and watched the store from the previous lesson lose one of them.

Key Points

  • The store reads, changes and writes. To create a ticket, create() reads tickets.json, adds the ticket to the list, and writes the whole list back.
  • Two tickets can arrive together. On a busy Saturday, Hana brings a kettle and Omar brings a fan, and two volunteers log them at the same moment. JavaScript runs on one thread, one line at a time, so you might expect that to be fine.
  • A short script sends both at once. Its post() function sends one ticket with fetch(), as a POST with a JSON body. The two post() calls start both requests without waiting for each other, and Promise.all() waits for both answers.
  • Both answers are 201 Created, and one ticket is gone. Each request was told its ticket was saved, but the list holds six tickets, not seven, and tickets.json agrees: Omar’s fan is there, and Hana’s kettle isn’t.
  • The result depends on timing, which makes it a race. Most runs lose one ticket, and which one can change. Now and then, both tickets survive, or the file ends up broken.
  • The requests take turns at their awaits. When a function reaches an await, it pauses there, and the event loop runs something else that’s ready. Hana’s request pauses at its read, and Omar’s request starts and pauses at the same read, so both reads are under way.
  • Both reads find five tickets. Hana’s read comes back with five tickets, and her request adds the kettle and starts writing six. Omar’s read had got the file before Hana’s write changed it, so his copy holds five tickets too, and his request adds the fan and writes six.
  • Omar’s six replace Hana’s six. In the run shown, the file was left with Omar’s six, and the kettle was gone. Node does the file work outside your JavaScript’s thread, so both writes were under way at once. That isn’t what lost the kettle, though, because Omar’s copy never had it.
  • No two lines of your code ran at the same moment. The requests took turns at their awaits, and that split each read from its write. When your tickets lived in an array in memory, the same script kept both, because pushing onto that array had no await in the middle.
  • One thread doesn’t stop a race. A read, an await, then a write can lose an update.

Here’s the script that sends both tickets at once, race.ts. Before each run, copy tickets.json from the course’s starting project, so it holds the five starting tickets again, even after a run that left it broken. Then start the app with node --watch app.ts, and run node race.ts from your second terminal. The script needs the app running, so its output below comes from a real run against it:

Language: TypeScript Filename: race.ts
const TICKETS_URL = "http://localhost:3000/tickets";

function post(name: string, item: string, fault: string) {
  return fetch(TICKETS_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, item, category: "electrical", fault }),
  });
}

const answers = await Promise.all([
  post("Hana", "kettle", "Won't switch off"),
  post("Omar", "fan", "Blades don't spin"),
]);
console.log(answers.map((answer) => answer.status));

const response = await fetch(TICKETS_URL);
if (!response.ok) {
  console.log(response.status);
} else {
  const page: unknown = await response.json();
  if (typeof page === "object" && page !== null && "total" in page) {
    console.log(page.total);
  }
}

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 Your store now saves every change in tickets.json, the café’s data file. To create a ticket, it reads the file, adds the ticket to the list, and writes the whole list back.

00:12 On a busy Saturday, two volunteers log tickets at the same moment. Hana brings a kettle, and Omar brings a fan. You might expect that to be fine. JavaScript runs on one thread, one line at a time, so how could two requests trip over each other?

00:31 In this lesson, you’ll send both tickets at once and see what your store does with them.

00:37 You need two requests that leave together, so write a short script, race.ts, to send them. Its post function sends one ticket with fetch, as a POST with a JSON body.

00:49 The two post calls start both requests without waiting for each other, and Promise.all waits for both answers. Then the script logs the two status codes and how many tickets the list holds.

01:02 Copy tickets.json from the starting project, so it holds the five starting tickets again. Start the app, and run the script from your second terminal. Both requests go through the create function on screen.

01:15 Your turn: pause the video and predict how many tickets the list will hold.

01:26 Six. Both answers are 201 Created, so each request was told its ticket was saved. But the list holds only one of the two.

01:38 Open tickets.json to see which one survived. Omar’s fan is there, and Hana’s kettle is gone. Copy the file back before each run, and run the script a few times.

01:50 The result changes. Most runs lose one ticket, and which one can change too. Now and then, both tickets survive, or the file ends up broken. When the result depends on timing like this, it’s called a race.

02:07 To see how one thread loses a ticket, go back to the moment both requests arrive. Remember the picture from async code: when a function reaches an await, it pauses there, and the event loop runs something else that’s ready.

02:21 Hana’s request calls create first, and pauses at its read. Omar’s request starts while it waits, and pauses at the same read. Both reads are now under way.

02:35 Hana’s read comes back first, with five tickets. Her request adds the kettle to that copy and starts writing six tickets. Then Omar’s read comes back. It had read the file before Hana’s write changed it, so his copy holds five tickets too.

02:52 Omar’s request adds the fan to its own copy of five and starts writing six tickets. This time, the file was left with Omar’s six, and the kettle is gone. Node does the file work outside your code’s thread, so both writes were under way at once.

03:09 But that isn’t what lost the kettle. Omar’s copy never had it. No two lines of your code ran at the same moment. The requests took turns at their awaits, and that split each read from its write.

03:25 When your tickets lived in an array in memory, the same script kept both. Pushing onto that array had no await in the middle, so one change finished before the next began.

03:37 One thread doesn’t stop a race. A read, an await, then a write can lose an update. Your store needs to stop splitting each read from its write. In the next lesson, Load Once and Queue Every Save, you’ll load the tickets once, change them in memory with no await in the middle, and put every save in line.

Become a Member to join the conversation.