Why Cloud Run terminates instances with a memory limit exceeded error, how files written to disk and concurrent requests count against memory, how to size the limit, and how to fix code that loads too much at once.

Cloud Run terminates any instance that uses more memory than its limit and logs a message such as "Memory limit of 512 MiB exceeded with 534 MiB used", and the requests that instance was handling fail with a 500 or 503 while a new one starts.
The limit is easy to raise, but on Cloud Run memory also covers files on disk and every concurrent request, so the same service can be fine at low traffic and crash at peak.
The Cloud Run memory limits page lists three things that need to fit: the service executable loaded in memory, the memory the process allocates, and files written to the file system. The default per instance is 512 MiB, and the container image size does not count.
Files are easy to overlook, because Cloud Run's file system is in memory, so a report rendered to /tmp/report.csv, an uploaded video transcoded locally or a library that caches downloads on disk all consume the same budget as the heap, and they stay there until deleted or the instance stops.
New services deployed with gcloud or Terraform accept up to 80 concurrent requests per vCPU on each instance by default, as the concurrency documentation describes. An endpoint that needs 20 MB per request fits easily one at a time and needs 1.6 GB with 80 requests in flight, so a service that passes every test can still crash during a traffic spike.
Two levers exist: lower the maximum concurrent requests for memory-heavy services, which makes Cloud Run start more instances instead, or raise memory to cover the peak. The Cloud Run concurrency guide covers the trade-off.
gcloud run services update orders-api --region europe-west1 --memory 1Gi
Memory and CPU are paired: the memory limits page lists up to 4 GiB with 1 vCPU, up to 8 GiB with 2 vCPU, and up to 32 GiB with 8 vCPU, so a large memory increase may also need --cpu. Raise memory based on what the service uses at peak, which the container memory utilization metric in Cloud Monitoring shows per revision, plus headroom.
GOMEMLIMIT to around 90 percent of the instance memory so the garbage collector reclaims memory before the instance is killed, as the Go GC guide describes.--max-old-space-size above the instance limit.The durable fix for most memory crashes is to stop holding the whole thing at once: read query results in a cursor or in pages, write output to Cloud Storage as it is produced, and return a link instead of a giant response body. That keeps memory flat whatever the size of the customer or the report.
Best fit: size memory from peak usage at the concurrency you run, keep large files out of the local file system, and stream exports.
Encore brings infrastructure from code: a service declares its database and buckets in the application, and when you deploy to GCP, Encore runs the service on Cloud Run or GKE with Cloud SQL and Cloud Storage in your project, as the GCP infrastructure docs describe. This export endpoint writes rows straight from a database cursor into a bucket, so memory use does not depend on how many orders a customer has:
Run in your terminal to get started locally.
// exports/exports.go
package exports
import (
"context"
"encoding/csv"
"fmt"
"strconv"
"time"
"encore.dev/storage/objects"
"encore.dev/storage/sqldb"
)
// migrations/1_create_orders.up.sql:
// CREATE TABLE orders (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
// customer_id text NOT NULL, total_cents bigint NOT NULL,
// created_at timestamptz NOT NULL DEFAULT now());
var db = sqldb.NewDatabase("exports", sqldb.DatabaseConfig{Migrations: "./migrations"})
var reports = objects.NewBucket("order-exports", objects.BucketConfig{})
type ExportResult struct {
URL string `json:"url"`
}
//encore:api public method=POST path=/customers/:customerID/export
func Export(ctx context.Context, customerID string) (*ExportResult, error) {
key := fmt.Sprintf("%s/%d.csv", customerID, time.Now().Unix())
w := reports.Upload(ctx, key)
rows, err := db.Query(ctx, `
SELECT id, total_cents, created_at FROM orders
WHERE customer_id = $1 ORDER BY created_at
`, customerID)
if err != nil {
w.Abort(err)
return nil, err
}
defer rows.Close()
cw := csv.NewWriter(w)
cw.Write([]string{"id", "total_cents", "created_at"})
for rows.Next() {
var id, total int64
var created time.Time
if err := rows.Scan(&id, &total, &created); err != nil {
w.Abort(err)
return nil, err
}
cw.Write([]string{strconv.FormatInt(id, 10), strconv.FormatInt(total, 10), created.Format(time.RFC3339)})
}
cw.Flush()
if err := cw.Error(); err != nil {
w.Abort(err)
return nil, err
}
if err := rows.Err(); err != nil {
w.Abort(err)
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
signed, err := reports.SignedDownloadURL(ctx, key, objects.WithTTL(15*time.Minute))
if err != nil {
return nil, err
}
return &ExportResult{URL: signed.URL}, nil
}
rows.Next reads from the database as the CSV is written, and the bucket writer streams the upload, so nothing is buffered in full in memory or in the in-memory file system. The object storage docs cover Upload, Abort and signed URLs, and the databases docs cover row iteration. encore run starts Postgres and a local object store, so you can seed a large customer and run the export locally, checking time and memory before it reaches Cloud Run.
An AI coding agent asked to "add a CSV export" tends to build the file in memory because that is the shortest code, so having a streaming export like this one in the codebase gives it a pattern to copy, and it can run the result against local infrastructure in the same change. If one service needs more memory than the rest, the infrastructure configuration docs describe running it as its own process.
Best fit: services on Cloud Run that produce exports, reports or processed files of unpredictable size.
The container used more memory than the instance's limit, which is 512 MiB by default, so Cloud Run terminated the instance. Memory includes the process, everything it allocates and any files written to the container's file system, which is held in memory.
Run gcloud run services update SERVICE --memory 1Gi, or set the memory in the console or in your infrastructure code. Higher memory needs more CPU, for example more than 4 GiB requires at least 2 vCPU.
Yes. The container file system is in memory, so a 300 MB temporary file uses 300 MB of the instance's memory limit until it is deleted. Stream large files to Cloud Storage instead of writing them locally.
Stream large data to an Encore bucket with bucket.Upload instead of building it in memory or in /tmp, and return a signed download URL. The export endpoint runs against local Postgres and object storage with encore run, so you can test it with a large dataset first.
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.