The Real Fullstack

The Invisible Mutation

Node.js is single-threaded. So how can one request change another request's data?

エクスプローラー6 分タイムラインシミュレーターコード課題
javascripttypescriptnodepython

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション:Find an interleaving of two concurrent requests that produces a wrong currency, then change the code so no interleaving can.背景 · 学習目標 ▾

Larkspur's pricing endpoint formats prices in the user's currency. A handful of European users report prices shown in US dollars, but only under load, and never in tests. The formatter keeps its options in a module-level defaults object.

ミッション: Find an interleaving of two concurrent requests that produces a wrong currency, then change the code so no interleaving can.

学習目標

  • Explain why shared mutable state is unsafe even without threads.
  • Use Object.freeze to make accidental mutation fail loudly.
  • Fix the bug with per-request copies of configuration.
シミュレーションシミュレーション値

シミュレーションを実行すると出力が表示されます。

シミュレーションを実行
const defaults = { currency: 'EUR', locale: 'en-IE' };   // module-level singletonexport async function priceLabel(req) {  const opts = defaults;               // not a copy — the same object for every request  opts.currency = req.user.currency;   // mutates the shared object  const amount = await pricing.lookup(req.params.sku);  // other requests run here  return new Intl.NumberFormat(opts.locale, { style: 'currency', currency: opts.currency }).format(amount);}

簡略化

Each request has two steps (set currency, await, format). Real servers interleave many more requests at every await. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

関連する課題

参考資料