Next.js Discord

Discord Forum

Serverless function timeouts

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
On my ServerSideProps pages I get
504: GATEWAY_TIMEOUT Code: FUNCTION_INVOCATION_TIMEOUT
in production deployed on vercel whereas it works in development.
Supposedly there may be an error in my ServerSideProps function but I dont know why that would be as the debug prints are also not appearing in the logs.

This happens on all my pages with ServerSideProps but let's take this one as an example:

export async function getServerSideProps(
  context: GetServerSidePropsContext<{ id: string }> & SSHProps
) {
  const id = context.params?.id;
  console.log("Test 1");
  if (id == null || !z.string().cuid().safeParse(id).success) {
    return {
      redirect: {
        destination: ".",
      },
    };
  }
  console.log("Test 2");

  const ssg = await serverSideHelper(context);
  await ssg.schedule.list.prefetch({ serverId: id });
  await ssg.servers.get.prefetch({ id: id });
  console.log("Test 3");
  return {
    props: {
      trpcState: ssg.dehydrate(),
      id,
    },
    // revalidate: 10,
  };
}

Does anyone know what could be causing this?

24 Replies

Spectacled bearOP
const ServerSchedulePage: NextPage<
  InferGetStaticPropsType<typeof getServerSideProps>
> = ({ id }) => {
  const [, setErrors] = useAtom(errorsAtom);
  const onError = (e: { message: string }) => {
    setErrors((prev) => [...prev, e.message]);
  };
  const { data: server } = api.servers.get.useQuery(
    { id: id },
    { onError: onError }
  );
  const { data: schedule } = api.schedule.list.useQuery(
    { serverId: id },
    { onError: onError }
  );
  if (server == null) return <ErrorPage statusCode={404} />;
  if (schedule == null) return <ErrorPage statusCode={422} />;

  return (
    <>
      <Head>
        <title>{`Manager - Schedule - ${server.name}`}</title>
      </Head>
      <BackBar
        href="../"
        content={
          <>
            <h1 className="text-lg font-bold">Servers</h1>
            <ArrowRight className="mb-2 mt-2" />
            <h1 className="text-lg font-bold">{server.name}</h1>
            <div className="ml-2 text-gray-500">
              {server.schedules} schedules{" "}
            </div>
          </>
        }
      />

      <Calendar serverId={id} />
    </>
  );
};
export type SSHProps = {
  req: IncomingMessage & {
    cookies: Partial<{ [key: string]: string }>;
  };
  res: ServerResponse<IncomingMessage>;
};

export async function serverSideHelper(opts: SSHProps) {
  return createServerSideHelpers({
    router: appRouter,
    ctx: createInnerTRPCContext({
      session: await getServerAuthSession(opts),
      token: undefined,
      serverId: undefined,
      revalidateSSG: null,
    }),
    transformer: SuperJSON,
  });
}
where do u host? if it is Vercel hobby, it is deployed to AWS lambda serverless, where there is 10 sec time cap, so upstream calls need to complete in 10 sec. or make it App Router with Suspense, deploy to Edge Runtime. or upgrade Vercel plan.
Spectacled bearOP
These requests should definitely take less than 10 seconds to execute I assume
Or why wouldn't they?
Besides, non of the debug prints are printed, there must be something else going wrong
Spectacled bearOP
Bump
Spectacled bearOP
Bump
@tafutada777 where do u host? if it is Vercel hobby, it is deployed to AWS lambda serverless, where there is 10 sec time cap, so upstream calls need to complete in 10 sec. or make it App Router with Suspense, deploy to Edge Runtime. or upgrade Vercel plan.
Japanese Terrier
What is the Edge Runtime? I have created an edge function, but still the Verchel server returns a 504 error
Function for POST and GET comments with Pusher
@Japanese Terrier in short, it is a runtime that runs on CloudFlare Worker, which implements subset of Node.js. Vercel uses AWS Lambda by default.
Technically, Edge Runtime is measured by CPU time cap, so you can reduce the chance of 504 Gateway Timeout error as long as it is I/O bound task.
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
i didn't know Pusher. but WaPo uses it. it's an interesting pub/sub service.
Dwarf Crocodile
@Spectacled bear Are you still having issues?

If it is no hassle, I suggest looking into using a logging library instead of console.log. In Node.js, console.log has undefined behavior and can be both synchronous and async, which I imagine isn't helping with this issue. Could get more useful logs with that

Minor quibble, and I can't imagine it will make a difference, but running the prefetch calls concurrently might save a little bit of time, though I can't imagine it's long enough to get that 504 error:

await Promise.all([
  ssg.schedule.list.prefetch({ serverId: id }),
  ssg.servers.get.prefetch({ id: id })
]);

I also assume that you're using session-based authentication (getServerAuthSession). Can you double check that the production environment's session management is configured correctly?
Spectacled bearOP
Well I'll be damned. I think the problem is that server side rendering is not compatible with MUI icons....
That is rather disappointing...
Spectacled bearOP
Does anyone know how to fix ssr issues with mui in the old router? For the new router it's well documented but not for the old one
@Japanese Terrier how you mean SSR issue with MUI?
Spectacled bearOP
This code works. But not if I uncomment the arrowRight icon. The problem is my entire app is built with mui icons so
Spectacled bearOP
It took a couple of weeks but now finally I've been able to formulate the question I needed to ask chatgpt.

https://chat.openai.com/share/787b6002-1da2-412b-809d-3d8ba4e64307

Apperently nextjs needs to know which parts of mui is server and client or something. Ill get at it tomorrow but now at least i have a lead to follow
Spectacled bearOP
Ultimately the problem was that in web development you gotta watch your imports. The problem was actually that mui's modules would take >10s to import. Which could be fixed by modularizeImports