How do you build a microservice in Node.js and call another service?

Topic: microservices, Node Side. Level: Intermediate.

Answer

A Node microservice is typically an Express/Fastify app exposing REST/JSON, run as its own process/container. For inter-service calls use `fetch`/axios/`undici` with an **AbortController timeout**, retries with backoff for idempotent calls, and a circuit breaker (e.g. `opossum`) with a fallback. Resolve peers by DNS/service name (k8s) rather than hardcoded IPs. ```js import CircuitBreaker from 'opossum' async function charge(order) { const ac = new AbortController() const t = setTimeout(() => ac.abort(), 3000) // bound the call try { const res = await fetch('http://payment-service/charge', { method: 'POST', signal: ac.signal, headers: { 'content-type': 'application/json' }, body: JSON.stringify(order), }) if (!res.ok) throw new Error(`payment ${res.status}`) return res.json() } finally { clearTimeout(t) } } const breaker = new CircuitBreaker(charge, { timeout: 3000, errorThresholdPercentage: 50 }) breaker.fallback(() => ({ status: 'declined' })) // graceful degradation ```