Multi-Cloud GPU Fleet Scaling CLI

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement the state persistence, reconciliation engine, and CLI entry point for gpulift, a command-line utility that scales fleets of cloud GPU virtual machines across heterogeneous cloud vendors behind a uniform Provider interface.

Rather than blindly launching N machines on every invocation, gpulift scale is declarative and idempotent: given a target --count, it inspects live cloud resources, reconciles differences against local tracking metadata in state.json, repairs failed boots, and converges the (provider, region, gpu_type) fleet to the requested size.

Implement StateStore, scale, and main against the provided abstractions:

class Provider(ABC):
    name = "base"
    def provision(self, gpu_type: str, region: str, token: str) -> str: ...
    def list_instances(self, gpu_type: str, region: str) -> List[Instance]: ...
    def get_status(self, instance_id: str) -> str: ...
    def terminate(self, instance_id: str) -> None: ...


class StateStore:
    def __init__(self, path: str) -> None: ...
    def load(self) -> dict: ...
    def save(self, state: dict) -> None: ...


def scale(
    provider: Provider,
    store: StateStore,
    gpu_type: str,
    region: str,
    count: int,
    max_rounds: int = 30,
    max_retries: int = 3,
    poll_seconds: float = 10.0,
    sleep: Callable[[float], None] = time.sleep,
    log: Callable[[str], None] = print,
) -> ScaleResult: ...


def main(
    argv: List[str],
    providers: Dict[str, Provider],
    store: StateStore,
    sleep: Callable[[float], None] = time.sleep,
) -> int: ...

Behavioral requirements:

  1. Crash-safe local state (StateStore):
    • load() returns the parsed JSON dictionary from self.path, or {"fleets": {}} when the file does not exist yet.
    • save(state) writes atomically (via temporary file + flush/fsync + atomic rename) so an interrupted write never leaves corrupt JSON on disk.
    • Key each fleet under state["fleets"][f"{provider.name}/{region}/{gpu_type}"] tracking "desired" (target integer), "instances" ({vm_id: token}), and "pending" (write-ahead list of idempotency tokens).
  2. Idempotent reconciliation (scale):
    • Raise ValueError if count < 0. Save desired = count to disk before issuing cloud API calls.
    • Across at most max_rounds polling cycles, merge provider.list_instances(gpu_type, region) with previously recorded VM IDs: verify any saved ID absent from a lagging listing via provider.get_status(vm_id), keeping "pending"/"running" VMs and dropping "terminated"/"not_found" ones.
    • Immediately terminate any VM in "failed" status and clear its pending token so its replacement uses a fresh token.
    • Count both "pending" (still booting) and "running" VMs toward current healthy size so slow boots never trigger duplicate launches. Return immediately once len(running) == count and zero VMs remain "pending".
    • Before calling provider.provision, persist client-generated idempotency tokens in "pending" (reusing leftover "pending" tokens from an interrupted run first) so crashes before or after VM creation never produce duplicates.
    • When scaling down, terminate "pending" VMs ahead of "running" ones. Sleep poll_seconds between incomplete rounds.
    • Retry RateLimitError up to max_retries times with exponential backoff delays of 1, 2, 4, ... seconds using the same token. If throttling still fails, leave remaining tokens in "pending", record an error in ScaleResult.errors, and stop creating. On ProvisionError (hard capacity/quota refusal), discard the unused token, record the error, and stop creating after the current batch without spinning for max_rounds.
  3. CLI entry point (main):
    • Support gpulift scale --gpu-type <TYPE> --count <INT> [--region <REGION>] [--provider <NAME>], defaulting --region to "us-east-1" and --provider to "aws".
    • Exit with status 2 (standard argparse error) on invalid flags, negative --count, or an unregistered --provider.
    • Return 0 when result.ok is True, or 1 when scaling finishes only partially.

Examples

Example 1

# 1) Empty fleet -> scale to 3 H100s in us-west-2
code1 = main(["scale", "--gpu-type", "H100", "--count", "3", "--region", "us-west-2"], providers, store)
# Logs:   [INFO] 0 instances found. Provisioning 3 additional H100...
# Output: [SUCCESS] 3 instances running (ID: vm-1, vm-2, vm-3)
# code1 == 0

# 2) Expand from 3 -> 4 H100s (launches only the delta of 1)
code2 = main(["scale", "--gpu-type", "H100", "--count", "4", "--region", "us-west-2"], providers, store)
# Logs:   [INFO] 3 instances found. Provisioning 1 additional H100...
# Output: [SUCCESS] 4 instances running (ID: vm-1, vm-2, vm-3, vm-4)
# code2 == 0

# 3) Re-running --count 4 is a pure no-op (0 provision/terminate calls)
code3 = main(["scale", "--gpu-type", "H100", "--count", "4", "--region", "us-west-2"], providers, store)
# code3 == 0

The first call creates three VMs (vm-1, vm-2, vm-3) and records desired = 3 in state.json. Raising --count to 4 discovers the three live VMs and provisions only vm-4. Repeating --count 4 sees delta = 0 with zero booting VMs and returns 0 immediately.

Example 2

# Fleet of L4 VMs in eu-central-1 where vm-2 fails during boot:
res = scale(provider, store, gpu_type="L4", region="eu-central-1", count=2)
# res.ok == True
# res.created == ["vm-1", "vm-2", "vm-3"]
# res.terminated == ["vm-2"]
# sorted(res.running) == ["vm-1", "vm-3"]

# Later scaling down to 1 terminates one VM:
shrunk = scale(provider, store, gpu_type="L4", region="eu-central-1", count=1)
# shrunk.ok == True, len(shrunk.running) == 1, len(shrunk.terminated) == 1

Round 1 creates vm-1 and vm-2 in "pending" state. While booting, Round 2 counts both toward the target of 2 and waits rather than over-provisioning. Once vm-2 transitions to "failed", the reconciler terminates vm-2, allocates a fresh token for vm-3, waits for vm-3 to reach "running", and reports ok = True. Scaling down to 1 then removes one excess instance and updates state.json.

Constraints

  • count >= 0 for valid scale calls (count < 0 raises ValueError in scale and exits with code 2 in main).
  • provider.provision(gpu_type, region, token) is idempotent per token on the cloud side and returns without waiting for boot completion.
  • Cloud list_instances results may lag behind recent provision calls, and VMs may be terminated externally outside gpulift.
  • Process termination may occur immediately before or immediately after any network call; re-running the identical command must converge without creating duplicate VMs.

Step-by-step walkthrough

  1. Understand the declarative goal and architecture

    Running gpulift scale --gpu-type H100 --count 4 --region us-west-2 is a declarative command: the user states the desired outcome (4 running H100 VMs), and the tool computes whatever actions are needed to get there — creating 1 more if 3 are running, terminating 2 if 6 are running, or doing nothing at all if 4 are already running. That property — running the exact same command twice produces the exact same end state without extra side effects — is idempotency.

    We split the design cleanly into three layers so adding a new cloud never touches CLI parsing or reconciliation logic:

    +---------------------------------------------------------------+
    | 1. CLI Layer (main)       parses flags, prints status, exits  |
    +---------------------------------------------------------------+
                                    |
                                    v
    +---------------------------------------------------------------+
    | 2. Reconciler (_Reconciler)  Read -> Plan -> Apply <-> state  |
    +---------------------------------------------------------------+
              |                     |                     |
              v                     v                     v
       +-------------+       +-------------+       +-----------------+
       | AWSProvider |       | GCPProvider |       | LambdaProvider  |
       +-------------+       +-------------+       +-----------------+
    

    One core rule governs state: the cloud is the source of truth for what actually exists, while state.json records what we want (desired) and what requests are currently in flight (pending tokens). Trusting state.json alone breaks the moment someone terminates a VM in a cloud web console or the CLI crashes mid-request.

  2. Design the cloud provider interface

    Every cloud adapter subclasses a single Provider abstract base class with four operations:

    • provision(gpu_type, region, token) -> vm_id: starts one VM tagged with token and returns its ID immediately without blocking for boot. Here token is an idempotency key — a unique client-generated string guaranteeing that if we retry a timed-out call with the same token, the provider returns the original VM instead of billing us for a duplicate (for example, AWS EC2's ClientToken).
    • list_instances(gpu_type, region) -> List[Instance]: returns all non-terminated VMs carrying gpulift's tag.
    • get_status(instance_id) -> str: queries a single VM ID directly ("pending", "running", "failed", "terminated", or "not_found").
    • terminate(instance_id) -> None: deletes a VM, treating "already gone" as success.

    We also distinguish two exception classes because the reconciler handles them differently: RateLimitError (transient HTTP 429 throttling — back off and retry) versus ProvisionError (definitive refusal like quota exceeded or out of stock — stop and report).

    from typing import List
    from abc import ABC, abstractmethod
    from dataclasses import dataclass
    
    HEALTHY = ("pending", "running")
    
    
    class RateLimitError(Exception):
        """The provider throttled the call. Nothing was created; retry later with the same token."""
    
    
    class ProvisionError(Exception):
        """The provider definitively refused to create the VM (no capacity, quota, unknown type)."""
    
    
    @dataclass
    class Instance:
        instance_id: str
        status: str  # "pending", "running", "failed" or "terminated"
        token: str   # idempotency token the VM was created with (kept as a tag on the VM)
    
    
    class Provider(ABC):
        """Everything gpulift needs from a cloud. Supporting a new cloud means writing one subclass."""
    
        name = "base"
    
        @abstractmethod
        def provision(self, gpu_type: str, region: str, token: str) -> str:
            """Request one VM tagged with token and return its id without waiting for it to boot."""
    
        @abstractmethod
        def list_instances(self, gpu_type: str, region: str) -> List[Instance]:
            """Every non-terminated VM of this GPU type and region that carries gpulift's tag."""
    
        @abstractmethod
        def get_status(self, instance_id: str) -> str:
            """One of "pending", "running", "failed", "terminated" or "not_found"."""
    
        @abstractmethod
        def terminate(self, instance_id: str) -> None:
            """Delete the VM. Terminating a VM that is already gone is not an error."""
    
  3. Persist state safely with atomic file replacement

    Inside state.json, each (provider, region, gpu_type) fleet stores three fields:

    {
      "fleets": {
        "aws/us-west-2/H100": {
          "desired": 4,
          "instances": {
            "vm-1": "gpulift-3f2a...",
            "vm-2": "gpulift-91bc...",
            "vm-3": "gpulift-08ce..."
          },
          "pending": ["gpulift-77d0..."]
        }
      }
    }
    
    • desired: target VM count, saved before any cloud API call.
    • instances: map of vm_id -> token for VMs we have observed.
    • pending: write-ahead log (WAL) of idempotency tokens written to disk before calling provision(), whose VM IDs we have not recorded yet.

    Never overwrite state.json directly with open(self.path, "w"): if the process dies halfway through writing, state.json is truncated to invalid JSON and lost. Instead, write to state.json.tmp, flush it to disk with os.fsync, and swap it into place with os.replace, which POSIX file systems execute atomically.

    import json
    import os
    
    
    class StateStore:
        """Crash-safe wrapper around local state.json."""
    
        def __init__(self, path: str) -> None:
            self.path = path
    
        def load(self) -> dict:
            if not os.path.exists(self.path):
                return {"fleets": {}}
            with open(self.path, encoding="utf-8") as f:
                return json.load(f)
    
        def save(self, state: dict) -> None:
            # Write to a sibling temp file, flush to disk, then atomically rename over self.path
            # so a crash mid-save never leaves a half-written, unparseable JSON file.
            tmp_path = self.path + ".tmp"
            with open(tmp_path, "w", encoding="utf-8") as f:
                json.dump(state, f, indent=2, sort_keys=True)
                f.flush()
                os.fsync(f.fileno())
            os.replace(tmp_path, self.path)
    
  4. Drive convergence with a Read-Plan-Apply loop

    Each polling round in _Reconciler.run performs three steps:

    1. Read (observe): fetch live VMs from the cloud and terminate any that failed to boot.
    2. Plan: compute delta = count - len(healthy), where healthy includes both "pending" (booting) and "running" VMs. Counting "pending" VMs is critical: GPU VMs take minutes to boot, so if you only counted "running" VMs, Round 2 would think 0 VMs exist and launch duplicate VMs every 10 seconds!
    3. Apply:
      • delta == 0 and booting_count == 0: every VM is up and running — return immediately.
      • delta > 0: create delta new VMs.
      • delta < 0: terminate -delta excess VMs.
      • delta == 0 and booting_count > 0: log progress and wait poll_seconds for boots to finish (or fail).
        def run(self, count: int, max_rounds: int) -> ScaleResult:
            self.result = ScaleResult(desired=count)
            self.fleet["desired"] = count
            # Persist desired count before making any network calls so a crash preserves the goal.
            self.save()
    
            for _ in range(max_rounds):
                # 1. READ actual cloud state (and clean up any VMs that failed to boot).
                healthy = self.observe()
    
                # 2. PLAN difference: count booting ("pending") VMs as healthy so slow boots do not spawn duplicates.
                delta = count - len(healthy)
                booting_count = 0
                for inst in healthy:
                    if inst.status == "pending":
                        booting_count += 1
    
                # Converged: exact count reached and every VM has finished booting into "running".
                if delta == 0 and booting_count == 0:
                    return self.finish(healthy)
    
                # 3. APPLY only the difference (scale up, scale down, or wait for pending boots).
                if delta > 0:
                    self.log(f"[INFO] {len(healthy)} instances found. "
                             f"Provisioning {delta} additional {self.gpu_type}...")
                    if not self.create(delta):
                        break
                elif delta < 0:
                    self.log(f"[INFO] {len(healthy)} instances found. Terminating {-delta}...")
                    self.remove(healthy, -delta)
                else:
                    self.log(f"[INFO] Waiting for VMs to boot ({booting_count} pending)...")
    
                self.sleep(self.poll_seconds)
    
            return self.finish(self.observe())
    
  5. Read actual cloud state and heal failed boots

    observe() reconciles cloud reality with state.json across three real-world edge cases:

    1. Adopting VMs after a crash: list_instances finds all VMs carrying gpulift's tag — even if the previous run crashed right after the cloud created a VM and before its ID was written to state.json.
    2. Defending against listing lag: cloud list_instances endpoints are often eventually consistent, meaning a newly created VM can take a few seconds to appear in search results. Before dropping any vm_id recorded in self.fleet["instances"] that is missing from the listing, we query get_status(vm_id) directly: if it is "pending" or "running", we keep it; only if it is "terminated" or "not_found" (for example, deleted in the web console) do we remove it so a replacement is planned.
    3. Healing partial boot failures: if 1 of 2 new VMs transitions from "pending" to "failed", observe() removes its token from pending first (so we never reuse a dead VM's token), terminates the broken VM so we do not pay for it, and excludes it from healthy so delta automatically provisions a replacement in the very same round.
        def observe(self) -> List[Instance]:
            """Merge cloud listing with saved IDs, terminate failed boots, and return healthy VMs."""
            # Phase 1: Discover all live VMs carrying gpulift's tag in the cloud.
            seen_by_id: Dict[str, Instance] = {}
            for inst in self.provider.list_instances(self.gpu_type, self.region):
                seen_by_id[inst.instance_id] = inst
    
            # Phase 2: Cloud listings can lag right after creation (eventual consistency),
            # so verify any previously saved vm_id directly via get_status before assuming it is gone.
            for vm_id in list(self.fleet["instances"]):
                if vm_id not in seen_by_id:
                    status = self.provider.get_status(vm_id)
                    if status in HEALTHY or status == "failed":
                        seen_by_id[vm_id] = Instance(vm_id, status, self.fleet["instances"][vm_id])
                    else:
                        # Deleted in web console or preempted externally: drop so Plan replaces it.
                        del self.fleet["instances"][vm_id]
    
            # Phase 3: Reconcile in-flight tokens, clean up failed boots, and collect healthy VMs.
            healthy: List[Instance] = []
            for inst in seen_by_id.values():
                # Clear pending token BEFORE checking status: even if this VM failed to boot,
                # its token already materialized a VM and must not be reused for the replacement.
                if inst.token in self.fleet["pending"]:
                    self.fleet["pending"].remove(inst.token)
    
                if inst.status == "failed":
                    self.log(f"[WARN] {inst.instance_id} failed to boot; terminating it")
                    self.provider.terminate(inst.instance_id)
                    self.fleet["instances"].pop(inst.instance_id, None)
                    self.result.terminated.append(inst.instance_id)
                elif inst.status in HEALTHY:
                    # Adopt VMs discovered via cloud tags even if a prior crash missed saving their ID.
                    self.fleet["instances"][inst.instance_id] = inst.token
                    healthy.append(inst)
    
            self.save()
            return healthy
    
  6. Apply changes safely: write-ahead tokens, backoff, and scale-down

    • Write-ahead tokens (create): we take any leftover pending tokens from an interrupted run first, generate UUID tokens for the rest, and save pending to disk before calling provision.
    • Exponential backoff (provision_with_retry): when RateLimitError occurs, we double our wait each retry (1s, 2s, 4s) while passing the exact same token. If throttling persists past max_retries, we leave remaining tokens in pending and stop creating so the user can re-run later. On ProvisionError (out of capacity), no VM was created, so we discard that token and stop after the batch rather than retrying a hard refusal for 30 rounds.
    • Graceful scale-down (remove): when delta < 0, we terminate "pending" VMs before "running" ones so VMs already serving workloads are spared whenever possible.
        def create(self, how_many: int) -> bool:
            """Provision how_many VMs. Return False if persistent throttling or refusal stops creation."""
            # Reuse write-ahead tokens from an interrupted run first so any VM they secretly created
            # is returned idempotently instead of duplicated.
            tokens = self.fleet["pending"][:how_many]
            while len(tokens) < how_many:
                tokens.append("gpulift-" + uuid.uuid4().hex)
    
            # Write-ahead log: save all tokens to disk BEFORE calling provision().
            self.fleet["pending"] = list(tokens)
            self.save()
    
            refused = False
            for token in tokens:
                try:
                    vm_id = self.provision_with_retry(token)
                except RateLimitError:
                    # Keep remaining tokens in pending so re-running continues cleanly.
                    self.result.errors.append(f"{self.provider.name} kept rate-limiting; re-run to continue")
                    return False
                except ProvisionError as exc:
                    # Definitive refusal created no VM, so discard this token.
                    self.fleet["pending"].remove(token)
                    self.result.errors.append(f"provisioning failed: {exc}")
                    refused = True
                else:
                    self.fleet["pending"].remove(token)
                    self.fleet["instances"][vm_id] = token
                    self.result.created.append(vm_id)
                self.save()
    
            return not refused
    
        def provision_with_retry(self, token: str) -> str:
            """Call provision(token) with exponential backoff (1s, 2s, 4s, ...) on RateLimitError."""
            delay = 1.0
            for _ in range(self.max_retries):
                try:
                    return self.provider.provision(self.gpu_type, self.region, token)
                except RateLimitError:
                    self.log(f"[WARN] Rate limited by {self.provider.name}; retrying in {delay:g}s")
                    self.sleep(delay)
                    delay *= 2
            # Final attempt after exhausting backoff sleeps; let RateLimitError propagate if still throttled.
            return self.provider.provision(self.gpu_type, self.region, token)
    
        def remove(self, healthy: List[Instance], how_many: int) -> None:
            """Scale down by terminating still-booting VMs first before touching running VMs."""
            victims: List[Instance] = []
            for inst in healthy:
                if inst.status == "pending":
                    victims.append(inst)
            for inst in healthy:
                if inst.status == "running":
                    victims.append(inst)
    
            for inst in victims[:how_many]:
                self.provider.terminate(inst.instance_id)
                self.fleet["instances"].pop(inst.instance_id, None)
                self.result.terminated.append(inst.instance_id)
                self.save()
    
  7. Trace a mid-provisioning crash and recovery

    Watch what happens when gpulift scale --gpu-type H100 --count 3 --region us-west-2 is killed right after the cloud creates vm-2, before provision(t2) returns to Python:

    Event                                   state.json on disk                          Cloud VMs
    ---------------------------------------------------------------------------------------------------
    1. Save desired=3                       desired=3, instances={}, pending=[]         (none)
    2. Write-ahead tokens                   pending=[t1, t2, t3]                        (none)
    3. provision(t1) -> vm-1, save          instances={vm-1:t1}, pending=[t2, t3]       vm-1
    4. provision(t2) creates vm-2 -> CRASH  instances={vm-1:t1}, pending=[t2, t3]       vm-1, vm-2
    
    --- User re-runs: gpulift scale --gpu-type H100 --count 3 --region us-west-2 ---
    
    Case A (listing is up to date):
    5a. observe() lists vm-1, vm-2(tag t2)  instances={vm-1:t1, vm-2:t2}, pending=[t3]  vm-1, vm-2
    6a. delta = 3 - 2 = 1 -> provision(t3)  instances={vm-1, vm-2, vm-3}, pending=[]    vm-1, vm-2, vm-3
    
    Case B (listing lags and hides vm-2):
    5b. observe() sees only vm-1            instances={vm-1:t1}, pending=[t2, t3]       vm-1, vm-2
    6b. delta = 3 - 1 = 2 -> reuse [t2, t3]
        provision(t2) returns existing vm-2!
        provision(t3) creates vm-3          instances={vm-1, vm-2, vm-3}, pending=[]    vm-1, vm-2, vm-3
    

    In both cases, the fleet converges to exactly 3 VMs with zero duplicates.

  8. Wire up the CLI and complete solution

    Finally, main parses CLI flags with argparse, validates --count >= 0 and --provider (exiting with code 2 on invalid flags), runs scale, and returns exit code 0 on full convergence or 1 on partial completion so shell scripts and CI pipelines can branch on the exit status.

    from typing import Callable, Dict, List
    from abc import ABC, abstractmethod
    from dataclasses import dataclass, field
    import argparse
    import json
    import os
    import time
    import uuid
    
    # Both booting ("pending") and booted ("running") VMs count toward fleet size so we do not over-provision.
    HEALTHY = ("pending", "running")
    
    
    class RateLimitError(Exception):
        """The provider throttled the call. Nothing was created; retry later with the same token."""
    
    
    class ProvisionError(Exception):
        """The provider definitively refused to create the VM (no capacity, quota, unknown type)."""
    
    
    @dataclass
    class Instance:
        instance_id: str
        status: str  # "pending", "running", "failed" or "terminated"
        token: str   # idempotency token the VM was created with (kept as a tag on the VM)
    
    
    class Provider(ABC):
        """Everything gpulift needs from a cloud. Supporting a new cloud means writing one subclass."""
    
        name = "base"
    
        @abstractmethod
        def provision(self, gpu_type: str, region: str, token: str) -> str:
            """Request one VM tagged with token and return its id without waiting for it to boot.
    
            Idempotent per token: if a VM was already created with this token, return its id
            instead of creating another. Raises RateLimitError or ProvisionError.
            """
    
        @abstractmethod
        def list_instances(self, gpu_type: str, region: str) -> List[Instance]:
            """Every non-terminated VM of this GPU type and region that carries gpulift's tag."""
    
        @abstractmethod
        def get_status(self, instance_id: str) -> str:
            """One of "pending", "running", "failed", "terminated" or "not_found"."""
    
        @abstractmethod
        def terminate(self, instance_id: str) -> None:
            """Delete the VM. Terminating a VM that is already gone is not an error."""
    
    
    class StateStore:
        """Crash-safe wrapper around local state.json."""
    
        def __init__(self, path: str) -> None:
            self.path = path
    
        def load(self) -> dict:
            if not os.path.exists(self.path):
                return {"fleets": {}}
            with open(self.path, encoding="utf-8") as f:
                return json.load(f)
    
        def save(self, state: dict) -> None:
            # Write to a sibling temp file, flush to disk, then atomically rename over self.path
            # so a crash mid-save never leaves a half-written, unparseable JSON file.
            tmp_path = self.path + ".tmp"
            with open(tmp_path, "w", encoding="utf-8") as f:
                json.dump(state, f, indent=2, sort_keys=True)
                f.flush()
                os.fsync(f.fileno())
            os.replace(tmp_path, self.path)
    
    
    @dataclass
    class ScaleResult:
        desired: int
        running: List[str] = field(default_factory=list)   # ids running at the end
        booting: List[str] = field(default_factory=list)   # ids still pending at the end
        created: List[str] = field(default_factory=list)
        terminated: List[str] = field(default_factory=list)
        errors: List[str] = field(default_factory=list)
    
        @property
        def ok(self) -> bool:
            return len(self.running) == self.desired and not self.booting
    
    
    class _Reconciler:
        """Executes the Read-Plan-Apply loop for a single (provider, region, gpu_type) fleet."""
    
        def __init__(self, provider: Provider, store: StateStore, gpu_type: str, region: str,
                     max_retries: int, poll_seconds: float,
                     sleep: Callable[[float], None], log: Callable[[str], None]) -> None:
            self.provider = provider
            self.store = store
            self.gpu_type = gpu_type
            self.region = region
            self.max_retries = max_retries
            self.poll_seconds = poll_seconds
            self.sleep = sleep
            self.log = log
    
            self.state = store.load()
            fleet_key = f"{provider.name}/{region}/{gpu_type}"
            if fleet_key not in self.state["fleets"]:
                self.state["fleets"][fleet_key] = {"desired": 0, "instances": {}, "pending": []}
    
            # Fleet state mini-shape:
            #   "desired":   int target count (e.g. 4)
            #   "instances": Dict[vm_id, token] for known VMs (e.g. {"vm-1": "gpulift-a1b2..."})
            #   "pending":   List[token] written ahead of provision() calls whose vm_id is not yet saved
            self.fleet = self.state["fleets"][fleet_key]
            self.result = ScaleResult(desired=0)
    
        def save(self) -> None:
            self.store.save(self.state)
    
        def run(self, count: int, max_rounds: int) -> ScaleResult:
            self.result = ScaleResult(desired=count)
            self.fleet["desired"] = count
            # Persist desired count before making any network calls so a crash preserves the goal.
            self.save()
    
            for _ in range(max_rounds):
                # 1. READ actual cloud state (and clean up any VMs that failed to boot).
                healthy = self.observe()
    
                # 2. PLAN difference: count booting ("pending") VMs as healthy so slow boots do not spawn duplicates.
                delta = count - len(healthy)
                booting_count = 0
                for inst in healthy:
                    if inst.status == "pending":
                        booting_count += 1
    
                # Converged: exact count reached and every VM has finished booting into "running".
                if delta == 0 and booting_count == 0:
                    return self.finish(healthy)
    
                # 3. APPLY only the difference (scale up, scale down, or wait for pending boots).
                if delta > 0:
                    self.log(f"[INFO] {len(healthy)} instances found. "
                             f"Provisioning {delta} additional {self.gpu_type}...")
                    if not self.create(delta):
                        break
                elif delta < 0:
                    self.log(f"[INFO] {len(healthy)} instances found. Terminating {-delta}...")
                    self.remove(healthy, -delta)
                else:
                    self.log(f"[INFO] Waiting for VMs to boot ({booting_count} pending)...")
    
                self.sleep(self.poll_seconds)
    
            return self.finish(self.observe())
    
        def observe(self) -> List[Instance]:
            """Merge cloud listing with saved IDs, terminate failed boots, and return healthy VMs."""
            # Phase 1: Discover all live VMs carrying gpulift's tag in the cloud.
            seen_by_id: Dict[str, Instance] = {}
            for inst in self.provider.list_instances(self.gpu_type, self.region):
                seen_by_id[inst.instance_id] = inst
    
            # Phase 2: Cloud listings can lag right after creation (eventual consistency),
            # so verify any previously saved vm_id directly via get_status before assuming it is gone.
            for vm_id in list(self.fleet["instances"]):
                if vm_id not in seen_by_id:
                    status = self.provider.get_status(vm_id)
                    if status in HEALTHY or status == "failed":
                        seen_by_id[vm_id] = Instance(vm_id, status, self.fleet["instances"][vm_id])
                    else:
                        # Deleted in web console or preempted externally: drop so Plan replaces it.
                        del self.fleet["instances"][vm_id]
    
            # Phase 3: Reconcile in-flight tokens, clean up failed boots, and collect healthy VMs.
            healthy: List[Instance] = []
            for inst in seen_by_id.values():
                # Clear pending token BEFORE checking status: even if this VM failed to boot,
                # its token already materialized a VM and must not be reused for the replacement.
                if inst.token in self.fleet["pending"]:
                    self.fleet["pending"].remove(inst.token)
    
                if inst.status == "failed":
                    self.log(f"[WARN] {inst.instance_id} failed to boot; terminating it")
                    self.provider.terminate(inst.instance_id)
                    self.fleet["instances"].pop(inst.instance_id, None)
                    self.result.terminated.append(inst.instance_id)
                elif inst.status in HEALTHY:
                    # Adopt VMs discovered via cloud tags even if a prior crash missed saving their ID.
                    self.fleet["instances"][inst.instance_id] = inst.token
                    healthy.append(inst)
    
            self.save()
            return healthy
    
        def create(self, how_many: int) -> bool:
            """Provision how_many VMs. Return False if persistent throttling or refusal stops creation."""
            # Reuse write-ahead tokens from an interrupted run first so any VM they secretly created
            # is returned idempotently instead of duplicated.
            tokens = self.fleet["pending"][:how_many]
            while len(tokens) < how_many:
                tokens.append("gpulift-" + uuid.uuid4().hex)
    
            # Write-ahead log: save all tokens to disk BEFORE calling provision().
            self.fleet["pending"] = list(tokens)
            self.save()
    
            refused = False
            for token in tokens:
                try:
                    vm_id = self.provision_with_retry(token)
                except RateLimitError:
                    # Keep remaining tokens in pending so re-running continues cleanly.
                    self.result.errors.append(f"{self.provider.name} kept rate-limiting; re-run to continue")
                    return False
                except ProvisionError as exc:
                    # Definitive refusal created no VM, so discard this token.
                    self.fleet["pending"].remove(token)
                    self.result.errors.append(f"provisioning failed: {exc}")
                    refused = True
                else:
                    self.fleet["pending"].remove(token)
                    self.fleet["instances"][vm_id] = token
                    self.result.created.append(vm_id)
                self.save()
    
            return not refused
    
        def provision_with_retry(self, token: str) -> str:
            """Call provision(token) with exponential backoff (1s, 2s, 4s, ...) on RateLimitError."""
            delay = 1.0
            for _ in range(self.max_retries):
                try:
                    return self.provider.provision(self.gpu_type, self.region, token)
                except RateLimitError:
                    self.log(f"[WARN] Rate limited by {self.provider.name}; retrying in {delay:g}s")
                    self.sleep(delay)
                    delay *= 2
            # Final attempt after exhausting backoff sleeps; let RateLimitError propagate if still throttled.
            return self.provider.provision(self.gpu_type, self.region, token)
    
        def remove(self, healthy: List[Instance], how_many: int) -> None:
            """Scale down by terminating still-booting VMs first before touching running VMs."""
            victims: List[Instance] = []
            for inst in healthy:
                if inst.status == "pending":
                    victims.append(inst)
            for inst in healthy:
                if inst.status == "running":
                    victims.append(inst)
    
            for inst in victims[:how_many]:
                self.provider.terminate(inst.instance_id)
                self.fleet["instances"].pop(inst.instance_id, None)
                self.result.terminated.append(inst.instance_id)
                self.save()
    
        def finish(self, healthy: List[Instance]) -> ScaleResult:
            if len(healthy) >= self.result.desired:
                self.fleet["pending"] = []
            self.save()
            for inst in healthy:
                if inst.status == "running":
                    self.result.running.append(inst.instance_id)
                else:
                    self.result.booting.append(inst.instance_id)
            return self.result
    
    
    def scale(provider: Provider, store: StateStore, gpu_type: str, region: str, count: int,
              max_rounds: int = 30, max_retries: int = 3, poll_seconds: float = 10.0,
              sleep: Callable[[float], None] = time.sleep,
              log: Callable[[str], None] = print) -> ScaleResult:
        """Make the fleet (provider, region, gpu_type) have exactly count running VMs."""
        if count < 0:
            raise ValueError("count must be >= 0")
        reconciler = _Reconciler(provider, store, gpu_type, region, max_retries, poll_seconds, sleep, log)
        return reconciler.run(count, max_rounds)
    
    
    def main(argv: List[str], providers: Dict[str, Provider], store: StateStore,
             sleep: Callable[[float], None] = time.sleep) -> int:
        """gpulift scale --gpu-type A100 --count 5 [--region us-east-1] [--provider aws]."""
        parser = argparse.ArgumentParser(prog="gpulift")
        commands = parser.add_subparsers(dest="command", required=True)
        scale_cmd = commands.add_parser("scale", help="make the fleet have exactly --count VMs")
        scale_cmd.add_argument("--gpu-type", required=True)
        scale_cmd.add_argument("--count", type=int, required=True)
        scale_cmd.add_argument("--region", default="us-east-1")
        scale_cmd.add_argument("--provider", default="aws")
    
        args = parser.parse_args(argv)
        if args.count < 0:
            parser.error("--count must be >= 0")
        if args.provider not in providers:
            known = ", ".join(sorted(providers))
            parser.error(f"unknown provider {args.provider}; known: {known}")
    
        result = scale(providers[args.provider], store, args.gpu_type, args.region, args.count, sleep=sleep)
        for error in result.errors:
            print(f"[ERROR] {error}")
        if result.ok:
            print(f"[SUCCESS] {len(result.running)} instances running (ID: {', '.join(result.running)})")
            return 0
        print(f"[PARTIAL] {len(result.running)} of {result.desired} instances running, "
              f"{len(result.booting)} booting; re-run the same command to continue")
        return 1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of gpulift scale --gpu-type H100 --count 4 --region us-west-2 like setting a room thermostat to 72°F rather than pressing a "heat +2 degrees" button. Instead of blindly launching 4 VMs every time it runs, the tool executes a reconciliation loop (repeatedly reading actual cloud state, comparing it against the desired target, and applying only the difference) backed by write-ahead logging (WAL) (saving unique request tokens to disk before calling the network) and idempotency keys (client-chosen tokens that guarantee retrying a request returns the original VM instead of creating a duplicate).

Why does a naive script that simply reads state.json, computes 4 - saved_count, and calls provision() fail in production? First, if an engineer deletes a VM in the cloud console, state.json becomes stale and under-provisions. Second, if the CLI crashes after the cloud creates a VM but before the HTTP response returns, re-running without saved idempotency tokens creates expensive duplicate GPU VMs. Third, if 1 of 2 new VMs fails during boot or hits HTTP 429 throttling, a one-shot script exits without cleaning up the dead VM or replacing it.

Walk through Example 2 — scaling an empty L4 fleet in eu-central-1 to count = 2 when vm-2 fails to boot: 1. Round 1: observe() sees 0 VMs (delta = 2). create(2) writes tokens [t1, t2] to state.json via atomic temp-file rename, then calls provision(t1) -> vm-1 and provision(t2) -> vm-2 (both start "pending"). 2. Round 2: observe() sees 2 "pending" VMs (delta = 2 - 2 = 0, booting = 2), so the loop waits instead of launching duplicates. 3. Round 3: vm-1 becomes "running", while vm-2 becomes "failed". observe() terminates vm-2, clears t2, and returns [vm-1]. Now delta = 2 - 1 = 1, so create(1) writes a fresh token [t3] and launches vm-3. 4. Round 4: once vm-3 reaches "running", delta == 0 and booting == 0, so scale returns ok = True (["vm-1", "vm-3"]).

Complexity

  • Cloud API calls per round: 1 list_instances call, at most n get_status calls for previously known VM IDs missing from a lagging listing (typically 0), and |delta| provision or terminate calls (with up to max_retries extra attempts per throttled provision). Network round-trips and VM boot latency dominate wall-clock time.
  • Local CPU work per round — O(n + |delta|): for a fleet of n tracked VMs and difference delta, we build a dictionary from the listing, scan known IDs, and iterate over delta creations or removals.
  • Disk I/O — O(n) bytes per state transition: rewriting state.json via temp-file + fsync + os.replace writes a few kilobytes for fleets of hundreds of VMs, trading negligible local disk time for crash safety after every step.
  • Memory — O(n + |delta|): holds only the JSON state dictionary, the current round's Instance objects, and the ScaleResult lists.

Edge cases

  • No-op re-run (--count 4 when 4 are already running): Round 1 observes 4 "running" VMs (delta = 0, booting = 0) and exits 0 with zero provision or terminate calls.
  • Scale to zero (--count 0): terminates every VM in the fleet; negative counts (--count -1) exit with code 2.
  • Slow-booting VMs: "pending" VMs count toward len(healthy) so subsequent rounds wait patiently instead of over-provisioning.
  • Partial boot failure (1 of 2 VMs enters "failed"): observe() terminates the failed VM, drops its old token so the replacement gets a fresh token, and triggers a replacement in the same round.
  • Eventual consistency (listing lag) vs. external deletion: known IDs absent from list_instances are verified with get_status(vm_id) — kept if "pending"/"running", dropped and replaced if "terminated"/"not_found".
  • Crash before or after cloud VM creation: write-ahead pending tokens plus cloud tag adoption prevent orphan or duplicate VMs on recovery.
  • Transient vs. persistent rate limits (RateLimitError): retried with exponential backoff (1s, 2s, 4s, doubling wait times between retries); if throttling persists, remaining tokens stay in pending and the CLI exits 1 so re-running resumes seamlessly.
  • Hard capacity refusal (ProvisionError): removes the unused token and stops after the current batch without spinning through 30 futile polling rounds.

Common mistakes

  • Computing delta from state.json alone instead of querying the cloud: drifts immediately when VMs are terminated externally or created right before a local crash.
  • Counting only "running" VMs in delta: launches a fresh batch of VMs on every 10-second poll while the first batch is still booting.
  • Saving VM IDs only after provision() returns, without write-ahead tokens: any crash or network timeout during provision() causes a duplicate VM on the next run.
  • Generating a brand-new token on each retry of a throttled/timed-out request: defeats idempotency if the earlier call actually succeeded server-side.
  • Retrying ProvisionError ("quota exceeded") in a loop, or aborting on the first RateLimitError: conflates permanent refusals with transient throttling.
  • Overwriting state.json in place (open("state.json", "w")): a crash mid-write leaves a truncated, corrupt file that breaks every future run.
  • Leaving "failed" VMs un-terminated: broken cloud instances can still hold billable disks, IPs, or quota slots.

Alternative approaches

  • Daemon / Kubernetes-style controller loop: run the exact same _Reconciler continuously in a background service rather than only when a human invokes the CLI, enabling automatic self-healing when VMs crash at 3 a.m.
  • Two-phase plan + apply CLI (Terraform style): add --dry-run or confirmation prompts before executing destructive scale-downs (delta < 0) so a typo (--count 1 instead of --count 10) does not kill active training jobs.
  • Bulk provisioning APIs: clouds like AWS (RunInstances(MinCount, MaxCount)) can launch multiple VMs per HTTP call, cutting rate-limit pressure at the cost of trickier per-VM idempotency tracking on partial failures.

Follow-up questions

  • What changes would let the reconciler manage interruptible spot VMs and recover automatically when instances are reclaimed? Extend Provider.provision with a capacity_type parameter ("spot" or "on_demand") stored on each VM's tags and state entry. Because a preempted spot VM transitions to "terminated", our existing observe() loop already detects the drop and provisions a replacement — the key architectural shift is running _Reconciler continuously as a lightweight daemon (or scheduled job) rather than waiting for manual CLI runs. In addition, poll the cloud's spot-interruption metadata endpoint inside each VM (2-minute warning on AWS, 30-second on GCP) to trigger training checkpoint saves, diversify across multiple availability zones, and automatically fall back to "on_demand" after N consecutive spot ProvisionErrors.

  • How would you coordinate state and prevent over-provisioning when several engineers run scaling commands concurrently? Without coordination, two engineers running scale --count 4 when 3 VMs exist will both observe 3, compute delta = 1, and create 2 VMs total (5 running). On a single shared bastion host, wrap scale() in an exclusive OS file lock (fcntl.flock on state.json.lock). Across developer laptops, move state.json to shared remote storage with distributed lease locking — for example, storing state in S3/GCS using conditional writes (If-Match ETag / generation number) alongside a lock record in DynamoDB or Postgres containing (owner, acquired_at, expires_at_ttl) so a crashed laptop's lock automatically expires after a short lease window while printing "Locked by alice@..." to waiting teammates.

  • How would you detect and replace 'zombie' GPU nodes that the cloud reports as running even though SSH or the GPU driver has hung? Cloud "running" status only proves the hypervisor booted, not that SSH is reachable or the GPUs haven't hung with an NVIDIA Xid hardware error. Add a check_health(instance_id) probe after observe() (either polling a lightweight agent heartbeat endpoint on the VM or running an SSH check that verifies nvidia-smi sees all expected GPUs within a short timeout). To prevent false-positive thrashing, apply a boot grace period (for example 5 minutes after transitioning to "running") and require 3 consecutive failed probes (~90 seconds) before marking a VM unhealthy and routing it through observe()'s existing "failed" terminate-and-replace path, capped by a circuit breaker (such as replacing at most 20% of the fleet per hour) so a broken network firewall cannot wipe out the entire cluster.

Follow-up questions

Similar questions

More Heygen interview questions

All 1 Heygen questions →