← Runtimes
Runtimes

Go runtime services and scheduling

What a compiled Go program still carries: stacks, a scheduler, a collector.

A native executable can still depend on runtime machinery for stacks, scheduling and memory reclamation.

Outcome

Explain which services the Go runtime provides and what the other languages do instead, and predict how a scheduler shares processors among request handlers, parks those waiting on I/O and balances work.

Terminology (7)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Goroutine
A function running concurrently under the Go runtime’s scheduler.
Processor (P)
A Go runtime execution resource used with an OS thread to run goroutines; the active P count follows GOMAXPROCS and each has a local run queue.
Preemption
Stopping a running task so another can run, even though it has not finished.
Parking
Setting a waiting task aside so it holds no processor until it is ready.
Work stealing
An idle processor taking runnable work from another processor’s queue.
Stack growth
Moving a goroutine’s stack to a larger one when a call needs more room.
Event loop
The single-threaded loop that runs JavaScript callbacks one at a time.

What the runtime supplies

A call stack stores active calls; a scheduler chooses runnable work; memory reclamation releases storage that is no longer needed. Compiling to machine code does not decide how these services are provided. Go includes a runtime that manages goroutines, their growable stacks and garbage collection. The other editions use their own engine, host or library arrangements.

These mechanisms answer different resource questions. Stack capacity limits how deeply one handler can call; scheduling decides when runnable handlers execute; a pollable I/O wait can park a handler until it is ready. Understanding a service therefore combines its call depth, CPU work and waiting work. A deterministic scheduler model can isolate those choices without predicting a real runtime’s timings or stack limits.

01Stacks

What happens a million calls deep?

A web service accepts deeply nested request bodies while also rendering PDFs and querying a database. After a port changes which requests survive and which handlers wait, the team needs to separate stack capacity from scheduling. Native compilation does not tell them which runtime services the programme still relies on.

The retained host bounded its main-thread stack at about 8 MB. Rust/C++ do not automatically copy each ordinary thread’s stack as Go does for a goroutine. Source calls can be inlined or otherwise transformed; a printed result alone does not tell us how many physical frames existed.

To isolate the service’s nesting problem, the probe constructs one million [ followed by one million ]. Its recursive source counts the leading opening brackets and stops at the first other byte. The generated body contains nested empty arrays. This reduced stack/resource experiment does not validate arbitrary JSON; it only inspects that initial bracket run.

V8 runs on the main thread’s stack and enforces its own limit.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A recursive-descent JSON reader makes one call per level of nesting.
// This one measures how deeply a request body nests: one million nested arrays.

function nesting(body: string, at: number): number {
  return body[at] === "[" ? 1 + nesting(body, at + 1) : 0;
}

const body = "[".repeat(1_000_000) + "]".repeat(1_000_000);

try {
  console.log(`nesting depth: ${nesting(body, 0)}`);
} catch (error) {
  console.log(`${(error as Error).name}: ${(error as Error).message}`);
}
In the retained Node/V8 default-stack run, what did the program print?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --strict --target ES2022 --module commonjs --noEmitOnError && node main.js

The depth predictions refer to retained native builds, including their compiler options and approximately 8 MB main-thread stack setting. They are not portable failure predictions or new runs. The programmes only count leading opening brackets; they do not validate JSON or measure individual stack frames. The TypeScript command explicitly emits ES2022 JavaScript before Node executes it.

02Runtime services

What does each program carry at run time?

Once intake caps depth, the service still has PDF work queued ahead of a health check. In the standard Go runtime, a goroutine runs using a processor (P) and an OS thread (M); preemption allows another runnable goroutine a turn. GOMAXPROCS bounds how many can execute user Go code simultaneously, while extra threads may exist for blocking calls and runtime work. A handler waiting through Go’s pollable network I/O can release execution capacity. This premise does not cover every database driver, syscall or cgo call. An idle P can search other run queues for work.

Who provides each service
LanguageConcurrent tasksStacksReclamation
TypeScriptOne thread with an event loop; workers are separate threadsHost/build-dependent thread capacity with V8’s own stack limitV8’s garbage collector
GoGoroutines share GOMAXPROCS execution slots; total OS threads may exceed that countGrowable per goroutineGo runtime garbage collector
RustOperating-system threads; async runtimes such as Tokio are librariesPer-thread capacity/guard policy depends on host runtime/platformOwnership/drop scopes, with actual destruction also depending on runtime control flow
C++Hosted std::thread execution; coroutine resumption/scheduling is supplied by application or library codePlatform thread capacity/checks; no portable C++ overflow resultDestructors and smart pointers
A standard Go server has 10,000 goroutines waiting through Go net connections registered with the network poller. Assuming pollable I/O rather than blocking foreign calls, how are those waits represented?

03Practice

Finish the scheduler model

The lab is one scheduler model for a web service. It reads requests from stdin, each a list of cpu steps (rendering, hashing, encoding) and io waits (the database or another service), and prints which request each processor runs on every tick. It simulates scheduling decisions; it runs no real threads or handlers. Each level supplies the parts that already work.

The scheduler model

Share the processor among handlers, park handlers waiting on I/O, then steal queued requests.

  1. easy · R-SCHED-V4-1 Share the processor
  2. medium · R-SCHED-V4-2 Park handlers waiting on I/O
  3. hard · R-SCHED-V4-3 Steal waiting work
In the frontend Does async give a render its own processor? Optional

A Node-based Next.js or SvelteKit server proposes this async wrapper to let another request run during a synchronous PDF render. Inspect the incomplete helper’s actual callback execution.

The resolved promise queues a continuation; it creates neither a goroutine nor a worker thread. What part of the render can another JavaScript request callback interrupt?

lib/render-request.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export async function renderRequest(render: () => string) {
  await Promise.resolve();
  return render();
}

The callback runs in a later microtask on the same JavaScript execution thread. Once a synchronous render starts, this wrapper supplies no points for other request callbacks to run inside it. Go runtime preemption is not a property that async adds to this Node helper.

Sources: Node.js: Event loop,ECMAScript: Await.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.