FeignClient
Declarative HTTP clients with OpenFeign, @FeignClient, ErrorDecoder, fallbacks
- Define a typed HTTP client with @FeignClient and interface methods
- Implement a FeignClient ErrorDecoder for domain-specific error handling
- Add fallback behavior with FeignClient fallback classes
A comprehensive reference covering Feign Client concepts, internal mechanics, custom encoder/decoder, error handling, retry logic, and configuration — deep enough to replace watching the original lecture.
Table of Contents
- What is Feign Client?
- What is Spring Cloud?
- Feign Client vs RestTemplate vs RestClient
- Project Setup — Maven Dependency
- Core Implementation — Four Required Steps
- How Feign Client Works Internally
- Writing Feign Client Methods — Annotation Reference
- Encoder & Decoder in Feign
- Error Decoder — Custom Exception Handling
- Retry Mechanism
- Per-Client Configuration
- Timeout Configuration via application.properties
- Complete Internal Flow Diagram
- Key Observations & Best Practices
- Common Mistakes
- Interview Notes
- Summary — Revision Bullets
1. What is Feign Client?
Overview
Feign is a declarative HTTP client originally developed by Netflix. It is now available in the Spring ecosystem via the Spring Cloud OpenFeign library.
The word declarative is the defining characteristic of Feign:
| Approach | What You Write |
|---|---|
| Imperative (RestTemplate, RestClient) | How to make the HTTP call — URL building, connection management, response parsing |
| Declarative (Feign) | What to call — just an interface with annotations; the framework handles how |
Why Feign Exists
In a microservices architecture, services constantly communicate with each other over HTTP. Without Feign, a developer must repeatedly write boilerplate code for:
- Building URLs (base URL + path variables + query params)
- Setting headers and content types
- Serializing request bodies to JSON
- Deserializing JSON responses to Java objects
- Handling error status codes
- Managing connection/read timeouts
- Implementing retry logic
Feign eliminates all of this by letting you define an interface that looks almost identical to a Spring MVC controller, and the framework generates the implementation at runtime.
Real-World Analogy
Think of Feign like ordering food at a restaurant. You (the developer) just say "I want the pasta" (declare the endpoint). You don't go into the kitchen and cook it yourself (write HTTP plumbing). The kitchen (Feign framework) knows how to fulfill the order.
2. What is Spring Cloud?
Spring Cloud is a set of tools and libraries built on top of Spring Boot that provides ready-made solutions for building distributed microservice systems.
Features Provided by Spring Cloud
| Feature | Purpose |
|---|---|
| Service Discovery | Register and discover services (Eureka, Consul) |
| Client-Side Load Balancing | Distribute requests across multiple instances (Spring Cloud LoadBalancer) |
| Circuit Breaker | Prevent cascading failures (Resilience4j) |
| API Gateway | Central entry point for all services (Spring Cloud Gateway) |
| Distributed Tracing | Track requests across services (Micrometer Tracing) |
| Centralized Configuration | Manage config for all services in one place (Spring Cloud Config) |
| OpenFeign | Declarative HTTP client for inter-service communication |
Why Use OpenFeign via Spring Cloud?
One major reason to use Feign (over alternatives) is its seamless integration with all other Spring Cloud modules. For example:
- Feign automatically integrates with Eureka for service discovery (use service name instead of URL).
- Feign integrates with Spring Cloud LoadBalancer for client-side load balancing.
- Feign integrates with Resilience4j for circuit breaking.
You get all of this with minimal additional configuration because they are all part of the same ecosystem.
3. Feign Client vs RestTemplate vs RestClient
| Feature | RestTemplate | RestClient | Feign Client |
|---|---|---|---|
| Style | Imperative | Imperative (fluent) | Declarative |
| Code Required | High | Medium | Minimal |
| Interface-based | No | No | Yes |
| Auto-serialization | Manual setup | Built-in | Built-in |
| Error Handling | Manual | Via onStatus | Via ErrorDecoder |
| Retry | Manual | Manual | Built-in configurable |
| Spring Cloud Integration | Limited | Limited | Native |
| Load Balancing | Manual | Manual | Auto with Spring Cloud LB |
| Recommended for | Legacy apps | Modern single services | Microservices |
4. Project Setup Maven Dependency
Adding the Dependency
1<!-- pom.xml -->2<dependencies>3 <dependency>4 <groupId>org.springframework.cloud</groupId>5 <artifactId>spring-cloud-starter-openfeign</artifactId>6 <!-- No version needed — managed by Spring Cloud BOM -->7 </dependency>8</dependencies>9
10<dependencyManagement>11 <dependencies>12 <dependency>13 <groupId>org.springframework.cloud</groupId>14 <artifactId>spring-cloud-dependencies</artifactId>15 <version>2023.0.3</version> <!-- Use latest compatible version -->16 <type>pom</type>17 <scope>import</scope>18 </dependency>19 </dependencies>20</dependencyManagement>Why `dependencyManagement`?
In a real microservices project, you will add multiple Spring Cloud libraries over time:
spring-cloud-starter-openfeign(Feign)spring-cloud-starter-netflix-eureka-client(Service Discovery)spring-cloud-starter-loadbalancer(Load Balancing)
All Spring Cloud libraries must be version-compatible with each other. Managing this manually is error-prone.
The spring-cloud-dependencies BOM (Bill of Materials) solves this: declare the BOM once, and every Spring Cloud dependency you add will automatically get the correct compatible version — no version tags needed on individual dependencies.
spring-boot-dependencies BOM. It centralizes version management so you never have to worry about compatibility.5. Core Implementation Four Required Steps
This section covers the minimum required to make Feign work. The example scenario:
- Order Service runs on port
8081and needs to call Product Service - Product Service runs on port
8082and exposes aGET /products/{id}endpoint
Step 1 Create the Feign Client Interface
1// ProductClient.java (inside Order Service)2import org.springframework.cloud.openfeign.FeignClient;3import org.springframework.web.bind.annotation.GetMapping;4import org.springframework.web.bind.annotation.PathVariable;5
6@FeignClient(name = "product-service", url = "${feign.client.product-service.url}")7public interface ProductClient {8
9 @GetMapping("/products/{id}")10 String getProductById(@PathVariable("id") Long id);11}◆ Line-by-Line Explanation
@FeignClient— marks this interface as a Feign client; Spring will generate a runtime implementation for it.name = "product-service"— an arbitrary logical name for this client; used for configuration lookup and Spring Cloud service discovery.url = "${feign.client.product-service.url}"— the base URL of the target service, read fromapplication.properties. You can also hardcode it:url = "http://localhost:8082".@GetMapping("/products/{id}")— exactly like a Spring MVC controller annotation; defines the relative path and HTTP method.@PathVariable("id") Long id— the{id}in the path will be replaced by this value at runtime.
Step 2 Configure `application.properties`
1# application.properties (Order Service)2
3# Base URL for the Product Service Feign client4feign.client.product-service.url=http://localhost:80825
6# Timeouts (optional — covered in detail later)7feign.client.config.product-service.connect-timeout=30008feign.client.config.product-service.read-timeout=5000feign.client.product-service.url is not a Spring standard. It is a custom key you defined in @FeignClient(url = "${feign.client.product-service.url}"). You can name it anything you like.Step 3 Enable Feign Clients in the Application Class
1// OrderServiceApplication.java2import org.springframework.boot.SpringApplication;3import org.springframework.boot.autoconfigure.SpringBootApplication;4import org.springframework.cloud.openfeign.EnableFeignClients;5
6@SpringBootApplication7@EnableFeignClients // Critical — tells Spring to scan for @FeignClient interfaces8public class OrderServiceApplication {9 public static void main(String[] args) {10 SpringApplication.run(OrderServiceApplication.class, args);11 }12}◆ Why `@EnableFeignClients` Is Required
Without this annotation, Spring Boot does not scan for interfaces annotated with @FeignClient. The interface will simply be ignored — no implementation will be generated, and autowiring will fail with a NoSuchBeanDefinitionException.
@EnableFeignClients is one of the most common mistakes when setting up Feign. Always add it to your main application class.Step 4 Use the Feign Client in a Controller or Service
1// OrderController.java2import org.springframework.beans.factory.annotation.Autowired;3import org.springframework.web.bind.annotation.GetMapping;4import org.springframework.web.bind.annotation.PathVariable;5import org.springframework.web.bind.annotation.RestController;6
7@RestController8public class OrderController {9
10 @Autowired11 private ProductClient productClient; // Autowired like any normal Spring bean12
13 @GetMapping("/order/{productId}")14 public String placeOrder(@PathVariable Long productId) {15 // Call the Product Service using Feign — one line, no boilerplate16 String productDetails = productClient.getProductById(productId);17
18 System.out.println("Response from Product API: " + productDetails);19 return "Order call successful. Product: " + productDetails;20 }21}ProductClient is an interface (and you cannot normally autowire interfaces without an implementation), Feign creates a runtime proxy object — so Spring's dependency injection works perfectly.The Four Steps Summary
6. How Feign Client Works Internally
This is the most important section. It answers the fundamental question:
"We created only an interface with no implementation. How does `@Autowired` work? Where does the implementation come from?"
When the Spring application starts (because of @EnableFeignClients), for every interface annotated with @FeignClient, Feign's framework invokes ReflectiveFeign.newInstance(). This method performs three steps.
Step 1 Parse Methods Create `MethodHandler` Objects
For each method in the interface, Feign creates a MethodHandler object by parsing:
- The method's annotations (
@GetMapping,@PostMapping, etc.) - The method's parameters and their annotations (
@PathVariable,@RequestParam,@RequestHeader,@RequestBody)
The MethodHandler object holds all the information needed to execute an actual HTTP request:
| Field in MethodHandler | How It's Derived |
|---|---|
targetUrl | Base URL (@FeignClient.url) + relative path (@GetMapping) |
httpMethod | From @GetMapping → GET, @PostMapping → POST, etc. |
headers | From @RequestHeader annotations on method parameters |
httpClient | Default: HttpURLConnection; configurable (e.g., Apache HttpClient, OkHttp) |
encoder | Default: Spring's Jackson-based encoder; configurable |
decoder | Default: Spring's Jackson-based decoder; configurable |
errorDecoder | Default: ErrorDecoder.Default; configurable |
logger | Default: Feign logger; configurable |
retryer | Default: Retryer.Default (5 attempts); configurable |
After all methods are parsed, Feign creates a map of {Method → MethodHandler}.
1Map {2 getProductById → MethodHandler { url, GET, encoder, decoder, retryer, ... }3 updateProduct → MethodHandler { url, PUT, headers, body, encoder, decoder, ... }4}Step 2 Create `InvocationHandler`
Feign creates an InvocationHandler object and populates it with the map from Step 1.
The InvocationHandler has:
- The
{Method → MethodHandler}map - A method called
invoke()— this is the bridge between the proxy (Step 3) and the actual HTTP execution
1InvocationHandler {2 map: { getProductById → MethodHandler, ... }3 invoke(method, args) → looks up MethodHandler → calls MethodHandler.invoke()4}Step 3 Create Dynamic Proxy (Runtime Implementation)
Feign uses Java's Dynamic Proxy (java.lang.reflect.Proxy) to create a runtime implementation of your interface.
You will never find this class in any source code — it is generated dynamically at runtime. For illustration, it would look something like this:
1// This class does NOT exist in source code.2// It is dynamically generated at runtime by Java's Proxy mechanism.3class FeignProductClientProxy implements ProductClient {4
5 private final InvocationHandler handler;6
7 FeignProductClientProxy(InvocationHandler handler) {8 this.handler = handler;9 }10
11 @Override12 public String getProductById(Long id) {13 // Get the Method object for this method via reflection14 Method method = ProductClient.class.getMethod("getProductById", Long.class);15 // Delegate to the InvocationHandler16 return (String) handler.invoke(this, method, new Object[]{id});17 }18}This proxy object is registered as a Spring bean, which is why @Autowired works.
Step 4 Runtime Call Flow (When You Actually Call the Method)
When your controller calls productClient.getProductById(1L):
The Full Internal Architecture Diagram
7. Writing Feign Client Methods Annotation Reference
Feign method signatures mirror Spring MVC controller methods almost exactly. Here is a comprehensive example:
1@FeignClient(name = "product-service", url = "${feign.client.product-service.url}")2public interface ProductClient {3
4 // Simple GET with path variable5 @GetMapping("/products/{id}")6 String getProductById(@PathVariable("id") Long id);7
8 // PUT with path variable, request param, custom header, and request body9 @PutMapping(value = "/products/update/{id}", consumes = "application/json")10 String updateProduct(11 @PathVariable("id") Long id,12 @RequestBody ProductDto productDto,13 @RequestParam("sendEmail") boolean sendEmail,14 @RequestHeader("X-Custom-Header") String customHeader15 );16
17 // POST with request body18 @PostMapping(value = "/products", consumes = "application/json")19 ProductDto createProduct(@RequestBody ProductDto productDto);20
21 // DELETE22 @DeleteMapping("/products/{id}")23 void deleteProduct(@PathVariable("id") Long id);24}Parameter Annotation Mapping
| Annotation | Maps To | Example |
|---|---|---|
@PathVariable | URL path segment (/products/{id}) | @PathVariable("id") Long id |
@RequestParam | Query parameter (?sendEmail=true) | @RequestParam("sendEmail") boolean flag |
@RequestHeader | HTTP header | @RequestHeader("X-Auth") String token |
@RequestBody | HTTP request body (JSON) | @RequestBody ProductDto dto |
Corresponding Product Service Controller (for reference)
1// ProductController.java (Product Service — port 8082)2@RestController3public class ProductController {4
5 @GetMapping("/products/{id}")6 public String getProduct(@PathVariable Long id) {7 return "Product details for ID: " + id;8 }9
10 @PutMapping("/products/update/{id}")11 public String updateProduct(12 @PathVariable Long id,13 @RequestBody ProductDto dto,14 @RequestParam boolean sendEmail,15 @RequestHeader("X-Custom-Header") String header16 ) {17 return "Product " + id + " updated";18 }19}8. Encoder & Decoder in Feign
What They Do
| Component | Direction | Purpose |
|---|---|---|
| Encoder | Java Object → HTTP Body | Serializes your @RequestBody objects to JSON (or other format) before sending |
| Decoder | HTTP Body → Java Object | Deserializes the response body (JSON) back into a Java object |
This is conceptually the same as serialization/deserialization in RestTemplate, but abstracted behind an interface.
Default Behavior
By default, Feign uses Spring's encoder/decoder, which internally uses Jackson (ObjectMapper):
- Encoder: Converts Java object → raw JSON string → places in request body
- Decoder: Reads response byte stream → converts JSON → Java object
You generally do not need to override these unless you have a special serialization format or custom logic.
Writing a Custom Encoder
1// CustomProductEncoder.java2import feign.codec.Encoder;3import feign.RequestTemplate;4import com.fasterxml.jackson.databind.ObjectMapper;5
6public class CustomProductEncoder implements Encoder {7
8 private final ObjectMapper objectMapper = new ObjectMapper();9
10 @Override11 public void encode(Object object, Type bodyType, RequestTemplate template) {12 try {13 // Convert Java object to JSON string14 String json = objectMapper.writeValueAsString(object);15 // Set JSON as the request body16 template.body(json);17 } catch (Exception e) {18 throw new RuntimeException("Encoding failed", e);19 }20 }21}Writing a Custom Decoder
1// CustomProductDecoder.java2import feign.codec.Decoder;3import feign.Response;4import com.fasterxml.jackson.databind.ObjectMapper;5
6import java.io.InputStream;7import java.lang.reflect.Type;8
9public class CustomProductDecoder implements Decoder {10
11 private final ObjectMapper objectMapper = new ObjectMapper();12
13 @Override14 public Object decode(Response response, Type type) throws Exception {15 // Read the response body as an InputStream16 try (InputStream inputStream = response.body().asInputStream()) {17 // Convert JSON bytes to the expected Java type18 return objectMapper.readValue(inputStream, objectMapper.constructType(type));19 }20 }21}Registering Custom Encoder/Decoder in Configuration
1// ProductClientConfig.java2import org.springframework.context.annotation.Bean;3import org.springframework.context.annotation.Configuration;4import feign.codec.Encoder;5import feign.codec.Decoder;6
7@Configuration8public class ProductClientConfig {9
10 @Bean11 public Encoder feignEncoder() {12 return new CustomProductEncoder();13 }14
15 @Bean16 public Decoder feignDecoder() {17 return new CustomProductDecoder();18 }19}Linking the Config to a Specific Feign Client
1@FeignClient(2 name = "product-service",3 url = "${feign.client.product-service.url}",4 configuration = ProductClientConfig.class // Apply config only to this client5)6public interface ProductClient {7 // ...8}configuration = ProductClientConfig.class, this encoder/decoder applies only to this Feign client. A different client (e.g., SalesClient) can have its own configuration without any conflict.Per-Client Configuration Why It Matters
Each Feign client can have completely independent configuration. This is clean, maintainable, and avoids cross-contamination between clients.
9. Error Decoder Custom Exception Handling
What is Error Decoder?
An Error Decoder in Feign is the equivalent of exception handling in RestClient. It handles HTTP responses with non-2xx status codes (4xx client errors, 5xx server errors).
Default Behavior
By default, Feign uses ErrorDecoder.Default, which wraps all error responses into a FeignException containing:
- HTTP status code
- Response body
- Response headers
1// What the default error decoder does internally2public class ErrorDecoder.Default implements ErrorDecoder {3 @Override4 public Exception decode(String methodKey, Response response) {5 // Returns a FeignException with status + body + headers6 return FeignException.errorStatus(methodKey, response);7 }8}Writing a Custom Error Decoder
◆ Step 1 Custom Exception Classes
1// ClientErrorException.java (4xx errors)2public class ClientErrorException extends RuntimeException {3
4 private final int statusCode;5
6 public ClientErrorException(int statusCode, String message) {7 super(message);8 this.statusCode = statusCode;9 }10
11 public int getStatusCode() {12 return statusCode;13 }14}15
16// ServerErrorException.java (5xx errors)17public class ServerErrorException extends RuntimeException {18
19 private final int statusCode;20
21 public ServerErrorException(int statusCode, String message) {22 super(message);23 this.statusCode = statusCode;24 }25
26 public int getStatusCode() {27 return statusCode;28 }29}◆ Step 2 Implement Custom Error Decoder
1// CustomErrorDecoder.java2import feign.Response;3import feign.codec.ErrorDecoder;4
5public class CustomErrorDecoder implements ErrorDecoder {6
7 // Fallback to the default decoder for unhandled cases8 private final ErrorDecoder defaultDecoder = new ErrorDecoder.Default();9
10 @Override11 public Exception decode(String methodKey, Response response) {12 int status = response.status();13
14 if (status >= 400 && status < 500) {15 // 4xx — client-side error16 return new ClientErrorException(status, "Client error: HTTP " + status);17 }18
19 if (status >= 500) {20 // 5xx — server-side error21 return new ServerErrorException(status, "Server error: HTTP " + status);22 }23
24 // Unknown error — delegate to the default decoder25 return defaultDecoder.decode(methodKey, response);26 }27}◆ Step 3 Register in Configuration
1// ProductClientConfig.java2@Configuration3public class ProductClientConfig {4
5 @Bean6 public ErrorDecoder errorDecoder() {7 return new CustomErrorDecoder();8 }9}Error Decoder Flow
Decoder.10. Retry Mechanism
When Does Retry Happen?
Retry in Feign is triggered only for retriable exceptions — primarily:
IOException(network errors)- Connection timeouts
Retry does not trigger for HTTP error status codes (4xx/5xx) — those go directly to the Error Decoder.
Default Retry Behavior
Feign uses Retryer.Default out of the box with these settings:
| Setting | Default Value | Meaning |
|---|---|---|
maxAttempts | 5 | Total attempts (1 real + 4 retries) |
period (initial wait) | 100ms | Wait before the first retry |
maxPeriod | 1000ms (1 second) | Maximum wait time between retries |
The wait time doubles between each retry (exponential backoff), capped at maxPeriod:
| Attempt | Wait Before This Attempt |
|---|---|
| 1st (original) | Immediate |
| 2nd (retry 1) | 100ms |
| 3rd (retry 2) | 200ms |
| 4th (retry 3) | 400ms |
| 5th (retry 4) | 800ms (capped at 1000ms) |
After all attempts are exhausted, the exception is passed to the Error Decoder.
Retry Flow in Method Handler
Option 1 Disable Retry (Never Retry)
1// ProductClientConfig.java2import feign.Retryer;3import org.springframework.context.annotation.Bean;4import org.springframework.context.annotation.Configuration;5
6@Configuration7public class ProductClientConfig {8
9 @Bean10 public Retryer retryer() {11 // Only 1 attempt — no retries at all12 return Retryer.NEVER_RETRY;13 }14}Option 2 Customize Default Retry (Change Values Only)
If you only want to change the timing/attempt values without rewriting the logic:
1// CustomRetryer.java2import feign.Retryer;3
4public class CustomRetryer extends Retryer.Default {5
6 public CustomRetryer() {7 super(8 200, // Initial period: 200ms (instead of 100ms)9 2000, // Max period: 2 seconds (instead of 1 second)10 3 // Max attempts: 3 (instead of 5)11 );12 }13 // All retry logic (doubling, capping) inherited from Default14}Option 3 Full Custom Retry (Complete Control)
1// FullCustomRetryer.java2import feign.RetryableException;3import feign.Retryer;4
5public class FullCustomRetryer implements Retryer {6
7 private final int maxAttempts = 3;8 private int attempt = 1;9
10 @Override11 public void continueOrPropagate(RetryableException e) {12 if (attempt >= maxAttempts) {13 throw e; // Exhausted all attempts — propagate the exception14 }15 attempt++;16 try {17 Thread.sleep(100); // Fixed 100ms wait (no doubling)18 } catch (InterruptedException ignored) {19 Thread.currentThread().interrupt();20 }21 }22
23 @Override24 public Retryer clone() {25 return new FullCustomRetryer(); // Required — Feign calls clone() per request26 }27}◆ Register in Configuration
1@Bean2public Retryer retryer() {3 return new CustomRetryer();4 // or: return new FullCustomRetryer();5}11. Per-Client Configuration
Full Configuration Class Example
1// ProductClientConfig.java2import feign.codec.Decoder;3import feign.codec.Encoder;4import feign.codec.ErrorDecoder;5import feign.Retryer;6import org.springframework.context.annotation.Bean;7import org.springframework.context.annotation.Configuration;8
9@Configuration10public class ProductClientConfig {11
12 @Bean13 public Encoder feignEncoder() {14 return new CustomProductEncoder();15 }16
17 @Bean18 public Decoder feignDecoder() {19 return new CustomProductDecoder();20 }21
22 @Bean23 public ErrorDecoder errorDecoder() {24 return new CustomErrorDecoder();25 }26
27 @Bean28 public Retryer retryer() {29 return new CustomRetryer(); // or Retryer.NEVER_RETRY30 }31}Attaching Configuration to the Client
1@FeignClient(2 name = "product-service",3 url = "${feign.client.product-service.url}",4 configuration = ProductClientConfig.class5)6public interface ProductClient {7 // Methods...8}ProductClientConfig, SalesClientConfig, UserClientConfig — each with its own timeouts, encoders, error handlers, and retry policies. They have zero impact on each other.12. Timeout Configuration via `application.properties`
Feign allows you to configure timeouts per client (using the name from @FeignClient) or globally.
Per-Client Timeout
1# Applies only to the Feign client named "product-service"2feign.client.config.product-service.connect-timeout=30003feign.client.config.product-service.read-timeout=5000Global Timeout (All Feign Clients)
1# Applies to ALL Feign clients unless overridden per client2feign.client.config.default.connect-timeout=50003feign.client.config.default.read-timeout=10000Priority Rule
When both are set, per-client configuration takes priority over the default configuration.
Timeout Meanings
| Property | Meaning |
|---|---|
connect-timeout | Maximum time (ms) to establish a TCP connection |
read-timeout | Maximum time (ms) to wait for a response after connection is established |
How Timeouts Relate to MethodHandler
These timeout values ultimately get read and applied when the MethodHandler builds its httpClient configuration before executing the request. The httpClient field in MethodHandler uses these values when establishing the connection and waiting for the response.
13. Complete Internal Flow Diagram
Startup Flow (Once, When Application Starts)
Request Flow (Every Time You Call a Feign Method)
14. Key Observations & Best Practices
Key Observations
- No implementation needed — Feign generates the implementation at runtime via Java Dynamic Proxy. The
@FeignClientinterface is all you write.
@EnableFeignClientsis mandatory — without it, Spring will not scan for Feign interfaces. This is the single most common setup mistake.
namein@FeignClienthas two purposes:
- Used as the key for
feign.client.config.properties in.* application.properties - Used as the service name for Spring Cloud service discovery (Eureka/Consul) — when discovery is active, you don't even need the
urlparameter
- Encoder/Decoder default to Jackson — you rarely need to override these unless you have a non-JSON format or special serialization logic.
- ErrorDecoder only handles non-2xx — it is not a general-purpose exception handler; it specifically handles HTTP error status codes.
- Retry only for retriable exceptions — HTTP 4xx/5xx go directly to ErrorDecoder; retry only triggers on
IOExceptionand network-level failures.
- Per-client configuration is clean — each Feign client can have its own encoder, decoder, error handler, retry policy, and timeouts without impacting other clients.
Best Practices
- Externalize base URLs to
application.properties— never hardcode them in the annotation. - Use
dependencyManagementfor Spring Cloud BOM — avoids version conflict headaches. - Create separate config classes per Feign client for isolation.
- Use
Retryer.NEVER_RETRYfor non-idempotent operations (POST, PATCH) where retrying could cause duplicate side effects. - Implement custom ErrorDecoder in production — the default
FeignExceptionis too generic for meaningful error handling. - Set explicit timeouts — never rely on the default, which can cause threads to hang indefinitely in production.
- When using Spring Cloud service discovery, remove the
urlfrom@FeignClientand use onlyname— Feign will resolve the URL dynamically.
15. Common Mistakes
Mistake 1 Forgetting `@EnableFeignClients`
1// WRONG — Feign interfaces are ignored; @Autowired will fail2@SpringBootApplication3public class OrderServiceApplication { ... }4
5// CORRECT6@SpringBootApplication7@EnableFeignClients8public class OrderServiceApplication { ... }Mistake 2 Providing an Implementation for the Feign Interface
1// WRONG — Do NOT implement the interface yourself2@Service3public class ProductClientImpl implements ProductClient {4 @Override5 public String getProductById(Long id) {6 // manual HTTP code...7 }8}9
10// CORRECT — Leave it as an interface; Feign generates the implementation11@FeignClient(name = "product-service", url = "...")12public interface ProductClient {13 @GetMapping("/products/{id}")14 String getProductById(@PathVariable("id") Long id);15}Mistake 3 Using the Wrong Base URL Format
1# WRONG — missing the protocol2feign.client.product-service.url=localhost:80823
4# CORRECT5feign.client.product-service.url=http://localhost:8082Mistake 4 Using Retry on Non-Idempotent Operations
Retrying a POST /orders on a network timeout could create duplicate orders. Use Retryer.NEVER_RETRY or use retry only for GET operations.
Mistake 5 Putting `@Configuration` on Feign Config Class and Letting It Be Component-Scanned
If ProductClientConfig is annotated with @Configuration and is in a package scanned by Spring, it becomes a global configuration applied to all Feign clients, not just the one specified in configuration = ProductClientConfig.class.
Fix: Either don't annotate with @Configuration, or place it in a sub-package that is not component-scanned.
1// To make it truly local to one client:2// Option A: Don't use @Configuration, just reference the class3// Option B: Place in a package excluded from @ComponentScan16. Interview Notes
Q: What does "declarative" mean in Feign Client?
Declarative means you declare what you want (which API to call, with what parameters), not how to do it (building URLs, managing connections, parsing responses). The framework handles the how.
Q: How does @Autowired work on a Feign interface if there's no implementation class?
Feign uses Java's Dynamic Proxy to generate a runtime implementation of the interface during application startup. This proxy object is registered as a Spring bean, making it available for@Autowiredinjection.
Q: What is MethodHandler in Feign?
AMethodHandleris an object created by Feign for each method in a@FeignClientinterface. It holds all information derived from the method's annotations (target URL, HTTP method, headers, encoder, decoder, retryer, error decoder) and contains the logic that actually executes the HTTP request.
Q: What is the role of InvocationHandler in Feign?
InvocationHandleracts as a bridge between the Dynamic Proxy and theMethodHandler. When a method is called on the proxy, the proxy callsInvocationHandler.invoke(), which looks up the correspondingMethodHandlerin its map and delegates execution to it.
Q: What is the difference between Encoder/Decoder and ErrorDecoder?
Encoderconverts a Java request body to JSON (outgoing).Decoderconverts a JSON response body to a Java object (incoming). Both deal with 2xx responses.ErrorDecoderis only invoked for non-2xx responses (4xx/5xx) and is responsible for throwing appropriate exceptions.
Q: When does Feign retry a request?
Only on retriable exceptions — specificallyIOExceptionand network/connection timeouts. HTTP error status codes (4xx/5xx) go directly to theErrorDecoderand are not retried.
Q: How do you apply different configurations to different Feign clients?
By specifying aconfigurationclass in the@FeignClientannotation. Each client can reference a different configuration class with its own@Beandefinitions for encoder, decoder, retryer, and errorDecoder.
Q: What is the purpose of the name in @FeignClient?
Two purposes: (1) it's the key used infeign.client.config.properties for per-client timeout configuration; (2) when Spring Cloud service discovery (Eureka) is active, it's the service name used to resolve the actual URL dynamically — eliminating the need for a hardcoded.* url.
Q: What is the spring-cloud-dependencies BOM and why is it important?
It's a Bill of Materials that centrally manages compatible versions of all Spring Cloud libraries. Without it, you must manually ensure that openfeign, eureka, loadbalancer, and other spring cloud dependencies are mutually compatible. With the BOM, you omit version tags and Maven resolves compatible versions automatically.
17. Summary Revision Bullets
- Feign = declarative HTTP client by Netflix; available in Spring via
spring-cloud-starter-openfeign. - Declarative = you tell what to call (interface + annotations); framework handles how.
- Spring Cloud = ecosystem of tools for distributed microservices; Feign integrates natively with all of them.
- BOM (
spring-cloud-dependencies) = manages compatible versions of all Spring Cloud deps; avoids manual version conflicts. - Four steps for basic Feign setup:
- Create
@FeignClientinterface with annotated methods - Set base URL in
application.properties - Add
@EnableFeignClientsto the main class @Autowiredthe interface and call its methods
- Internal mechanics — 3 steps at startup:
- Parse each method → create
MethodHandler(holds URL, method, encoder, decoder, retryer, etc.) - Create
InvocationHandler(holds the Method→MethodHandler map; hasinvoke()bridge) - Create Dynamic Proxy (implements the interface; delegates all calls to
InvocationHandler)
MethodHandleris the core object — it holds everything needed to make an HTTP call and actually executes it.- Encoder = Java object → JSON (request body serialization); default uses Jackson.
- Decoder = JSON → Java object (response deserialization); default uses Jackson.
- ErrorDecoder = handles non-2xx responses; default throws
FeignException; fully customizable. - Retry = only for
IOException/network errors (not for 4xx/5xx); default = 5 attempts with doubling backoff; configurable or disable withRetryer.NEVER_RETRY. - Per-client config =
configuration = MyConfig.classon@FeignClient; isolates encoder/decoder/retry/errors per client. - Timeout config =
feign.client.config.and.connect-timeout read-timeout; usedefaultto apply to all clients. @EnableFeignClientsis not optional — without it, Feign interfaces are completely ignored.
End of Study Guide
Mastery check
How well can you recall this?
Finished this lesson?