1

I have an HTTP Firebase Cloud Function that occasionally can take very long to finish. For this particular use case, I don't want my users to wait until the function has finished to receive a 200 response.

So I do res.status(200).send(); as usual, but instead of doing it at the end of execution I've tried doing it at the start of the function. The problem is that this stops execution.

As a workaround I'm considering moving the heavy load to a different function and trigger it from a write in the Realtime Database, but it would be much easier to just have this logic in a single function.

Is there a way around this limitation?

Pier
  • 10,298
  • 17
  • 67
  • 113

1 Answers1

9

There is no way to continue execution after the response has been sent. Your instinct to trigger a second, background function via a write to the Realtime Database is a good one (using Cloud Pub/Sub is also a good option).

While this may feel like extra steps, it's also generally a good practice -- you can control the retry and timing semantics of your extended processing independently of the user-critical request path. In general, this kind of thing is a textbook case for a message queue. :)

Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
  • Thank you Michael! – Antuan Aug 24 '18 at 19:47
  • Is this actually true? I'm running this, and it's working perfectly: ``` res.send({ status: 'ok', data }); userActions.addNotification(notification); ``` It's not stopping the function execution – Broda Noel Feb 20 '19 at 19:48
  • Actually, check this https://stackoverflow.com/questions/16180502/why-can-i-execute-code-after-res-send – Broda Noel Feb 20 '19 at 19:51
  • I believe you can continue the execution. What you can not do is to call the `.send` function again (but that's not the question here) – Broda Noel Feb 20 '19 at 19:53
  • 2
    Execution *may* continue for a short time, but you can't count on it. When a response is sent via `send()` the function is considered "complete" and the underlying VM may be torn down at any moment. In addition, hard limits are placed on CPU and memory usage when there isn't an "active" invocation. – Michael Bleigh Feb 21 '19 at 18:40