The JavaScript Event Loop: Call Stack, Task Queue & Microtasks
DEV Community

The JavaScript Event Loop: Call Stack, Task Queue & Microtasks

JavaScript runs on a single thread. That thread has one call stack, one memory heap, and one thing it can execute at any given moment.

Yet a properly written Node.js server handles tens of thousands of concurrent connections without spawning a thread per request, without blocking, and without the kind of concurrency bugs that plague multi-threaded systems in Java or C++. The mechanism behind that is the event loop.

Every setTimeout, every await, every .then(), every fs.readFile callback - all of it runs because the event loop coordinates when JavaScript code actually executes. If you do not understand the event loop at a mechanical level, you will write bugs that only appear under production load, bugs that are nearly impossible to reproduce locally, and bugs where your logging shows no obvious error but requests hang or return stale data.

This article walks through the event loop from first principles to production-grade async patterns. Every code sample is the kind you would write in a real backend service, not a toy example.

The Call Stack

When JavaScript calls a function, the runtime pushes an execution context onto the call stack. That context holds the function's local variables, its arguments, and a return address pointing back to the calling code. When the function returns, its context pops off the stack. The stack is LIFO - last in, first out.

import { createServer, IncomingMessage, ServerResponse } from 'http';
import { URL } from 'url';

function extractPathSegments(rawUrl: string, base: string): string[] {
  const url = new URL(rawUrl, base);
  return url.pathname.split('/').filter(Boolean);
}

function buildRouteKey(method: string, segments: string[]): string {
  const normalized = segments.map((s) => (/^\d+$/.test(s) ? ':id' : s));
  return `${method.toUpperCase()} /${normalized.join('/')}`;
}

function resolveRoute(req: IncomingMessage): string {
  const segments = extractPathSegments(req.url ?? '/', 'http://localhost');
  return buildRouteKey(req.method ?? 'GET', segments);
}

const server = createServer((req: IncomingMessage, res: ServerResponse) => {
  const routeKey = resolveRoute(req);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(routeKey);
});

server.listen(3000);

When a request arrives and resolveRoute is called, the call stack builds up in layers: the createServer callback at the bottom, then resolveRoute, then extractPathSegments, then the URL constructor deep inside. The stack unwinds in reverse as each function returns.

At no point does JavaScript execute two of these functions simultaneously. buildRouteKey does not start until extractPathSegments returns. resolveRoute does not return until buildRouteKey returns. This sequential, deterministic execution within synchronous code is the foundation everything else builds on.

The call stack is not concurrent. It is a strict execution order enforced by the runtime.

The stack has a hard size limit determined by the engine and the available memory. Unbounded recursion exhausts it. In V8 (the engine used by Node.js and Chrome), the limit is typically around 10,000-15,000 frames depending on frame size. Hitting that limit throws a RangeError: Maximum call stack size exceeded and crashes the current execution context.

Why Blocking the Stack Destroys Server Performance

Because JavaScript has one thread and one call stack, any synchronous operation that takes time blocks every other operation from running. There is no scheduler. There is no OS-level preemption. The event loop cannot move to the next task until the call stack is empty.

import { readFileSync, readdirSync } from 'fs';
import { createServer, IncomingMessage, ServerResponse } from 'http';

interface ConfigFile {
  name: string;
  content: Record<string, unknown>;
}

function loadAllConfigs(configDir: string): ConfigFile[] {
  const files = readdirSync(configDir);
  return files
    .filter((f) => f.endsWith('.json'))
    .map((file) => {
      const raw = readFileSync(`${configDir}/${file}`, 'utf8');
      return {
        name: file,
        content: JSON.parse(raw) as Record<string, unknown>,
      };
    });
}

const server = createServer((_req: IncomingMessage, res: ServerResponse) => {
  const configs = loadAllConfigs('./config');
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(configs));
});

server.listen(3000);

readdirSync and readFileSync are synchronous filesystem calls. They tell the OS to read from disk, then block the JavaScript thread until the OS returns the data. During that blocking period - which might be 1ms on a warm OS cache or 50ms on a cold HDD - every other incoming HTTP connection sits waiting.

No other request handler runs. No timer callbacks fire. No database responses get processed. The single thread is occupied waiting for the filesystem.

A server handling 500 concurrent requests where each request blocks for 10ms on config reads is, in practice, a server that can only serve 2 requests per second despite having idle CPU cores. The CPU is not the bottleneck. The single blocked thread is.

This is why Node.js exposes async versions of every I/O operation and why you should never call the sync variants inside request handlers. readFileSync is appropriate in build scripts and CLI tools that run once. It has no place in a server.

The Event Loop's Role: Web APIs and the Task Queue

JavaScript itself does not perform I/O. The runtime environment - Node.js, the browser - provides APIs that delegate I/O to the operating system using non-blocking system calls (epoll on Linux, kqueue on macOS, IOCP on Windows). libuv, the library under Node.js, abstracts these into a unified async I/O model.

When you call fs.readFile, setTimeout, fetch, or net.connect, you hand work off to the runtime. Node.js pushes the call onto the stack, the runtime registers the operation with the OS, and then pops the call off the stack and keeps executing. The OS does the actual work - reading disk sectors, waiting for a network packet - while JavaScript's thread continues processing other code.

When the OS finishes the operation, it signals libuv, which places the callback you provided into the task queue (also called the macrotask queue or callback queue). The event loop then checks: if the call stack is empty, dequeue one task and push it onto the stack for execution.

import { readFile } from 'fs/promises';
import { createServer, IncomingMessage, ServerResponse } from 'http';
import path from 'path';

const ALLOWED_EXTENSIONS = new Set(['.json', '.txt', '.html']);

async function readSafeFile(filename: string, baseDir: string): Promise<string> {
  const resolvedBase = path.resolve(baseDir);
  const resolvedTarget = path.resolve(baseDir, filename);
  if (!resolvedTarget.startsWith(resolvedBase)) {
    throw new RangeError(`Path traversal attempt: ${filename}`);
  }
  const ext = path.extname(filename);
  if (!ALLOWED_EXTENSIONS.has(ext)) {
    throw new TypeError(`Disallowed file type: ${ext}`);
  }
  return readFile(resolvedTarget, 'utf8');
}

const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
  const url = new URL(req.url ?? '/', 'http://localhost');
  const filename = url.searchParams.get('file') ?? '';
  if (!filename) {
    res.writeHead(400);
    res.end('Missing file parameter');
    return;
  }
  try {
    const content = await readSafeFile(filename, path.join(process.cwd(), 'public'));
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(content);
  } catch (err) {
    if (err instanceof RangeError || err instanceof TypeError) {
      res.writeHead(403);
      res.end(err.message);
    } else {
      res.writeHead(500);
      res.end('Internal server error');
    }
  }
});

server.listen(3000);

readFile from fs/promises returns a Promise backed by libuv's async file I/O. When you await it, JavaScript suspends execution of the async function and frees the call stack. The thread continues processing other requests, timer callbacks, or database responses. When the OS finishes reading the file, libuv places the Promise resolution into the microtask queue, and the async function resumes from where it paused.

Notice the path traversal guard. path.resolve canonicalizes the path before comparing it to the base directory. A filename like ../../etc/passwd resolves to a path outside baseDir, and the check catches it before touching the filesystem. Async I/O does not make your code safe by itself - it just makes it non-blocking. Security checks are still your responsibility.

The Microtask Queue: Higher Priority Than Everything Else

The task queue holds callbacks from timers, I/O, and system events. Promises use a separate, higher-priority queue: the microtask queue. The event loop drains the entire microtask queue before it picks up the next macrotask. Every .then() callback, every await continuation, every queueMicrotask() call lands in the microtask queue.

import { EventEmitter } from 'events';

class AsyncJobQueue extends EventEmitter {
  private queue: Array<() => Promise<void>> = [];
  private running = false;

  enqueue(job: () => Promise<void>): void {
    this.queue.push(job);
    queueMicrotask(() => this.drain());
  }

  private async drain(): Promise<void> {
    if (this.running) return;
    this.running = true;
    while (this.queue.length > 0) {
      const job = this.queue.shift()!;
      try {
        await job();
        this.emit('job:complete');
      } catch (err) {
        this.emit('job:error', err);
      }
    }
    this.running = false;
    this.emit('queue:empty');
  }
}

const jobQueue = new AsyncJobQueue();

jobQueue.on('job:complete', () => {
  console.log('job finished');
});

jobQueue.on('queue:empty', () => {
  console.log('all jobs processed');
});

jobQueue.on('job:error', (err: Error) => {
  console.error('job failed:', err.message);
});

jobQueue.enqueue(async () => {
  await new Promise<void>((resolve) => setTimeout(resolve, 100));
  console.log('job A');
});

jobQueue.enqueue(async () => {
  console.log('job B');
});

queueMicrotask(() => this.drain()) schedules drain as a microtask rather than calling it immediately. This matters for two reasons. First, it prevents re-entrant calls to drain when enqueue is called from inside a job. Second, if multiple jobs are enqueued synchronously in the same turn of the event loop, all of them land in this.queue before drain starts. drain then processes the batch rather than getting called once per job and thrashing the running lock.

The microtask queue runs to completion before the next macrotask. That means the drain microtask fires after all synchronous code in the current turn finishes, but before any setTimeout callback. The while loop inside drain keeps processing jobs as long as the queue has items. Each await job() pauses the async function, but between awaits the event loop can process other pending microtasks. It cannot process new I/O callbacks or timer callbacks until drain returns or hits an await.

Emitting events synchronously from within an async function is intentional here. EventEmitter.emit is synchronous - all listeners for job:complete run before emit returns. This makes the event timing predictable: listeners fire immediately after each job, not after the entire batch.

If you're enjoying what you've read so far, we recommend Writing Your Own API From Scratch in TypeScript as your next read.

Execution Order: Putting the Queues Together

Understanding the exact order in which microtasks and macrotasks fire is not an academic exercise. It determines whether a cache invalidation fires before or after a database write, whether a cleanup handler runs before a response is sent, and whether a rate limit counter updates before or after you check it.

import { createClient } from 'redis';

type RequestPhase = 'start' | 'cache-miss' | 'db-query' | 'cache-set' | 'response';

interface TraceEvent {
  phase: RequestPhase;
  timestamp: number;
  source: 'sync' | 'microtask' | 'macrotask';
}

async function traceRequestPipeline(
  redis: ReturnType<typeof createClient>,
  userId: number,
): Promise<TraceEvent[]> {
  const trace: TraceEvent[] = [];
  const now = () => performance.now();
  trace.push({ phase: 'start', timestamp: now(), source: 'sync' });
  const cached = await redis.get(`user:${userId}`);
  if (cached !== null) {
    trace.push({ phase: 'response', timestamp: now(), source: 'microtask' });
    return trace;
  }
  trace.push({ phase: 'cache-miss', timestamp: now(), source: 'microtask' });
  const dbResult = await new Promise<string>((resolve) => {
    setTimeout(() => {
      resolve(JSON.stringify({ id: userId, name: 'Alice' }));
    }, 0);
  });
  trace.push({ phase: 'db-query', timestamp: now(), source: 'macrotask' });
  await redis.set(`user:${userId}`, dbResult, { EX: 300 });
  trace.push({ phase: 'cache-set', timestamp: now(), source: 'microtask' });
  Promise.resolve().then(() => {
    trace.push({ phase: 'response', timestamp: now(), source: 'microtask' });
  });
  return trace;
}

Walk through the execution order. The trace.push({ phase: 'start' }) call runs synchronously - it is plain JavaScript on the call stack. await redis.get(...) suspends the async function and surrenders the call stack. The Redis client sends a command over TCP and returns a Promise. When Redis responds, libuv resolves the Promise and queues the continuation as a microtask.

The async function resumes at the if (cached !== null) line - this is a microtask continuation, so it runs before any pending setTimeout callbacks. The setTimeout(() => resolve(...), 0) wrapping the simulated DB query places a callback in the macrotask queue. The async function awaits the Promise wrapping that callback.

After the await, the event loop sees an empty call stack, drains microtasks (none pending), then picks up the setTimeout callback from the macrotask queue, which resolves the Promise. The async function's next continuation queues as a microtask and runs before any other macrotask.

This trace makes the queue priority visible. Everything after an await redis.get is a microtask continuation. Everything after an await new Promise(resolve => setTimeout(...)) is a macrotask continuation followed immediately by a microtask continuation.

The Right Way to Handle Database I/O

Every await pool.query(...)

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.