koakoa2

Koa send response immediately and then continue executing code after the response


I'm building a backend that has to handle a lot of incoming webhooks, and these are very demanding on response times.

My backend is in Koa and I would simply like to send a 200 response immediately, to then continue the code execution and perform the longer tasks such as processing (calculations, accessing the db etc).

I've tried several ways, but by both calling next() and await next() the response is sent only when all the middleware have executed their part of code.

NOTE: I have already read these answers on SO

Respond to Koa request immediately, continue middleware chain

Running code AFTER the response has been sent by Koa

Delay koa request 30 minutes but send 200 header immediately

My basic code looks like this:

const webhookHandler = async (ctx: Context, next: Next): Promise<void> => {
  console.log('Handling webhook event');

  // 1 check request
  const event = ctx.request.body;
  if (!event || !event.type) {
    ctx.status = 400;
    ctx.body = { received: false };
    return;
  }

  // 2 send response immediately
  ctx.status = 200;
  ctx.body = { received: true };
  next();

  // 3 handle event
  switch (event.type) {
    case 'a':
      // long running task here
      break;

    default:
      console.log(`Unhandled event type: ${event.type}`);
      break;
  }
};

Solution

  • Koa will not send the request until your middleware function ends. Assuming your task can be handled asynchronously, the task probably needs to be wrapped in an async function that you don't await.

    If your task is fully CPU bound then you gotta rethink running the task in the process altogether