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
Set memory in a v2 onRequest function
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.
1import { onRequest } from "firebase-functions/v2/https";23export 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 memory11 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.
Set memory in a v2 onCall callable function
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.
1import { onCall, HttpsError } from "firebase-functions/v2/https";23export 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 logic14 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.
Set memory in event-triggered functions
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.
1import { onDocumentCreated } from "firebase-functions/v2/firestore";23export 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 metadata13 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.
Monitor memory usage in Cloud Console
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.
1// Add memory logging to your function for debugging2import { onRequest } from "firebase-functions/v2/https";34export 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.
Set different memory allocations per function
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.
1import { onRequest } from "firebase-functions/v2/https";2import { onDocumentCreated } from "firebase-functions/v2/firestore";34// Lightweight function — default 256 MiB is fine5export const healthCheck = onRequest(async (req, res) => {6 res.json({ status: "ok" });7});89// Medium function — needs more memory for data processing10export const processOrder = onDocumentCreated(11 { document: "orders/{orderId}", memory: "512MiB" },12 async (event) => {13 // Order processing logic14 }15);1617// Heavy function — image/AI processing18export const generateThumbnail = onRequest(19 { memory: "2GiB", timeoutSeconds: 120 },20 async (req, res) => {21 // Sharp or Jimp image processing22 res.json({ status: "done" });23 }24);Expected result: Each function deploys with its own memory allocation, optimizing cost and performance across your project.
Migrate from v1 runWith to v2 options
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.
1// v1 syntax (still works but deprecated pattern)2import * as functions from "firebase-functions";34export const oldFunction = functions5 .runWith({ memory: "1GB", timeoutSeconds: 120 })6 .https.onRequest(async (req, res) => {7 res.send("v1 function");8 });910// v2 syntax (recommended)11import { onRequest } from "firebase-functions/v2/https";1213export 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
1// Firebase Cloud Functions v2 — Memory Configuration Examples2import { onRequest, onCall, HttpsError } from "firebase-functions/v2/https";3import { onDocumentCreated } from "firebase-functions/v2/firestore";4import { onObjectFinalized } from "firebase-functions/v2/storage";56// Default memory (256 MiB) — lightweight endpoints7export 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});1415// 512 MiB — moderate data processing16export 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 notification28 }29);3031// 1 GiB — callable function with concurrency32export 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 aggregation43 return { reportId: "rpt_" + Date.now() };44 }45);4647// 2 GiB — image processing on storage upload48export 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 here61 }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.
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.
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.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation