Microservices Communication
Synchronous vs async communication, RestTemplate, RestClient, inter-service HTTP patterns
- Compare synchronous and asynchronous inter-service communication
- Use RestTemplate and RestClient to call downstream services
- Handle errors and timeouts in service-to-service calls
RestTemplate, to its limitations and the motivation for RestClient. Every concept, code example, and internal mechanism is explained in full detail.Table of Contents
- Goal and Setup
- HTTP Fundamentals — Requests, Responses, and Keep-Alive
- Types of Inter-Service Communication
- Plain Java HTTP Communication (No Framework)
- RestTemplate — Spring's Classic HTTP Client
- RestTemplate Internal Flow
- RestTemplate Methods — Complete Reference
- RestTemplate Limitations
- What Comes Next — RestClient and Feign
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Revision Bullets
1. Goal and Setup
Overview
The fundamental challenge in microservices is this: how does one service call another? This guide walks through the answer progressively — from raw TCP/HTTP in plain Java to the Spring-managed RestTemplate.
The Two Microservices
We set up two independent Spring Boot applications:
| Service | Port | Responsibility |
|---|---|---|
| Order Service | 8081 | Receives orders; calls Product Service |
| Product Service | 8082 | Provides product data |
Project Creation
Both services are created via Spring Initializr with only Spring Web as a dependency. No Spring Cloud is added yet — this is intentional to build the foundational understanding first.
`application.properties` Order Service
1server.port=8081`application.properties` Product Service
1server.port=8082Product Service Endpoint
1@RestController2public class ProductController {3
4 @GetMapping("/product/{id}")5 public String getProduct(@PathVariable String id) {6 return "Product fetched with ID: " + id;7 }8}Order Service Endpoint (calls Product Service)
1@RestController2public class OrderController {3
4 @GetMapping("/order/{id}")5 public String getOrder(@PathVariable String id) {6 // This method must somehow call Product Service's /product/{id}7 // — we'll see three different implementations below8 }9}Architecture
2. HTTP Fundamentals Requests, Responses, and Keep-Alive
Before looking at communication code, we must understand what actually travels over the network. This knowledge is directly referenced in the internal workings of RestTemplate.
2.1 HTTP GET Request Structure
1GET /product/1 HTTP/1.12Host: localhost:80823User-Agent: curl/7.68.04Accept: application/json| Field | Meaning |
|---|---|
GET | HTTP method (GET, POST, PUT, DELETE) |
/product/1 | URI — the path being requested |
HTTP/1.1 | Protocol version |
Host: localhost:8082 | Target host — URL and port number |
User-Agent | Client/tool making the request (curl, Postman, Java, etc.) |
Accept | Format the client expects in the response |
2.2 HTTP POST Request Structure
1POST /product HTTP/1.12Host: localhost:80823User-Agent: curl/7.68.04Content-Type: application/json5Content-Length: 456
7{"name": "Laptop", "price": 999.99}| Extra Field | Meaning |
|---|---|
Content-Type | Format of the request body being sent |
Content-Length | Size of the request body in bytes |
| Body | The actual data (e.g., a new product object in JSON) |
2.3 HTTP Response Structure
1HTTP/1.1 200 OK2Content-Type: application/json3Content-Length: 384Connection: keep-alive5Keep-Alive: timeout=5, max=506
7{"id": 1, "name": "Laptop", "price": 999.99}| Field | Meaning |
|---|---|
Content-Type | Format of the response body |
Content-Length | Size of response body in bytes |
Connection: keep-alive | Tells client the TCP connection can be reused |
Keep-Alive: timeout=5, max=50 | Connection rules (see below) |
2.4 HTTP Keep-Alive Critical Concept
This is one of the most important concepts for understanding how RestTemplate manages connections internally.
HTTP 1.0 vs HTTP 1.1 Connection Behavior
| Version | Default Behavior | After Response |
|---|---|---|
| HTTP 1.0 | Connection: close | TCP connection is terminated |
| HTTP 1.1 | Connection: keep-alive | TCP connection is kept open and reused |
Keep-Alive Configuration Parameters
| Parameter | Meaning |
|---|---|
timeout=5 | Close the idle TCP connection after 5 seconds of inactivity |
max=50 | Allow a maximum of 50 requests over the same TCP connection |
Connection Lifecycle with Keep-Alive
WebSocket vs HTTP Connection Persistence
| Protocol | Connection Type | Direction |
|---|---|---|
| HTTP 1.0 | Terminates after each response | Client → Server only |
| HTTP 1.1 | Persistent (keep-alive) | Client → Server only |
| WebSocket | Persistent (always open) | Bidirectional |
3. Types of Inter-Service Communication
Synchronous Communication
Definition: The calling service (client) waits (blocks) until it receives a response from the called service (server) before continuing execution.
- Blocking in nature — the calling thread is held until response arrives
- Simple to reason about — request → wait → response
- Types:
RestTemplate,RestClient,FeignClient
RestTemplate and RestClient — as FeignClient internally uses similar HTTP mechanisms.Asynchronous Communication
Definition: The calling service sends a message and does not wait for a response. Processing continues immediately.
- Non-blocking — thread is freed immediately
- Uses message brokers like RabbitMQ, Kafka
- Covered separately — this guide focuses on synchronous communication
4. Plain Java HTTP Communication (No Framework)
Why Start Here?
Before using RestTemplate (which abstracts the details), we must understand what happens at the raw Java level. RestTemplate internally uses the same mechanism — just hidden from the developer. Understanding the raw flow makes debugging and optimization much easier.
4.1 The Three Steps of Plain Java HTTP Communication
4.2 Full Plain Java Example
Product Service Controller
1@RestController2public class ProductController {3
4 // This endpoint will be called by Order Service5 @GetMapping("/product/{id}")6 public String getProduct(@PathVariable String id) {7 return "Product fetched with ID: " + id;8 }9}Order Service Controller Plain Java HTTP
1@RestController2public class OrderController {3
4 @GetMapping("/order/{id}")5 public String getOrder(@PathVariable String id) throws Exception {6
7 // ===== STEP 1: Create the HttpURLConnection "envelope" =====8 URL url = new URL("http://localhost:8082/product/" + id);9
10 HttpURLConnection connection = (HttpURLConnection) url.openConnection();11 // NOTE: openConnection() does NOT create a TCP connection yet.12 // It only creates the HttpURLConnection object — the "envelope".13
14 connection.setRequestMethod("GET");15 connection.setRequestProperty("Accept", "application/json");16 connection.setConnectTimeout(5000); // 5 seconds to establish TCP connection17 connection.setReadTimeout(5000); // 5 seconds to wait for server response18
19 // ===== STEP 2: Trigger TCP connection and send request =====20 // Calling getInputStream() internally:21 // 1. Calls connection.connect() → creates TCP connection (3-way handshake)22 // 2. Sends the HTTP request to the server23 // 3. Waits for response (blocked here — synchronous)24 // 4. Returns an InputStream containing the response body25 InputStream inputStream = connection.getInputStream();26
27 // ===== Read response from InputStream =====28 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));29 StringBuilder response = new StringBuilder();30 String line;31 while ((line = reader.readLine()) != null) {32 response.append(line);33 }34 reader.close();35
36 System.out.println("Response: " + response.toString());37
38 // ===== STEP 3: Close the connection =====39 connection.disconnect();40
41 return "Order placed for product: " + response.toString();42 }43}4.3 Line-by-Line Explanation
Step 1 Creating the Envelope
1URL url = new URL("http://localhost:8082/product/" + id);2HttpURLConnection connection = (HttpURLConnection) url.openConnection();new URL(...)— constructs aURLobject representing the target endpointurl.openConnection()— creates aHttpURLConnectionobject but does NOT establish any network connection yet- Think of this as preparing an envelope: writing the address, choosing delivery method, setting options
1connection.setRequestMethod("GET");2connection.setRequestProperty("Accept", "application/json");3connection.setConnectTimeout(5000);4connection.setReadTimeout(5000);| Setting | Meaning |
|---|---|
setRequestMethod("GET") | HTTP method to use |
setRequestProperty(...) | Add a request header |
setConnectTimeout(5000) | Max time (ms) to establish the TCP connection. Throws SocketTimeoutException if exceeded. |
setReadTimeout(5000) | Max time (ms) to wait for server response after connection is established |
Step 2 Triggering TCP Connection
Three methods on HttpURLConnection each trigger a real TCP connection:
| Method | Effect |
|---|---|
connection.connect() | Explicitly creates the TCP connection |
connection.getInputStream() | Implicitly calls connect(), sends request, waits for response, returns stream |
connection.getResponseCode() | Same as getInputStream() — internally calls connect() and sends request |
In the example, getInputStream() is used — it does everything in sequence automatically.
Step 3 Closing the Connection
1connection.disconnect();What disconnect() actually does internally:
1if (response stream NOT fully read) {2 Close the TCP socket immediately (discard the connection)3} else {4 Mark the underlying HTTP client as "not in use"5 Return it to the keep-alive cache6 // It can be reused for future requests to the same host:port7}disconnect() does not always physically close the TCP connection. If the response was fully read, the underlying connection is placed back in a keep-alive cache (keyed by host:port) and can be reused for subsequent requests to the same server.4.4 The Keep-Alive Cache in Plain Java
4.5 Disadvantages of Plain Java Approach
| Problem | Description |
|---|---|
| Too much boilerplate | Opening connection, setting headers, reading stream, closing — all manual |
| Manual response parsing | Must read stream line-by-line and convert to desired type manually |
| Manual error handling | HTTP error codes must be checked and handled explicitly |
| No connection pooling support | The keep-alive cache is basic and not configurable |
| No retry / circuit breaker | Must implement manually |
| No interceptors / filters | No clean hook points for cross-cutting concerns |
1// Everything you must write manually just to make ONE GET call:2URL url = new URL("http://localhost:8082/product/" + id);3HttpURLConnection connection = (HttpURLConnection) url.openConnection();4connection.setRequestMethod("GET");5connection.setRequestProperty("Accept", "application/json");6connection.setConnectTimeout(5000);7connection.setReadTimeout(5000);8InputStream inputStream = connection.getInputStream();9BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));10StringBuilder response = new StringBuilder();11String line;12while ((line = reader.readLine()) != null) { response.append(line); }13reader.close();14connection.disconnect();15// Then manually parse `response.toString()` into whatever object you need5. RestTemplate Spring's Classic HTTP Client
Overview
RestTemplate is Spring's abstraction over raw HTTP communication. It eliminates boilerplate code by wrapping the HttpURLConnection mechanics we saw in plain Java into a clean, single-method API.
RestTemplate is considered a legacy (traditional) way to call REST APIs in Spring applications. It is currently in maintenance mode — only bug fixes, no new features. The modern replacement is RestClient (covered in the next section). However, RestTemplate is still widely used and important to know.5.1 Basic Setup
Creating a RestTemplate Bean
1@Configuration2public class AppConfig {3
4 @Bean5 public RestTemplate restTemplate() {6 return new RestTemplate(); // Uses default timeouts7 }8}RestTemplate uses SimpleClientHttpRequestFactory internally, which sets its own default connection timeout and read timeout values. For production use, always configure explicit timeouts.Creating RestTemplate with Custom Timeouts
1@Configuration2public class AppConfig {3
4 @Bean5 public RestTemplate restTemplate() {6 SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();7 factory.setConnectTimeout(5000); // 5 seconds (in milliseconds)8 factory.setReadTimeout(5000); // 5 seconds (in milliseconds)9
10 return new RestTemplate(factory);11 }12}What is SimpleClientHttpRequestFactory?
It is a factory that creates ClientHttpRequest objects. A ClientHttpRequest is the Spring abstraction representing a single HTTP request — it wraps HttpURLConnection internally. By providing a factory to RestTemplate, you control how each request object is created and what default settings it has.
5.2 Using RestTemplate in Order Service
1@RestController2public class OrderController {3
4 @Autowired5 private RestTemplate restTemplate; // Spring injects the bean we declared6
7 @GetMapping("/order/{id}")8 public String getOrder(@PathVariable String id) {9
10 // ONE LINE replaces all the boilerplate from plain Java11 String productResponse = restTemplate.getForObject(12 "http://localhost:8082/product/" + id,13 String.class // How to parse the response body14 );15
16 System.out.println("Response from Product API: " + productResponse);17 return "Order placed. " + productResponse;18 }19}Output
1Response from Product API: Product fetched with ID: 1All of this is now handled automatically by RestTemplate:
- Creating
HttpURLConnection - Setting headers
- Establishing TCP connection (with keep-alive cache)
- Sending the HTTP request
- Waiting for response
- Parsing the response stream
- Closing the stream (not the TCP connection — it goes back to cache)
6. RestTemplate Internal Flow
Understanding what happens inside RestTemplate when you call getForObject(url, String.class) maps directly to the plain Java flow — just abstracted behind framework layers.
6.1 Step-by-Step Internal Execution
6.2 The Three Internal Steps Mapped to Plain Java
| Plain Java Step | RestTemplate Internal Equivalent |
|---|---|
Create HttpURLConnection, set method/headers/timeouts | factory.createRequest() → returns SimpleClientHttpRequest |
Call getInputStream() → connect + send + receive | request.execute() → internally calls connection.connect() + getResponseCode() |
Read stream manually + call disconnect() | RestTemplate reads stream via message converters + closes stream (TCP stays in cache) |
6.3 Message Converters Automatic Response Parsing
When you specify String.class or Product.class as the response type, RestTemplate uses HttpMessageConverter implementations to automatically deserialize the response stream.
| Response Type Specified | Converter Used |
|---|---|
String.class | StringHttpMessageConverter |
Custom class (e.g., Product.class) | MappingJackson2HttpMessageConverter (uses Jackson) |
byte[] | ByteArrayHttpMessageConverter |
This means you never write objectMapper.readValue(stream, Product.class) manually — RestTemplate does it automatically.
7. RestTemplate Methods Complete Reference
7.1 GET Methods
`getForObject` Returns Response Body Only
1// Syntax2T getForObject(String url, Class<T> responseType, Object... uriVars)3
4// Example — response as String5String response = restTemplate.getForObject(6 "http://localhost:8082/product/{id}",7 String.class,8 "1" // replaces {id}9);10
11// Example — response as custom object12Product product = restTemplate.getForObject(13 "http://localhost:8082/product/{id}",14 Product.class,15 "1"16);Returns: Just the response body, automatically deserialized to the specified type. No access to status code or headers.
`getForEntity` Returns Full Response (Body + Status + Headers)
1// Syntax2ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVars)3
4// Example5ResponseEntity<Product> responseEntity = restTemplate.getForEntity(6 "http://localhost:8082/product/{id}",7 Product.class,8 "1"9);10
11HttpStatus statusCode = responseEntity.getStatusCode(); // e.g., 200 OK12HttpHeaders headers = responseEntity.getHeaders(); // all response headers13Product body = responseEntity.getBody(); // the actual product dataReturns: ResponseEntity — full HTTP response including status code, headers, and body.
Comparison `getForObject` vs `getForEntity`
| Method | Return Type | Access to Status | Access to Headers | Access to Body |
|---|---|---|---|---|
getForObject | T (body only) | ❌ | ❌ | ✅ |
getForEntity | ResponseEntity | ✅ | ✅ | ✅ |
getForObject when you only need the data. Use getForEntity when you also need to inspect the HTTP status code or response headers (e.g., for error handling or reading custom headers).7.2 POST Methods
`postForObject` Returns Response Body Only
1// Syntax2T postForObject(String url, Object request, Class<T> responseType)3
4// Example5Product newProduct = new Product("Laptop", 999.99);6
7Product createdProduct = restTemplate.postForObject(8 "http://localhost:8082/product",9 newProduct, // request body — automatically serialized to JSON10 Product.class // expected response type11);`postForEntity` Returns Full Response
1ResponseEntity<Product> response = restTemplate.postForEntity(2 "http://localhost:8082/product",3 newProduct,4 Product.class5);6
7HttpStatus status = response.getStatusCode(); // 201 Created8Product created = response.getBody();7.3 PUT Method
1// Syntax — no return value (void)2void put(String url, Object request, Object... uriVars)3
4// Example5Product updatedProduct = new Product("Laptop Pro", 1299.99);6
7restTemplate.put(8 "http://localhost:8082/product/{id}",9 updatedProduct, // request body10 "1" // path variable replacing {id}11);12// No return — PUT typically has no response body7.4 DELETE Method
1// Syntax — no return value (void)2void delete(String url, Object... uriVars)3
4// Example5restTemplate.delete(6 "http://localhost:8082/product/{id}",7 "1" // path variable8);9// No return — DELETE has no response body7.5 `exchange` Full Control Over Headers and Body
Use exchange when you need to:
- Set custom request headers (e.g., Authorization, custom tokens)
- Control the HTTP method explicitly
- Access the full response (status + headers + body)
- But still want Spring to handle serialization/deserialization automatically
1// Step 1: Build custom headers2HttpHeaders headers = new HttpHeaders();3headers.setContentType(MediaType.APPLICATION_JSON);4headers.set("Authorization", "Bearer my-jwt-token");5headers.set("X-Custom-Header", "custom-value");6
7// Step 2: Create request body8Product productToCreate = new Product("Laptop", 999.99);9
10// Step 3: Combine headers + body into HttpEntity11HttpEntity<Product> httpEntity = new HttpEntity<>(productToCreate, headers);12
13// Step 4: Call exchange14ResponseEntity<Product> response = restTemplate.exchange(15 "http://localhost:8082/product", // URL16 HttpMethod.POST, // HTTP method (explicit control)17 httpEntity, // headers + body combined18 Product.class // expected response type (auto-deserialized)19);20
21HttpStatus status = response.getStatusCode();22Product created = response.getBody();exchange always returns ResponseEntity — you always get the full response. The key advantage is manual control over headers and HTTP method, while Spring still handles JSON serialization/deserialization automatically.7.6 `execute` Full Manual Control
Use execute when you need complete control over everything — including how the request is built and how the response is parsed. This is the lowest-level method; all other RestTemplate methods internally call execute.
1// RequestCallback — functional interface giving access to ClientHttpRequest2RequestCallback requestCallback = (ClientHttpRequest request) -> {3 // Manually set headers4 request.getHeaders().setContentType(MediaType.APPLICATION_JSON);5 request.getHeaders().set("Authorization", "Bearer my-token");6
7 // Manually serialize request body8 Product product = new Product("Laptop", 999.99);9 byte[] bodyBytes = new ObjectMapper().writeValueAsBytes(product);10 request.getBody().write(bodyBytes); // Write to request body stream11};12
13// ResponseExtractor — functional interface giving access to ClientHttpResponse14ResponseExtractor<String> responseExtractor = (ClientHttpResponse response) -> {15 // Manually parse the response stream16 return StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);17};18
19// Execute20String result = restTemplate.execute(21 "http://localhost:8082/product",22 HttpMethod.POST,23 requestCallback,24 responseExtractor25);26
27System.out.println(result);Comparison `getForObject` vs `exchange` vs `execute`
| Method | Header Control | Body Control | Auto Serialization | Auto Deserialization |
|---|---|---|---|---|
getForObject / postForObject | ❌ (default headers) | ❌ (Spring manages) | ✅ | ✅ |
exchange | ✅ (full control) | ✅ (set explicitly) | ✅ | ✅ |
execute | ✅ (full control) | ✅ (manual bytes) | ❌ (manual) | ❌ (manual) |
getForObject or postForObject. Use exchange when you need custom headers. Use execute only in rare cases where you need byte-level control.7.7 Complete Method Summary Table
| Method | HTTP Verb | Returns | When to Use |
|---|---|---|---|
getForObject | GET | Body (T) | Simple GET, only body needed |
getForEntity | GET | ResponseEntity | GET + need status/headers |
postForObject | POST | Body (T) | Simple POST, only body needed |
postForEntity | POST | ResponseEntity | POST + need status/headers |
put | PUT | void | Update resource, no response expected |
delete | DELETE | void | Delete resource, no response expected |
exchange | Any | ResponseEntity | Need custom headers or explicit HTTP method |
execute | Any | Custom (T) | Full manual control, rare use |
8. RestTemplate Limitations
Why `RestTemplate` Is Considered Legacy
RestTemplate was designed before modern HTTP client needs became apparent. Over time, its design choices became problematic enough that Spring moved it to maintenance mode — meaning no new features, only critical bug fixes.
8.1 Overloaded Methods Explosion
Every HTTP operation has multiple overloaded variants. For example, getForObject alone has three overloads:
1getForObject(String url, Class<T> responseType, Object... uriVars)2getForObject(String url, Class<T> responseType, Map<String, ?> uriVars)3getForObject(URI url, Class<T> responseType)Multiply this across getForEntity, postForObject, postForEntity, put, delete, exchange, execute — and then for every new feature (retry, circuit breaker, interceptors), new overloads must be added for every method variant.
RestTemplate. Any new functionality requires adding overloaded methods to every existing operation. The API grows unbounded and becomes impossible to remember or maintain cleanly.8.2 Not Designed for Modern HTTP Features
RestTemplate was built before many modern HTTP client requirements emerged:
| Modern Need | RestTemplate Support |
|---|---|
| Retry logic | Possible but awkward |
| Circuit breaker | Possible but complex |
| Request/response interceptors | Supported but not intuitive |
| Reactive/non-blocking | Not supported |
| Fluent API style | Not supported |
8.3 Difficult to Maintain
- Hard to remember which overload to use
- Parameter lists are long and confusing
- Inconsistent patterns across GET/POST/PUT/DELETE
- New team members face a steep learning curve
9. What Comes Next RestClient and Feign
RestClient The Modern Replacement
RestClient was introduced in Spring 6.1 / Spring Boot 3.2 as the successor to RestTemplate. It uses a fluent (builder-style) API that eliminates overloaded methods.
1// RestClient equivalent of restTemplate.getForObject(url, String.class)2String response = restClient.get()3 .uri("http://localhost:8082/product/{id}", id)4 .retrieve()5 .body(String.class);1// POST with custom headers — clean fluent style2Product created = restClient.post()3 .uri("http://localhost:8082/product")4 .header("Authorization", "Bearer my-token")5 .contentType(MediaType.APPLICATION_JSON)6 .body(newProduct)7 .retrieve()8 .body(Product.class);RestTemplate vs RestClient
| Aspect | RestTemplate | RestClient |
|---|---|---|
| API Style | Method-per-operation (overloaded) | Fluent / builder chain |
| Readability | Moderate | High |
| Maintainability | Low (overloads) | High |
| Modern features | Limited | Full support |
| Status | Maintenance mode | Actively developed |
| Spring version | Legacy | Spring 6.1+ |
FeignClient Spring Cloud Declarative Client
FeignClient is the recommended approach when using Spring Cloud (Eureka, load balancing, etc.). It is declarative — you define an interface, and Spring generates the implementation.
1@FeignClient(name = "product-service", url = "http://localhost:8082")2public interface ProductClient {3
4 @GetMapping("/product/{id}")5 String getProduct(@PathVariable("id") String id);6}1// Usage — just inject and call like a regular method2@Autowired3private ProductClient productClient;4
5String product = productClient.getProduct("1");FeignClient internally uses HTTP mechanisms similar to what we covered. Understanding RestTemplate and RestClient makes it much easier to debug FeignClient behavior and configure timeouts, retries, and interceptors properly.10. Common Mistakes
Mistake 1 Not Configuring Timeouts
1// ❌ WRONG — default timeouts may be too long or infinite in some environments2@Bean3public RestTemplate restTemplate() {4 return new RestTemplate();5}6
7// ✅ CORRECT — always set explicit timeouts in production8@Bean9public RestTemplate restTemplate() {10 SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();11 factory.setConnectTimeout(3000); // 3 seconds12 factory.setReadTimeout(10000); // 10 seconds13 return new RestTemplate(factory);14}Mistake 2 Creating RestTemplate Inside a Method (Not as a Bean)
1// ❌ WRONG — new instance created per request, loses keep-alive cache benefit2@GetMapping("/order/{id}")3public String getOrder(@PathVariable String id) {4 RestTemplate rt = new RestTemplate(); // Don't do this5 return rt.getForObject("http://localhost:8082/product/" + id, String.class);6}7
8// ✅ CORRECT — single shared bean, connection cache is shared across requests9@Autowired10private RestTemplate restTemplate;Mistake 3 Hardcoding Service URLs
1// ❌ WRONG — hardcoded URL, breaks when service moves or port changes2String response = restTemplate.getForObject("http://localhost:8082/product/" + id, String.class);3
4// ✅ CORRECT — externalize to application.properties5// application.properties:6// product.service.url=http://localhost:80827
8@Value("${product.service.url}")9private String productServiceUrl;10
11String response = restTemplate.getForObject(productServiceUrl + "/product/" + id, String.class);Mistake 4 Ignoring HTTP Error Responses
1// ❌ WRONG — getForObject throws HttpClientErrorException for 4xx/5xx2// but this is not caught3String response = restTemplate.getForObject(url, String.class);4
5// ✅ CORRECT — handle HTTP errors explicitly6try {7 String response = restTemplate.getForObject(url, String.class);8} catch (HttpClientErrorException e) {9 // 4xx errors — e.g., 404 Not Found, 400 Bad Request10 System.err.println("Client error: " + e.getStatusCode());11} catch (HttpServerErrorException e) {12 // 5xx errors — e.g., 500 Internal Server Error13 System.err.println("Server error: " + e.getStatusCode());14}Mistake 5 Confusing `getForObject` with `getForEntity`
1// ❌ WRONG — using getForObject when you need the status code2String body = restTemplate.getForObject(url, String.class);3// You cannot access the HTTP status code here4
5// ✅ CORRECT — use getForEntity when you need more than the body6ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);7if (response.getStatusCode() == HttpStatus.OK) {8 String body = response.getBody();9}11. Best Practices
| Practice | Reason |
|---|---|
Always declare RestTemplate as a @Bean | Enables connection pool sharing and Spring management |
| Always configure explicit timeouts | Prevents indefinitely hanging threads |
Externalize service URLs to application.properties | Easier environment-specific configuration |
Use getForEntity when you need status code or headers | Provides full response access |
Use exchange when you need custom headers | Cleaner than building raw requests |
Catch HttpClientErrorException and HttpServerErrorException | Graceful error handling |
Plan to migrate to RestClient for new code | RestTemplate is in maintenance mode |
Use FeignClient in Spring Cloud environments | Better integration with service discovery and load balancing |
Set reasonable connectTimeout (2-5s) and readTimeout (5-30s) | Tune based on expected service response times |
12. Interview Notes
Q: What is the difference between synchronous and asynchronous microservice communication?
Synchronous: the calling thread blocks and waits for a response before continuing (RestTemplate, RestClient, FeignClient). Asynchronous: the calling service publishes a message and continues immediately without waiting (Kafka, RabbitMQ).
Q: What is `HttpURLConnection` and what role does it play?
HttpURLConnection is the Java standard library's class for HTTP connections. It wraps a TCP socket and holds all request configuration (method, headers, timeouts, URL). RestTemplate creates and manages HttpURLConnection objects internally through its ClientHttpRequestFactory.
Q: What is the difference between `connectTimeout` and `readTimeout`?
connectTimeout is the maximum time allowed for the TCP handshake to complete (client connecting to server). readTimeout is the maximum time the client will wait for a response from the server after the connection is established.
Q: What is HTTP Keep-Alive and why does it matter for microservices?
Keep-Alive (default in HTTP 1.1) allows the same TCP connection to be reused for multiple HTTP requests. This avoids the overhead of TCP 3-way handshake for every call. In high-throughput microservices where a service calls another hundreds of times per second, this significantly reduces latency and resource consumption.
Q: What is the difference between `getForObject` and `getForEntity`?
getForObject returns only the deserialized response body. getForEntity returns a ResponseEntity containing the body, HTTP status code, and response headers.
Q: When would you use `exchange` instead of `getForObject`?
When you need to set custom HTTP headers (Authorization, custom tokens), use an HTTP method not covered by a specific method, or access the full response including status and headers.
Q: Why is `RestTemplate` considered legacy?
It is in maintenance mode — no new features, only bug fixes. Its design (many overloaded methods per operation) doesn't scale cleanly as new HTTP features are added. RestClient (Spring 6.1+) is the modern replacement with a fluent API.
Q: What does `RestTemplate` use internally for HTTP connections?
By default, it uses SimpleClientHttpRequestFactory, which creates HttpURLConnection objects. These internally use Java's keep-alive connection cache (keyed by host:port) to reuse TCP connections across requests.
Q: What is the difference between `RestTemplate`, `RestClient`, and `FeignClient`?
RestTemplate — legacy Spring HTTP client, imperative, maintenance mode. RestClient — modern Spring HTTP client, fluent API, actively developed. FeignClient — declarative interface-based client for Spring Cloud, integrates with service discovery and load balancing.
13. Practice Questions
Easy
- What are the two services set up in this guide and on which ports do they run?
- What is the difference between
connectTimeoutandreadTimeout? - What does HTTP Keep-Alive mean? What do
timeout=5andmax=50mean? - What is
HttpURLConnection? When does a TCP connection actually get created? - What is
SimpleClientHttpRequestFactoryinRestTemplate?
Medium
- Explain the three steps in plain Java HTTP communication. What happens at each step?
- What is the difference between
getForObjectandgetForEntity? When would you choose each? - Trace what happens internally when you call
restTemplate.getForObject(url, String.class). - Explain the keep-alive cache in
RestTemplate. How does it reuse connections? - When would you use
exchangeoverpostForObject? Give a concrete example.
Hard
- Why does HTTP 1.1 keep TCP connections alive? What are the performance implications for microservices that make frequent inter-service calls?
- Explain the architectural flaw in
RestTemplatethat led to it being placed in maintenance mode. How doesRestClientsolve it? - Write a
RestTemplatecall usingexecutethat sends a POST request with a custom Authorization header and manually parses the response as aProductobject. - How would you implement retry logic with
RestTemplate? What are the limitations? - Compare
FeignClientandRestTemplateacross: ease of use, Spring Cloud integration, declarative vs imperative style, and production readiness for new projects.
14. Summary Revision Bullets
- Two microservices: Order Service (8081) and Product Service (8082); set up with Spring Web only (no Spring Cloud initially)
- Synchronous communication = calling thread blocks until response received; types:
RestTemplate,RestClient,FeignClient - HTTP GET request = method + URI + protocol + host + headers; POST adds
Content-Type,Content-Length, and body - HTTP 1.0 = connection closes after each response; HTTP 1.1 =
Connection: keep-aliveby default → TCP reused - Keep-Alive config:
timeout=5(idle seconds before close) +max=50(max requests per connection) - Plain Java: create
HttpURLConnection→ callgetInputStream()(triggers connect + request + response) → read stream →disconnect() disconnect()does NOT always close TCP — if stream fully read, connection returns to keep-alive cache (key:host:port)- RestTemplate wraps all plain Java mechanics:
createRequest()→execute()→ parse withHttpMessageConverter→ close stream (TCP stays in cache) getForObject→ body only;getForEntity→ fullResponseEntity(body + status + headers)postForObject/postForEntityfor POST;put()anddelete()return voidexchange→ full control over headers + HTTP method + body, Spring still auto-serializes/deserializesexecute→ full manual control including serialization; all other methods callexecuteinternally- RestTemplate limitations: overloaded method explosion, not designed for modern features, in maintenance mode (no new features)
- RestClient (Spring 6.1+) = fluent builder API, modern replacement; FeignClient = declarative interface-based, Spring Cloud recommended approach
RestTemplate (and later RestClient and FeignClient) is just an abstraction over the same underlying TCP/HTTP mechanics.Mastery check
How well can you recall this?
Finished this lesson?