Node.js
Service communication
Learn inter-service HTTP communication.
Service communication
Services talk to each other over HTTP. The calling service sends a request to another service and waits for a response. In Node.js you use http.request or fetch for this.
Example: the user service sends a request to the order service with http.get("http://order-service:3001/orders"). When the response arrives, the user service processes the data. Synchronous HTTP is simple, but if the called service is slow, the caller also slows down. That is why large systems prefer a message queue (RabbitMQ, Kafka). HTTP fits the client-server model; a message queue is asynchronous and does not require the called service to be up. The right choice depends on latency and reliability needs.
Synchronous vs asynchronous communication
In synchronous communication the caller waits for a response (HTTP). In asynchronous communication the caller drops a message in a queue and moves on (message queue). Each pattern has its own trade-offs.
In synchronous HTTP, if the called service is down, the caller gets an error. In an async queue, the message waits in the queue and is processed when the service comes back up. Synchronous is suitable for tasks that need quick feedback (a user query). Async is suitable for long-running tasks (sending email, generating a report). Many systems use both: user queries synchronous, background jobs asynchronous. The right mix balances user experience and system reliability.
Exercise Write a service call with fetch
Define an async callOrderService function. Send a request with await fetch("http://localhost:3001/orders") and return the body with res.json(). Print "fetch ready" with console.log.
Show example solution
async function callOrderService() {
const res = await fetch("http://localhost:3001/orders");
return res.json();
}
console.log("fetch ready");
Test yourself
-
Complete the HTTP request method
const res = await ____("/orders");
Show answer
const res = await fetch("/orders");
-
Match each pattern to its trait
- synchronous HTTP
- Waits for response
- async queue
- Drops in queue
- fetch
- Sends an HTTP request
- RabbitMQ
- Message queue
-
When is async communication preferred?
queue.push(job) → worker
- When instant response is needed
- Only during debugging
- For long-running background jobs
- Only in single-machine systems
Show answer
For long-running background jobs — Async is preferred for long-running jobs.
Next lesson: API gateway