Library

Volume 1 · Cloud-Native Architecture

Notebook
Sign in

Section 21

AWS AI/ML Stack

1,374 words · about 6 min

21.1 Service Reference — Architecture and When to Use Each

Service Category Architecture Role When to Use
Bedrock Managed GenAI Foundation model access (Claude, Llama, Titan), Knowledge Bases (RAG), Guardrails, Agents Fastest path to production GenAI; no model hosting ops; need BAA/compliance coverage
SageMaker Custom ML platform Processing → Training → Model Registry → Endpoint → Monitor, full MLOps lifecycle Custom models (XGBoost, fine-tuned transformers), need full control over training/serving
Lambda Serverless compute Event-driven glue — triggers, lightweight inference, orchestration steps Sub-15-min, stateless, spiky workloads; document ingestion triggers
EKS Container orchestration GPU node pools for self-hosted LLM serving (vLLM/TGI), stateful multi-agent workflows Need K8s-native scheduling, GPU sharing, service mesh, long-running inference servers
EMR Big data processing Managed Spark/Hadoop for large-scale ETL and feature engineering Petabyte-scale data prep before training; Spark-native teams
OpenSearch Search/Vector DB Hybrid search (BM25 + kNN vector), stays inside VPC RAG retrieval layer when data residency/VPC isolation is required
MSK (Kafka) Streaming/messaging Durable event bus, ordered per-partition delivery High-throughput event sourcing, CDC pipelines, multi-consumer fan-out
Kinesis Streaming Managed real-time stream ingestion + Kinesis Analytics (SQL over streams) Real-time telemetry/IoT/clickstream ingestion feeding into Lambda/Firehose

21.2 Bedrock Architecture Deep Dive

Application → Bedrock Runtime API → Model Selection
                                       │
                          ┌────────────┼─────────────┐
                          ▼            ▼             ▼
                     Claude Sonnet  Llama 3.1     Titan
                     (reasoning)    405B/70B      Embeddings
                          │
                ┌─────────┼──────────────┐
                ▼         ▼              ▼
          Knowledge   Guardrails     Agents with
          Bases       (PII/content   Action Groups
          (managed    filtering,     (tool-calling,
          RAG:        denied topics) Lambda-backed
          ingest,                    orchestration)
          chunk,
          embed,
          retrieve)
Bedrock Feature Use Case Benefit
Knowledge Bases RAG over enterprise docs/policy corpora Managed ingestion, chunking, embedding, retrieval — no custom pipeline
Guardrails PII filtering, content safety, denied topics Built-in compliance layer, configurable without code changes
Agents Multi-step task automation with tool use Managed orchestration loop + Lambda action groups
Custom Model Import Fine-tuned domain models Bring your own fine-tuned weights into managed serving
Model Evaluation Compare model quality/cost/latency Built-in eval framework across candidate models

21.3 SageMaker Deep Dive

Data → SageMaker Processing (Spark) → Feature Store → Training Job
     → Model Registry → Endpoint Deployment → A/B Testing → Model Monitor
  • Processing Jobs: distributed data preprocessing/feature engineering, typically Spark-based on managed clusters.
  • Training: built-in algorithms (XGBoost) or custom containers (fine-tuned transformers, NER models); supports Spot Training for cost savings on interruptible jobs.
  • Endpoints: real-time inference (GPU instance types like ml.g5.xlarge), or Serverless Inference for spiky/low-traffic models, or Batch Transform for offline bulk scoring.
  • Pipelines: automated retraining workflows triggered by data drift or schedule.
  • Model Monitor: continuous drift detection on live traffic vs. training baseline; alerts before silent accuracy degradation.

21.4 Complete AWS AI Reference Architecture

┌─────────────────────────────────────────────────┐
│ Compute                                          │
│  EKS (Kubernetes)   ← Microservices, GPU serving │
│  Lambda             ← Event-driven, serverless   │
│  SageMaker Endpoints← Managed ML model serving   │
├─────────────────────────────────────────────────┤
│ AI/ML Services                                   │
│  Bedrock            ← GenAI (LLMs, RAG, Agents)  │
│  SageMaker          ← Custom ML (prediction, NER)│
│  Textract           ← Document OCR               │
│  Comprehend Medical ← Clinical/domain NER         │
│  Transcribe         ← Speech-to-text              │
├─────────────────────────────────────────────────┤
│ Data                                             │
│  S3                 ← Raw docs, model artifacts  │
│  OpenSearch         ← Vector search, hybrid RAG  │
│  RDS/Aurora         ← Transactional data          │
│  DynamoDB           ← Session state, agent memory │
│  Redshift           ← Analytics, reporting        │
│  EMR/Glue           ← ETL, big data processing    │
├─────────────────────────────────────────────────┤
│ Streaming                                        │
│  Kinesis            ← Real-time event ingestion  │
│  MSK (Kafka)        ← Durable message bus         │
│  SQS                ← Task queues, async work     │
│  EventBridge        ← Event routing               │
├─────────────────────────────────────────────────┤
│ Security & Compliance                            │
│  KMS  IAM  CloudTrail  Config  VPC  PrivateLink  │
└─────────────────────────────────────────────────┘

21.5 AWS Core Services Reference (Broader EA Context)

Compute

Service Type When to Use
EC2 VMs Custom config, stateful workloads, lift-and-shift
ECS (Fargate) Managed containers Containers without cluster management overhead
EKS Managed Kubernetes Complex orchestration, K8s-native teams, GPU scheduling
Lambda Serverless functions Event-driven, short-lived, spiky
App Runner Managed app platform Simple containerized web apps
Batch Batch computing HPC, ML training, large data jobs

Networking

Service Purpose
VPC Private network — subnets, route tables, IGW
ALB L7 load balancer — HTTP/HTTPS, path/host routing, WAF
NLB L4 load balancer — TCP/UDP, ultra-low latency
CloudFront CDN — edge caching, WAF, Lambda@Edge
Route 53 DNS — latency routing, failover, geolocation
Transit Gateway Hub-and-spoke VPC connectivity
PrivateLink Private cross-VPC/account service exposure
API Gateway REST/HTTP/WebSocket API management

Storage

Service Type Use Case
S3 Object Data lake, backups, static hosting
EBS Block EC2 root volumes, high-IOPS DBs
EFS File (NFS) Shared FS across EC2/ECS
FSx Managed FS Windows SMB / Lustre HPC
Glacier Archive Long-term compliance archives

Database

Service Type Best For
RDS Relational Managed MySQL/PostgreSQL/Oracle
Aurora Relational (AWS-native) High-performance, 5x throughput, auto-scaling storage
DynamoDB NoSQL Single-digit ms latency at any scale
ElastiCache In-memory Redis/Memcached caching, sessions
Redshift Data warehouse Petabyte-scale columnar analytics
Neptune Graph Social graphs, fraud detection
Timestream Time series IoT, operational metrics
DocumentDB MongoDB-compatible Document workloads

21.6 Terraform Example — Aurora Cluster for AI Metadata Store

resource "aws_rds_cluster" "ai_platform_db" {
  cluster_identifier          = "ai-platform-aurora"
  engine                      = "aurora-postgresql"
  engine_version               = "15.3"
  database_name                = "aiplatform"
  master_username               = "admin"
  manage_master_user_password  = true  # Secrets Manager auto-rotation

  backup_retention_period = 7
  preferred_backup_window  = "02:00-03:00"
  deletion_protection      = true

  vpc_security_group_ids = [aws_security_group.rds_sg.id]
  db_subnet_group_name   = aws_db_subnet_group.main.name

  tags = { Environment = "production", Team = "ai-platform" }
}

21.7 Interview Q&A

Q1: Design the cloud architecture for an enterprise AI platform on AWS.

A: I’d structure it in five tiers. Ingestion: S3 for documents, Kinesis for real-time events, API Gateway for external feeds. Processing: EKS for microservices (mixed-language APIs + Python ML services), Lambda for event-driven tasks. AI/ML: Bedrock for GenAI (RAG, summarization, agents), SageMaker for custom ML (classification, NER, ranking). Data: Aurora for transactional data, OpenSearch for vector search/hybrid RAG, Redshift for analytics, DynamoDB for session/agent state. Security: VPC with private subnets, PrivateLink for Bedrock/SageMaker so traffic never crosses the public internet, KMS encryption everywhere, CloudTrail audit, least-privilege IAM.

Key decisions I’d defend: start with Bedrock over self-hosting for GenAI (lower ops burden, faster time-to-value), migrate high-volume/latency-sensitive models to self-hosted SageMaker or EKS+vLLM later once usage patterns justify the ops cost. Choose EKS over ECS when the team needs GPU node scheduling and a service mesh for mTLS between services — ECS Fargate can’t run GPU workloads.

Q2: When would you NOT choose AWS Lambda for an AI workload?

A: Lambda excels at event-driven, stateless, spiky workloads, but I avoid it when: (1) cold start is unacceptable — Lambda cold starts range 100ms–several seconds, and for latency-sensitive inference APIs I’d use ECS Fargate with provisioned concurrency or EKS instead; (2) long-running processes — 15-minute max timeout rules out batch document processing or model training, which belong on AWS Batch or ECS Tasks; (3) GPU inference — Lambda has no GPU support, so any model serving needs SageMaker endpoints or EKS GPU node pools; (4) complex shared state — a model warmed once and reused across requests needs a long-lived process, not a stateless function; (5) high steady-state throughput — at high sustained request rates, reserved EC2/ECS capacity is often cheaper than per-invocation Lambda pricing.

Q3: Explain Aurora vs. RDS PostgreSQL and when you’d choose each.

A: Aurora is AWS’s cloud-native relational engine, MySQL/PostgreSQL-compatible but with a custom distributed storage layer. Advantages: storage auto-grows in 10GB increments to 128TB with no provisioning; up to 15 read replicas with <10ms lag versus RDS’s 5 replicas with higher lag; failover in under 30 seconds versus RDS’s 1–2 minutes; Aurora Serverless v2 scales compute in seconds between 0.5–128 ACUs for variable workloads; Global Database supports one primary plus up to 5 secondary regions with sub-second lag. I choose Aurora when HA is critical, read scalability is needed, or multi-region is required. I choose standard RDS for simple/small workloads, when a specific engine version isn’t available on Aurora, or for cost-sensitive dev/test environments.

Q4: When would you use Lambda vs. EKS for AI workloads specifically?

A: Lambda for event-driven, stateless, sub-15-minute, no-GPU work — document ingestion triggers, lightweight text processing, variable-traffic API backends. EKS for stateful, long-running, GPU-required, complex-networking work — self-hosted LLM serving with vLLM, real-time NLP pipelines, multi-agent orchestration. Most production systems are hybrid: Lambda for event triggers and lightweight glue, EKS for core GPU-backed services, SageMaker endpoints for managed model inference where full K8s control isn’t needed.