Managing Memory and Scaling Issues in Production AI Agent Systems

gradient_labs · Tech · 2025 · source Agentic: yes · promotional bias: low · source-backed · extracted with prompt 0.5.6 (schema v2)

Generated from extraction.json — do not edit by hand. Every claim cites verbatim source evidence; stated means the quote directly asserts the claim, implied means it supports it indirectly.

Problem

Domain: Production AI-agent infrastructure reliability

Gradient Labs needed its Cloud Run and Temporal-based customer-conversation agent to keep responding reliably while memory growth, workflow cache sizing, provider latency, and autoscaling behavior interacted in production.

Constraints:

Architecture

Gradient Labs runs a Go-based AI agent on Google Cloud Run, with each conversation represented as a long-running Temporal workflow that manages state, timers, and child workflows. Platform and agent metrics page on-call engineers. When memory alerts fired, the team used redeployment, profiler flame graphs, hypothesis tests, and Temporal cache tuning. When latency later rose, they adjusted LLM failover first, then diagnosed Cloud Run instance under-scaling and restored throughput with minimum instance tuning.

Diagram confidence: explicit (topology described by the source).

flowchart LR
  Conversations["Customer conversation workload"] --> Agent["Cloud Run agent service"]
  Agent --> Workflows["Temporal workflows"]
  Workflows --> Cache["Temporal workflow cache"]
  Workflows --> Child["Child response workflows"]
  Child --> Failover["LLM provider failover"]
  Agent --> Metrics["Platform and agent metrics"]
  Metrics --> Profiler["Profiler investigation"]
  Profiler --> Cache
  Agent --> Autoscaler["Cloud Run autoscaler"]
  Workflows --> TemporalCloud["Temporal Cloud"]
  Cache --> TemporalCloud
Drag to pan · scroll or use +/− to zoom · reconstructed from the source's described component topology

Components

Component Role Interacts with
Customer conversation workload Active conversations that require the AI agent to reply without leaving customers waiting. Cloud Run agent service
Cloud Run agent service Go service hosting the AI agent containers and Temporal workers. Customer conversation workload, Temporal workflows, Cloud Run autoscaler, Platform and agent metrics
Temporal workflows Long-running per-conversation workflows that manage conversation state, timers, and child workflows. Cloud Run agent service, Temporal workflow cache, Child response workflows, Temporal Cloud
Temporal workflow cache Stores workflow execution histories to reduce Temporal Cloud retrievals and latency, but consumes container memory. Temporal workflows, Temporal Cloud
Child response workflows Generate and safeguard AI-agent replies through the system's model-provider and prompt stack. Temporal workflows, LLM provider failover
LLM provider failover Routes around provider incidents when latency suggests an external model-provider problem. Child response workflows
Platform and agent metrics Alerting and observability layer for memory, latency, activity execution rates, provider behavior, and platform health. Cloud Run agent service, Profiler investigation
Profiler investigation Google Cloud Profiler flame graphs used to identify Temporal top-level functions and cache growth as the memory root cause. Platform and agent metrics, Temporal workflow cache
Cloud Run autoscaler Scales container count from HTTP, event, CPU, and crash-handling signals; under-scaled the polling Temporal workload after crashes stopped. Cloud Run agent service
Temporal Cloud Managed Temporal backend that stores workflow histories and schedules activities for workers to execute. Temporal workflows, Temporal workflow cache

Data flow

Customer conversations enter the AI agent service on Cloud Run. Each conversation is handled as a Temporal workflow that stores state, manages timers, and invokes child workflows to generate and safeguard replies. Temporal workers use a workflow cache to avoid repeatedly fetching histories from Temporal Cloud. Metrics and profiler traces feed incident investigation; cache-size and memory changes affect container stability, while Cloud Run instance counts determine how quickly scheduled Temporal activities can start executing.

3 supporting quotes
“our platform and AI agent are written in Go and deployed using Cloud Run. Each conversation that our agent participates in [is a long-running Temporal workflow]”article, stated
“which manages the conversation’s state, timers, and runs child workflows to generate responses.”article, stated
“This cache stores workflow execution histories so that they don't always need to be retrieved from Temporal Cloud when a workflow resumes.”article, stated

Why this architecture

Temporal gives each conversation durable state, timers, and child workflow structure, which fits long-running customer interactions. Cloud Run provides managed container deployment and autoscaling, but the incident shows that workflow polling does not automatically produce the HTTP, event, or CPU signals Cloud Run expects. The architecture therefore needs explicit cache and instance-count tuning, provider failover, and deep observability across the model and infrastructure stack.

3 supporting quotes
“Each conversation that our agent participates in is a long-running Temporal workflow which manages the conversation’s state, timers,”article, stated
“Cloud Run auto-scales, in both directions, and so originally we had been reliant on this and had set a low, non-zero minimum instance count.”article, stated
“Running an AI agent at scale means that we need to finely tune every single layer of our systems: the prompts, the LLM providers, the databases, and all the way through to the containers.”article, stated

Models used: LLMs from multiple providers · AI agent

Scale

Alternatives considered (roads not taken)

Treat the memory alert as a conventional application memory leak

Rejected because: Memory-intensive agent components and parallel processing were inspected, but no retained resources explained the growth.

“There are several different parts of our AI agent that we expect to be memory intensive, particularly parts that are operating with many (variably sized) documents.”article, stated
“We revisited all of these to ensure that resources were not being left in memory when no longer in use. None of these turned up anything useful;”article, stated

Only increase container memory

Rejected because: More memory bought time and showed a plateau, but the durable fix was lowering the Temporal worker cache size.

“we bought ourselves some time by redeploying the agent with more memory. The alert was resolved within minutes, but we knew that a deep investigation was required to get to a root cause.”article, stated
“We closed this out by tuning our worker cache size.”article, stated

Assume increased latency was only an LLM provider incident

Rejected because: Provider failover initially helped, but the recurring cross-provider latency was actually Temporal activities waiting for too few workers.

“Usually, this is an early symptom that one of the many LLM model providers that we use might be about to declare an incident.”article, stated
“This time, however, there were no reported outages from LLM providers (and no other errors, like rate limits).”article, stated

Rely entirely on default Cloud Run autoscaling

Rejected because: The Temporal polling workload did not drive the HTTP, event, or CPU signals that Cloud Run used for scaling.

“Importantly, it auto scales based on incoming HTTP requests, event consumption and CPU utilisation. Since our agent is a Temporal workflow, it had none of these:”article, stated

Patterns

durable-execution (runtime)

Each customer conversation runs as a long-running Temporal workflow that preserves state, timers, and child workflow orchestration across response generation.

“Each conversation that our agent participates in is a long-running Temporal workflow which manages the conversation’s state, timers,”article, stated

observability-tracing (operations)

The team used alerts, platform/agent metrics, Google Cloud Profiler flame graphs, and activity-execution metrics to isolate memory and scaling failures.

“We have alerts across many of our platform and agent metrics, some of which page an on-call Engineer.”article, stated
“The Google Cloud Profiler flame graphs deltas for our agent's memory usage finally shed some light.”article, stated

fallback-strategy (resilience)

When latency looked like an LLM provider incident, the team adjusted its LLM failover system to route around provider degradation.

“one of the many LLM model providers that we use might be about to declare an incident. On that day, that was indeed the case, and so we adjusted our LLM fail-over system”article, stated

latency-optimization (operations)

Temporal cache and Cloud Run instance counts were tuned against latency, network calls, infrastructure cost, and activity-start delays.

“This was a trade-off between: how much memory we need to provision for our instances (infrastructure cost) vs how large we could make the cache (which reduces network calls to Temporal Cloud, and thus overall latency).”article, stated

Tradeoffs

Tune Temporal workflow cache size

Chose Smaller worker cache sized to container memory over Larger cache that reduces Temporal Cloud calls but risks crashes.

Rationale: The smaller cache made memory sustainable while accepting possible latency and network-call costs.

“This was a trade-off between: how much memory we need to provision for our instances (infrastructure cost) vs how large we could make the cache”article, stated
“which reduces network calls to Temporal Cloud, and thus overall latency”article, stated

Buy time during the memory incident

Chose Redeploy with more memory to clear the immediate alert over Keep the service under memory pressure while investigating.

Rationale: The immediate priority was maintaining customer replies while preserving time for deeper root-cause analysis.

“Our top priority is always to ensure that no customers are left hanging: i.e., that our agent is replying in all its active conversations.”article, stated
“we bought ourselves some time by redeploying the agent with more memory. The alert was resolved within minutes, but we knew that a deep investigation was required”article, stated

Set minimum Cloud Run instances explicitly

Chose Manual minimum-instance tuning over Let Cloud Run infer Temporal workload demand from default autoscaling signals.

Rationale: Temporal polling and low CPU did not create the signals Cloud Run needed, so default autoscaling throttled activity execution.

“Importantly, it auto scales based on incoming HTTP requests, event consumption and CPU utilisation. Since our agent is a Temporal workflow, it had none of these:”article, stated
“By manually editing the minimum instance count, we saw an immediate uptick in activity executions and everything returned to normal.”article, stated

Gotchas (what bit them)

A workflow cache can look like a memory leak when its plateau exceeds container limits.

Root cause: Temporal's workflow cache stores execution histories, and the prior container memory limit was below the cache's plateau value.

Resolution: Gradient Labs tested memory and cache-size changes, then tuned the worker cache size down.

“It seemed that we had found our answer: our previous container memory limit was below the cache’s “plateau” value: containers were crashing as the cache was trying to fill up.”article, stated
“We then deployed a change to decrease the worker’s cache size down by 10x.”article, stated

Fixing crashes removed an accidental autoscaling signal.

Root cause: Cloud Run had been keeping enough instances alive partly because it gracefully handled crashing containers; after cache tuning stopped crashes, the service scaled down too far.

Resolution: The team manually increased the minimum instance count, restoring activity execution throughput.

“Cloud Run also attempts to gracefully handle cases where containers are crashing, which had stopped ever since we fixed the workflow cache problem 🤦.”article, stated
“By manually editing the minimum instance count, we saw an immediate uptick in activity executions and everything returned to normal.”article, stated

Temporal polling did not fit Cloud Run's default autoscaling signals.

Root cause: The agent polled Temporal Cloud instead of receiving HTTP requests or consuming events, and CPU utilization was low.

Resolution: The team recognized Cloud Run's signal mismatch and adjusted minimum instances rather than trusting default autoscaling.

“Since our agent is a Temporal workflow, it had none of these: it polls Temporal Cloud (rather than receiving HTTP requests), it does not consume events, and the CPU utilisation had been fairly low.”article, stated

A first plausible latency explanation can hide an internal bottleneck.

Root cause: LLM provider incidents are a common latency cause, but the recurrence cut across providers and prompts.

Resolution: The team checked activity scheduling metrics and found scheduled activities waiting for available workers.

“this apparent change in latency seemed to be across the board, spanning agent skills that used different model providers and prompts”article, stated
“Most of them were scheduled, but then stuck waiting for an available worker to execute them—and there were far too few to execute them swiftly.”article, stated

Evaluation

Gradient Labs used production alerts, profiler flame graphs, deliberate memory and cache-size experiments, latency monitoring, provider-outage checks, Temporal activity scheduling metrics, and manual instance-count intervention to validate root causes and fixes.

Metrics: memory boosted to 5x previous allocation during hypothesis testing · worker cache size decreased by 10x · Temporal scheduling-to-start delay sometimes more than 10x · autoscaling bottleneck identified and fixed in less than an hour · activity execution rate recovered after increasing minimum instances

4 supporting quotes
“To validate whether our problem was indeed related to the workflow cache, we made a sequence of intentional changes:”article, stated
“The first change was to boost the agent’s memory to 5x what it previously had.”article, stated
“We then deployed a change to decrease the worker’s cache size down by 10x.”article, stated
“the time between scheduling and starting to execute our Temporal activities had grown substantially (sometimes more than 10x), while our rate of executions had dropped.”article, stated

Outcomes

The case describes a production customer-conversation AI agent, 5x memory and 10x cache-size experiments, more than 10x Temporal activity scheduling delay, and a sub-hour autoscaling fix.

3 supporting quotes
“The container’s memory continued to grow, but plateaued at a much lower value.”article, stated
“By manually editing the minimum instance count, we saw an immediate uptick in activity executions and everything returned to normal.”article, stated
“Running an AI agent at scale means that we need to finely tune every single layer of our systems: the prompts, the LLM providers, the databases, and all the way through to the containers.”article, stated