Library

Volume 2 · GenAI Foundations & LLM Architecture

Notebook
Sign in

Section 6

Model Serving & Deployment

1,628 words · about 7 min

6.1 Serving Frameworks Comparison

Framework Type Best For Key Feature
vLLM Self-hosted High-throughput production serving PagedAttention, continuous batching — highest throughput
TGI (Text Generation Inference) Self-hosted Hugging Face model ecosystem Token streaming, built-in quantization
Triton Inference Server Self-hosted Multi-model serving GPU sharing, model ensembles
TensorRT-LLM Self-hosted (NVIDIA) Maximum GPU utilization Deep NVIDIA hardware optimization
Ollama Local Development/prototyping Simple, Docker-like UX
SageMaker Endpoints Managed (AWS) AWS-native production Auto-scaling, model registry integration
Azure OpenAI / Azure ML Endpoints Managed (Azure) Azure-native PTU (provisioned throughput), content filtering built-in
AWS Bedrock Fully managed (AWS) Zero-ops multi-model Serverless, multiple model providers

6.2 Deployment Patterns

flowchart TD
    App["Enterprise Application"] --> Router["Intelligent Model Router\n(Evaluates Complexity, Latency & Data Classification)"]

    subgraph ManagedTier["Pattern 1: Managed Cloud API"]
        Bedrock["AWS Bedrock / Azure OpenAI\n(Zero Ops / Auto-Scaled Frontier Models)"]
    end

    subgraph SelfHostedTier["Pattern 2: Dedicated GPU Fleet"]
        vLLM["Kubernetes GPU Nodes\n(vLLM / TensorRT-LLM / Triton)"]
    end

    subgraph EdgeTier["Pattern 3: Edge & On-Prem"]
        Edge["Local SLMs / Edge Nodes\n(GGUF / ONNX / Phi-3 / Gemma)"]
    end

    Router -->|High Complexity / General SaaS| Bedrock
    Router -->|High Volume / Private VPC Data| vLLM
    Router -->|Zero Latency / Offline Privacy| Edge

Deployment Pattern Comparison:

  • Pattern 1: Managed APIs (AWS Bedrock / Azure OpenAI)
    • Pros: Zero GPU operational burden, turn-key auto-scaling, integrated content moderation.
    • Cons: Linear per-token pricing, potential vendor lock-in, data egress considerations.
  • Pattern 2: Self-Hosted on Cloud GPUs (vLLM on Kubernetes)
    • Pros: Strict VPC data residency, customizable runtime kernels, cost-effective at sustained high throughput.
    • Cons: GPU cluster management overhead, cold-start provisioning delays.
  • Pattern 3: Hybrid Routing Architecture (Recommended Enterprise Default)
    • Dynamically routes requests based on security classification, query complexity, and latency budgets across cloud, VPC, and edge runtimes.

6.3 Production Serving Architecture (Detail)

flowchart TD
    User["Client Requests / Applications"] --> GW["API Gateway\n(Rate Limiting / Token Bucket / JWT Auth)"]
    GW --> LB["Layer 4 / 7 Load Balancer"]

    subgraph PodFleet["Scalable GPU Inference Fleet"]
        P1["vLLM Replica 1\n(A100 / H100 GPU)"]
        P2["vLLM Replica 2\n(A100 / H100 GPU)"]
        P3["vLLM Replica 3\n(A100 / H100 GPU)"]
    end

    LB --> P1 & P2 & P3

    subgraph Telemetry["Observability & Governance Layer"]
        M["Prometheus / Datadog\n(P95 TTFT & Queue Depth)"]
        L["OpenTelemetry Traces\n(Prompt / Output Tokens)"]
        C["FinOps Governance\n(Per-Tenant Cost Attribution)"]
    end

    P1 & P2 & P3 -.-> M & L & C

6.4 Right-Sizing Inference Infrastructure

Model Parameter Size Precision Mode VRAM Footprint Recommended Hardware
7B – 8B parameters FP16 (Uncompressed) ~14–16 GB 1× NVIDIA A10G / L4 (24GB)
13B – 14B parameters FP16 (Uncompressed) ~26–28 GB 1× NVIDIA A100 (40GB)
70B parameters FP16 (Uncompressed) ~140 GB 2× NVIDIA A100 (80GB) via Tensor Parallelism
70B parameters INT4 Quantized (AWQ / GPTQ) ~35–38 GB 1× NVIDIA A100 (40GB) or 2× L4 (24GB)

6.5 The ML Engineering Framework Stack

Serving infrastructure sits on top of a training/experimentation stack an architect is expected to know even if a dedicated ML engineering team owns day-to-day use:

Layer Tooling Architect-relevant concern
Training framework PyTorch (dominant for LLM research and fine-tuning — dynamic graphs, torch.compile for JIT speedups, native distributed training via FSDP/DeepSpeed) vs. TensorFlow (still common in legacy enterprise CV/tabular pipelines, static-graph SavedModel deployment story via TF Serving) Which framework a candidate model/checkpoint ships in determines your serving-stack choice (vLLM and TGI are PyTorch-native; TF models need TF Serving or ONNX conversion)
Model/tokenizer hub & fine-tuning ergonomics Hugging Face (transformers, peft for LoRA/QLoRA, datasets, accelerate for multi-GPU) The de facto standard for loading, fine-tuning, and pushing open-weight models (Llama, Mistral, Phi, Gemma); most PEFT/quantization libraries (bitsandbytes, GPTQ, AWQ) plug directly into this ecosystem
RAG/agent data framework LlamaIndex (data connectors, indexing strategies, query engines — strong on structured/semi-structured retrieval and evaluation) vs. LangChain/LangGraph (broader agent-orchestration surface — see Section 30) LlamaIndex is often the better fit when the RAG pipeline itself (ingestion, indexing, retrieval) is the primary engineering surface; LangGraph/CrewAI/Agno are the better fit when multi-step agent orchestration is the primary surface. Production systems frequently use both — LlamaIndex for retrieval, LangGraph for orchestration.
Serving vLLM / TGI / Triton / TensorRT-LLM (Section 6.1) Bridges training-framework checkpoints to production inference

6.6 Autoscaling, Rate-Limiting & Resource Governance for Inference

  • Autoscaling on GPU-bound workloads doesn’t behave like CPU autoscaling — GPU utilization alone is a lagging/misleading signal because a saturated batch can show 100% utilization while still having queue-depth headroom. Scale on a composite signal: request queue depth + P95 time-to-first-token + GPU memory pressure, not raw utilization percentage alone. KEDA with a custom metrics adapter (queue length from the inference gateway) is the common Kubernetes-native pattern; scale-to-zero for bursty/dev workloads, minimum-warm-replica floors for production to avoid cold-start latency spikes.
  • Rate-limiting at the API Gateway layer (Volume 1 Section 8) protects both cost and fairness — per-tenant token-bucket limits (Volume 3 Section 22) prevent one noisy client from starving others, and a separate, tighter limit on concurrent in-flight requests (not just requests/sec) matters specifically for LLM workloads because request duration is highly variable (a 50-token completion and a 4,000-token completion consume the same “1 request” quota but wildly different GPU-time).
  • Resource governance at the platform level means per-team/per-project token budgets with alerting before hard cutoffs, model-tier access control (only approved teams get access to the most expensive frontier models, others route to a cheaper/smaller model by default), and chargeback/showback dashboards so cost ownership is visible to the teams generating it — this is the same FinOps discipline as Volume 1 Section 26 applied specifically to inference spend.

6.7 Adaptive Reasoning Control

For agentic and reasoning-model workloads specifically, a mature platform doesn’t treat “how much the model thinks” as fixed — it adapts reasoning depth/effort to the request:

  • Complexity-based routing: classify the incoming request (heuristically, or with a cheap classifier model) and route simple queries to a fast/non-reasoning path and complex/multi-step queries to an extended-reasoning or agentic path, rather than paying extended-reasoning latency and cost on every request uniformly.
  • Budget-capped reasoning: for models that support variable “thinking budget” (extended chain-of-thought token allowances), cap the budget per request tier so a single pathological query can’t consume disproportionate cost/latency, with a fallback to “best answer so far” if the cap is hit rather than a hard failure.
  • Escalation on low confidence: start with a cheaper/faster reasoning depth and escalate to deeper reasoning (or a larger model) only when a confidence/self-consistency check (Section 11.4) indicates the first pass is unreliable — this mirrors the model-routing cost strategy in Section 9.2 but applied to reasoning depth rather than model selection.

Section 6 — Interview Q&A

Q: Compare AWS Bedrock vs Azure OpenAI vs self-hosted (SageMaker/vLLM) for an enterprise AI platform. A: Bedrock offers model variety (Claude, Llama, Titan, Mistral) with zero ops and pay-per-token pricing, well-suited when you want provider flexibility within AWS. Azure OpenAI gives strong GPT-4-family access with PTU for predictable throughput and tight Azure ecosystem integration. Self-hosted (vLLM/TGI on SageMaker or Kubernetes GPU nodes) gives maximum data control, no per-token markup at scale, and the best latency (no external network hop), at the cost of operational burden (scaling, patching, GPU fleet management). My typical recommendation is hybrid: managed API as the default for general workloads and fast time-to-market, self-hosted open-source for high-volume or highly sensitive workloads where the economics favor fixed infrastructure cost over linear per-token cost — the break-even point is usually in the tens of thousands of requests/day range.

Q: How would you architect model serving to support cloud, edge, and on-prem environments simultaneously? A: I’d build a model router abstraction that decouples the application layer from the specific inference backend. Cloud handles the bulk of general traffic via a managed API or self-hosted vLLM cluster. Edge deployment uses a distilled or quantized small model (e.g., a Phi-3/Gemma-class SLM in GGUF format) running locally for latency-critical or offline-capable scenarios. On-prem uses self-hosted open-source models (Llama family) behind the same API contract as the cloud service, satisfying data-residency requirements. The router selects a backend based on request classification (complexity, data sensitivity, latency budget) and all backends expose a consistent API surface so the application code is backend-agnostic — this is essential for regulated industries needing options across all three deployment modes without maintaining three separate application integrations.

Q: How do you decide between PyTorch/Hugging Face and TensorFlow for a new enterprise AI initiative, and where does LlamaIndex fit versus LangChain? A: For any new LLM/GenAI initiative I default to the PyTorch + Hugging Face stack — it’s where the open-weight model ecosystem (Llama, Mistral, Phi, Gemma), the PEFT libraries (LoRA/QLoRA via peft+bitsandbytes), and the serving frameworks (vLLM, TGI) all live natively, so it minimizes conversion friction end-to-end. TensorFlow only wins if the organization has an existing TF Serving investment or a legacy CV/tabular pipeline where a rewrite isn’t justified — in that case I’d isolate the new LLM component behind a service boundary rather than forcing framework unification. On LlamaIndex vs. LangChain: I treat them as complementary, not competing — LlamaIndex when the retrieval/indexing pipeline is the hard engineering problem (structured data connectors, advanced index types, retrieval evaluation), LangGraph/LangChain when multi-step agent orchestration and tool-calling is the hard problem; a mature RAG-plus-agent platform commonly uses LlamaIndex for the retrieval layer feeding into a LangGraph-orchestrated agent.

Q: How do you keep inference cost and latency under control for a platform serving many teams with wildly different usage patterns? A: Three levers together, not any single one: autoscaling on the right signal (queue depth and P95 time-to-first-token, not raw GPU utilization, per Section 6.6, since GPU-bound inference misreports headroom under naive utilization-based scaling); per-tenant governance (token budgets, concurrent-in-flight-request caps rather than plain requests/sec limits, and model-tier access control so only approved workloads reach the most expensive frontier models); and adaptive reasoning control (Section 6.7) so reasoning-heavy/agentic requests only pay for extended thinking budget when a complexity classifier or a low-confidence signal actually warrants it, rather than applying maximum reasoning depth uniformly across all traffic.