Next.js Discord

Discord Forum

Fire and Forget backend function not working (NextJS + Vercel)

Unanswered
Baldfaced hornet posted this in #help-forum
Open in Discord
Baldfaced hornetOP
In my route.ts file I have a function that gets awaited:
    await drawGiftExchange(supabase, id);
    return NextResponse.json({ success: true });
  } catch (error) {
    return logError(error);
  }

and then inside that awaited function I have a fire and forget function that runs in the background of things. Like so:
      generateAndStoreSuggestions(
        supabase,
        exchangeId,
        giver.user_id,
        recipient.user_id,
        exchange.budget,
      );
    }

    // Update exchange status to active
    const { error: statusError } = await supabase
      .from('gift_exchanges')
      .update({ status: 'active' })
      .eq('id', exchangeId);

    if (statusError) {
      throw new SupabaseError(
        'Failed to update exchange status',
        statusError.code,
        statusError,
      );
    }
  } catch (error) {
    throw error;
  }

It works completely fine and smooth on localhost, but when running on vercel it doesnt work at all. It only works for a short time when I refresh the page and when it's done refreshing the function stops again and then continues when I refresh another time.

I am not sure why it's doing this. I did debugging and I know for sure that nothing is erroring in the code.

3 Replies

American black bear
well most likely due to serverless runtime
can you explain what the function does so I can recommend an alternative pattern
@American black bear can you explain what the function does so I can recommend an alternative pattern
Baldfaced hornetOP
the function calls our AI LLM model that generates 3 objects. It runs concurrently per user too. then inside the function it calls google custom search and then takes that image and the AI generated object and squishes them together and cleans things up. Then it'll store each object into our database