← Back to Node.js, page 9

nodejs-0169 · Hard senior

How do you handle errors, deadlines, metadata and interceptors in gRPC with Node.js?

gRPC errors are status codes (NOT_FOUND, INVALID_ARGUMENT, DEADLINE_EXCEEDED, UNAUTHENTICATED, UNAVAILABLE and others), not HTTP codes. The client sets a deadline on every call, and the server should stop work when the deadline passes or the call is cancelled. Metadata carries headers such as authorization and request ids. Interceptors on the client or server add cross-cutting behaviour like auth, logging and retries for transient codes.

Full answer

Status codes

  • Server handlers return errors with callback({ code: grpc.status.NOT_FOUND, message: '...' }).
  • Common codes: OK, INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED, UNAUTHENTICATED, RESOURCE_EXHAUSTED (rate limits), FAILED_PRECONDITION, ABORTED, DEADLINE_EXCEEDED, UNIMPLEMENTED, INTERNAL, UNAVAILABLE.
  • Retry only idempotent calls and only transient codes such as UNAVAILABLE (and sometimes DEADLINE_EXCEEDED or ABORTED, if the operation is safe). Use exponential backoff with jitter.

Deadlines

  • The client passes { deadline: Date.now() + 500 } in call options. When it expires the client call fails with DEADLINE_EXCEEDED, and the server call is cancelled.
  • No deadline means the call may wait forever. Set one on every call, and let each hop pass a shorter deadline on to its own downstream calls.
  • On the server, watch call.cancelled or the 'cancelled' event and stop expensive work.

Metadata

  • Key-value pairs sent with a call (headers) and returned (headers and trailers). The client builds new grpc.Metadata() and calls set('authorization', 'Bearer ...'). The server reads call.metadata.get('authorization').
  • Use it for tokens, request ids and tracing. Binary values use keys that end in -bin.

Interceptors

  • Client interceptors wrap outgoing calls to add metadata, log latency or retry. Server interceptors (supported in grpc-js through a wrapper or the server interceptors option in newer versions) check authentication and log.
  • Keep one place for authentication so no handler forgets it.

Operations: use TLS, health checking service (grpc.health.v1), reflection for debugging tools, and keepalive settings behind load balancers.

javascript
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grpc2-'));
const protoFile = path.join(dir, 'app.proto');
fs.writeFileSync(protoFile, `
syntax = "proto3";
package app;
service Greeter { rpc Hello (Name) returns (Reply); }
message Name { string name = 1; }
message Reply { string text = 1; }
`);
const app = grpc.loadPackageDefinition(protoLoader.loadSync(protoFile, { keepCase: true })).app;
const statusName = (code) => Object.keys(grpc.status).find((k) => grpc.status[k] === code);

const server = new grpc.Server();
server.addService(app.Greeter.service, {
  Hello: (call, callback) => {
    const token = call.metadata.get('authorization')[0];
    if (token !== 'Bearer good') return callback({ code: grpc.status.UNAUTHENTICATED, message: 'bad token' });
    const { name } = call.request;
    if (!name) return callback({ code: grpc.status.INVALID_ARGUMENT, message: 'name is required' });
    if (name === 'ghost') return callback({ code: grpc.status.NOT_FOUND, message: 'no such person' });
    const trailer = new grpc.Metadata(); trailer.set('request-id', 'abc-123');
    if (name === 'slow') return setTimeout(() => callback(null, { text: 'finally' }), 300);       // slower than the deadline
    callback(null, { text: 'Hello ' + name, request_id: 'abc-123' }, trailer);
  },
});

server.bindAsync('127.0.0.1:0', grpc.ServerCredentials.createInsecure(), (err, port) => {
  // A client interceptor that adds the authorization metadata to every call.
  const addAuth = (token) => (options, nextCall) => new grpc.InterceptingCall(nextCall(options), {
    start(metadata, listener, next) { metadata.set('authorization', token); next(metadata, listener); },
  });
  const clientFor = (token) => new app.Greeter(`127.0.0.1:${port}`, grpc.credentials.createInsecure(), { interceptors: [addAuth(token)] });

  const call = (client, name, deadlineMs) => new Promise((resolve) => {
    const options = deadlineMs ? { deadline: Date.now() + deadlineMs } : {};
    client.Hello({ name }, options, (error, reply) => resolve(error ? (error.code === grpc.status.DEADLINE_EXCEEDED ? statusName(error.code) : `${statusName(error.code)} (${error.details})`) : `OK "${reply.text}"`));
  });

  (async () => {
    const good = clientFor('Bearer good');
    console.log('normal call        :', await call(good, 'Asha'));
    console.log('empty name         :', await call(good, ''));
    console.log('unknown person     :', await call(good, 'ghost'));
    console.log('wrong token        :', await call(clientFor('Bearer bad'), 'Asha'));
    console.log('deadline of 100 ms :', await call(good, 'slow', 100));
    console.log('no deadline        :', await call(good, 'slow'));
    server.forceShutdown();
    fs.rmSync(dir, { recursive: true });
  })();
});

A client interceptor adds the token. The calls return OK and four different status codes, and the slow call fails with DEADLINE_EXCEEDED only when a deadline is set. Install first with npm install @grpc/grpc-js @grpc/proto-loader (run here with @grpc/grpc-js 1.14.7, @grpc/proto-loader 0.8.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): normal call : OK "Hello Asha" empty name : INVALID_ARGUMENT (name is required) unknown person : NOT_FOUND (no such person) wrong token : UNAUTHENTICATED (bad token) deadline of 100 ms : DEADLINE_EXCEEDED no deadline : OK "finally"

Key points

  • Errors are gRPC status codes, not HTTP codes.
  • Set a deadline on every call and propagate a shorter one downstream.
  • Metadata carries tokens and request ids.
  • Interceptors centralise auth, logging and retries.
  • Retry only idempotent calls on transient codes.

Common mistakes

  • Making calls with no deadline.
  • Returning INTERNAL for every error.
  • Retrying non-idempotent calls on DEADLINE_EXCEEDED.
  • Sending tokens without TLS.
  • Not stopping server work after the client cancelled.

Follow-ups

  • How do you pass a deadline from one service to the next?
  • What does the health checking protocol do?
  • How do you test a gRPC service?

Tips

  • Name five status codes.
  • Say 'deadline on every call'.
  • Mention interceptors for auth.