Blog→Infrastructure
Artificial intelligenceAI agentsDevOps

How to host AI agents on AWS: Lambda, Fargate or AgentCore?

2 Aug 2026 · approx. 12 min read

The AI agent works on your laptop. It answers, uses tools and handles its first real tasks. But as soon as you make it available to users, new questions appear:

  • What if a single run takes several minutes?
  • Where do you store access keys safely?
  • How do you keep the conversation history after a restart?
  • How do you prevent an infinite loop and an unexpected bill?

In this article we compare three sensible ways to host an AI agent on AWS: AWS Lambda, Amazon ECS with AWS Fargate and Amazon Bedrock AgentCore Runtime. Then we walk through a practical architecture on Fargate — from the Docker image to security, monitoring and long-running tasks.

Quick recommendation: Lambda suits short and irregular tasks. Fargate offers the most control over your own runtime. AgentCore is interesting where you want a managed operation designed specifically for agents.

Developing an AI agent and deploying it to the cloud

Why an AI agent is not deployed like an ordinary API

From the outside, an agent may look like a regular web service: it accepts a request and returns a response. Inside, however, it often performs several steps — calls the model, uses a tool, evaluates the result and continues.

This changes the infrastructure requirements:

  • A run can take seconds or minutes. You need to watch the timeouts of the web server, the API gateway and the load balancer.
  • The response is often streamed. The user should not wait at a blank screen while the agent finishes the whole run.
  • State must not live only in process memory. The conversation, task progress and result need to be stored outside the container or function.
  • Tools have real permissions. An agent can read a database, send e-mails or modify data. Each tool therefore needs limited permissions and clear boundaries.
  • The cost is not just the server. You also pay for tokens, external APIs, network traffic, logs and services that run continuously.

So first clarify one thing: will the agent respond synchronously, or will it work asynchronously in the background?

A synchronous run makes sense for chat and shorter tasks where the client holds the connection and receives the response progressively. For longer work it is more reliable to return a task ID to the user, put the request in a queue and deliver the result later.

Three ways to host an AI agent on AWS

1. AWS Lambda: for short and bursty tasks

Lambda runs your code only when a request arrives. You don’t manage a server, and with low or irregular traffic you don’t pay for idle compute capacity.

It is a good fit, for example, for:

  • classification or data extraction;
  • a simple agent with a few predictable steps;
  • webhooks and asynchronous processing of messages from SQS;
  • a prototype with irregular traffic.

But count on a hard limit: a single Lambda function can run for at most 15 minutes. API Gateway REST API can now stream a response from Lambda, but streaming must be explicitly configured and also has time and network limits. For an agent that may work for tens of minutes, a queue or a different runtime is more appropriate.

A cold start is not a reason to dismiss Lambda automatically. It is, however, worth measuring with your real dependency bundle and in the region where the application will run.

2. Amazon ECS + AWS Fargate: for your own runtime and full control

On ECS Fargate you run the agent as a Docker container without managing virtual servers. You choose the framework, the model, the web server and the streaming method yourself.

Fargate is the right choice when you need:

  • FastAPI, WebSocket or Server-Sent Events;
  • your own agent loop or multiple processes;
  • a long-running API or worker;
  • precise control over CPU, memory, networking and deployment.

You pay for the flexibility with more infrastructure. Besides the container itself you handle networking, a load balancer, scaling, logs and rolling out new versions.

What about AWS App Runner? It deploys a container more simply than ECS, but an HTTP request has a total limit of 120 seconds. For a short API it can be a pleasant choice; for long streams and multi-minute agent runs this limit is fundamental.

3. Amazon Bedrock AgentCore Runtime: a managed runtime for agents

Amazon Bedrock AgentCore Runtime is a serverless environment designed specifically for running agents and their tools. It is not tied to a single framework or to Bedrock models — it supports LangGraph, CrewAI, Strands Agents and custom solutions, for example, and the model can also run outside Amazon Bedrock.

Its main advantages include:

  • isolation of user sessions in separate microVMs;
  • synchronous and asynchronous runs;
  • support for runs of up to eight hours;
  • managed scaling and less infrastructure of your own.

AgentCore makes sense when you want to keep your own agent code but don’t want to build the whole operational foundation on ECS. Before deciding, verify service availability, supported regions, the authentication method and the pricing model for your scenario.

Beware of older tutorials: Amazon Bedrock Agents is now called Bedrock Agents Classic and is not open to new customers. For new projects AWS recommends exploring AgentCore for similar scenarios.

A practical agent architecture on ECS Fargate

Now let’s walk through a universal variant: an agent written in Python exposes an API via FastAPI, runs in ECS Fargate and calls the model via Amazon Bedrock or an external API.

The basic flow looks like this:

Text
Uživatel → HTTPS / Application Load Balancer → ECS Fargate → LLM a nástroje
                                                   ├── DynamoDB (stav)
                                                   ├── Secrets Manager (tajné klíče)
                                                   └── CloudWatch (logy a metriky)

For longer tasks add an asynchronous branch:

Text
API → SQS → Fargate worker → DynamoDB (stav a výsledek)

After submitting, the client receives a job_id and checks the status via the API, WebSocket or a notification. A dropped HTTP connection therefore does not cancel the whole job.

Step 1: Prepare the application to run in a container

Next to the agent endpoint add a simple health check. It should not call the LLM or a remote database — the load balancer needs to verify quickly that the process accepts requests.

Python
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}

A basic Dockerfile can look like this:

DOCKERFILE
FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt \
    && useradd --create-home appuser

COPY --chown=appuser:appuser . .
USER appuser

EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

In production, use pinned dependency versions and tag images with an immutable tag, such as the commit hash. The latest tag makes it hard to trace which version is actually running.

Step 2: Push the image to Amazon ECR

Amazon ECR is a private Docker image registry in AWS:

Bash
AWS_REGION=eu-central-1
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
REPOSITORY_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/muj-agent

aws ecr create-repository --repository-name muj-agent
aws ecr get-login-password --region $AWS_REGION \
  | docker login --username AWS --password-stdin \
    $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com

docker build -t muj-agent .
docker tag muj-agent:latest $REPOSITORY_URI:1.0.0
docker push $REPOSITORY_URI:1.0.0

The commands assume a configured AWS CLI and permissions for ECR. In a team it is better to automate build and push in CI/CD than to run them from a laptop.

Step 3: Create a task definition and an ECS service

A task definition describes the image, CPU, memory, ports, logging and permissions. An ECS service maintains the desired number of instances, replaces crashed tasks and deploys new versions.

Don’t confuse two different IAM roles:

  • The task execution role is used by ECS, for example to pull the image from ECR and send logs.
  • The task role is given to the application itself when it accesses DynamoDB, Bedrock or another AWS service.

Start with a small capacity, but verify CPU and memory with a load test. There is no rule like “1 GB is enough for every agent” — it depends on the libraries, request concurrency and document processing.

Step 4: Store secrets in Secrets Manager

Keys for external LLM APIs don’t belong in code, the repository or the Docker image. Store them in AWS Secrets Manager and reference them in the task definition:

JSON
{
  "secrets": [
    {
      "name": "OPENAI_API_KEY",
      "valueFrom": "arn:aws:secretsmanager:eu-central-1:123456789012:secret:muj-agent/openai"
    }
  ]
}

If the agent calls Amazon Bedrock, it usually needs no long-lived API key at all. Grant access through the task role with the minimum necessary IAM permissions.

Also watch out for rotation: a secret injected into an environment variable does not refresh itself in a running task. After changing the secret you need to replace the task, or load the value at runtime via the SDK.

Step 5: Set up networking, HTTPS and timeouts

In a standard production architecture only the Application Load Balancer is public and the Fargate tasks run in private subnets. The HTTPS certificate can be managed by AWS Certificate Manager.

The default idle timeout of the Application Load Balancer is 60 seconds. If the agent has longer pauses between parts of the stream, adjust the timeout of both the load balancer and the application server and send data continuously. Raising the timeout alone, however, is no substitute for asynchronous processing of long tasks.

A private task that calls a public LLM API needs outbound access via NAT. A NAT Gateway has hourly and data charges, and for a small project it can cost more than the container itself. For AWS services use VPC endpoints where it makes sense, and include the network in your cost estimate before deploying.

Step 6: Store state outside the container

A Fargate task is replaceable. After a restart, neither the conversation history nor information about a task in progress may be lost.

For a typical start, these work well:

  • DynamoDB for sessions, messages, task state and keys against duplicate processing;
  • ElastiCache for Redis for a very fast temporary cache or coordination;
  • S3 for larger documents and outputs.

In DynamoDB, don’t store the whole ever-growing conversation in a single item. You can store individual messages under the partition key session_id and order them with a sort key. Set a TTL for temporary data.

Step 7: Add scaling and safe deployment

An ECS service can scale by CPU, memory or custom metrics. For workers over SQS, a metric based on the number of waiting messages per task is more useful.

When deploying, verify:

  • that the new version’s health check passes before the old one is detached;
  • that a request in progress gets time to finish;
  • that a failed deployment automatically rolls back to the previous version;
  • that messages which fail repeatedly end up in a separate queue for manual inspection (dead-letter queue).

Production checklist: what to watch from day one

Security and permissions

  • Authenticate users and limit the number of requests.
  • Give each tool only the permissions it needs.
  • Have a human confirm destructive operations, such as deleting data or sending a payment.
  • Expect prompt injection: neither user text nor document content is a trusted instruction.
  • Run sensitive code or a shell only in an isolated sandbox with restricted network and time.

Reliability

  • Set a maximum number of steps, run time and token budget.
  • Retry only errors where another attempt makes sense. Gradually lengthen the interval between attempts and add a small random deviation (exponential backoff with jitter).
  • Design write tools idempotently so that a retry does not create two orders or two e-mails.
  • For long tasks use SQS, task state and a dead-letter queue.
  • Make it possible to cancel a run and shut it down safely.

Observability

For each run store the trace ID, the prompt and model version used, the duration of individual steps, tokens, tool calls and errors. Also track success rate, latency, queue length and the cost per completed task.

Don’t send secret keys, personal data or the model’s internal “chain of thought” to logs. For debugging, a structured record of tool inputs and outputs, step-level decisions and technical metrics is enough. You can complement CloudWatch with specialised tracing, such as Langfuse or LangSmith.

Costs

It cannot be said in general that tokens will always be the most expensive item. With Fargate you pay for the task’s reserved CPU and memory; the ALB, public IPv4 addresses, NAT Gateway, data transfer, CloudWatch and Secrets Manager have their own prices too. For a busy agent, models may dominate; for a small internal tool, the fixed network infrastructure may.

Before launch:

  1. make an estimate in the AWS Pricing Calculator;
  2. set up AWS Budgets and alerts;
  3. measure tokens and cost for each type of task;
  4. limit the number of steps and the context size;
  5. regularly review costs by service and tag.

So which option should you choose?

Choose Lambda if a run safely finishes within 15 minutes, traffic is irregular and you don’t need full control over a long connection.

Choose ECS Fargate if you want your own container, long streams, APIs and workers, and you don’t mind managing networking, deployment and scaling.

Choose Bedrock AgentCore Runtime if you want a runtime built specifically for agents, need isolated user sessions or long runs, and prefer a managed platform over your own container architecture.

For a longer process, regardless of platform, separate accepting the request from processing it with a queue. It is more reliable than keeping a single HTTP connection open for tens of minutes.

Conclusion: start with requirements, not with a service

The right architecture does not follow from which service is currently popular. Start with run length, the streaming requirement, the sensitivity of the tools, the expected traffic and how much infrastructure you want to manage.

For a short prototype, Lambda may be best. For your own production APIs and workers, ECS Fargate makes sense. If you want an operating environment designed specifically for agents, look into AgentCore Runtime.

Whatever you choose, from day one store state outside the process, bound the agent loop, use minimal permissions and measure the cost of every run. These fundamentals decide whether a successful prototype becomes a reliable service.

Want to not only build AI agents but also get them into production?

In the AI Agent Developer course you go through
designing the agent loop, working with tools, memory and security — and learn to turn a prototype into a solution
you can run reliably. Hands-on, on real tasks and with a lecturer’s support.

See the AI agents course →

Zdeněk Vais

About the author

Zdeněk Vais

Founder · Senior Principal Software Engineer, Oracle

Zdeněk has been programming since high school. Since then he has gone from programmer through team leader to architect, building large financial systems, scientific applications and IoT solutions for aircraft along the way. He currently works as a senior principal software engineer at Oracle, where he builds the cloud for media services.

Meet our team

← Back to all articles