Square CloudSquare Cloud

Best way to host an AI agent

For agents that run for minutes, use an API that queues the task and an always-on worker that runs the loop. Serverless functions suit short agents, and a VPS fits when you need control of the whole machine.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Understand what changes when you host an AI agent instead of a chatbot
  • Compare serverless, containers, a VPS and a queue with a worker on the criteria that matter
  • Build a queue and worker that resumes the agent after a failure
On this page

A chatbot answers a question and is done. An AI agent gets a goal and works in a loop: the model asks for a tool, your code runs it, the result goes back to the model, and that repeats until the task is finished. The loop can take two seconds or twenty minutes, and that duration decides where it should run.

Below are the four most common options (a serverless function, an always-on container, a VPS and a queue with a worker), compared on what matters for an agent. To write the loop itself, see LangChain, LlamaIndex, AI SDK or the provider SDK.

What changes when you host an agent instead of a chatbot?#

  • Unpredictable duration. Each step adds a model call, a few seconds, plus a tool run. The model decides how many steps the task takes, so every agent needs a step limit.
  • It is mostly waiting. The process spends most of its time waiting on the network. The CPU sits idle but the clock keeps running, and on platforms that bill by duration the waiting shows up on the bill.
  • State that grows. In the most common format, you resend the loop's history (messages, calls and results) at every step. If the process dies at step 12 without having saved that history, the task starts over.
  • Side effects. Tools write to databases, send emails, open tickets, each with its own credential. Rerunning a whole task after a failure can repeat those effects.

Which criteria decide where the agent runs?#

Criterion Question to ask What changes
Duration How long is the longest task, not the average? Past a few minutes, per-invocation deadlines become a risk
State Must the task survive a restart? Needs a checkpoint in a queue or database
Streaming Does the user watch each step live? Needs a long-lived connection (SSE or WebSocket)
Cost Do you pay by duration or for fixed capacity? With a lot of waiting, duration billing gets expensive
Secrets Who else runs on the same machine? Tools that execute code need isolation
Concurrency How many tasks can the model provider take in parallel? Caps the number of workers and causes 429 errors

Streaming progress uses the same techniques as a chat, explained in how to stream AI responses. When many agents run at once, the provider's limit shows up as a 429 error.

Is a serverless function enough for an agent?#

It works for short, event-driven agents: classify a ticket and open a task, answer a webhook in two or three steps. An AWS Lambda function runs for up to 30 minutes per invocation, and a Google Cloud Run service accepts requests of up to 60 minutes (5 by default). Google itself recommends that requests longer than 15 minutes be idempotent or resumable, because the client may reconnect to a different instance.

The weak points: the environment can be discarded between invocations (the history goes to a database), duration billing includes the wait on the model, and a fresh environment has a cold start. The full comparison is in serverless vs containers.

There is a middle ground: durable execution platforms. Lambda durable functions save a checkpoint at each step, resume after an interruption by skipping work already done, don't charge for compute while waiting, and one execution can last up to a year. In exchange, your code depends on the provider's durable execution SDK.

Always-on container or VPS?#

An always-on container runs the agent as a continuous process: no per-invocation deadline, long-lived connections for streaming and in-memory state while the process lives. The cost is fixed by the reserved capacity, not by the time spent waiting. Restarts and deploys wipe memory, so you still need checkpoints.

A VPS gives you control of the whole machine: root access, a headless browser, system tools, a sandbox for code the agent generates. In exchange, you handle security updates, the firewall, TLS, the process supervisor and monitoring. The differences are in VPS vs cloud platform. An agent that runs model-generated code should run that code in an isolated environment, never in the same process that holds the keys.

Why use a queue and a worker for long tasks?#

The pattern separates whoever takes the request from whoever does the work. The API writes the task to a queue and answers right away with 202 and an ID; a worker, a separate process, runs the loop and stores the result; the client polls the ID. No HTTP request stays open for twenty minutes, the queue keeps the tasks if the worker restarts, and you control how many run in parallel. Queues with BullMQ and Celery are covered in detail in how to run background jobs.

Here is an example in Node.js with BullMQ, a queue built on Redis (npm install bullmq ioredis express openai). First the API:

js
// api.mjs: takes the request, queues it and returns the ID right away
import { Job, Queue } from "bullmq";
import express from "express";
import { Redis } from "ioredis";

const queue = new Queue("agent", { connection: new Redis(process.env.REDIS_URL) });
const app = express();
app.use(express.json());

app.post("/tasks", async (req, res) => {
  const job = await queue.add(
    "run",
    { request: String(req.body.request).slice(0, 2000) },
    { attempts: 3, backoff: { type: "exponential", delay: 10_000 } },
  );
  res.status(202).json({ id: job.id });
});

app.get("/tasks/:id", async (req, res) => {
  const job = await Job.fromId(queue, req.params.id);
  if (!job) return res.status(404).json({ error: "task not found" });
  res.json({
    state: await job.getState(), // waiting, active, completed, failed...
    progress: job.progress,
    result: job.returnvalue,
    error: job.failedReason,
  });
});

app.listen(Number(process.env.PORT ?? 3000), "0.0.0.0");

Then the worker, which runs the tool calling loop with the OpenAI SDK and saves a checkpoint at each step:

js
// worker.mjs: a separate process that runs the agent loop
import { Worker } from "bullmq";
import { Redis } from "ioredis";
import OpenAI from "openai";

const connection = new Redis(process.env.REDIS_URL, { maxRetriesPerRequest: null });
const openai = new OpenAI(); // reads OPENAI_API_KEY from the environment
const MODEL = process.env.OPENAI_MODEL;
const MAX_STEPS = 20;

const tools = [
  {
    type: "function",
    name: "daily_sales",
    description: "Orders and revenue for the store on a given day (YYYY-MM-DD).",
    strict: true,
    parameters: {
      type: "object",
      properties: { day: { type: "string" } },
      required: ["day"],
      additionalProperties: false,
    },
  },
];

async function dailySales({ day }) {
  // Replace with a query to your database (read-only)
  return JSON.stringify({ day, orders: 42, revenue: 3150.9 });
}

const worker = new Worker(
  "agent",
  async (job) => {
    // Resume from the last saved step if the task ran before (retry or restart)
    const items = job.data.items ?? [{ role: "user", content: job.data.request }];
    for (let step = job.data.step ?? 1; step <= MAX_STEPS; step++) {
      const response = await openai.responses.create({ model: MODEL, tools, input: items });
      items.push(...response.output);
      const calls = response.output.filter((item) => item.type === "function_call");
      if (calls.length === 0) return { text: response.output_text, steps: step };

      for (const call of calls) {
        const output = await dailySales(JSON.parse(call.arguments));
        items.push({ type: "function_call_output", call_id: call.call_id, output });
      }
      // Checkpoint: the loop state lives in Redis, not only in process memory
      await job.updateData({ ...job.data, items, step: step + 1 });
      await job.updateProgress({ step });
    }
    throw new Error(`the agent went past ${MAX_STEPS} steps`);
  },
  { connection, concurrency: 4 },
);

worker.on("failed", (job, err) => console.error(`task ${job?.id} failed: ${err.message}`));

What each detail solves:

  • maxRetriesPerRequest: null is required on the worker's connection: without it, BullMQ throws an exception. BullMQ declares ioredis as an optional peer dependency, which is why it is in the npm install.
  • concurrency: 4 caps how many tasks the process runs at once. Match it to your provider's request limits.
  • attempts and backoff retry after a failure. With the checkpoint in job.updateData, the new attempt continues from the last saved step. A task whose worker stops renewing its lock is marked as stalled and goes back to the queue, up to a limit.
  • Tools with side effects (charging, sending email) must be idempotent, with one key per action, because a step interrupted halfway can run again.

To notify the client without polling, BullMQ's QueueEvents class emits progress and completed events, which the API can forward over SSE.

How do you handle the agent's state, secrets and limits?#

  • State outside memory. Beyond the task's checkpoint, conversations that continue days later go to a database, with one ID per conversation.
  • Three caps. Number of steps, total time and tokens per task. A task that hits any of them fails with a clear message instead of burning the budget.
  • Secrets per process. The tools' keys live in the worker's environment variables; the API doesn't need them. Never put a key in the prompt, because the model may repeat it.
  • Least privilege. OWASP lists excessive agency among the risks of LLM applications and recommends limiting tools to what is needed, giving them minimal permissions and requiring human approval for high-impact actions.
  • External content is suspect. Pages, emails and documents the tools read can carry hidden instructions. Read what prompt injection is.
  • Log every step: the tool called, its arguments (without secrets), duration and tokens.

Which one should you pick for each scenario?#

Scenario Recommendation
Short agent triggered by a webhook, done in seconds Serverless function
Chat where the user follows every step Always-on container with streaming (SSE or WebSocket)
Tasks that take minutes (reports, research, migrations) API, queue and an always-on worker
Tasks that wait hours for human approval Queue with state in a database, or durable execution
Agent that runs generated code or drives a browser VPS or container with an isolated sandbox
Agent that runs every day at the same time A cron job that queues the task for the worker
Prototype A single process with a step limit; add the queue when tasks get longer

There is no universal winner: the duration of the longest task, and what happens when it gets interrupted, decide almost everything.

How to do this on Square Cloud#

On Square Cloud, the queue pattern becomes two applications and a database. The API is a web application: it listens on 0.0.0.0 on the port in the PORT variable, gets a *.squareweb.app subdomain with HTTPS and uses at least 512 MB of the plan's RAM pool. The worker is a separate application without a subdomain, which receives no inbound traffic and needs at least 256 MB. Both run in always-on containers, with no cold start and no sleep on inactivity. With automatic restart on, a worker that exits with an error comes back by itself; after running out of memory it doesn't, so raise its RAM and start it again. The proxy doesn't cut long connections, and the progress SSE passes through unbuffered.

The queue's Redis can live in the same account, from the Standard plan (R$44.99 per month): at least 512 MB, persistence and mandatory TLS, with a rediss:// URL and the client trusting the CA downloaded from the dashboard. It closes idle clients after 5 minutes, so keep the client's automatic reconnection on. One application can't read another's variables: set REDIS_URL on both and the tools' keys only on the worker.

For the model, the AI Gateway, also from Standard, serves cubic through an OpenAI-compatible API, with function calling (up to 32 tools) and streaming. The worker then uses chat.completions.create from the OpenAI SDK, with tool_calls and role: "tool" messages, and resends the history at each step, since the gateway keeps no state (up to 500 messages). Match concurrency to the plan's simultaneous requests (up to 4 on Standard, with 1 second between requests, 8 on Pro and 16 on Enterprise), retry after concurrent_limit_reached and wait for the daily reset at 00:00 UTC after daily_limit_reached. See plans and runtimes on API hosting.

AI

Host AI apps in always-on containers

API hosting

FAQs

Can an AI agent run in a serverless function?

Yes, if the task finishes well before the invocation time limit: up to 30 minutes on AWS Lambda, and up to 60 minutes per request on a Cloud Run service. For longer agents, use an always-on worker or a platform with durable execution.

Why use a queue for an AI agent?

Because the HTTP request doesn't have to wait for the agent to finish. The API writes the task to the queue and answers right away with an ID; a worker runs the loop, saves progress and retries if something fails.

How much memory does an AI agent need?

Little, if the model runs at a provider behind an API: the process spends most of its time waiting on the network. Usage grows with the history kept in memory, with heavy tools such as a browser, and with parallel tasks. Measure under real load.

Where should I keep the keys the agent's tools use?

In environment variables of the process that runs the tools, never in the prompt or the code. Give each key only the permission its tool needs, read-only when possible.

Next articleHow to use an AI agent to fix deploy errorsTo fix a failed deploy with AI, give the agent the full log, the start command and your dependencies, ask for the cause before the fix and review every change.