Let a client construct a complex object one step at a time, with readable named steps for required and optional parts, and defer creation until a final build() call that validates the entire configuration and returns a complete, consistent object.
Builder separates how you configure an object from the moment you create it. You call a series of named steps on a builder object, skip the ones you do not need, and finish with build(), which checks the whole configuration and returns a finished, usually immutable, product.
This guide follows one scenario throughout: the provisioning API of a fictional cloud provider that has to turn messy virtual machine requests into valid specs. You will see the problem, the structure, pseudocode, and the same runnable implementation in TypeScript, Python and PHP, plus the questions interviewers tend to ask about it.
The problem
A situation where the obvious design starts to hurt.
You are on the four-person provisioning team at Driftwood Cloud. Every virtual machine starts life as a VmSpec with nine settings: name, region, CPU cores, memory, a list of data disks, a GPU count, a public IP flag, SSH keys and tags. Only four of them are required. The rest are optional, and most requests leave them empty.
Today the code creates specs like new VmSpec("api-1", "eu-west-2", 4, 16, [], 0, false, [], {}). Nobody can tell at a glance which 0 is the GPU count and which false means no public IP. Three callers build specs this way: the REST handler, the command-line tool and the internal autoscaler. Each one copies a slightly different set of rules: cores between 1 and 64, at least 2 GiB of memory per core, no more than 8 data disks, each disk between 10 and 16384 GiB, GPU machines need at least 8 cores, and a machine with a public IP must have at least one SSH key.
Last month the autoscaler skipped the SSH key rule and a spec with a public IP and no key reached the scheduler. Adding a new optional field means touching every call site and every copy of the validation. You need a way to create specs that reads clearly, makes optional parts truly optional, and enforces the rules in exactly one place, before an invalid spec can exist.
The solution
What the pattern proposes.
Move construction into a VmSpecBuilder. The builder holds the in-progress configuration in private fields and exposes one method per step: named(), inRegion(), withCompute(), addDisk(), withGpus(), withPublicIp(), addSshKey() and tag(). Each step records its value and returns the builder, so calls chain and read like a sentence. Steps you do not need, you simply do not call; defaults live in the builder.
The builder never hands out a half-configured object. Only build() creates a VmSpec, and before it does, it runs every rule against the full configuration and collects all failures into one InvalidSpecError. Cross-field rules such as "a GPU needs at least 8 cores" work naturally here because, unlike in a setter, every field is known at that point. If validation passes, build() copies the collections and returns an immutable spec.
Common configurations go into a director, MachinePresets, which runs a known sequence of steps on a builder it receives. The REST handler, CLI and autoscaler all go through the same builder, so they share one set of rules, and a new optional field means one new step method and maybe one new rule.
An everyday analogy
The same idea, outside software.
Think of ordering a custom bicycle at a small bike shop. You tell the mechanic what you want in whatever order it comes to mind: a medium frame, flat handlebars, a rear rack, maybe dynamo lights, no mudguards. The mechanic writes each choice on an order sheet but does not cut or bolt anything yet.
When you say you are done, the mechanic reads the whole sheet and checks it as a set: the rack needs frame mounts, the wide tyres must clear the brakes. If something does not fit, you hear about every problem at once, before any parts are assembled. Only a sheet that passes the check turns into a bike. The shop also keeps a few ready-made sheets, like a commuter setup, that you can start from and tweak.
Structure
The pieces and how they relate.
Participants
- VmSpec (Product)
- The complex object being built. Its fields are read-only and it has no public way to change after creation, so any VmSpec in the system has already passed validation.
- VmSpecBuilder (Builder)
- Holds the in-progress configuration, exposes one fluent method per step, applies defaults for optional parts, and in build() validates the whole configuration and creates the product.
- MachinePresets (Director)
- Knows the order and values of steps for common machine shapes, such as a web server. It works on a builder passed in, so the client can add more steps before calling build().
- Disk
- A small value object the builder creates for each addDisk() call and the product composes as a list.
- InvalidSpecError
- Carries every validation failure found by build(), so the caller can report all problems in one response instead of fixing them one at a time.
- ProvisioningApi (Client)
- Any caller that needs a spec: the REST handler, CLI or autoscaler. It picks a preset or starts from an empty builder, adds steps, and calls build().
Pseudocode
The solution to the scenario, language-neutral.
class VmSpecBuilder
fields: name = "", region = "", cores = 0, memoryGiB = 0,
disks = [], gpuCount = 0, publicIp = false,
sshKeys = [], tags = {}
method named(n): name = n; return this
method inRegion(r): region = r; return this
method withCompute(c, m): cores = c; memoryGiB = m; return this
method addDisk(size, type = "ssd"): disks.append(new Disk(size, type)); return this
method withGpus(count): gpuCount = count; return this
method withPublicIp(): publicIp = true; return this
method addSshKey(key): sshKeys.append(key); return this
method tag(k, v): tags[k] = v; return this
method build()
errors = []
if name is empty: errors.add("name is required")
if region is empty: errors.add("region is required")
if cores < 1 or cores > 64: errors.add("cores must be between 1 and 64")
if memoryGiB < cores * 2: errors.add("memory must be at least 2 GiB per core")
if disks.length > 8: errors.add("at most 8 data disks")
if any disk size outside 10..16384: errors.add("disk size must be 10 to 16384 GiB")
if gpuCount > 0 and cores < 8: errors.add("GPU machines need at least 8 cores")
if publicIp and sshKeys is empty: errors.add("a public IP requires at least one SSH key")
if errors not empty: throw InvalidSpecError(errors)
return new VmSpec(copies of all fields)
class MachinePresets
static method webServer(builder)
return builder.withCompute(2, 4).addDisk(50).withPublicIp()
.addSshKey("ops-deploy").tag("role", "web")
// client
spec = MachinePresets.webServer(new VmSpecBuilder())
.named("checkout-web-1").inRegion("eu-west-2").tag("team", "checkout")
.build()The code
The same solution in TypeScript, Python and PHP.
type DiskType = "ssd" | "hdd";
class Disk {
constructor(readonly sizeGiB: number, readonly type: DiskType) {}
}
class VmSpec {
constructor(
readonly name: string,
readonly region: string,
readonly cores: number,
readonly memoryGiB: number,
readonly disks: readonly Disk[],
readonly gpuCount: number,
readonly publicIp: boolean,
readonly sshKeys: readonly string[],
readonly tags: Readonly<Record<string, string>>,
) {}
}
class InvalidSpecError extends Error {
constructor(readonly errors: string[]) {
super(`Invalid VM spec: ${errors.join("; ")}`);
this.name = "InvalidSpecError";
}
}
class VmSpecBuilder {
private name = "";
private region = "";
private cores = 0;
private memoryGiB = 0;
private disks: Disk[] = [];
private gpuCount = 0;
private publicIp = false;
private sshKeys: string[] = [];
private tags: Record<string, string> = {};
named(name: string): this {
this.name = name;
return this;
}
inRegion(region: string): this {
this.region = region;
return this;
}
withCompute(cores: number, memoryGiB: number): this {
this.cores = cores;
this.memoryGiB = memoryGiB;
return this;
}
addDisk(sizeGiB: number, type: DiskType = "ssd"): this {
this.disks.push(new Disk(sizeGiB, type));
return this;
}
withGpus(count: number): this {
this.gpuCount = count;
return this;
}
withPublicIp(): this {
this.publicIp = true;
return this;
}
addSshKey(key: string): this {
this.sshKeys.push(key);
return this;
}
tag(key: string, value: string): this {
this.tags[key] = value;
return this;
}
build(): VmSpec {
const errors: string[] = [];
if (!this.name) errors.push("name is required");
if (!this.region) errors.push("region is required");
if (this.cores < 1 || this.cores > 64) errors.push("cores must be between 1 and 64");
if (this.memoryGiB < this.cores * 2) errors.push("memory must be at least 2 GiB per core");
if (this.disks.length > 8) errors.push("at most 8 data disks");
if (this.disks.some((d) => d.sizeGiB < 10 || d.sizeGiB > 16384)) {
errors.push("disk size must be 10 to 16384 GiB");
}
if (this.gpuCount > 0 && this.cores < 8) errors.push("GPU machines need at least 8 cores");
if (this.publicIp && this.sshKeys.length === 0) {
errors.push("a public IP requires at least one SSH key");
}
if (errors.length > 0) throw new InvalidSpecError(errors);
return new VmSpec(
this.name,
this.region,
this.cores,
this.memoryGiB,
Object.freeze([...this.disks]),
this.gpuCount,
this.publicIp,
Object.freeze([...this.sshKeys]),
Object.freeze({ ...this.tags }),
);
}
}
class MachinePresets {
static webServer(builder: VmSpecBuilder): VmSpecBuilder {
return builder
.withCompute(2, 4)
.addDisk(50)
.withPublicIp()
.addSshKey("ops-deploy")
.tag("role", "web");
}
}
const spec = MachinePresets.webServer(new VmSpecBuilder())
.named("checkout-web-1")
.inRegion("eu-west-2")
.tag("team", "checkout")
.build();
console.log(spec.name, spec.cores, spec.memoryGiB, spec.disks.length);
// checkout-web-1 2 4 1
try {
new VmSpecBuilder()
.named("trainer")
.inRegion("us-east-1")
.withCompute(4, 16)
.withGpus(2)
.withPublicIp()
.build();
} catch (e) {
if (e instanceof InvalidSpecError) console.log(e.errors.join("\n"));
}
// GPU machines need at least 8 cores
// a public IP requires at least one SSH keyfrom dataclasses import dataclass
from types import MappingProxyType
from typing import Literal, Mapping
DiskType = Literal["ssd", "hdd"]
@dataclass(frozen=True)
class Disk:
size_gib: int
type: DiskType = "ssd"
@dataclass(frozen=True)
class VmSpec:
name: str
region: str
cores: int
memory_gib: int
disks: tuple[Disk, ...]
gpu_count: int
public_ip: bool
ssh_keys: tuple[str, ...]
tags: Mapping[str, str]
class InvalidSpecError(ValueError):
def __init__(self, errors: list[str]) -> None:
super().__init__("Invalid VM spec: " + "; ".join(errors))
self.errors = errors
class VmSpecBuilder:
def __init__(self) -> None:
self._name = ""
self._region = ""
self._cores = 0
self._memory_gib = 0
self._disks: list[Disk] = []
self._gpu_count = 0
self._public_ip = False
self._ssh_keys: list[str] = []
self._tags: dict[str, str] = {}
def named(self, name: str) -> "VmSpecBuilder":
self._name = name
return self
def in_region(self, region: str) -> "VmSpecBuilder":
self._region = region
return self
def with_compute(self, cores: int, memory_gib: int) -> "VmSpecBuilder":
self._cores = cores
self._memory_gib = memory_gib
return self
def add_disk(self, size_gib: int, type: DiskType = "ssd") -> "VmSpecBuilder":
self._disks.append(Disk(size_gib, type))
return self
def with_gpus(self, count: int) -> "VmSpecBuilder":
self._gpu_count = count
return self
def with_public_ip(self) -> "VmSpecBuilder":
self._public_ip = True
return self
def add_ssh_key(self, key: str) -> "VmSpecBuilder":
self._ssh_keys.append(key)
return self
def tag(self, key: str, value: str) -> "VmSpecBuilder":
self._tags[key] = value
return self
def build(self) -> VmSpec:
errors: list[str] = []
if not self._name:
errors.append("name is required")
if not self._region:
errors.append("region is required")
if self._cores < 1 or self._cores > 64:
errors.append("cores must be between 1 and 64")
if self._memory_gib < self._cores * 2:
errors.append("memory must be at least 2 GiB per core")
if len(self._disks) > 8:
errors.append("at most 8 data disks")
if any(d.size_gib < 10 or d.size_gib > 16384 for d in self._disks):
errors.append("disk size must be 10 to 16384 GiB")
if self._gpu_count > 0 and self._cores < 8:
errors.append("GPU machines need at least 8 cores")
if self._public_ip and not self._ssh_keys:
errors.append("a public IP requires at least one SSH key")
if errors:
raise InvalidSpecError(errors)
return VmSpec(
name=self._name,
region=self._region,
cores=self._cores,
memory_gib=self._memory_gib,
disks=tuple(self._disks),
gpu_count=self._gpu_count,
public_ip=self._public_ip,
ssh_keys=tuple(self._ssh_keys),
tags=MappingProxyType(dict(self._tags)),
)
class MachinePresets:
@staticmethod
def web_server(builder: VmSpecBuilder) -> VmSpecBuilder:
return (
builder.with_compute(2, 4)
.add_disk(50)
.with_public_ip()
.add_ssh_key("ops-deploy")
.tag("role", "web")
)
spec = (
MachinePresets.web_server(VmSpecBuilder())
.named("checkout-web-1")
.in_region("eu-west-2")
.tag("team", "checkout")
.build()
)
print(spec.name, spec.cores, spec.memory_gib, len(spec.disks))
# checkout-web-1 2 4 1
try:
(
VmSpecBuilder()
.named("trainer")
.in_region("us-east-1")
.with_compute(4, 16)
.with_gpus(2)
.with_public_ip()
.build()
)
except InvalidSpecError as e:
print("\n".join(e.errors))
# GPU machines need at least 8 cores
# a public IP requires at least one SSH key<?php
declare(strict_types=1);
final class Disk
{
public function __construct(
public readonly int $sizeGiB,
public readonly string $type = 'ssd',
) {}
}
final class VmSpec
{
/**
* @param Disk[] $disks
* @param string[] $sshKeys
* @param array<string, string> $tags
*/
public function __construct(
public readonly string $name,
public readonly string $region,
public readonly int $cores,
public readonly int $memoryGiB,
public readonly array $disks,
public readonly int $gpuCount,
public readonly bool $publicIp,
public readonly array $sshKeys,
public readonly array $tags,
) {}
}
final class InvalidSpecError extends InvalidArgumentException
{
/** @param string[] $errors */
public function __construct(public readonly array $errors)
{
parent::__construct('Invalid VM spec: ' . implode('; ', $errors));
}
}
final class VmSpecBuilder
{
private string $name = '';
private string $region = '';
private int $cores = 0;
private int $memoryGiB = 0;
/** @var Disk[] */
private array $disks = [];
private int $gpuCount = 0;
private bool $publicIp = false;
/** @var string[] */
private array $sshKeys = [];
/** @var array<string, string> */
private array $tags = [];
public function named(string $name): static
{
$this->name = $name;
return $this;
}
public function inRegion(string $region): static
{
$this->region = $region;
return $this;
}
public function withCompute(int $cores, int $memoryGiB): static
{
$this->cores = $cores;
$this->memoryGiB = $memoryGiB;
return $this;
}
public function addDisk(int $sizeGiB, string $type = 'ssd'): static
{
$this->disks[] = new Disk($sizeGiB, $type);
return $this;
}
public function withGpus(int $count): static
{
$this->gpuCount = $count;
return $this;
}
public function withPublicIp(): static
{
$this->publicIp = true;
return $this;
}
public function addSshKey(string $key): static
{
$this->sshKeys[] = $key;
return $this;
}
public function tag(string $key, string $value): static
{
$this->tags[$key] = $value;
return $this;
}
public function build(): VmSpec
{
$errors = [];
if ($this->name === '') $errors[] = 'name is required';
if ($this->region === '') $errors[] = 'region is required';
if ($this->cores < 1 || $this->cores > 64) $errors[] = 'cores must be between 1 and 64';
if ($this->memoryGiB < $this->cores * 2) $errors[] = 'memory must be at least 2 GiB per core';
if (count($this->disks) > 8) $errors[] = 'at most 8 data disks';
foreach ($this->disks as $disk) {
if ($disk->sizeGiB < 10 || $disk->sizeGiB > 16384) {
$errors[] = 'disk size must be 10 to 16384 GiB';
break;
}
}
if ($this->gpuCount > 0 && $this->cores < 8) $errors[] = 'GPU machines need at least 8 cores';
if ($this->publicIp && count($this->sshKeys) === 0) {
$errors[] = 'a public IP requires at least one SSH key';
}
if ($errors !== []) {
throw new InvalidSpecError($errors);
}
// PHP arrays are copied by value, so later builder calls cannot change this spec.
return new VmSpec(
$this->name,
$this->region,
$this->cores,
$this->memoryGiB,
$this->disks,
$this->gpuCount,
$this->publicIp,
$this->sshKeys,
$this->tags,
);
}
}
final class MachinePresets
{
public static function webServer(VmSpecBuilder $builder): VmSpecBuilder
{
return $builder
->withCompute(2, 4)
->addDisk(50)
->withPublicIp()
->addSshKey('ops-deploy')
->tag('role', 'web');
}
}
$spec = MachinePresets::webServer(new VmSpecBuilder())
->named('checkout-web-1')
->inRegion('eu-west-2')
->tag('team', 'checkout')
->build();
echo "{$spec->name} {$spec->cores} {$spec->memoryGiB} " . count($spec->disks) . PHP_EOL;
// checkout-web-1 2 4 1
try {
(new VmSpecBuilder())
->named('trainer')
->inRegion('us-east-1')
->withCompute(4, 16)
->withGpus(2)
->withPublicIp()
->build();
} catch (InvalidSpecError $e) {
echo implode(PHP_EOL, $e->errors) . PHP_EOL;
}
// GPU machines need at least 8 cores
// a public IP requires at least one SSH keyWhen to use it
Situations where it pays off.
A constructor has many parameters, several of them optional, and call sites are full of positional zeros, nulls and booleans.
Named steps make each value self-describing, and optional parts are just steps you skip. This removes the telescoping constructor and the guessing that comes with it.
Validity depends on combinations of fields, such as a GPU requiring enough cores or a public IP requiring an SSH key.
Setters on the product can only check one field at a time. A builder checks the whole configuration in build(), when every value is known, and refuses to create an inconsistent object.
You want the product to be immutable but still configured incrementally, for example from parsed request fields or CLI flags arriving one by one.
The builder is the mutable scratchpad; the product is created once with final values. Code that receives a product never has to wonder whether it is complete.
Several callers create the same kind of object and keep duplicating defaults and rules.
Centralising defaults and validation in one builder means a rule change happens in one place, and presets in a director capture common configurations without copy-paste.
The same construction steps should produce different representations, such as a spec and a price quote.
Put the steps behind a builder interface and give each representation its own concrete builder. A director can then drive any of them with the same sequence.
How to implement it
Steps to introduce it in existing code.
Write down the product's fields and split them into required and optional. Decide on a default for every optional field.
Make the product immutable: read-only fields, collections copied or frozen, and no setters. Its constructor is meant to be called only by the builder.
Create the builder with private fields for every setting, initialised to the defaults or to an "unset" marker for required values.
Add one method per step. Each method stores its argument and returns the builder so calls can chain. Use add-style methods for repeating parts like disks and SSH keys.
Implement build(): run every single-field and cross-field rule, collect all failures, and throw one error listing them. Only if the list is empty, create the product from copies of the builder's state.
If several callers share the same configurations, add a director with methods that run a known sequence of steps on a builder they receive.
Replace the old constructor calls with the builder, then make the product's constructor harder to reach (package-private, internal, or documented as builder-only) so nobody bypasses validation.
Pros and cons
What you gain and what you pay.
Pros
- Call sites become readable:
.withCompute(4, 16).withPublicIp()says what it means, unlike a row of positional arguments. - Optional parts are genuinely optional, with defaults defined in one place.
- All validation, including cross-field rules, runs once in build(), so an invalid product can never exist.
- The product can be fully immutable while still being configured step by step.
- Collecting all errors at once gives callers a complete report instead of one failure per attempt.
- Directors let you name and reuse common configurations without duplicating step sequences.
Cons
- You write and maintain a second class that mirrors the product's fields, and every new field touches both.
- Required fields are only enforced at runtime in build(), not at compile time, unless you add a more elaborate staged builder with separate types per step.
- A mutable builder that is shared or reused across threads or requests can leak state between products if you are not careful.
- For objects with three or four fields and no cross-field rules, a builder is ceremony; a constructor with named or keyword arguments is simpler.
Relations with other guides
Patterns it's often confused or combined with.
- Long Parameter List
A constructor with a long list of positional and optional parameters is the usual signal that a builder will help. The builder replaces the list with named steps.
- Introduce Parameter Object: Bundle Parameters That Travel Together
Introduce Parameter Object groups related arguments into one value. Builder goes further when that object has optional parts and rules that span several fields.
- Factory Method: Let Subclasses Decide Which Object to Create
Factory Method creates an object in one call and focuses on which class to instantiate. Builder focuses on how to assemble one object through several steps before returning it.
- Abstract Factory: Create Families of Objects That Belong Together
Abstract Factory returns families of related products immediately. Builder returns a single product, and only at the end of a sequence of configuration steps.
- Composite Pattern: Treat Single Items and Groups Through One Interface
Builders are handy for assembling Composite trees, since a step can add a child node and build() can validate the whole tree before handing it out.
- Prototype Pattern: Create Objects by Cloning a Configured Instance
Prototype starts from a copy of an existing object. You can combine them by seeding a builder from an existing product, changing a few steps and building a new one.
Common questions
Short answers to the usual doubts.
Why validate in build() instead of in each step method?
Some rules depend on several fields, and steps can arrive in any order. When withGpus(2) runs, the builder may not know the core count yet. In build() every value is set, so cross-field rules are reliable. You can still reject obviously bad single values early, such as a negative disk size, but the final check belongs in build(), and collecting all errors there gives callers a complete report.
Is a director required?
No. Many builders in real code have no director; the client calls the steps directly. A director earns its place when several callers repeat the same step sequences, as with Driftwood's web server preset. Having it accept a builder, rather than create one, lets the client add steps afterwards.
How is Builder different from a constructor with named or keyword arguments?
Keyword arguments solve readability and optional parameters for simple objects, and in Python or PHP 8 that is often enough. Builder adds incremental construction (values gathered over time, repeated parts like addDisk()), a place for cross-field validation and defaults, reusable presets, and the option to build different representations from the same steps.
Can I reuse a builder after calling build()?
Only if build() copies its collections into the product, as all three implementations here do. Otherwise the product would share lists with the builder and change when you add another disk. Even with copies, do not share one builder across threads or concurrent requests, because its fields are mutable.
How would you make missing required fields a compile-time error?
Use a staged builder: each step returns a different interface that only exposes the next required step, for example named() returns a type with only inRegion(), and only the final stage has build(). It costs one interface per required step, so teams usually reserve it for public APIs where misuse is common.
Where does the GoF builder interface come in?
When you need several representations from the same steps. Driftwood could add a QuoteBuilder that implements the same step methods but sums an hourly price instead of producing a spec. With both behind a MachineBuilder interface, MachinePresets.webServer() could drive either one without changes.