
A RAG proof of concept usually runs on a laptop with an API key in a .env file. Production at an enterprise customer means something else: the service runs in private subnets, no long-lived keys exist anywhere, model traffic never crosses the public internet, every deploy can roll back on its own, and the on-call engineer can see token usage and Bedrock throttling on a dashboard. Getting from one to the other is a core Forward Deployed Engineer skill, and it is mostly platform work rather than AI work.
This tutorial deploys a containerised FastAPI RAG service to Amazon ECS on AWS Fargate behind an Application Load Balancer, with Secrets Manager, separate IAM task and execution roles, private subnets with VPC endpoints, CloudWatch logs and metrics, autoscaling, and a CI/CD outline. Retrieval uses Amazon Bedrock Knowledge Bases and generation uses the Bedrock Converse API. All service behaviour was checked against AWS documentation on 5 December 2026. The architecture, names, sizes and thresholds are illustrative; size them from your own load tests.
Why ECS on Fargate rather than EKS
For a single stateless HTTP service that calls managed model and retrieval APIs, ECS on Fargate is the smaller operational footprint: there are no nodes to patch, the service, autoscaling, load balancer registration and rollback are built in, and AWS documents that each Fargate task has its own isolation boundary and does not share the kernel, CPU, memory or network interface with another task. That isolation and the absence of a cluster to run are easy to justify in a customer security review.
Choose EKS instead when the customer already runs an EKS platform with its own GitOps, policy and observability tooling; when you need GPUs in the same cluster (the gpu task definition parameter is not valid for Fargate tasks); or when the system is many services that benefit from Kubernetes-native tooling. Our Kubernetes guide for LLM apps covers that path. The application code and container image below work unchanged on either.
Reference architecture (illustrative)
- VPC across two Availability Zones. Public subnets hold only the ALB. Private subnets hold the Fargate tasks and the interface VPC endpoints. No NAT gateway: every AWS API the task needs is reached through an endpoint.
- Application Load Balancer with an HTTPS listener (certificate from ACM) and an HTTP listener that redirects to HTTPS. One target group of type
ip, port 8000, health check path/healthz. - ECS service on Fargate, desired count 2 or more, tasks in private subnets with
assignPublicIpdisabled. Task security group allows port 8000 only from the ALB's security group. - Bedrock Knowledge Base for retrieval (built as in our production Knowledge Bases tutorial) and a Bedrock model or inference profile for generation, both reached over PrivateLink.
- Secrets Manager for the few secrets the app still needs (for example a database password for chat history). Bedrock itself is called with the task role's temporary credentials, so there is no model API key at all.
- CloudWatch: container logs through the
awslogsdriver, Container Insights with enhanced observability, ALB metrics, and custom metrics (tokens, Bedrock latency, throttles) emitted as Embedded Metric Format log lines.
Step 1: repository structure
rag-service/
app/
main.py # FastAPI app, lifespan, routes
config.py # settings from environment
rag.py # retrieve + generate with Bedrock
metrics.py # CloudWatch Embedded Metric Format helper
tests/
test_api.py # fake Bedrock clients via dependency overrides
deploy/
taskdef.json # ECS task definition template
scaling-policy.json # target tracking configuration
iam/
task-role-policy.json
execution-role-secrets.json
Dockerfile
requirements.txt
.github/workflows/deploy.yml
Step 2: the application
The service exposes a health endpoint, a JSON endpoint and a streaming endpoint. boto3 is synchronous, so the JSON endpoint is a plain def (FastAPI runs it in the threadpool) and the streaming endpoint moves each blocking call off the event loop with asyncio.to_thread. Authentication is left out to keep the focus on the platform; protect /v1 with your identity provider's tokens before go-live (our FastAPI interview guide covers JWT validation).
# app/config.py
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
region: str = os.environ["APP_REGION"] # e.g. ap-south-1
kb_id: str = os.environ["KB_ID"]
model_id: str = os.environ["MODEL_ID"] # model ID or inference profile ID
max_output_tokens: int = int(os.environ.get("MAX_OUTPUT_TOKENS", "800"))
top_k: int = int(os.environ.get("TOP_K", "5"))
settings = Settings()
# app/rag.py
import boto3
from botocore.config import Config
from app.config import settings
# Standard retry mode is boto3's default; set it explicitly with total attempts,
# and keep read_timeout below the ALB idle timeout so the app decides what users see.
_cfg = Config(
region_name=settings.region,
retries={"total_max_attempts": 3, "mode": "standard"},
connect_timeout=5,
read_timeout=55,
)
def make_clients():
return (
boto3.client("bedrock-agent-runtime", config=_cfg), # Retrieve
boto3.client("bedrock-runtime", config=_cfg), # Converse / ConverseStream
)
SYSTEM = ("Answer only from the provided context. If the context does not contain the "
"answer, say you don't know. Cite sources as (1), (2) using the context numbers.")
def retrieve(agent_rt, question: str) -> list[dict]:
resp = agent_rt.retrieve(
knowledgeBaseId=settings.kb_id,
retrievalQuery={"text": question},
retrievalConfiguration={"vectorSearchConfiguration": {"numberOfResults": settings.top_k}},
)
return resp["retrievalResults"]
def build_messages(question: str, chunks: list[dict]) -> list[dict]:
context = "\n\n".join(
f"({i}) {c['content']['text']}" for i, c in enumerate(chunks, start=1)
)
prompt = f"Context:\n{context}\n\nQuestion: {question}"
return [{"role": "user", "content": [{"text": prompt}]}]
def sources(chunks: list[dict]) -> list[dict]:
return [{"n": i, "location": c.get("location"), "score": c.get("score")}
for i, c in enumerate(chunks, start=1)]
# app/metrics.py -- Embedded Metric Format: one JSON log line becomes CloudWatch metrics
import json, time
def emit(route: str, **values: float) -> None:
print(json.dumps({
"_aws": {
"Timestamp": int(time.time() * 1000),
"CloudWatchMetrics": [{
"Namespace": "RagService",
"Dimensions": [["Route"]], # keep dimensions low-cardinality
"Metrics": [{"Name": k, "Unit": "Count" if k.endswith("Tokens") or k == "Throttles"
else "Milliseconds"} for k in values],
}],
},
"Route": route,
**values,
}), flush=True)
# app/main.py
import asyncio, time
from collections.abc import AsyncIterable
from contextlib import asynccontextmanager
from botocore.exceptions import ClientError
from fastapi import FastAPI, HTTPException, Request
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel, ConfigDict, Field
from app import rag
from app.config import settings
from app.metrics import emit
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.agent_rt, app.state.rt = rag.make_clients() # create clients once
yield
app = FastAPI(lifespan=lifespan)
class Ask(BaseModel):
model_config = ConfigDict(extra="forbid")
question: str = Field(min_length=3, max_length=2000)
@app.get("/healthz")
def healthz():
# Liveness only. Never call Bedrock here: a provider slowdown would fail every task.
return {"ok": True}
@app.post("/v1/ask")
def ask(body: Ask, request: Request):
t0 = time.perf_counter()
try:
chunks = rag.retrieve(request.app.state.agent_rt, body.question)
resp = request.app.state.rt.converse(
modelId=settings.model_id,
system=[{"text": rag.SYSTEM}],
messages=rag.build_messages(body.question, chunks),
inferenceConfig={"maxTokens": settings.max_output_tokens, "temperature": 0.2},
)
except ClientError as e:
if e.response["Error"]["Code"] == "ThrottlingException":
emit("ask", Throttles=1)
raise HTTPException(503, "Model busy, retry shortly", headers={"Retry-After": "5"})
raise
usage = resp["usage"]
emit("ask", LatencyMs=(time.perf_counter() - t0) * 1000,
InputTokens=usage["inputTokens"], OutputTokens=usage["outputTokens"])
text = resp["output"]["message"]["content"][0]["text"]
return {"answer": text, "sources": rag.sources(chunks)}
@app.post("/v1/ask/stream", response_class=EventSourceResponse)
async def ask_stream(body: Ask, request: Request) -> AsyncIterable[ServerSentEvent]:
chunks = await asyncio.to_thread(rag.retrieve, request.app.state.agent_rt, body.question)
yield ServerSentEvent(data={"sources": rag.sources(chunks)}, event="sources")
resp = await asyncio.to_thread(
request.app.state.rt.converse_stream,
modelId=settings.model_id,
system=[{"text": rag.SYSTEM}],
messages=rag.build_messages(body.question, chunks),
inferenceConfig={"maxTokens": settings.max_output_tokens, "temperature": 0.2},
)
events = iter(resp["stream"])
while True:
event = await asyncio.to_thread(next, events, None) # blocking read, off the loop
if event is None:
break
if await request.is_disconnected():
break # stop generating for nobody
if "contentBlockDelta" in event:
yield ServerSentEvent(data={"t": event["contentBlockDelta"]["delta"].get("text", "")},
event="token")
elif "metadata" in event:
u = event["metadata"]["usage"]
emit("ask_stream", InputTokens=u["inputTokens"], OutputTokens=u["outputTokens"])
yield ServerSentEvent(raw_data="done", event="done")
The stream follows the ConverseStream event order documented by AWS: messageStart, then content block events including one or more contentBlockDelta, then messageStop with the stop reason, then metadata with token usage and latency. Errors raised mid-stream cannot change the HTTP status any more; production code should catch them inside the generator and send an error event before ending.
Step 3: the container image
# requirements.txt (pin what you tested; these were current on PyPI on 5 Dec 2026)
fastapi[standard]==0.165.1
boto3==1.44.19
# Dockerfile
FROM python:3.14-slim
# Pin the base image by digest in real pipelines so rebuilds are reproducible.
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /code
# Dependencies first: this layer stays cached until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
RUN useradd --uid 10001 --no-create-home appuser
USER 10001
EXPOSE 8000
# Exec form so SIGTERM reaches Uvicorn and lifespan shutdown runs.
# Trust X-Forwarded-* only from inside the VPC (the ALB), not from everyone.
# Keep-alive above the ALB idle timeout, as AWS recommends, to avoid 502s.
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", \
"--proxy-headers", "--forwarded-allow-ips", "10.0.0.0/16", \
"--timeout-keep-alive", "75", "--timeout-graceful-shutdown", "100"]
One Uvicorn process per container: the FastAPI docs recommend handling replication at the orchestrator level rather than running workers inside each container, and ECS scaling then works on task count. Our guide to containerising LLM apps goes deeper into image size, scanning and multi-stage builds.
Step 4: network and VPC endpoints
Because the private subnets have no NAT gateway, the task can reach only what you give it an endpoint for. The ECR documentation states that Fargate tasks on platform version 1.4.0 or later need both ECR interface endpoints and the S3 gateway endpoint (image layers are stored in S3), and that Fargate tasks in a VPC without an internet gateway that use awslogs need the CloudWatch Logs endpoint.
| Endpoint (ap-south-1 shown) | Type | Why the task needs it |
|---|---|---|
com.amazonaws.ap-south-1.ecr.api | Interface | ECR API calls during image pull |
com.amazonaws.ap-south-1.ecr.dkr | Interface (private DNS must be enabled) | Docker registry API for the pull |
com.amazonaws.ap-south-1.s3 | Gateway (associate the private route tables) | Image layers live in S3 |
com.amazonaws.ap-south-1.logs | Interface | awslogs log delivery |
com.amazonaws.ap-south-1.secretsmanager | Interface | Injecting secrets at task start |
com.amazonaws.ap-south-1.bedrock-runtime | Interface | Converse and ConverseStream |
com.amazonaws.ap-south-1.bedrock-agent-runtime | Interface | Knowledge Base Retrieve |
Enable private DNS on the interface endpoints so the SDK's default hostnames resolve to them with no code change; the Bedrock docs note that without private DNS you must pass the endpoint URL explicitly. The endpoints' security group must allow inbound 443 from the task security group. Endpoint policies are a second layer of control; the Bedrock security and private networking guide shows how to restrict the Bedrock endpoints to specific actions and how cross-Region inference interacts with data residency.
Step 5: IAM, the two roles
ECS uses two different roles, and mixing them up is the most common first-deploy failure.
- Task execution role: used by the ECS and Fargate agents, not your code. It pulls the image from ECR, sends logs to CloudWatch and fetches the Secrets Manager values referenced in the task definition. Attach the AWS managed
AmazonECSTaskExecutionRolePolicyand addsecretsmanager:GetSecretValueon the specific secret (pluskms:Decrypton the key if the secret uses a customer managed KMS key). - Task role: the credentials your application code gets through the SDK. It needs only the Bedrock calls the app makes. AWS recommends a separate role per task definition or service with minimum permissions, and
aws:SourceAccount/aws:SourceArnconditions in the trust policy against the confused deputy problem.
Task role policy, deploy/iam/task-role-policy.json (illustrative; scope each Resource to your own ARNs):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Generate",
"Effect": "Allow",
"Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"],
"Resource": ["arn:aws:bedrock:ap-south-1::foundation-model/MODEL_ID"]
},
{
"Sid": "RetrieveFromKnowledgeBase",
"Effect": "Allow",
"Action": ["bedrock:Retrieve"],
"Resource": ["arn:aws:bedrock:ap-south-1:ACCOUNT_ID:knowledge-base/KB_ID"]
}
]
}
Converse needs bedrock:InvokeModel and ConverseStream needs bedrock:InvokeModelWithResponseStream, per the Bedrock user guide. If MODEL_ID is a cross-Region inference profile, the policy must also cover the inference profile ARN and the foundation model in each destination Region; the Bedrock security guide linked above walks through that.
Trust policy used by both roles:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ecs-tasks.amazonaws.com"},
"Action": "sts:AssumeRole",
"Condition": {
"ArnLike": {"aws:SourceArn": "arn:aws:ecs:ap-south-1:ACCOUNT_ID:*"},
"StringEquals": {"aws:SourceAccount": "ACCOUNT_ID"}
}
}]
}
Step 6: secrets
Store secrets as JSON in Secrets Manager and reference individual keys from the task definition. The full valueFrom form is arn:aws:secretsmanager:region:account:secret:name:json-key:version-stage:version-id; trailing fields are optional but their colons are required. Referencing a JSON key or version needs Fargate platform version 1.4.0 or later.
Two behaviours to plan for, both stated in the ECS docs: the value is injected when the container starts, so after a rotation running tasks keep the old value until you launch new tasks (for a service, use Force new deployment); and anything in the container, including logs and debugging tools, can read environment variables, so never log the environment. If a secret must rotate without a redeploy, have the app read it from Secrets Manager at runtime with a short cache instead (task role permission, not execution role).
Step 7: the task definition
{
"family": "rag-api",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "1024",
"memory": "2048",
"runtimePlatform": {"cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX"},
"executionRoleArn": "arn:aws:iam::ACCOUNT_ID:role/rag-api-execution",
"taskRoleArn": "arn:aws:iam::ACCOUNT_ID:role/rag-api-task",
"volumes": [{"name": "tmp"}],
"containerDefinitions": [
{
"name": "rag-api",
"image": "ACCOUNT_ID.dkr.ecr.ap-south-1.amazonaws.com/rag-api:GIT_SHA",
"essential": true,
"portMappings": [{"containerPort": 8000, "protocol": "tcp"}],
"environment": [
{"name": "APP_REGION", "value": "ap-south-1"},
{"name": "KB_ID", "value": "KB_ID"},
{"name": "MODEL_ID", "value": "MODEL_OR_INFERENCE_PROFILE_ID"},
{"name": "MAX_OUTPUT_TOKENS", "value": "800"}
],
"secrets": [
{
"name": "DB_PASSWORD",
"valueFrom": "arn:aws:secretsmanager:ap-south-1:ACCOUNT_ID:secret:rag-api/prod-AbCdEf:db_password::"
}
],
"readonlyRootFilesystem": true,
"mountPoints": [{"sourceVolume": "tmp", "containerPath": "/tmp"}],
"stopTimeout": 120,
"healthCheck": {
"command": ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=3)\" || exit 1"],
"interval": 30,
"timeout": 5,
"retries": 3,
"startPeriod": 30
},
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/rag-api",
"awslogs-region": "ap-south-1",
"awslogs-stream-prefix": "ecs",
"mode": "non-blocking",
"max-buffer-size": "25m"
}
}
}
]
}
Notes on the choices:
- Size. 1 vCPU with 2 GB is one of the documented Fargate combinations (1024 CPU units allow 2 to 8 GB). A RAG API that only calls Bedrock spends most of its time waiting on the network, so start small and let load tests decide.
- Read-only root file system with a bind-mounted
/tmpvolume, since Fargate does not supporttmpfs. stopTimeoutdefaults to 30 seconds and can be at most 120 on Fargate. Long streams need the higher value, with Uvicorn's graceful shutdown set just below it.- Health check: the slim Python image has no
curl, so the command uses Python itself. ECS health check defaults are a 30 s interval, 5 s timeout and 3 retries;startPeriod(0 to 300 s) is off by default. The command runs inside the container, so whatever it calls must exist in the image. - Logging mode. Since 25 June 2025 the ECS default log driver mode is
non-blocking, which keeps the app responsive if log delivery stalls at the cost of possible log loss; it is set explicitly here so the behaviour is visible in review. - Image tag is the git commit SHA, never
latest, so every task definition revision maps to exactly one build.
Step 8: load balancer and service
# Target group: awsvpc tasks REQUIRE target type ip
aws elbv2 create-target-group --name rag-api-tg --protocol HTTP --port 8000 \
--vpc-id VPC_ID --target-type ip \
--health-check-path /healthz --matcher HttpCode=200
# Long answers: raise the ALB idle timeout from its 60 s default
aws elbv2 modify-load-balancer-attributes --load-balancer-arn ALB_ARN \
--attributes Key=idle_timeout.timeout_seconds,Value=120
aws ecs create-service --cluster rag-prod --service-name rag-api \
--task-definition rag-api --desired-count 2 \
--launch-type FARGATE --platform-version 1.4.0 \
--network-configuration "awsvpcConfiguration={subnets=[SUBNET_A,SUBNET_B],securityGroups=[SG_TASKS],assignPublicIp=DISABLED}" \
--load-balancers "targetGroupArn=TG_ARN,containerName=rag-api,containerPort=8000" \
--health-check-grace-period-seconds 60 \
--deployment-configuration "maximumPercent=200,minimumHealthyPercent=100,deploymentCircuitBreaker={enable=true,rollback=true}"
The deployment circuit breaker watches whether new tasks reach RUNNING and then whether they pass ELB and container health checks. With the default BOUNDED_PERCENT threshold of 50, the failure threshold is half the desired count, clamped between 3 and 200, so a two-task service rolls back after 3 failed tasks. Rollback goes to the most recent deployment in COMPLETED state. Add an EventBridge rule on SERVICE_DEPLOYMENT_FAILED so a failed deploy pages someone.
Step 9: autoscaling
CPU is a weak signal for this workload: a task streaming twenty answers is mostly idle while it waits for Bedrock. Track requests per target as the primary signal and keep CPU as a safety net. ECS scales out if any target tracking policy wants to, and scales in only when all of them agree.
aws application-autoscaling register-scalable-target \
--service-namespace ecs --scalable-dimension ecs:service:DesiredCount \
--resource-id service/rag-prod/rag-api --min-capacity 2 --max-capacity 10
deploy/scaling-policy.json (the target value is illustrative; derive it from load tests). The ResourceLabel joins the final part of the load balancer ARN and the final part of the target group ARN with a slash:
{
"TargetValue": 40.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ALBRequestCountPerTarget",
"ResourceLabel": "app/rag-alb/ALB_ID/targetgroup/rag-api-tg/TG_ID"
}
}
aws application-autoscaling put-scaling-policy --policy-name rag-requests \
--service-namespace ecs --scalable-dimension ecs:service:DesiredCount \
--resource-id service/rag-prod/rag-api --policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration file://deploy/scaling-policy.json
Behaviours worth knowing from the ECS docs: target tracking scales out as fast as it can and scales in gradually; it does not scale on insufficient data; scale-in is paused while a deployment is in progress; do not edit the CloudWatch alarms it creates; and ALBRequestCountPerTarget is not supported with the blue/green deployment type. Remember the other ceiling: more tasks do not raise your Bedrock quotas. If throttles climb while tasks scale out, the fix is a quota increase, provisioned capacity or a smaller per-request token budget, not more containers.
Step 10: logs, metrics and alarms
- Container Insights. AWS recommends Container Insights with enhanced observability for container-level CPU, memory, network and disk metrics:
aws ecs update-cluster-settings --cluster rag-prod --settings name=containerInsights,value=enhanced. Its metrics are billed as custom metrics (since 1 October 2026RunningTaskCountis not billed). - ALB metrics. Alarm on
HTTPCode_Target_5XX_Count,HTTPCode_ELB_502_CountandUnHealthyHostCount. Note thatTargetResponseTimemeasures time until the target starts sending response headers, so for a streaming endpoint it reflects time to first byte, not total answer time. - Application metrics through Embedded Metric Format (the
emithelper above): input and output tokens, Bedrock latency and throttle counts. CloudWatch extracts them from the log events; keep dimensions low-cardinality, because every unique dimension combination becomes a billed custom metric (never use a request ID as a dimension). - Logs. Set a retention period on
/ecs/rag-api. Log request IDs, latency, token counts and retrieved document IDs; don't log full prompts or answers unless the customer has agreed to that retention. Bedrock model invocation logging is a separate, account-level decision covered in the Bedrock security guide.
Step 11: CI/CD outline
An outline, not a finished pipeline; our CI/CD for AI applications guide covers evaluation gates in depth.
- Authenticate without stored keys. GitHub Actions requests an OIDC token (
permissions: id-token: write) andaws-actions/configure-aws-credentialsexchanges it for a role viarole-to-assume. The IAM OIDC provider ishttps://token.actions.githubusercontent.comwith audiencests.amazonaws.com; restrict the role's trust policy on thesubclaim to your repository and the protected branch or environment. - Test. Unit tests with fake Bedrock clients via dependency overrides, linting and type checks.
- Build and scan. Build the image, tag it with the commit SHA, scan it, push to ECR.
- Evaluate. Deploy to a staging service and run a fixed RAG evaluation set (faithfulness, retrieval hit rate, refusal behaviour) against it; fail the pipeline on regression. See RAG evaluation metrics for what to measure.
- Release. Render a new task definition revision with the new image, update the production service, and wait for the service to become stable. The circuit breaker handles automatic rollback; a manual approval step before production is common in regulated customers.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Task stops with "The task cannot pull ... There is a connection issue between the task and Amazon ECR" or "Context canceled" | No route to ECR from the private subnet | Create both ECR interface endpoints (private DNS on for ecr.dkr) and the S3 gateway endpoint on the private route tables; allow 443 from the task SG to the endpoint SG |
| "The task can't pull the image. Check that the role has the permissions..." | Execution role lacks ECR permissions, or wrong image URI/tag | Attach AmazonECSTaskExecutionRolePolicy; confirm the tag exists in the repository |
| Task stops with "The task can't pull secrets from AWS Secrets Manager..." | No Secrets Manager endpoint, missing secretsmanager:GetSecretValue on the execution role, missing kms:Decrypt, or wrong ARN or Region | Add the endpoint; fix the execution role; check the ARN. Network failures show strings such as i/o timeout or context deadline exceeded in the message |
| "failed to initialize logging driver" | The log group doesn't exist, or no Logs endpoint | Create /ecs/rag-api (or set awslogs-create-group and grant the permission); add the logs endpoint |
| Targets never become healthy | Target group type instance, task SG not allowing the ALB, wrong health check path, or the app binding to 127.0.0.1 | Use target type ip; allow 8000 from the ALB SG; bind 0.0.0.0; raise health check grace period if start-up is slow |
AccessDeniedException from Bedrock | Bedrock permissions put on the execution role instead of the task role, or Resource ARNs don't match the model or inference profile actually called | Move them to the task role; for inference profiles include the profile and the destination-Region model ARNs |
| Bedrock calls hang, then time out | No bedrock-runtime or bedrock-agent-runtime endpoint, or private DNS off | Create the endpoints with private DNS, or pass endpoint_url explicitly |
ThrottlingException under load | Bedrock quota, not ECS capacity | Return 503 with Retry-After, bound concurrency per task, request quota increases; don't add tasks to fix it |
| Streams cut off around 60 seconds | ALB idle timeout default of 60 s | Raise idle_timeout.timeout_seconds; SSE keep-alive comments keep the connection active |
| Bursts of 502 during deploys | Tasks killed while streams are open, or app keep-alive shorter than ALB idle timeout | Set stopTimeout up to 120 s with matching graceful shutdown; set Uvicorn keep-alive above the ALB idle timeout |
| Deployment rolls back immediately | Circuit breaker counted failed tasks or health checks | Read the service events and stopped-task reasons; run the image locally with the same environment |
| Rotated secret not picked up | Secrets are injected only at container start | Force a new deployment, or read the secret at runtime |
What to take into the customer conversation
The architecture answers the security review's usual questions directly: no static credentials (task role, OIDC for CI), no public IPs on tasks, model and retrieval traffic over PrivateLink, least-privilege roles split by duty, automatic rollback, and metrics for cost and throttling. When you present it, be explicit about what you have not solved yet, such as end-user authentication, multi-Region failover or per-tenant isolation in the knowledge base. That kind of clarity is what the FDE interview scenarios test, and the services behind it are summarised in AWS for AI engineers.
Practise this at Cloud Soft Solutions
Cloud Soft Solutions' AI, GenAI and Agentic AI training includes hands-on labs on containerising RAG services, deploying them to AWS with private networking and IAM roles, and wiring up monitoring and CI/CD. Classes run in our Ameerpet, Hyderabad classroom and online, and you work in real AWS environments rather than slides.
Sources
- Amazon ECS task IAM role, checked 5 December 2026
- Amazon ECS task execution IAM role, checked 5 December 2026
- Pass Secrets Manager secrets through Amazon ECS environment variables, checked 5 December 2026
- Amazon ECS task definition differences for Fargate, checked 5 December 2026
- Amazon ECS task definition parameters, checked 5 December 2026
- ECS API reference: HealthCheck, checked 5 December 2026
- Use an Application Load Balancer for Amazon ECS, checked 5 December 2026
- How the Amazon ECS deployment circuit breaker detects failures, checked 5 December 2026
- Use a target metric to scale Amazon ECS services, checked 5 December 2026
- Amazon ECS and Application Auto Scaling, checked 5 December 2026
- Application Auto Scaling API: PredefinedMetricSpecification, checked 5 December 2026
- Container Insights with enhanced observability for Amazon ECS, checked 5 December 2026
- Amazon ECS account settings, checked 5 December 2026
- Troubleshooting ResourceInitializationError errors, checked 5 December 2026
- CannotPullContainer task errors, checked 5 December 2026
- Amazon ECR interface VPC endpoints, checked 5 December 2026
- Amazon Bedrock interface VPC endpoints, checked 5 December 2026
- Amazon Bedrock: Inference using the Converse API, checked 5 December 2026
- Bedrock Agents Runtime API: Retrieve, checked 5 December 2026
- Service Authorization Reference: Amazon Bedrock actions, checked 5 December 2026
- Application Load Balancer attributes, checked 5 December 2026
- CloudWatch metrics for Application Load Balancers, checked 5 December 2026
- CloudWatch Embedded Metric Format specification, checked 5 December 2026
- Boto3: Retries, checked 5 December 2026
- GitHub Docs: Configuring OpenID Connect in Amazon Web Services, checked 5 December 2026
- FastAPI in Containers: Docker, checked 5 December 2026
- FastAPI: Server-Sent Events, checked 5 December 2026
- Uvicorn settings, checked 5 December 2026
📞 Call +91 96660 19191 · +91 99496 16388 · WhatsApp
Cloud Soft Solutions, 513, 5th Floor, Aditya Enclave, Nilagiri Block, beside Ameerpet Metro Station, Ameerpet, Hyderabad 500016, Telangana, India
Frequently Asked Questions
What is the difference between the ECS task role and the task execution role?
The task execution role is used by the ECS and Fargate agents to pull images, send awslogs logs and fetch secrets referenced in the task definition. The task role supplies credentials to your application code, for example to call Amazon Bedrock.
Which VPC endpoints does a Fargate task in a private subnet need to pull from ECR?
For platform version 1.4.0 or later, both Amazon ECR interface endpoints (ecr.api and ecr.dkr, with private DNS on ecr.dkr) and the Amazon S3 gateway endpoint. Tasks using the awslogs driver without an internet gateway also need the CloudWatch Logs endpoint.
Do ECS tasks pick up a rotated Secrets Manager secret automatically?
No. Secrets referenced in the task definition are injected when the container starts. After an update or rotation you must launch new tasks, for example with Force new deployment on the service.
What target type must an ALB target group use for Fargate tasks?
Tasks using the awsvpc network mode, which Fargate always uses, must be registered with target type ip, not instance, because each task has its own elastic network interface.
Why do long LLM responses get cut off behind an Application Load Balancer?
The ALB connection idle timeout defaults to 60 seconds. Send data at least once per idle period (for example SSE keep-alive comments) or raise idle_timeout.timeout_seconds, valid from 1 to 4000 seconds.
What IAM permissions does Bedrock ConverseStream need?
Calling Converse requires bedrock:InvokeModel and calling ConverseStream requires bedrock:InvokeModelWithResponseStream on the model or inference profile resources being called.



