Service communication
- Node.js course
- Advanced
- Lesson 50/83
- 5 min
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.
Practice 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.
Starter code
// Define the callOrderService async function
// write here
// Print "fetch ready"
// write hereSample solution
async function callOrderService() {
const res = await fetch("http://localhost:3001/orders");
return res.json();
}
console.log("fetch ready");Expected output
fetch ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the HTTP request method
const res = await ____("/orders");
const res = await fetch("/orders");
Explanation: fetch sends an HTTP request.
2 Match each pattern to its trait
| Term | Meaning |
|---|---|
synchronous HTTP |
Waits for response |
async queue |
Drops in queue |
fetch |
Sends an HTTP request |
RabbitMQ |
Message queue |
3 When is async communication preferred?
queue.push(job) → worker- When instant response is needed
- Only during debugging
- For long-running background jobs Correct answer
- Only in single-machine systems
Explanation: Async is preferred for long-running jobs.