AWS Builder Center

GPU Is Just Expensive Compute: Production MLOps Patterns for Teams That Can't Afford a Five-Figure Surprise

The most predictable failure mode in AI infrastructure right now isn't a model quality problem. It's an operations discipline problem.

Senior DevOps & SRE | IEEE Senior Member | AI Observability & Cloud Resilience

The most predictable failure mode in AI infrastructure right now isn't a model quality problem. It's an operations discipline problem.
GPU compute is expensive at a rate that makes traditional infrastructure cost intuitions useless. A runaway EC2 instance costs you $50/hour. A P5 cluster in a bad state costs you $2,000/hour. The observability patterns, cost controls, and deployment governance that work for standard compute workloads need to be recalibrated for GPU-accelerated infrastructure — or you find out the hard way during an incident.
This post covers three production patterns for operationalizing GPU-accelerated ML workloads on AWS with the same rigor you'd apply to any other latency-sensitive, cost-sensitive production service. All patterns are implemented in the  agentsre  library and target teams running LLM inference on P5/G-series instances.



The Operational Gaps That Cause the Largest Surprises

Before the code: the three gaps I've seen consistently between ML research infrastructure and production ML infrastructure:
Gap 1: No cost rate monitor with automatic severance Teams deploy cost anomaly alerts calibrated for standard compute. A GPU workload that looks like a 10x cost spike on a standard alert might be a 500x spike in absolute dollars. The alert fires after the bill accumulates, not before.
Gap 2: Inference treated as a batch workload LLM inference is a latency-sensitive service with p99 requirements, queue dynamics, and cascade failure modes. Teams that treat it like a batch processing job don't instrument it like a service, don't load-test it like a service, and don't have runbooks for it like a service.
Gap 3: Model weight deployment with no rollback path Model artifacts are large, deployment is slow, and rollback under pressure is painful without a pre-built artifact governance pipeline. Teams discover this during an incident, when they need to roll back a bad model version at 2:00 AM and the process doesn't exist.



Pattern 1: GPU Cost Rate Monitor with Circuit Breaker

The first control to deploy before anything else: a per-session cost rate monitor that tracks GPU spend against a hard budget and severs inference authority before the bill becomes a finance conversation.
python
import boto3
import logging
import threading
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional

logger = logging.getLogger(__name__)

class GPUInstanceType(str, Enum):
"""
Approximate on-demand cost per hour (USD) for AWS GPU instance families.
Update from AWS pricing API for your region.
"""
P5_48XLARGE = "p5.48xlarge" # ~$98/hr (8x H100)
P4D_24XLARGE = "p4d.24xlarge" # ~$32/hr (8x A100)
G6_12XLARGE = "g6.12xlarge" # ~$4/hr (1x L40S)
G5_12XLARGE = "g5.12xlarge" # ~$5.67/hr (4x A10G)
G4DN_12XLARGE = "g4dn.12xlarge" # ~$3.91/hr (4x T4)

HOURLY_COST_USD: dict[GPUInstanceType, float] = {
GPUInstanceType.P5_48XLARGE: 98.32,
GPUInstanceType.P4D_24XLARGE: 32.77,
GPUInstanceType.G6_12XLARGE: 4.02,
GPUInstanceType.G5_12XLARGE: 5.67,
GPUInstanceType.G4DN_12XLARGE: 3.91,
}

@dataclass
class GPUCostConfig:
"""
Cost monitoring configuration for a GPU workload session.

Attributes
----------
session_id : str
Unique session identifier for audit logging.
instance_type : GPUInstanceType
GPU instance type being used. Determines cost rate.
instance_count : int
Number of instances in the session fleet.
max_session_cost_usd : float
Hard cost ceiling for the session. Circuit trips at this value.
max_hourly_rate_usd : float
Maximum acceptable cost rate ($/hr). Circuit trips if exceeded.
check_interval_seconds : int
How often the monitor evaluates cost rate. Default 60s.
sns_alert_topic_arn : str or None
SNS topic for cost breach alerts.
cloudwatch_namespace : str
CloudWatch namespace for cost metrics.
"""
session_id: str
instance_type: GPUInstanceType
instance_count: int
max_session_cost_usd: float
max_hourly_rate_usd: float
check_interval_seconds: int = 60
sns_alert_topic_arn: Optional[str] = None
cloudwatch_namespace: str = "SRE/GPUCost"

@dataclass
class CostSnapshot:
"""Point-in-time cost telemetry for a GPU session."""
session_id: str
elapsed_seconds: float
accumulated_cost_usd: float
current_hourly_rate_usd: float
instance_count: int
circuit_open: bool = False
breach_reason: str = ""

class GPUCostCircuitBreaker:
"""
Real-time GPU cost monitor with automatic circuit breaker.

Tracks accumulated spend and cost rate against configured ceilings.
On breach: publishes a CloudWatch metric, sends an SNS alert, and
returns circuit_open=True to the caller — signaling that GPU workload
authority should be suspended.

The circuit breaker doesn't stop AWS charges on its own. The caller
is responsible for acting on circuit_open=True (stopping instances,
scaling fleet to zero, revoking session credentials). This separation
is intentional: the monitor is an observer, not an executor.

Parameters
----------
config : GPUCostConfig
Cost ceiling and notification configuration.

Example
-------
>>> cb = GPUCostCircuitBreaker(config)
>>> cb.start()
>>> while inference_session_running():
... snapshot = cb.get_snapshot()
... if snapshot.circuit_open:
... scale_fleet_to_zero()
... page_oncall(snapshot.breach_reason)
... break
... run_inference_batch()
"""

def __init__(self, config: GPUCostConfig):
self.config = config
self._start_time = time.time()
self._circuit_open = False
self._breach_reason = ""
self._lock = threading.Lock()
self._cw = boto3.client("cloudwatch")
self._monitor_thread: Optional[threading.Thread] = None
self._hourly_rate = (
HOURLY_COST_USD.get(config.instance_type, 0.0) * config.instance_count
)

def start(self):
"""Start background cost monitoring thread."""
self._monitor_thread = threading.Thread(
target=self._monitor_loop, daemon=True
)
self._monitor_thread.start()
logger.info(
"GPU cost monitor started",
extra={
"session_id": self.config.session_id,
"instance_type": self.config.instance_type,
"instance_count": self.config.instance_count,
"hourly_rate_usd": self._hourly_rate,
"max_session_cost_usd": self.config.max_session_cost_usd,
"max_hourly_rate_usd": self.config.max_hourly_rate_usd,
},
)

def get_snapshot(self) -> CostSnapshot:
"""Return current cost telemetry. Call before each inference batch."""
elapsed = time.time() - self._start_time
accumulated = self._hourly_rate * (elapsed / 3600)
with self._lock:
return CostSnapshot(
session_id=self.config.session_id,
elapsed_seconds=round(elapsed, 1),
accumulated_cost_usd=round(accumulated, 4),
current_hourly_rate_usd=self._hourly_rate,
instance_count=self.config.instance_count,
circuit_open=self._circuit_open,
breach_reason=self._breach_reason,
)

def _monitor_loop(self):
while True:
time.sleep(self.config.check_interval_seconds)
snapshot = self.get_snapshot()
self._emit_metrics(snapshot)

with self._lock:
if self._circuit_open:
return # Already tripped

# Accumulated cost ceiling check
if snapshot.accumulated_cost_usd > self.config.max_session_cost_usd:
self._trip(
f"Session cost ceiling breached: "
f"${snapshot.accumulated_cost_usd:.2f} > "
f"${self.config.max_session_cost_usd:.2f}"
)
return

# Hourly rate ceiling check
if snapshot.current_hourly_rate_usd > self.config.max_hourly_rate_usd:
self._trip(
f"Hourly cost rate ceiling breached: "
f"${snapshot.current_hourly_rate_usd:.2f}/hr > "
f"${self.config.max_hourly_rate_usd:.2f}/hr"
)
return

def _trip(self, reason: str):
with self._lock:
self._circuit_open = True
self._breach_reason = reason

logger.error(
"GPU cost circuit breaker OPEN",
extra={
"session_id": self.config.session_id,
"reason": reason,
"instance_type": self.config.instance_type,
"instance_count": self.config.instance_count,
"hourly_rate_usd": self._hourly_rate,
},
)

try:
self._cw.put_metric_data(
Namespace=self.config.cloudwatch_namespace,
MetricData=[{
"MetricName": "CostCircuitBreakerOpen",
"Dimensions": [
{"Name": "SessionId", "Value": self.config.session_id},
{"Name": "InstanceType", "Value": self.config.instance_type},
],
"Value": 1,
"Unit": "Count",
}],
)
except Exception as e:
logger.warning("CW metric emit failed", extra={"error": str(e)})

if self.config.sns_alert_topic_arn:
try:
boto3.client("sns").publish(
TopicArn=self.config.sns_alert_topic_arn,
Subject=f"[COST ALERT] GPU circuit breaker open — {self.config.session_id}",
Message=(
f"Session: {self.config.session_id}\n"
f"Instance: {self.config.instance_type} x{self.config.instance_count}\n"
f"Rate: ${self._hourly_rate:.2f}/hr\n"
f"Breach: {reason}\n\n"
f"ACTION: Scale GPU fleet to zero immediately."
),
)
except Exception as e:
logger.error("SNS alert failed", extra={"error": str(e)})

def _emit_metrics(self, snapshot: CostSnapshot):
try:
self._cw.put_metric_data(
Namespace=self.config.cloudwatch_namespace,
MetricData=[
{
"MetricName": "AccumulatedCostUSD",
"Dimensions": [{"Name": "SessionId", "Value": self.config.session_id}],
"Value": snapshot.accumulated_cost_usd,
"Unit": "None",
},
{
"MetricName": "HourlyRateUSD",
"Dimensions": [{"Name": "SessionId", "Value": self.config.session_id}],
"Value": snapshot.current_hourly_rate_usd,
"Unit": "None",
},
],
)
except Exception as e:
logger.warning("Cost metric emit failed", extra={"error": str(e)})



Pattern 2: Inference SLI Framework

LLM inference is a latency-sensitive service. It needs SLIs. The three that matter most in production:
  • First-token latency (FTL): Time from request receipt to first generated token. This is what the user feels.
  • Token throughput: Tokens generated per second across the fleet. Proxy for GPU utilization efficiency.
  • Queue depth: Requests waiting for an available GPU slot. Leading indicator of saturation before FTL degrades.
python
import time
from dataclasses import dataclass
from collections import deque
from typing import Optional
import boto3
import logging

logger = logging.getLogger(__name__)

@dataclass
class InferenceSLIConfig:
"""
SLI thresholds for an LLM inference service.

Attributes
----------
service_name : str
Logical name of the inference service (e.g. "llama3-70b-prod").
ftl_p99_budget_ms : float
First-token latency p99 budget in milliseconds.
throughput_min_tokens_per_sec : float
Minimum acceptable token throughput across the fleet.
max_queue_depth : int
Maximum acceptable queue depth before saturation alert.
error_budget_pct : float
Fraction of requests permitted to breach SLI [0.0, 1.0].
Default 0.001 = 99.9% SLO.
measurement_window : int
Number of requests in the rolling measurement window.
cloudwatch_namespace : str
CloudWatch namespace for SLI metrics.
"""
service_name: str
ftl_p99_budget_ms: float
throughput_min_tokens_per_sec: float
max_queue_depth: int
error_budget_pct: float = 0.001
measurement_window: int = 1000
cloudwatch_namespace: str = "SRE/InferenceSLI"

@dataclass
class InferenceObservation:
"""A single inference request observation."""
request_id: str
first_token_latency_ms: float
tokens_generated: int
generation_time_ms: float
queue_wait_ms: float
error: bool = False

@property
def throughput_tokens_per_sec(self) -> float:
if self.generation_time_ms == 0:
return 0.0
return self.tokens_generated / (self.generation_time_ms / 1000)

@dataclass
class SLIReport:
"""
Rolling SLI report for an inference service.

Attributes
----------
service_name : str
window_size : int
Number of observations in this report window.
ftl_p99_ms : float
Observed first-token latency at p99.
ftl_budget_ms : float
Configured FTL budget.
ftl_breaching : bool
True when observed p99 exceeds budget.
throughput_tokens_per_sec : float
Average token throughput across the observation window.
throughput_breaching : bool
True when throughput falls below minimum.
error_rate : float
Fraction of requests in error.
error_budget_remaining_pct : float
Fraction of error budget not yet consumed. Negative = budget exhausted.
budget_exhausted : bool
True when error_budget_remaining_pct < 0.
"""
service_name: str
window_size: int
ftl_p99_ms: float
ftl_budget_ms: float
ftl_breaching: bool
throughput_tokens_per_sec: float
throughput_breaching: bool
error_rate: float
error_budget_remaining_pct: float
budget_exhausted: bool

class InferenceSLITracker:
"""
Rolling SLI tracker for LLM inference services.

Tracks first-token latency, token throughput, and error rate against
configured budgets in a rolling observation window. Emits CloudWatch
metrics on every report so dashboards and alarms stay current.

This applies the same error budget discipline used for traditional
services to LLM inference. The model being impressive does not exempt
the inference service from SLI accountability.

Parameters
----------
config : InferenceSLIConfig
SLI thresholds and reporting configuration.

Example
-------
>>> tracker = InferenceSLITracker(config)
>>> # In the inference request handler:
>>> start = time.time()
>>> first_token_time = wait_for_first_token(request)
>>> response = complete_generation(request)
>>> tracker.record(InferenceObservation(
... request_id=request.id,
... first_token_latency_ms=(first_token_time - start) * 1000,
... tokens_generated=len(response.tokens),
... generation_time_ms=(time.time() - first_token_time) * 1000,
... queue_wait_ms=request.queue_wait_ms,
... ))
>>> report = tracker.report()
>>> if report.budget_exhausted:
... freeze_non_critical_deploys()
"""

def __init__(self, config: InferenceSLIConfig):
self.config = config
self._observations: deque[InferenceObservation] = deque(
maxlen=config.measurement_window
)
self._cw = boto3.client("cloudwatch")

def record(self, obs: InferenceObservation):
"""Record a single inference observation."""
self._observations.append(obs)

def report(self) -> SLIReport:
"""
Compute and emit the current SLI report.

Returns a SLIReport covering the current rolling window.
Also emits all metrics to CloudWatch for dashboards and alarms.
"""
if not self._observations:
return SLIReport(
service_name=self.config.service_name,
window_size=0,
ftl_p99_ms=0.0,
ftl_budget_ms=self.config.ftl_p99_budget_ms,
ftl_breaching=False,
throughput_tokens_per_sec=0.0,
throughput_breaching=False,
error_rate=0.0,
error_budget_remaining_pct=1.0,
budget_exhausted=False,
)

obs_list = list(self._observations)
n = len(obs_list)

ftl_values = sorted(o.first_token_latency_ms for o in obs_list)
p99_idx = max(0, int(n * 0.99) - 1)
ftl_p99 = ftl_values[p99_idx]

avg_throughput = sum(o.throughput_tokens_per_sec for o in obs_list) / n
error_count = sum(1 for o in obs_list if o.error)
error_rate = error_count / n
budget_remaining = self.config.error_budget_pct - error_rate

report = SLIReport(
service_name=self.config.service_name,
window_size=n,
ftl_p99_ms=round(ftl_p99, 2),
ftl_budget_ms=self.config.ftl_p99_budget_ms,
ftl_breaching=ftl_p99 > self.config.ftl_p99_budget_ms,
throughput_tokens_per_sec=round(avg_throughput, 2),
throughput_breaching=avg_throughput < self.config.throughput_min_tokens_per_sec,
error_rate=round(error_rate, 6),
error_budget_remaining_pct=round(budget_remaining, 6),
budget_exhausted=budget_remaining < 0,
)

self._emit(report)

if report.ftl_breaching or report.budget_exhausted:
logger.warning(
"Inference SLI breach detected",
extra={
"service_name": self.config.service_name,
"ftl_p99_ms": report.ftl_p99_ms,
"ftl_budget_ms": report.ftl_budget_ms,
"ftl_breaching": report.ftl_breaching,
"error_rate": report.error_rate,
"budget_exhausted": report.budget_exhausted,
},
)

return report

def _emit(self, report: SLIReport):
try:
dims = [{"Name": "ServiceName", "Value": self.config.service_name}]
self._cw.put_metric_data(
Namespace=self.config.cloudwatch_namespace,
MetricData=[
{"MetricName": "FTL_P99_ms", "Dimensions": dims,
"Value": report.ftl_p99_ms, "Unit": "Milliseconds"},
{"MetricName": "TokenThroughput", "Dimensions": dims,
"Value": report.throughput_tokens_per_sec, "Unit": "Count"},
{"MetricName": "ErrorRate", "Dimensions": dims,
"Value": report.error_rate, "Unit": "None"},
{"MetricName": "ErrorBudgetRemaining", "Dimensions": dims,
"Value": max(0.0, report.error_budget_remaining_pct), "Unit": "None"},
],
)
except Exception as e:
logger.warning("SLI metric emit failed", extra={"error": str(e)})



Pattern 3: Model Artifact Governance Gate

Large model weights need the same deployment governance you apply to application code — version control, checksum validation, rollback path, deployment window compliance. This gate validates all of it before any traffic shift.
python
import hashlib
import json
import boto3
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from typing import Optional

logger = logging.getLogger(__name__)

class ArtifactGateVerdict(str, Enum):
APPROVED = "APPROVED"
BLOCKED_CHECKSUM = "BLOCKED_CHECKSUM"
BLOCKED_WINDOW = "BLOCKED_WINDOW"
BLOCKED_LINEAGE = "BLOCKED_LINEAGE"
BLOCKED_SIZE = "BLOCKED_SIZE"

@dataclass
class ModelArtifact:
"""
A versioned model weight artifact pending deployment.

Attributes
----------
model_id : str
Unique model identifier (e.g. "llama3-70b-instruct-v2-1").
s3_uri : str
S3 URI of the model artifact (e.g. s3://model-registry/llama3-70b/v2.1/).
expected_checksum_sha256 : str
Expected SHA-256 of the artifact manifest file.
training_run_id : str
ID of the training run that produced this artifact (lineage provenance).
size_gb : float
Expected artifact size in GB. Gate checks actual vs expected.
max_size_variance_pct : float
Maximum acceptable size variance from expected. Default 2%.
approved_deployment_windows : list[tuple[int, int]]
List of (start_hour_utc, end_hour_utc) tuples defining when
this artifact may be deployed to production. Empty = no restriction.
"""
model_id: str
s3_uri: str
expected_checksum_sha256: str
training_run_id: str
size_gb: float
max_size_variance_pct: float = 2.0
approved_deployment_windows: list = None

def __post_init__(self):
if self.approved_deployment_windows is None:
self.approved_deployment_windows = []

@dataclass
class ArtifactGateResult:
"""Result of model artifact pre-deployment validation."""
model_id: str
verdict: ArtifactGateVerdict
approved: bool
checks_passed: list[str]
checks_failed: list[str]
block_reason: str = ""
evaluated_at_utc: datetime = None

def __post_init__(self):
if self.evaluated_at_utc is None:
self.evaluated_at_utc = datetime.now(tz=timezone.utc)

def validate_model_artifact(
artifact: ModelArtifact,
s3_client=None,
sns_alert_topic_arn: Optional[str] = None,
) -> ArtifactGateResult:
"""
Pre-deployment governance gate for model weight artifacts.

Validates:
1. Checksum — SHA-256 of the S3 artifact manifest matches expected value
2. Deployment window — current UTC hour falls within an approved window
3. Lineage — training_run_id is resolvable in the artifact metadata
4. Size — actual artifact size within max_size_variance_pct of expected

All checks are logged with full context. Failed checks produce a
BLOCKED verdict and prevent the deployment from proceeding.

Parameters
----------
artifact : ModelArtifact
The artifact pending deployment.
s3_client : boto3 S3 client or None
Injected for testability. Creates a default client if None.
sns_alert_topic_arn : str or None
SNS topic for block notifications.

Returns
-------
ArtifactGateResult
approved=True when all checks pass.

Example
-------
>>> result = validate_model_artifact(
... artifact=ModelArtifact(
... model_id="llama3-70b-v2-1",
... s3_uri="s3://model-registry/llama3-70b/v2.1/",
... expected_checksum_sha256="abc123...",
... training_run_id="run-2025-07-01-001",
... size_gb=140.0,
... approved_deployment_windows=[(2, 6), (14, 18)],
... )
... )
>>> if not result.approved:
... raise RuntimeError(f"Artifact gate blocked: {result.block_reason}")
"""
s3 = s3_client or boto3.client("s3")
now_utc = datetime.now(tz=timezone.utc)
passed = []
failed = []

# --- Check 1: Deployment window ---
if artifact.approved_deployment_windows:
current_hour = now_utc.hour
in_window = any(
start <= current_hour < end
for start, end in artifact.approved_deployment_windows
)
if not in_window:
block_reason = (
f"Deployment outside approved windows. "
f"Current UTC hour: {current_hour}. "
f"Approved windows: {artifact.approved_deployment_windows}"
)
return _blocked(artifact, ArtifactGateVerdict.BLOCKED_WINDOW,
block_reason, passed, failed, sns_alert_topic_arn)
passed.append("DEPLOYMENT_WINDOW")
else:
passed.append("DEPLOYMENT_WINDOW_UNRESTRICTED")

# --- Check 2: Artifact size validation ---
bucket, key_prefix = _parse_s3_uri(artifact.s3_uri)
manifest_key = f"{key_prefix}manifest.json"
try:
head = s3.head_object(Bucket=bucket, Key=manifest_key)
actual_size_bytes = head["ContentLength"]
actual_size_gb = actual_size_bytes / (1024 ** 3)
variance_pct = abs(actual_size_gb - artifact.size_gb) / artifact.size_gb * 100
if variance_pct > artifact.max_size_variance_pct:
return _blocked(
artifact, ArtifactGateVerdict.BLOCKED_SIZE,
f"Size variance {variance_pct:.1f}% exceeds limit {artifact.max_size_variance_pct}%. "
f"Expected: {artifact.size_gb:.1f}GB | Actual: {actual_size_gb:.1f}GB",
passed, failed, sns_alert_topic_arn,
)
passed.append("ARTIFACT_SIZE")
except Exception as e:
return _blocked(artifact, ArtifactGateVerdict.BLOCKED_SIZE,
f"Manifest size check failed: {e}", passed, failed, sns_alert_topic_arn)

# --- Check 3: Checksum validation ---
try:
manifest_obj = s3.get_object(Bucket=bucket, Key=manifest_key)
manifest_bytes = manifest_obj["Body"].read()
actual_checksum = hashlib.sha256(manifest_bytes).hexdigest()
if actual_checksum != artifact.expected_checksum_sha256:
return _blocked(
artifact, ArtifactGateVerdict.BLOCKED_CHECKSUM,
f"Checksum mismatch. Expected: {artifact.expected_checksum_sha256[:16]}... "
f"Actual: {actual_checksum[:16]}...",
passed, failed, sns_alert_topic_arn,
)
passed.append("CHECKSUM")
except Exception as e:
return _blocked(artifact, ArtifactGateVerdict.BLOCKED_CHECKSUM,
f"Checksum validation failed: {e}", passed, failed, sns_alert_topic_arn)

# --- Check 4: Lineage provenance ---
try:
manifest_data = json.loads(manifest_bytes)
recorded_run_id = manifest_data.get("training_run_id", "")
if recorded_run_id != artifact.training_run_id:
return _blocked(
artifact, ArtifactGateVerdict.BLOCKED_LINEAGE,
f"Lineage mismatch. Expected run: {artifact.training_run_id} | "
f"Manifest records: {recorded_run_id}",
passed, failed, sns_alert_topic_arn,
)
passed.append("LINEAGE")
except Exception as e:
return _blocked(artifact, ArtifactGateVerdict.BLOCKED_LINEAGE,
f"Lineage check failed: {e}", passed, failed, sns_alert_topic_arn)

logger.info(
"Model artifact gate: APPROVED",
extra={
"model_id": artifact.model_id,
"checks_passed": passed,
"s3_uri": artifact.s3_uri,
},
)

return ArtifactGateResult(
model_id=artifact.model_id,
verdict=ArtifactGateVerdict.APPROVED,
approved=True,
checks_passed=passed,
checks_failed=[],
)

def _blocked(
artifact: ModelArtifact,
verdict: ArtifactGateVerdict,
reason: str,
passed: list,
failed: list,
sns_arn: Optional[str],
) -> ArtifactGateResult:
failed.append(verdict.value)
logger.error(
"Model artifact gate: BLOCKED",
extra={
"model_id": artifact.model_id,
"verdict": verdict,
"reason": reason,
"checks_passed": passed,
"checks_failed": failed,
},
)
if sns_arn:
try:
boto3.client("sns").publish(
TopicArn=sns_arn,
Subject=f"[MODEL GATE] Deployment blocked — {artifact.model_id}",
Message=(
f"Model: {artifact.model_id}\n"
f"Verdict: {verdict}\n"
f"Reason: {reason}\n"
f"S3 URI: {artifact.s3_uri}\n"
),
)
except Exception as e:
logger.warning("SNS notify failed", extra={"error": str(e)})

return ArtifactGateResult(
model_id=artifact.model_id,
verdict=verdict,
approved=False,
checks_passed=passed,
checks_failed=failed,
block_reason=reason,
)

def _parse_s3_uri(s3_uri: str) -> tuple[str, str]:
"""Parse s3://bucket/key/prefix/ into (bucket, key/prefix/)."""
without_scheme = s3_uri.replace("s3://", "")
parts = without_scheme.split("/", 1)
bucket = parts[0]
key_prefix = parts[1] if len(parts) > 1 else ""
return bucket, key_prefix



The Operational Philosophy

GPU is expensive compute. Model weights are large artifacts. Inference is a latency-sensitive service. These three statements contain the entire design philosophy for production ML infrastructure.
The teams that win aren't the ones with the fanciest models. They're the ones that paired ML talent with infrastructure engineers who had lived through production incidents — and made them fight it out until the system was boring.
These patterns ship as the  gpu_ops  module in the  agentsre  library.


What's the most expensive production lesson your team learned from ML infrastructure? Drop it in the comments.


Tags:  mlops **  aws **  gpu **  llmops **  sre **  platform-engineering **  cost-optimization **  python **  production 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article