Understanding how asynchronous tasks in serverless environments can cause logs from different requests to appear under the wrong request ID.
Function environment is ready to handle requests
Notice how the orphaned task's log appears under Request B's ID
// CORRECT: Await tasks needed for response
const [user, products] = await Promise.all([
db.users.find(request.user.id),
db.products.getForUser(request.user.id),
]);
return Response.json({ user, products });import { waitUntil } from '@vercel/functions';
// Background task won't block response
waitUntil(
fetch('https://analytics.com/api/log', {
method: 'POST',
body: JSON.stringify({ event: 'viewed' }),
})
);
return new Response('Success!');