Design a Multi-Cloud GPU Fleet Manager CLI
System DesignModel answerLast updated
Design the architecture and reconciliation logic for a CLI tool that provisions and manages GPU VMs across heterogeneous cloud providers.
Scenario
Your team operates GPU workloads across several cloud providers. Each provider has its own API, its own quirks, and its own way of reporting instance state. Engineers are spending too much time writing one-off scripts and reconciling drift between what they asked for and what's actually running.
You've been asked to design a command-line tool called cloudgpu that gives users a single, consistent interface to manage GPU VM fleets regardless of the underlying provider.
The core command to support is:
cloudgpu fleet --gpu A100 --count 5 --region us-east-1
What You Need to Design
1. Provider interface
Define a minimal abstraction so that new cloud providers can be added without touching the CLI or core reconciliation logic. What operations does every provider need to expose? How do you register providers and dispatch to the right one?
2. Desired-state reconciliation
The fleet command is declarative: --count 5 means "I want 5 running instances," not "give me 5 more." Describe the read-plan-apply loop that bridges desired state and actual state. Your design must handle:
- Running the same command twice without creating duplicates.
- Recovering cleanly if the process crashes mid-provisioning.
3. State persistence
You have a local state.json available for persistence. Explain what you store there, how you keep it consistent, and what happens if it becomes stale or corrupt.
Expected CLI Behavior
# First invocation — nothing running yet
$ cloudgpu fleet --gpu A100 --count 2
[INFO] Pool us-east-1/A100 — desired: 2, actual: 0 → provisioning 2
[OK] 2 instances running (vm-a1b2, vm-c3d4)
# Scaling up — 2 already healthy
$ cloudgpu fleet --gpu A100 --count 3
[INFO] Pool us-east-1/A100 — desired: 3, actual: 2 → provisioning 1
[OK] 3 instances running (vm-a1b2, vm-c3d4, vm-e5f6)
# Idempotent re-run — nothing to do
$ cloudgpu fleet --gpu A100 --count 3
[INFO] Pool us-east-1/A100 — desired: 3, actual: 3 → no change
[OK] 3 instances running
Edge Cases to Address
- A provider returns a rate-limit error during provisioning. How does your tool respond?
- One out of two requested VMs fails to boot. What does your tool do with the healthy one, the failed one, and the reported exit state?
Hints
Hint 1
Think about where the authoritative view of running instances lives. If state.json gets corrupted or deleted, can your tool still recover? What makes that possible?
Hint 2
Idempotency under crashes is the hard part. Before you call a provider API, what do you need to write to disk — and what property must the provider support — so that a crash between 'API called' and 'result recorded' doesn't leave a phantom VM?
Hint 3
For edge cases, separate the concerns: rate limits are a retry problem, partial boot failures are a convergence problem. You don't need to roll back healthy instances — running the command again should be enough to reach the desired state.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Mental Model: Cloud as Source of Truth
The single most important design decision is where actual state lives. It lives in the cloud, not in state.json. The local file is a write-ahead log and a cache — not an authoritative record. This distinction determines how you handle crashes, stale files, and out-of-band deletions.
1. Provider Abstraction
Define a four-method abstract base class. Every concrete provider implements exactly this contract:
class Provider(ABC):
@abstractmethod
def provision(self, gpu_type: str, region: str, token: str, tags: dict) -> str:
"""Create one VM. Must be idempotent on `token`. Returns instance ID."""
@abstractmethod
def terminate(self, instance_id: str) -> None: ...
@abstractmethod
def get_status(self, instance_id: str) -> str: ... # "pending"|"running"|"failed"
@abstractmethod
def list_instances(self, tags: dict) -> list[Instance]: ...
Register providers with a decorator so the CLI stays unchanged when you add a new one:
PROVIDERS: dict[str, type[Provider]] = {}
def register(name: str):
def deco(cls):
PROVIDERS[name] = cls
return cls
return deco
@register("aws")
class AWSProvider(Provider): ...
Each provider translates its native errors into shared exceptions (RateLimitError, ProvisionError). The reconciler never sees AWS-specific exceptions — it handles the same two error types regardless of provider.
The token parameter is the key to idempotency. Pass a stable, deterministic (or pre-generated and persisted) token; the provider uses it to deduplicate calls. AWS EC2 calls this ClientToken. For providers without native support, check by tag or name before provisioning.
2. Desired vs. Actual State
Desired state is what the user requested: count for a given (provider, region, gpu_type) pool. Persist it in state.json before touching any cloud API.
Actual state is discovered at runtime via list_instances filtered by a pool tag (cloudgpu-pool=aws/us-east-1/A100). Tagging is what enables recovery after a complete loss of state.json — every VM you own is discoverable.
3. Read-Plan-Apply Loop
READ → list_instances(tags) # ask the cloud what exists
PLAN → delta = desired - len(actual)
APPLY → provision delta VMs, or terminate -delta VMs
This is the same model used by Terraform and Kubernetes controllers. Each invocation is a pure function of desired - actual, so running it twice with the same --count is always safe.
Crash Safety via Write-Ahead Tokens
The dangerous window is: "API call succeeded, but process crashed before recording the result." Handle it like this:
- Generate a UUID token.
- Write the token to
state.jsonunderpendingand atomically flush to disk (write to a temp file, thenos.replace). - Call
provision(token=...). - On success, move the token from
pendingtoinstancesand save again.
On the next run, pending tokens are cross-referenced against list_instances. If the VM exists (the API call got through), record it and clear the token. If it doesn't exist, retry with the same token — the provider deduplicates. Either path produces no phantom VMs.
4. State File Concerns
- Atomic writes: always write to a temp file in the same directory, then rename. A crash mid-write leaves either the old or new file, never a partial one.
- Stale entries: on every run, prune
state.jsonto match what the cloud reports. The file is a cache; the cloud wins on conflict. - Corrupt or missing file: the tool can reconstruct running state entirely from
list_instancesusing tags. Desired state is lost, but that's a recoverable UX issue (user re-runs the command), not a data-integrity issue.
5. Edge Cases
Rate limit exceeded
Wrap every provider call in exponential backoff with jitter — e.g., sleep = base * 2^attempt + rand(0, base), capped at 5–6 attempts. If retries are exhausted, leave pending tokens in state.json, report partial progress with a non-zero exit code, and exit. The next invocation picks up exactly where provisioning stalled.
Partial boot failure (1 of 2 VMs fails)
- Terminate the failed VM immediately (no point paying for it).
- Keep the healthy VM running — do not roll it back.
- Report
1/2 provisionedand exit non-zero. - Re-running
fleet --count 2will computedelta = 1and provision only the missing instance.
Converging forward is cheaper and more predictable than rolling back. Rollback makes sense only if the pool requires an all-or-nothing guarantee (e.g., a tightly coupled MPI job), and even then it's a higher-level policy on top of this loop, not a change to the reconciler itself.
Scale-down
delta is negative. Terminate the excess instances, newest first (they've done the least useful work). With --count 0, tear down the entire pool.
Out-of-band deletions
If a user terminates an instance through the cloud console, it disappears from list_instances. On the next run, actual count drops, delta becomes positive, and the reconciler replaces it. No manual intervention needed.
Complexity
- API calls: O(N + |Δ| · R), where N is pool size (one paginated list call), |Δ| is the number of VMs to provision or terminate, and R is bounded retries per call.
- Wall-clock time: dominated by VM boot polling. In production, provision concurrently (e.g.,
ThreadPoolExecutor) to keep this at O(boot_time) rather than O(|Δ| · boot_time). - Space: O(N) in memory and on disk.
Common Mistakes
- Trusting only the local file. If
state.jsonis the source of truth, any crash or manual change causes over-provisioning or silent drift. Always verify against the cloud. - No idempotency token before the API call. Writing the token after a successful call means a crash in that window creates a VM you can't find and will try to provision again.
- Rolling back partial successes. This is operationally risky and usually wrong. Converge forward; the reconciler handles it naturally.
- Non-atomic file writes. A
json.dumpdirectly to the target file is not atomic. A crash mid-write produces a file thatjson.loadwill reject on the next run.