Designing a Prepaid Credit Meter for Shared GPU Clusters
System DesignModel answerLast updated
Design a multi-tenant system that reserves, meters, and settles GPU credits across many nodes, with hierarchical budgets, idempotent APIs, and scheduler integration.
You are asked to design the credit accounting layer for a shared GPU platform. Organizations receive credit allowances (say, a monthly allotment), and their users launch jobs that run across a fleet of GPU nodes. Credits must be deducted as compute is actually used.
Cover the following in your design:
- Real-time tracking of per-job GPU consumption across many nodes, with credits deducted as work happens.
- APIs for granting credits, moving credits down a scope tree (org → project → user), adding purchased credits, reading balances, and charging for jobs.
- Enforcement of budgets, per-user and per-project quotas, and rate limits under high concurrency, with no double-spend and only tightly bounded overspend.
- Integration with the job scheduler / admission controller so workloads are admitted, throttled, or rejected based on credits and limits.
- Both prepaid (hard stop) and postpaid (credit line, invoiced later) billing.
- Fair usage when GPUs are scarce — who gets to run first across users and orgs.
- Idempotency, consistency model, data model, failure recovery, partitioning/caching, audit logging, reporting, and observability/alerting.
Expect to be pushed on numbers (fleet size, event rates), the consistency guarantees you actually need, and what happens during partial failures.
Hints
Hint 1
The request rate here is small — say so early — and frame the difficulty as correctness under concurrency, not throughput.
Hint 2
Model spending as an authorization-then-capture flow: reserve credits before the job runs, meter while it runs, settle at the end.
Hint 3
Shard by organization so a single hold can check user, project, and org limits in one ACID transaction instead of a distributed one.
Hint 4
Overspend is bounded by lease length × running GPUs × price — tighten leases as balances shrink to shrink the bound.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The first thing to establish is that this is a metering-plus-ledger problem bolted onto a scheduler. The write rate is modest; the correctness bar is high. State that up front, then pin down assumptions.
Ask about: fleet size, number of tenants, job concurrency and duration, and — most importantly — how much overspend is tolerable. Suggested assumptions to propose and confirm:
- ~100k GPUs on ~12k nodes, a few SKUs with different prices.
- ~10k orgs, ~100k projects, ~1M users, in an org → project → user tree.
- ~1M jobs/day, ~50k concurrent, durations from seconds to weeks.
- Overspend tolerance: at most about one minute worth of a tenant's currently running GPUs. That number drives lease length later.
Rough load: nodes report every ~10s, giving ~1.2k usage events/s; lease renewals per job about once a minute, ~1k/s; a few hundred submissions/s. This is a few thousand writes per second — trivially handled. The challenge is consistency, hot tenants, and clean recovery.
Store credits as integer micro-credits, never floats. Price is credits-per-GPU-second times a SKU multiplier, snapshotted onto the job at admission so later price changes don't rewrite history.
The core pattern: authorize → meter → capture
This is the card-network flow applied to compute.
- Authorize (hold): before a job starts, reserve credits for a bounded lease (e.g. 10 minutes × GPUs × price) by writing hold entries. The scheduler gets an allow/deny.
- Meter: node agents report actual usage continuously; the meter service aggregates per job.
- Capture/renew: each renewal converts consumed usage into captured entries and extends the lease, re-checking limits.
- Settle: at completion, capture the final usage and release any unused reservation.
API surface
Every mutating call carries an idempotency_key.
POST /grants {scope_id, amount, expires_at, source}
POST /topups {org_id, amount, payment_ref}
POST /transfers {from_scope, to_scope, amount}
GET /balances/{scope_id} -> {granted, allocated, held, spent, available, limit}
POST /holds {job_id, scope_path, gpus, sku, duration_s} -> {hold_id, expires_at} | DENIED(reason)
POST /holds/{id}/renew {usage_since_last} -> extended | DENIED
POST /holds/{id}/settle {final_usage}
POST /usage {job_id, node_id, seq, gpu_seconds, window}
Data model
- accounts: scope id, parent id, type, billing model, credit limit, GPU quota, version counter.
- ledger_entries: append-only double-entry rows (txn id, account, signed amount, kind = grant/transfer/hold/capture/release/expire, job id, timestamp). Each transaction sums to zero. This is the source of truth.
- balances: materialized view of the ledger with available/held/spent and a version, updated in the same transaction as the ledger insert.
- holds: hold id, job id, account path, amount, consumed, expiry, state.
- usage_records: keyed by (job_id, node_id, seq) so duplicate reports dedupe for free.
- idempotency: key → request hash and response, with TTL.
Partitioning: shard everything by org. Since a hold must check the whole tree together, co-locating org, projects, and users on one shard turns that into a single-shard ACID transaction — no distributed commit needed. Use sharded Postgres, CockroachDB, or Spanner.
Architecture
Clients -> API Gateway (auth, rate limit) -> Job Service -> Scheduler / Admission Controller
| hold / renew / settle
Node Agents --usage--> Kafka --> Metering Service -------> Credit Service (ledger, shard by org)
| outbox / CDC
Kafka -> Billing, OLAP Reporting, Alerts
Admission: the scheduler picks a placement, calls hold for a lease, and the credit service checks in one transaction that every scope on the path has enough available balance (or room within the credit line for postpaid), plus concurrent-GPU quota and rate limits. On deny it returns a reason; the scheduler queue, throttles, or rejects.
Running: node agents sample per-GPU allocation from cgroups/DCGM and emit usage with a monotonic sequence number. The meter aggregates and drives renewals. If a renewal is denied for exhausted credits, the scheduler signals the job to checkpoint and preempts after a grace period.
Completion: settle captures the final usage and frees the remainder.
Deep dives
No double-spend, bounded overspend. Spending only happens against holds; holds are created under row locks or optimistic version CAS on the balance rows. The worst-case overspend is lease length × running GPUs × price — so shrink the lease when a tenant nears zero (10 min → 1 min below ~5% remaining). Idempotency keys make retries safe; (job_id, node_id, seq) makes usage replay harmless.
Hot tenants. One huge org can fire thousands of jobs per second at a single balance row. Split its balance into N sub-buckets (per region or scheduler cell); holds draw locally and a rebalancer moves credit between slices. You strand a little capacity in exchange for linear scaling.
Consistency. Serializable per-org for holds, balances, and transfers. Eventually consistent for dashboards and invoices, fed through a transactional outbox to Kafka. Balance reads may come from a cache with a staleness label — but admission decisions never read the cache.
Prepaid vs postpaid. Same ledger, different policy. Prepaid: available minus holds ≥ 0; grants expire and are consumed earliest-expiry-first. Postpaid: the balance may go negative up to a credit limit, and a month-end job invoices the captured entries; credit limits get adjusted by risk checks.
Fairness under scarcity. Credits answer "may you run"; fairness answers "who runs first". Give each org/project a guaranteed reserved quota plus weighted access to idle capacity. Rank the queue with weighted fair queuing or dominant-resource fairness, using exponentially decayed recent usage so heavy recent consumers yield. Borrowed capacity is preemptible with checkpoint-friendly grace when the owner reclaims its reservation; per-user caps keep one user from starving teammates.
Failure recovery. Node agents keep a local WAL and replay after crashes or partitions; the server dedupes by sequence. If the meter crashes, it rebuilds offsets from Kafka. Expired holds are swept by a background job that releases reservations for dead jobs — never leave credits stuck on a crashed executor. All state changes are derived from the append-only ledger, so any materialized view can be rebuilt.
Observability and audit. Track hold-denial rate by reason, lease-renewal latency, ledger-vs-materialized balance drift (should be zero), stuck holds older than their lease, and per-org overspend incidents. The ledger itself is the audit log; export it to an OLAP store for reporting.
Common mistakes
- Using floats for money.
- Checking only the user's balance and ignoring parent scopes.
- Deciding from a cached balance.
- Long leases with no tightening, which blows the overspend bound.
- No expiry sweeper, leaving credits pinned by dead jobs.
- Routing a single org's traffic across shards, forcing distributed transactions you didn't need.