Skip to content

Refactor trpc.ts Middleware for Better Production PerformanceΒ #2123

@wolfcarves

Description

@wolfcarves

Is your feature request related to a problem? Please describe.

The current implementation in /server/api/trpc.ts applies artificial delays in both development and production, leading to unnecessary performance issues in production. This will improve performance in production environments while still providing the delay in development for simulating network latency.

Describe the solution you'd like to see

Refactor the timingMiddleware to only apply artificial delays during development (t._config.isDev) and not in production.

FROM

const timingMiddleware = t.middleware(async ({ next, path }) => {
  const start = Date.now();

  if (t._config.isDev) {
    // artificial delay in dev
    const waitMs = Math.floor(Math.random() * 400) + 100;
    await new Promise((resolve) => setTimeout(resolve, waitMs));
  }

  const result = await next();

  const end = Date.now();
  console.log(`[TRPC] ${path} took ${end - start}ms to execute`);

  return result;
});

export const publicProcedure = t.procedure.use(timingMiddleware);

TO

const timingMiddleware = t.middleware(async ({ next, path }) => {
    const start = Date.now();

    const waitMS = Math.floor(Math.random() * 400) + 100;
    await new Promise((resolve) => setTimeout(resolve, waitMS));

    const result = await next();

    const end = Date.now();
    console.log(`[TRPC] ${path} took ${end - start}ms to execute`);

    return result;
});

export const publicProcedure = t._config.isDev
    ? t.procedure.use(timingMiddleware)
    : t.procedure;

Describe alternate solutions

For a simplier approach

export const publicProcedure = t.procedure.use(t._config.isDev ? timingMiddleware : undefined);

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions