01 - The Runtime
📋 Jump to Takeaways🎁 Go runs thousands of goroutines in parallel. Node.js runs everything on one thread. How does a single-threaded runtime handle thousands of simultaneous database calls without blocking?
One thread. One call stack. No goroutines, no threads, no parallel execution. If you're coming from Go, this is the biggest mental shift. Everything runs on one thread, and the whole language is built around that.
Node can create threads (worker_threads) and processes (child_process). But the programming model is single threaded. In Java, every HTTP request gets its own thread. You write synchronous code and deal with locks, race conditions, and thread safety. In Node, every request runs on the same thread. No locks, no data races, because nothing else touches your variables between synchronous operations. You can still have logical race conditions — two async operations reading and writing the same variable with await in between — but you'll never corrupt memory. The event loop handles thousands of concurrent connections without threads because it never blocks waiting for I/O. That's the trade.
One Call Stack
Every function call pushes a frame onto the stack. When it returns, the frame pops off. If something takes a long time, nothing else runs.
function a(): void {
console.log("a start");
b();
console.log("a end");
}
function b(): void {
console.log("b");
}
a();
// a start
// b
// a endSimple enough. But what happens when you need to read a file, hit a database, or wait for a network response? You can't block the thread. There's only one.
The Event Loop
This is how concurrency works without threads. Three pieces:
- Call stack where your synchronous code runs
- Microtask queue where resolved promises and
queueMicrotaskcallbacks go - Callback queue (also called macrotask queue) where
setTimeout, I/O callbacks, etc. go
The loop: run everything on the call stack. When the stack is empty, drain the entire microtask queue. Then pick one item from the callback queue. Repeat.
console.log("1");
setTimeout(() => {
console.log("2 - setTimeout");
}, 0);
Promise.resolve().then(() => {
console.log("3 - promise");
});
console.log("4");
// 1
// 4
// 3 - promise
// 2 - setTimeoutEven with a 0ms delay, setTimeout goes to the callback queue. The promise goes to the microtask queue. Microtasks always run first. This ordering matters when you're debugging async code.
Why Async Is Everywhere
Node.js uses non-blocking I/O for everything: file reads, network calls, database queries. Instead of blocking the thread while waiting for a disk read, Node hands the operation to the OS, keeps executing other code, and picks up the result when it's ready.
In Go, you'd spin up a goroutine:
go func() {
data, err := os.ReadFile("config.json")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
}()
// main keeps running, goroutine does its thingIn TypeScript/Node, you write this:
import { readFile } from "node:fs/promises";
// Start the read, but don't await yet
const configPromise = readFile("config.json", "utf-8");
// This runs immediately while the file read is in progress
console.log("doing other work...");
// Now wait for the result
const data = await configPromise;
console.log(data);Go's scheduler multiplexes goroutines onto OS threads. Node's event loop never blocks. Different mechanism, same goal.
Blocking the Event Loop
One thread means CPU-heavy work freezes everything. No HTTP requests get handled. No timers fire. Nothing.
function blockForSeconds(seconds: number): void {
const start = Date.now();
while (Date.now() - start < seconds * 1000) {
// spinning... everything else is frozen
}
}
setTimeout(() => {
console.log("This should fire after 100ms");
}, 100);
blockForSeconds(3);
console.log("Done blocking");
// Done blocking
// This should fire after 100ms (fires ~3 seconds late)The setTimeout callback can't run until the call stack is empty. The blocking loop holds the stack for 3 seconds.
In Go, a CPU-heavy goroutine doesn't block other goroutines (the scheduler preempts it). In Node, a CPU-heavy function blocks everything. Never put heavy computation on the main thread.
How to avoid it: worker_threads. Yes, Node can create real OS threads. But they're separate from the main thread. Your application code still runs single threaded. Workers are for offloading heavy computation, not for general concurrency.
import { Worker } from "node:worker_threads";
// Offload CPU work to a separate OS thread
const worker = new Worker("./heavy-computation.js");
worker.on("message", (result) => {
console.log("Result from worker:", result);
});
// Main thread keeps handling requests while the worker crunches numbersworker_threads communicate via message passing, similar to Go channels. You don't share memory by default. Think of them as a last resort for CPU-bound work, not as goroutines.
Microtask Ordering
You won't write process.nextTick or queueMicrotask in normal code. But you'll hit ordering bugs where a callback fires before or after you expected. This is why.
When the call stack empties, Node doesn't just grab the next thing. It follows a strict order. Three separate places where code lives:
- Call stack: your code running right now. Nothing else executes until it's empty.
- Microtask queue: follow-up work from something that just finished (promise callbacks,
queueMicrotask). - Macrotask queue: scheduled work from the outside (
setTimeout,setInterval, I/O).
The event loop always drains all microtasks before touching the next macrotask.
- Run all
process.nextTickcallbacks - Run all microtasks (resolved promises,
queueMicrotask) - Run one macrotask (
setTimeout,setInterval, I/O callbacks) - Go back to step 1
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");
// sync (call stack, runs first)
// nextTick (step 1: nextTick queue)
// promise (step 2: microtask queue)
// timeout (step 3: macrotask queue)setTimeout(fn, 0) doesn't mean "run immediately." It means "run after everything else that's already queued." That's why promises resolve before timeouts even when both have zero delay.
In practice, async/await handles all of this for you. You only need this mental model when something fires in the wrong order and you're staring at logs wondering why.
The Mental Model
In Go, you think in goroutines. Spawn concurrent work and let the scheduler figure it out. Blocking is fine because the scheduler handles it.
In TypeScript, you think in callbacks and promises. Schedule work and the event loop runs it when the call stack is clear. Blocking is never fine because there's no scheduler to save you.
// Go mental model (pseudocode):
// go handleRequest(conn) // fire and forget, scheduler manages it
// JS mental model:
async function handleRequest(req: Request): Promise<Response> {
const data = await db.query("SELECT ..."); // yields to event loop
return new Response(JSON.stringify(data)); // resumes when data is ready
}Both models handle thousands of concurrent operations. Go does it with cheap threads. Node does it by never waiting. You'll get used to it fast, and by lesson 8 you'll be writing async code without thinking about it.
Key Takeaways
- One thread and one call stack. No parallelism in your code by default.
- The event loop processes microtasks (promises) before macrotasks (setTimeout, I/O callbacks)
- Node.js uses non-blocking I/O.
awaityields to the event loop, it doesn't block the thread. - CPU-heavy synchronous code freezes everything. Use worker threads for heavy computation.
process.nextTick>queueMicrotask/ promises >setTimeoutin execution priority- Go spawns goroutines. JS schedules callbacks. Different model, same goal: handle concurrency efficiently.
🎁 JavaScript has two kinds of nothing — null and undefined — and they're not interchangeable. Mixing them up causes bugs that === won't catch. What's the actual difference, and when do you use each?