Some operations take too much time, which lead the request to time out.
How do I finish responding to the request first, then continue that operation?
You need the flush() call to have the response sent to the browser immediately.
flush()