Nov 18, 202610 min read

How to Deploy a Mastra Agent to Your Own AWS or GCP Account

Run a Mastra agent with tools and Postgres-backed memory inside a TypeScript service, keep the model key in a secret, and deploy it to your own cloud.

Illustration for How to Deploy a Mastra Agent to Your Own AWS or GCP Account

Mastra is a TypeScript framework for agents: an Agent with instructions, a model and tools, plus memory, workflows and a local Studio for testing. Getting an agent to answer in Studio takes a few minutes. Getting it in front of users means a database for its memory, a model API key stored outside .env, authentication so one user cannot read another user's threads, and somewhere to run it.

This guide builds a small order-support agent with @mastra/core 1.x and deploys it to your own AWS or GCP account. The agent's memory lives in Postgres through Mastra's own PostgresStore, and its tool reads from the same database.

What You Will Build

One service called support with:

  • An orders table the agent can query through a tool.
  • A Mastra Agent with one tool, lookup-order, and Memory backed by PostgresStore.
  • POST /chat/:threadId, an authenticated endpoint that sends the user's message to the agent and returns the reply, with history scoped to that user.

Two Ways to Run Mastra in Production

Mastra's deployment docs describe two broad routes, and the choice decides how much infrastructure you own.

Mastra server (mastra build)Agent inside your own API
What runsA standalone Hono server generated from src/mastraYour service, which constructs the Agent and calls generate
HTTP routesMastra's routes for agents and workflowsThe routes you define, with your auth and validation
Memory storageAny Mastra storage adapterSame, often the database your app already uses
Fits whenThe agent is the whole productThe agent is one feature of a larger backend

The rest of this guide takes the second route, which suits a support agent that has to read order data and sit behind the same auth as the rest of the app. The first route is covered in the DIY section further down.

Set Up the Project

You need Node.js 22.13 or later, which Mastra lists as its minimum, Docker for the local database, and the Encore CLI. Install the CLI with the command for your operating system, create an app from the Empty app template, and add the Mastra packages:

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create mastra-support$ cd mastra-support$ npm install @mastra/core @mastra/memory @mastra/pg @ai-sdk/openai zod
// support/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("support");

How Encore Provides the Database and the Key

Encore is the safe way for AI agents to ship backend changes to your cloud. Here it supplies the two things the Mastra agent needs from outside its own code. The Postgres database is declared in TypeScript, encore run starts it locally in Docker, and a deploy creates it as RDS or Cloud SQL. The OpenAI key is a secret, set once per environment and stored in your cloud's secret manager rather than in the repository, so a coding agent working in the repo cannot read the production value. A local override in .secrets.local.cue is readable if it is present.

Add the Database

The migration only creates the app's own table. Mastra creates its memory tables itself on first use.

-- support/migrations/1_create_orders.up.sql CREATE TABLE orders ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, status TEXT NOT NULL, carrier TEXT, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX orders_user ON orders (user_id);
// support/db.ts import { SQLDatabase } from "encore.dev/storage/sqldb"; export const db = new SQLDatabase("support", { migrations: "./migrations" });

db.connectionString returns the connection string for whichever environment the code runs in, which is how ORMs and other libraries connect to an Encore database. Mastra's PostgresStore uses it the same way.

Define the Tool

createTool takes an id, a description the model reads, a Zod input schema and an execute function. In Mastra 1.x, execute receives the parsed input as its first argument and an execution context as its second.

The tool only returns orders that belong to the signed-in user. The model chooses the order ID, so the ownership check has to happen in code rather than in the prompt.

// support/tools.ts import { createTool } from "@mastra/core/tools"; import { z } from "zod"; import { db } from "./db"; export function lookupOrderTool(userId: string) { return createTool({ id: "lookup-order", description: "Look up the status and carrier of one of the user's orders by order ID.", inputSchema: z.object({ orderId: z.string() }), outputSchema: z.object({ found: z.boolean(), status: z.string().optional(), carrier: z.string().optional(), updatedAt: z.string().optional(), }), execute: async ({ orderId }) => { const row = await db.queryRow<{ status: string; carrier: string | null; updated_at: Date }>` SELECT status, carrier, updated_at FROM orders WHERE id = ${orderId} AND user_id = ${userId}`; if (!row) return { found: false }; return { found: true, status: row.status, carrier: row.carrier ?? undefined, updatedAt: row.updated_at.toISOString(), }; }, }); }

Create the Agent with Postgres Memory

The model key is a secret. Secret values are read at runtime, so the provider is created inside a function rather than at module load. Memory keeps the last 20 messages of each thread and stores them through PostgresStore, which points at the service's own database.

// support/agent.ts import { Agent } from "@mastra/core/agent"; import { Memory } from "@mastra/memory"; import { PostgresStore } from "@mastra/pg"; import { createOpenAI } from "@ai-sdk/openai"; import { secret } from "encore.dev/config"; import { db } from "./db"; import { lookupOrderTool } from "./tools"; const openaiKey = secret("OpenAIKey"); let memory: Memory | undefined; function getMemory(): Memory { memory ??= new Memory({ storage: new PostgresStore({ id: "support-memory", connectionString: db.connectionString }), options: { lastMessages: 20 }, }); return memory; } export function supportAgent(userId: string): Agent { const openai = createOpenAI({ apiKey: openaiKey() }); return new Agent({ id: "support-agent", name: "Order support", instructions: "You help customers with questions about their orders. " + "Always call lookup-order before describing an order. " + "If the order is not found, say so and ask the customer to check the ID.", model: openai("gpt-5-mini"), tools: { lookupOrder: lookupOrderTool(userId) }, memory: getMemory(), }); }

The agent is built per request so the tool is bound to the caller's user ID. The Memory instance, and with it the Postgres connection pool, is created once and shared.

Add Auth and the Chat Endpoint

An auth handler validates the Authorization header before any endpoint marked auth: true runs. The example checks a token against a secret, which is enough to try the flow. Replace it with your real session or JWT check.

// support/auth.ts import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { secret } from "encore.dev/config"; const demoToken = secret("DemoToken"); interface AuthParams { authorization: Header<"Authorization">; } interface AuthData { userID: string; } export const auth = authHandler<AuthParams, AuthData>(async (params) => { // Demo only: "Bearer <token>:<userID>". Swap in your session or JWT check. const [token, userID] = params.authorization.replace("Bearer ", "").split(":"); if (token !== demoToken() || !userID) { throw APIError.unauthenticated("invalid token"); } return { userID }; }); export const gateway = new Gateway({ authHandler: auth });

The chat endpoint passes the user ID from the auth data as Mastra's resource and builds the thread ID from the user ID plus the ID in the path. Mastra loads history by thread, so prefixing it with the user ID keeps one user from reading another user's conversation by guessing a thread ID.

// support/chat.ts import { api } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; import { supportAgent } from "./agent"; interface ChatRequest { threadId: string; message: string; } interface ChatResponse { reply: string; } export const chat = api( { expose: true, auth: true, method: "POST", path: "/chat/:threadId" }, async ({ threadId, message }: ChatRequest): Promise<ChatResponse> => { const { userID } = getAuthData()!; const result = await supportAgent(userID).generate(message, { memory: { thread: `${userID}:${threadId}`, resource: userID }, maxSteps: 5, }); return { reply: result.text }; }, );

Run It Locally

Set the secrets for local development, then start the app. encore run starts Postgres in Docker, applies the migration, and serves the API on port 4000 with a local dashboard for traces.

~/mastra-support
$ encore secret set --type dev,local OpenAIKey$ encore secret set --type dev,local DemoToken$ encore run

Insert a test order with encore db shell support and ask about it:

~/mastra-support
$ curl -X POST localhost:4000/chat/t1 \ -H "Authorization: Bearer <DemoToken>:user-42" \ -d '{"message":"Where is order A-1001?"}'

A second message on t1 such as "Which carrier was that again?" is answered from memory, because Mastra loads the earlier turns for that thread and resource. The trace in the local dashboard shows the HTTP request and the SQL queries, including the ones PostgresStore runs against its own tables.

Deploy to AWS or GCP

Set the production values, then push:

~/mastra-support
$ encore secret set --type prod OpenAIKey$ encore secret set --type prod DemoToken$ git add -A && git commit -m "Mastra support agent"$ git push encore main

In the Encore dashboard, connect your AWS or GCP account and create an environment on it. For this app, a deploy creates one Postgres database (RDS on AWS, Cloud SQL on GCP), stores both secrets in Secrets Manager or Secret Manager, and runs the service as a container on ECS Fargate or Cloud Run. Encore provisions an IAM role for the service, or a service account on GCP. A deploy fails if a secret the code uses has no value in that environment, so a missing key shows up before traffic does.

Doing It Yourself with the Mastra Server

If you prefer the standalone server, the work splits into the same pieces, owned by you:

  1. Build. mastra build writes a Node.js server to .mastra/output. Wrap it in a Dockerfile on a Node.js 22.13 or later base image and push it to ECR or Artifact Registry.
  2. Database. Create an RDS for PostgreSQL or Cloud SQL instance in private subnets, a database user for the app, and security group or VPC connector rules that let the container reach it. Pass the URL to PostgresStore. The Mastra server guide warns against keeping a SQLite database file in the folder that gets copied into the build output.
  3. Secrets. Store the OpenAI key in Secrets Manager or Secret Manager and inject it into the task definition or Cloud Run service as an environment variable. Grant the task role or service account read access to that one secret.
  4. Run. Create an ECS service behind an Application Load Balancer, or a Cloud Run service. Long agent runs need the load balancer idle timeout and the Cloud Run request timeout raised above the defaults, which are 60 seconds and 5 minutes.
  5. Auth. Mastra's server has its own auth options. Configure them, or put the server behind an API gateway that validates your tokens.

This is a reasonable amount of Terraform or console work for one agent, and it is repeated for each environment. The difference with the Encore route is where the database and secrets are declared, not what gets created in your account.

Production Notes

  • Memory tables. PostgresStore creates and alters its tables on first use. For tighter control, set disableInit: true and run storage.init() from your deploy pipeline instead.
  • Tool permissions. Anything a tool can reach, the model can reach. Scope every query in a tool to the authenticated user, as lookup-order does, and keep write tools behind explicit confirmation.
  • Timeouts. A tool-calling loop can take tens of seconds. maxSteps: 5 on the generate call caps the loop. Keep a cap and return a clear error when the model provider is slow.
  • Model provider. Switching to another provider is one import and one secret, for example @ai-sdk/anthropic and an AnthropicKey secret.

Frequently asked questions

How do I deploy a Mastra agent to AWS or GCP?

Either build the standalone Mastra server with mastra build and run the output as a container on ECS, Cloud Run or a VM, with a Postgres database and a secret store you set up yourself, or call the agent from an API endpoint in an existing TypeScript backend and deploy that backend. Both need a Postgres database for memory and a secret for the model API key.

Where does Mastra store agent memory in production?

Memory needs a storage adapter. PostgresStore from @mastra/pg takes a connection string and creates its own tables on first use, so production memory can live in the same Postgres database as the rest of your data. Pass a thread and a resource on each generate call so history is grouped per conversation and per user.

Does Mastra need its own server?

No. Mastra ships a Hono-based server you can build with mastra build, but an Agent is a plain TypeScript object. You can construct it in any Node.js process and call agent.generate from your own HTTP handlers.

What Node.js version does Mastra need?

Mastra's deployment docs list Node.js 22.13.0 or later, Bun, Deno and Cloudflare as supported runtimes.

Can I run a Mastra agent without writing Terraform?

Yes. With Encore the database and the API key secret are declared in the TypeScript code next to the agent, encore run starts Postgres locally, and a git push provisions RDS or Cloud SQL and Secrets Manager or Secret Manager in your own AWS or GCP account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders