Skip to main content
RapidDev - Software Development Agency
firebase-tutorial

How to Increase Memory Allocation for a Firebase Cloud Function

Firebase Cloud Functions v2 let you set memory from 128 MB to 32 GB using the memory option in your function definition. Pass it directly in onCall, onRequest, or event trigger options. Higher memory automatically increases CPU allocation. Monitor memory usage in Cloud Console logs to pick the right tier and avoid paying for resources you do not need.

What you'll learn

  • How to configure memory and CPU for v2 Cloud Functions using function options
  • How to monitor memory usage to determine the right allocation
  • How to set different memory for different functions in the same project
  • How to migrate memory settings from v1 runWith to v2 options syntax
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Beginner9 min read10-15 minFirebase Cloud Functions v2 (2nd gen), firebase-functions v4+, Node.js 18/20/22March 2026RapidDev Engineering Team
TL;DR

Firebase Cloud Functions v2 let you set memory from 128 MB to 32 GB using the memory option in your function definition. Pass it directly in onCall, onRequest, or event trigger options. Higher memory automatically increases CPU allocation. Monitor memory usage in Cloud Console logs to pick the right tier and avoid paying for resources you do not need.

Configuring Memory for Firebase Cloud Functions

Cloud Functions run in containers with fixed memory limits. When a function exceeds its allocation, it crashes with an out-of-memory error. Firebase Cloud Functions v2 (built on Cloud Run) support memory from 128 MB to 32 GB, configured directly in the function definition. This tutorial shows you how to set memory for different function types, monitor usage, and choose the right allocation for your workload.

Prerequisites

  • A Firebase project on the Blaze (pay-as-you-go) plan
  • Firebase CLI installed and logged in (firebase-tools v12+)
  • Cloud Functions already deployed or a functions directory initialized
  • Basic familiarity with writing Cloud Functions in TypeScript or JavaScript

Step-by-step guide

1

Set memory in a v2 onRequest function

For v2 HTTP functions, pass the memory option directly in the onRequest or onCall options object. The memory value is a string like '256MiB', '512MiB', '1GiB', '2GiB', up to '32GiB'. Firebase automatically assigns CPU based on memory: 1 vCPU for up to 2 GiB, 2 vCPUs for up to 4 GiB, 4 vCPUs for up to 8 GiB, and 8 vCPUs for up to 32 GiB. You can also override CPU explicitly.

typescript
1import { onRequest } from "firebase-functions/v2/https";
2
3export const processImage = onRequest(
4 {
5 memory: "1GiB",
6 timeoutSeconds: 120,
7 region: "us-central1",
8 },
9 async (req, res) => {
10 // Image processing logic that needs more memory
11 res.json({ status: "processed" });
12 }
13);

Expected result: The function deploys with 1 GiB of memory and 1 vCPU, visible in the Google Cloud Console under Cloud Run.

2

Set memory in a v2 onCall callable function

Callable functions use the same options pattern. Pass memory in the first argument to onCall. This is common for functions that process data sent from your app, such as generating PDFs, resizing images, or running AI model inference. Callable functions also support concurrency, which controls how many requests one instance handles simultaneously.

typescript
1import { onCall, HttpsError } from "firebase-functions/v2/https";
2
3export const generateReport = onCall(
4 {
5 memory: "2GiB",
6 timeoutSeconds: 300,
7 concurrency: 10,
8 },
9 async (request) => {
10 if (!request.auth) {
11 throw new HttpsError("unauthenticated", "Login required");
12 }
13 // Heavy report generation logic
14 return { reportUrl: "https://storage.example.com/report.pdf" };
15 }
16);

Expected result: The callable function deploys with 2 GiB memory and can handle up to 10 concurrent requests per instance.

3

Set memory in event-triggered functions

Firestore triggers, Storage triggers, Auth triggers, and Pub/Sub triggers all accept the same memory option. This is especially important for Firestore triggers that process large documents or Storage triggers that handle file uploads. Event-triggered functions have a lower timeout ceiling (540 seconds) than HTTP functions, so memory allocation matters even more — faster processing avoids timeouts.

typescript
1import { onDocumentCreated } from "firebase-functions/v2/firestore";
2
3export const onImageUploaded = onDocumentCreated(
4 {
5 document: "uploads/{docId}",
6 memory: "1GiB",
7 timeoutSeconds: 300,
8 region: "us-central1",
9 },
10 async (event) => {
11 const data = event.data?.data();
12 // Process the uploaded image metadata
13 console.log(`Processing upload: ${data?.filename}`);
14 }
15);

Expected result: The Firestore trigger deploys with 1 GiB memory, giving it enough headroom for document processing.

4

Monitor memory usage in Cloud Console

Before increasing memory, check how much your function actually uses. Go to the Google Cloud Console, navigate to Cloud Run (v2 functions are Cloud Run services), and select your function. The Metrics tab shows memory utilization over time. Look at the peak memory usage — if it consistently stays below 50% of the allocated amount, you are over-provisioned. If it hits 100%, your function is crashing and needs more memory.

typescript
1// Add memory logging to your function for debugging
2import { onRequest } from "firebase-functions/v2/https";
3
4export const memoryCheck = onRequest(
5 { memory: "512MiB" },
6 async (req, res) => {
7 const used = process.memoryUsage();
8 res.json({
9 heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)} MB`,
10 heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)} MB`,
11 rss: `${Math.round(used.rss / 1024 / 1024)} MB`,
12 external: `${Math.round(used.external / 1024 / 1024)} MB`,
13 });
14 }
15);

Expected result: You can see your function's actual memory usage and determine whether the current allocation is appropriate.

5

Set different memory allocations per function

Each function in your project can have its own memory setting. Lightweight functions like auth triggers or simple Firestore writes can use the default 256 MiB, while heavy functions like image processing or AI inference can use 1 GiB or more. This keeps costs low for simple functions while giving resource-intensive functions the memory they need.

typescript
1import { onRequest } from "firebase-functions/v2/https";
2import { onDocumentCreated } from "firebase-functions/v2/firestore";
3
4// Lightweight function — default 256 MiB is fine
5export const healthCheck = onRequest(async (req, res) => {
6 res.json({ status: "ok" });
7});
8
9// Medium function — needs more memory for data processing
10export const processOrder = onDocumentCreated(
11 { document: "orders/{orderId}", memory: "512MiB" },
12 async (event) => {
13 // Order processing logic
14 }
15);
16
17// Heavy function — image/AI processing
18export const generateThumbnail = onRequest(
19 { memory: "2GiB", timeoutSeconds: 120 },
20 async (req, res) => {
21 // Sharp or Jimp image processing
22 res.json({ status: "done" });
23 }
24);

Expected result: Each function deploys with its own memory allocation, optimizing cost and performance across your project.

6

Migrate from v1 runWith to v2 options

If you have existing v1 functions using runWith, migrate them to v2 syntax. The v1 runWith method is still supported but v2 functions offer better performance, higher limits, and concurrency. The memory values are slightly different: v1 uses plain numbers (e.g., '1GB'), while v2 uses IEC units ('1GiB'). Both generations can coexist in the same project during migration.

typescript
1// v1 syntax (still works but deprecated pattern)
2import * as functions from "firebase-functions";
3
4export const oldFunction = functions
5 .runWith({ memory: "1GB", timeoutSeconds: 120 })
6 .https.onRequest(async (req, res) => {
7 res.send("v1 function");
8 });
9
10// v2 syntax (recommended)
11import { onRequest } from "firebase-functions/v2/https";
12
13export const newFunction = onRequest(
14 { memory: "1GiB", timeoutSeconds: 120 },
15 async (req, res) => {
16 res.send("v2 function");
17 }
18);

Expected result: Your function is migrated from v1 runWith to v2 options syntax with the correct memory unit format.

Complete working example

functions/src/index.ts
1// Firebase Cloud Functions v2 — Memory Configuration Examples
2import { onRequest, onCall, HttpsError } from "firebase-functions/v2/https";
3import { onDocumentCreated } from "firebase-functions/v2/firestore";
4import { onObjectFinalized } from "firebase-functions/v2/storage";
5
6// Default memory (256 MiB) — lightweight endpoints
7export const healthCheck = onRequest(async (req, res) => {
8 const mem = process.memoryUsage();
9 res.json({
10 status: "ok",
11 memoryUsedMB: Math.round(mem.rss / 1024 / 1024),
12 });
13});
14
15// 512 MiB — moderate data processing
16export const processOrder = onDocumentCreated(
17 {
18 document: "orders/{orderId}",
19 memory: "512MiB",
20 timeoutSeconds: 120,
21 region: "us-central1",
22 },
23 async (event) => {
24 const order = event.data?.data();
25 if (!order) return;
26 console.log(`Processing order ${event.params.orderId}`);
27 // Order validation, inventory check, email notification
28 }
29);
30
31// 1 GiB — callable function with concurrency
32export const generateReport = onCall(
33 {
34 memory: "1GiB",
35 timeoutSeconds: 300,
36 concurrency: 5,
37 },
38 async (request) => {
39 if (!request.auth) {
40 throw new HttpsError("unauthenticated", "Login required");
41 }
42 // PDF generation or data aggregation
43 return { reportId: "rpt_" + Date.now() };
44 }
45);
46
47// 2 GiB — image processing on storage upload
48export const resizeImage = onObjectFinalized(
49 {
50 memory: "2GiB",
51 timeoutSeconds: 120,
52 cpu: 2,
53 region: "us-central1",
54 },
55 async (event) => {
56 const filePath = event.data.name;
57 if (!filePath) return;
58 if (filePath.startsWith("thumbnails/")) return;
59 console.log(`Resizing image: ${filePath}`);
60 // Sharp or Jimp resize logic here
61 }
62);

Common mistakes when increasing Memory Allocation for a Firebase Cloud Function

Why it's a problem: Using v1 memory units ('1GB') in v2 function options instead of IEC units ('1GiB')

How to avoid: V2 functions use IEC binary units: '128MiB', '256MiB', '512MiB', '1GiB', '2GiB', '4GiB', '8GiB', '16GiB', '32GiB'. Using '1GB' will cause a deployment error.

Why it's a problem: Setting memory too high for all functions, causing unnecessarily high costs

How to avoid: Monitor actual memory usage in Cloud Console metrics before increasing allocation. Most simple functions work fine with the default 256 MiB.

Why it's a problem: Forgetting that higher concurrency means memory is shared across concurrent requests on the same instance

How to avoid: If you set concurrency to 10 with 1 GiB memory, each concurrent request effectively has about 100 MB. Increase memory proportionally to concurrency.

Why it's a problem: Not setting minInstances alongside increased memory, leading to cold starts on memory-heavy functions

How to avoid: For functions that need fast response times and high memory, set minInstances: 1 to keep a warm instance ready. This costs approximately $3-8/month per warm instance.

Best practices

  • Start with the default 256 MiB and only increase memory when you see out-of-memory crashes or slow performance in logs
  • Use process.memoryUsage().rss to log actual memory consumption during development and testing
  • Set different memory allocations per function — lightweight functions should stay at 256 MiB to minimize cost
  • Use IEC binary units in v2 function options: MiB and GiB, not MB and GB
  • Increase CPU explicitly with the cpu option when your function is CPU-bound rather than memory-bound
  • Combine minInstances with higher memory to avoid cold starts on resource-intensive functions
  • Deploy functions selectively with --only functions:functionName to avoid unnecessary redeployments
  • Review Cloud Console metrics monthly and right-size your memory allocations based on actual peak usage

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

I have a Firebase Cloud Function v2 that processes images and keeps crashing with out-of-memory errors. Show me how to increase the memory to 2 GiB, set the CPU to 2, add a timeout of 120 seconds, and keep one warm instance to avoid cold starts. The function is an onObjectFinalized trigger for Firebase Storage.

Firebase Prompt

Update my Firebase Cloud Function to use 1 GiB of memory with a 300-second timeout. The function is a v2 onCall callable that generates PDF reports. Also set concurrency to 5 and region to us-central1. Show the complete function definition with proper v2 imports.

Frequently asked questions

What is the default memory allocation for Firebase Cloud Functions v2?

The default is 256 MiB. This is sufficient for most lightweight functions like auth triggers, simple Firestore writes, and basic HTTP endpoints. Functions that process files, images, or large datasets typically need more.

What is the maximum memory I can allocate to a Firebase Cloud Function?

V2 functions support up to 32 GiB of memory. Available tiers are 128 MiB, 256 MiB, 512 MiB, 1 GiB, 2 GiB, 4 GiB, 8 GiB, 16 GiB, and 32 GiB. Higher memory automatically increases CPU allocation.

Does increasing memory also increase CPU?

Yes, by default. Firebase assigns CPU based on memory: 1 vCPU for up to 2 GiB, 2 vCPUs for up to 4 GiB, 4 vCPUs for up to 8 GiB, and 8 vCPUs for up to 32 GiB. You can override this with the cpu option.

How much does increased memory cost?

Cloud Functions billing is based on memory-seconds and CPU-seconds. At 256 MiB, you pay roughly $0.000000231 per 100ms. At 1 GiB, that quadruples. The Blaze plan includes 2 million free invocations per month, so the cost depends on your volume.

Can I set different memory for v1 and v2 functions in the same project?

Yes. V1 functions use runWith({ memory: '1GB' }) and v2 functions use options like { memory: '1GiB' }. Both can coexist in the same project and deploy together.

Why does my function still crash after increasing memory?

Check for memory leaks in your code — global variables that accumulate data across invocations, unclosed streams, or event listeners that are never removed. Also verify your deployment succeeded by checking the Cloud Console for the updated memory setting.

Can RapidDev help optimize my Firebase Cloud Functions performance?

Yes. RapidDev can audit your Cloud Functions for memory leaks, right-size memory allocations, configure cold start mitigation with minInstances, and optimize your function architecture for cost and performance.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.