gRPC Client Deadline and Timeout Control

Propagate per-call deadlines through gRPC clients with timeout headers, cancellation signals, and DEADLINE_EXCEEDED error classification.

TypescriptNodeData Fetching

Code

typescriptsnippet
43 lines
import * as grpc from '@grpc/grpc-js';
import { echo } from './generated/echo_grpc_pb';

const client = new echo(
  'api.example.com:443',
  grpc.credentials.createSsl(),
);

function callWithDeadline(payload: string, timeoutMs: number) {
  return new Promise<string>((resolve, reject) => {
    // 每次调用独立截止时间,随调用元数据传播到下游
    const callOptions = { deadline: Date.now() + timeoutMs };

    client.echo(
      { payload } as never,
      new grpc.Metadata(),
      callOptions,
      (err: grpc.ServiceError | null, response?: { payload: string }) => {
        if (err) {
          if (err.code === grpc.status.DEADLINE_EXCEEDED) {
            reject(Object.assign(new Error('deadline exceeded'), { retryable: false }));
            return;
          }
          if (err.code === grpc.status.UNAVAILABLE) {
            reject(Object.assign(new Error('unavailable'), { retryable: true }));
            return;
          }
          reject(new Error('rpc failed: ' + err.details));
          return;
        }
        resolve(response?.payload ?? '');
      },
    );
  });
}

try {
  const echoed = await callWithDeadline('ping', 2_000);
  console.log('echo ok:', echoed.length);
} catch (err) {
  const { message, retryable } = err as Error & { retryable?: boolean };
  console.log('failed:', message, 'retryable:', retryable ?? false);
}

How it works

The working surface is the function callWithDeadline — everything else is wiring.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. From @grpc/grpc-js it pulls echo — the imports name exactly which library surface the snippet touches.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • @grpc/grpc-js must be installed first — the snippet imports it directly.

Using it

Entry signature: function callWithDeadline(payload: string, timeoutMs: number)

The demo output is labeled (echo ok:, failed:), so every printed line maps back to its originating operation.

Key statements

resolve(response?.payload ?? '');
const echoed = await callWithDeadline('ping', 2_000);

Interactive Tools for This Topic

FAQ

Does `callWithDeadline` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
What does this need from the package registry?
These are real dependencies: `@grpc/grpc-js`. Without it the snippet will not load.