0
0
FirebaseDebug / FixBeginner · 3 min read

How to Fix Firebase Function Timeout Quickly and Easily

Firebase function timeouts happen when your function runs longer than the set limit, usually 60 seconds by default. To fix this, optimize your code to finish faster or increase the timeout setting using runWith({ timeoutSeconds: X }) where X is the new timeout in seconds.
🔍

Why This Happens

Firebase functions time out because they take too long to finish. This can happen if your code waits for slow operations, like long database queries or external API calls, without ending the function properly.

javascript
const functions = require('firebase-functions');

exports.slowFunction = functions.https.onRequest(async (req, res) => {
  await new Promise(resolve => setTimeout(resolve, 70000)); // waits 70 seconds
  res.send('Done');
});
Output
Error: Function execution took longer than 60 seconds and timed out.
🔧

The Fix

To fix the timeout, either make your function finish faster or increase the timeout limit. Use runWith to set a longer timeout if needed. Also, make sure to end your function by sending a response or returning a promise.

javascript
const functions = require('firebase-functions');

exports.fixedFunction = functions.runWith({ timeoutSeconds: 120 }).https.onRequest(async (req, res) => {
  await new Promise(resolve => setTimeout(resolve, 70000)); // waits 70 seconds
  res.send('Done within extended timeout');
});
Output
HTTP 200 OK with message: 'Done within extended timeout'
🛡️

Prevention

To avoid timeouts, keep your functions efficient by:

  • Limiting long waits or heavy processing inside functions.
  • Using asynchronous calls properly and returning promises.
  • Setting appropriate timeout values with runWith based on expected work.
  • Testing functions locally or with logs to find slow parts.
⚠️

Related Errors

Other common errors include:

  • Unhandled promise rejections: Always return or await promises to avoid hanging functions.
  • Memory limits exceeded: Optimize memory usage or increase limits with runWith({ memory: '256MB' }).

Key Takeaways

Firebase functions time out if they run longer than the set timeout limit.
Use runWith({ timeoutSeconds: X }) to increase the timeout when needed.
Always end functions by sending a response or returning a promise.
Keep functions efficient by avoiding long waits and heavy processing.
Test and monitor functions to catch slow operations early.