You design a finetuning LoRA API service by separating the workload into four cooperating layers: a control plane that tracks jobs and artifacts, an orchestrator that schedules GPU work, a worker that runs the actual training, and an inference gateway that hot-swaps adapters. The key condition is that LoRA adapters are small, so you should store and serve them as throwaway artifacts keyed to a base model, not as separate model deployments. Get those boundaries right and the rest is mostly queue design, storage layout, and cost control.
This guide walks through the full build in the order you would actually do it, using stable knowledge about LoRA (Low-Rank Adaptation) training and service architecture. It doesn't claim any live prices or current version numbers; wherever a value changes over time, I'll name the quantity to check rather than guess it.
Start With the Job Contract, Not the Code
Before touching GPUs, write down what one API call promises and what it does not. A finetuning request typically accepts a dataset reference, a base model identifier, and hyperparameters, and returns a job ID immediately. That distinction matters: training takes minutes to hours, so the API is asynchronous by design. A synchronous endpoint that blocks until training finishes will time out at any load balancer and will tie up a worker connection for the entire run.
Your contract needs to pin down at least these fields:
Base model and revision. A LoRA adapter is only valid against the exact weights it was trained on. "Llama-family 8B" is not a contract; a specific model identifier plus a content hash is. Dataset reference and a schema version. Point to object storage rather than uploading gigabytes through a JSON body. Hyperparameters with defaults. Rank, alpha, dropout, target modules, learning rate, epochs, batch size, sequence length. Output artifact. A path or ID for the adapter weights plus a metadata record listing every training input. Lifecycle states. Queued, running, succeeded, failed, canceled, and expired. Clients poll or subscribe; the server is the source of truth.
One design decision to make early: does the service support only text-generation models, or also classifiers, embedding models, and diffusion models? Each adds its own data format and evaluation path. I recommend launching with a single family and a single task type. The request schema can carry a task field from day one so you can expand later without a breaking change.
Also decide the trust boundary. If arbitrary users can submit training jobs, they can also submit malicious datasets or prompts. That has implications for sandboxing, network access from workers, and output scanning, which I'll return to.
The Service Decomposition: Control Plane, Queue, Workers, Store
A LoRA finetuning service is naturally four components, and the cleanest designs keep them independently deployable:
The control plane is a stateless HTTP API (plus an auth layer) that validates requests, writes job records to a database, and enqueues work. It never touches a GPU. Because it's stateless, you can run many replicas behind a load balancer.
The queue is a durable message broker or a database-backed job table. The critical property is at-least-once delivery with visibility timeouts, so a crashed worker's job becomes claimable again. Job state transitions should be idempotent: claiming a job, marking it running, and writing a terminal state should each be safe to repeat.
The workers are GPU-attached processes that pull a job, download the dataset and base model (usually cached locally), run the trainer, upload the adapter, and report results. Workers should be cattle, not pets. Don't let a worker hold unique state that isn't also in the store.
The artifact store holds datasets, base model caches, adapters, logs, and evaluation reports. Object storage with a predictable key layout is the default choice:
The metadata file is the single most valuable artifact. It should record the base model hash, the exact hyperparameters, the dataset version and row count, the library and CUDA versions, the random seed, and the final training loss. When an adapter misbehaves months later, that file is the only way to reconstruct what happened.
An important structural rule: the control plane and the inference gateway should both read from the same artifact store and the same metadata database. If they diverge, you'll eventually serve a stale adapter or an adapter attached to the wrong base model.
Design the Asynchronous Job API
A clean job API has a small number of endpoints with obvious semantics:
1: Create a job. POST /v1/finetune/jobs validates the payload, resolves the dataset and base model, checks quota, and inserts a record with status queued. Return 202 Accepted with the job ID and a Location header. 2: Read a job. GET /v1/finetune/jobs/{id} returns status, timestamps, progress counters, and error details if failed. Make it cheap enough to poll every few seconds; caching helps. 3: List jobs. GET /v1/finetune/jobs?status=running&limit=50 with cursor pagination. Tenants should only ever see their own jobs. 4: Cancel a job. POST /v1/finetune/jobs/{id}/cancel sets a cancellation flag. The worker checks it between steps; the queue removes the job if it hasn't started. Cancellation is cooperative, never a hard kill of a half-written artifact. 5: Download the artifact. Either a signed URL to object storage or a short-lived token-gated endpoint. Don't proxy large files through the control plane.
A useful addition is a server-sent events or webhook notification path so clients don't have to poll. Webhooks need signing and retry with exponential backoff, and they need a dead-letter path because a client's endpoint will go down eventually.
Errors deserve the same care. Distinguish validation errors (400, the request is malformed), authorization errors (403), quota errors (429 with a Retry-After), and server errors (500). Return a machine-readable error code plus a human message. A failed training job should surface the last N lines of the trainer log and a stable failure category, such as dataset_invalid, oom, or base_model_mismatch.
Version the API path from day one (/v1/). When you change the request schema in a way that breaks clients, add /v2/ rather than mutating behavior underneath existing callers.
The Training Worker: What Actually Runs
The worker is the part with the most failure modes. Its job:
1: Claim a job and atomically mark it running with a lease and a heartbeat. 2: Resolve and download inputs into a local cache. Cache base model weights across jobs on the same node, keyed by content hash. This is the single biggest win for cost and cold-start time. 3: Validate the dataset: required columns, row count within limits, token length distribution after truncation, and a check that the format matches the task (instruction/response pairs for supervised finetuning, for example). 4: Load the base model in the training precision you can afford, attach the LoRA layers to the chosen target modules, and run the trainer. 5: Periodically checkpoint so a preempted job can resume rather than restart. 6: On success, save the adapter weights, compute a checksum, write metadata, upload, and mark succeeded. On failure, write a categorized error and clean up scratch space.
The LoRA-specific mechanics you need to get right:
Rank and alpha. The adapter matrices have rank r; the effective scaling is alpha/r in the common formulation. If you change rank without adjusting alpha, the adapter's behavior shifts even though the training config "looks the same." Store both and expose them to clients. Target modules. Which attention and MLP projections get adapters depends on the architecture. Document the defaults per model family; changing them changes adapter size and quality. Merging. For serving, you can either merge the adapter into a copy of the base weights (fastest inference, one full model copy per adapter) or keep it separate and apply it at runtime (cheap to store, some per-request overhead). Most services keep adapters unmerged. Precision and memory. The training precision, gradient checkpointing, and batch size interact to determine whether a job fits. Your worker should estimate memory before launching and reject or shrink the job rather than crash with an opaque out-of-memory error.
Checkpointing deserves a specific note. On preemptible GPUs, a job that can't resume will restart from scratch and may never finish. Save every N steps to local disk, upload to object storage, and record the step number in job metadata. On resume, reload the latest checkpoint and continue.
A simple success check after training: load the adapter into a reference inference process, run a handful of held-out examples, and confirm the output isn't degenerate (empty, repetitive, or refusing everything). That smoke test catches most broken jobs before a user does.
Serving Adapters at Inference Time
The inference side of a LoRA service has a pleasant property: adapters are small relative to the base model, often a fraction of a percent of the base weights. That means a single loaded base model can host many adapters, swapped or loaded per request.
Two main serving strategies:
Merge per adapter. Each adapter gets its own merged weights. Simplest to reason about, and inference is as fast as the base model. But you pay full model memory per adapter, and loading a new one means a full model load. This works well when a tenant has a small number of frequently used adapters.
Dynamic adapter loading. A single base model stays resident, and the serving framework loads adapters into a registry keyed by adapter ID. Requests specify which adapter to use. If the adapter isn't loaded, the server loads it on demand and evicts under an LRU policy. This is the design that makes a multi-tenant LoRA service economical. The trade-off is added request latency on a cold adapter and the need for a registry that stays consistent with the artifact store.
Whichever you choose, enforce these rules:
Pin the base model. The serving side must load the exact base model revision the adapter was trained against. A mismatch can silently produce garbage output. Check the metadata hash at load time and refuse mismatched adapters. Authenticate every request. Tenants must not be able to address another tenant's adapter by ID. Authorization belongs in the gateway, checked against the same database the control plane writes. Bound concurrent adapters. Cap the number of loaded adapters per GPU and the total GPU memory used by the registry. Without a cap, one tenant enumerating many adapters can evict everyone else's. Version adapters. Never overwrite an existing adapter ID with retrained weights. Create a new version and let clients pin the version they want. This is how you roll back a bad finetune without a redeploy.
An adapter registry table should hold: adapter ID, tenant, base model hash, artifact path, checksum, created time, and a status (active, deprecated). The gateway reads this table; it doesn't infer existence from files in storage.
Multi-Tenancy, Isolation, and Security
Finetuning APIs handle untrusted data and prompts, which raises the stakes. The core safety moves:
Isolate training from serving. Training jobs run on their own GPU pool with their own network policy. They should not be able to reach the inference pool's internal endpoints. If training code can execute arbitrary user-supplied Python (a training script, a custom loss), sandbox it hard and accept only declared dependencies.
Isolate tenants from each other. Don't let a tenant's adapter be loadable by another tenant's requests. Don't let one tenant's dataset path be guessable. Use per-tenant key prefixes in object storage and authorization checks at every read.
Treat datasets and prompts as sensitive. They may contain PII or proprietary content. Encrypt at rest, redact logs, and set retention policies. Define how long datasets and adapters live, and provide deletion. A finetune artifact derived from a deleted dataset needs a defined fate.
Validate the dataset format before queueing. A malformed dataset wastes a GPU run and can crash workers. Run schema and size checks in the control plane or a lightweight preflight step, and reject early with a clear error.
Set quotas. Per-tenant limits on concurrent jobs, GPU-hours per period, and number of stored adapters prevent one tenant from starving the rest. Return 429 with Retry-After when the quota is hit.
Estimating Cost and Capacity Before You Build
You can reason about costs without a live price sheet; the method matters more than the number. The quantities you need to measure or estimate:
GPU-hours per training run. Roughly (training tokens × epochs) / (throughput tokens per second per GPU × 3600). Measure throughput once on your target hardware, then apply it. GPU-hours per 1,000 training runs, which drives the training bill. This scales with job size and concurrency, not with the number of tenants, so long as jobs are queued rather than run in parallel without limits. Inference overhead per adapter. Dynamic loading adds some latency per request and some GPU memory per loaded adapter; merged serving adds no per-request overhead but multiplies model memory by the number of concurrent adapters. Storage. Base model caches dominate disk usage; adapters are small. Budget for a handful of base models (each copy in a couple of precisions) plus checkpoints during training, which can be several times the adapter size per run.
A worked illustration: if a typical job trains on 200,000 tokens for 3 epochs at a measured 1,000 tokens per second per GPU, that's about 600,000 token-passes, or roughly 10 minutes of GPU time, ignoring startup overhead. Startup overhead (loading the model, downloading data) can easily equal or exceed the training time for small jobs, which is why base-model caching on workers pays for itself quickly. The takeaway: for small jobs, optimize startup; for large jobs, optimize throughput.
Capacity planning, then, is a queueing problem. You choose a worker pool size for training (which sets a maximum concurrent training throughput) and a pool of inference replicas sized for expected request rate and adapter fan-out. Set concurrency limits and autoscale on queue depth for training, not on CPU. Don't try to fit arbitrary jobs by reducing batch size until the model barely loads; instead, define a small set of supported configurations and let clients pick from them.
Evaluation, Reproducibility, and Lifecycle
A finetuning service without evaluation produces adapters you can't trust. Add three things:
A fixed input manifest. Every job's metadata records the base model hash, dataset version, hyperparameters, library versions, and seed. With that, a rerun is reproducible to within nondeterminism of the training stack, which is a real limitation you should document.
A held-out evaluation step. Before an adapter is marked active, run it on a small held-out split and record a metric appropriate to the task (loss, exact-match, or a rubric score). This need not be perfect; it needs to catch obvious failure modes.
An explicit lifecycle. An adapter moves from training to evaluated to active to deprecated to deleted, with each transition recorded. Deprecation should not silently break clients; return a clear error or a warning header, and keep the artifact readable for a defined grace period.
The metadata file is what makes all of this tractable. Treat it as a first-class API output: expose it in GET /v1/finetune/jobs/{id} and let clients download it alongside the adapter. That is also your best defense when a client claims "the adapter got worse" after an unrelated change.
Operational Hardening and Failure Modes
A few failures recur in almost every build of this kind:
Orphaned jobs. A worker dies mid-job and the job stays running forever. Fix it with leases and heartbeats: if the heartbeat stops, the queue requeues the job. Reaping should be automatic. Duplicate uploads. At-least-once delivery means a job can finish twice. The artifact upload should be idempotent, keyed by job ID and checksum, so the second completion overwrites the same path rather than creating a new one. GPU memory fragmentation. Loading and unloading many adapters over time fragments the allocator. Restart workers on a schedule or use a framework with a memory pool; otherwise cold loads eventually fail. Stale registry entries. An artifact is deleted from storage but the registry still lists it. The gateway should verify existence lazily and mark entries stale, and the lifecycle job should reconcile the two. The retraining storm. A client retries a failed job automatically and repeatedly. Rate-limit creation and require idempotency keys on POST /finetune/jobs so a client's retry of the same request returns the same job rather than creating a duplicate GPU run. Adapter drift from base model updates. When the base model is updated, existing adapters no longer match. Keep the old base revision available until every adapter trained on it is deprecated.
Observability should follow the same structure: per-job traces, per-tenant usage metrics (GPU-seconds consumed), queue depth and age of oldest job, worker health, and adapter load/evict counters on the inference side. Alert on queue age, not just queue depth, because a stuck job with a healthy-looking queue is the most common silent failure.
What to Build First
A practical sequence for a first version: start with the control plane and job table, plus a single worker that runs a fixed training recipe on a single GPU. Add the artifact store and metadata file. Then add the inference gateway in merged-per-adapter mode, which is simpler and lets you validate end-to-end before tackling dynamic loading. Add authentication, quotas, and the registry table early, because retrofitting isolation is much harder than designing it in. Defer multiple model families, webhooks, and autoscaling until you have real usage to measure.
A warning worth repeating: don't let the API accept raw training scripts from clients in version one. Accept structured parameters only. The moment clients can run arbitrary code on your GPUs, your security model and your cost model both change. If you eventually need custom training code, isolate it on a separate worker pool with its own network policy and a hard GPU-hour budget, and treat review of that code as a gate.
The design that survives contact with real traffic is the one where the base model is pinned, the adapter is a versioned artifact with complete metadata, job state is durable and requeueable, and the gateway authorizes every adapter by tenant. Everything else—caching, evaluation, dashboards, frameworks—makes those invariants easier to hold, not harder.