Quiz: Spring Cloud and Microservices
Test your knowledge on microservices architecture and Spring Cloud.
30 questions - Click on each question to reveal the answer.
Questions 1-10: Microservices Architecture
Question 1: What is the difference between monolith and microservices?
Answer:
| Monolith | Microservices |
|---|---|
| Single application | Independent services |
| One database | DB per service |
| Global deployment | Independent deployment |
| Global scaling | Scaling per service |
| Simple at first | Complex at first |
| Strong coupling | Loose coupling |
Question 2: When to choose a microservices architecture?
Answer:
- Large team (multiple teams)
- Need for differentiated scalability
- Different technologies per service
- Frequent independent deployments
- Fault tolerance per service
Avoid for: small teams, prototypes, simple applications.
Question 3: What is Service Discovery?
Answer: Mechanism allowing services to dynamically find each other without static IP address configuration.
Service A: "Where is Service B?"
↓
Eureka Server: "Service B is at 192.168.1.10:8081 and 192.168.1.11:8081"
↓
Service A calls Service B
Question 4: What is an API Gateway?
Answer: Single entry point for all microservices:
- Routing to services
- Centralized authentication
- Rate limiting
- Load balancing
- Logging/Monitoring
Client → API Gateway → Service A
→ Service B
→ Service C
Question 5: What is a Circuit Breaker?
Answer: Resilience pattern that "cuts" calls to a failing service:
States:
CLOSED → Normal calls
OPEN → Calls blocked (fallback)
HALF_OPEN → Recovery test
Prevents failure cascades.
Question 6: What is the Saga pattern?
Answer: Management of distributed transactions via a sequence of local transactions with compensations:
Order → Payment → Inventory → Shipping
↓ (failure)
Compensation: refund
Each service manages its transaction and can cancel (compensate) if necessary.
Question 7: What is CQRS?
Answer: Command Query Responsibility Segregation - separate read and write operations:
Commands (Write) → Command Service → Write DB
Queries (Read) → Query Service → Read DB (optimized)
Allows optimizing each side independently.
Question 8: What is Event Sourcing?
Answer: Store all events rather than the current state:
Events:
1. UserCreated {id: 1, name: "John"}
2. UserEmailChanged {id: 1, email: "john@new.com"}
3. UserDeleted {id: 1}
State = replay of all events
Advantages: complete audit, state reconstruction, event replay.
Question 9: What are the 12 factors of a cloud-native application?
Answer:
- Codebase: one repo, multiple deployments
- Dependencies: declared and isolated
- Config: in the environment
- Backing services: treated as attached resources
- Build, release, run: strictly separated stages
- Processes: stateless
- Port binding: self-contained
- Concurrency: horizontal scale
- Disposability: fast startup/shutdown
- Dev/prod parity: similar environments
- Logs: event streams
- Admin processes: one-off tasks
Question 10: How to manage inter-service communication?
Answer:
| Type | Protocol | Usage |
|---|---|---|
| Synchronous | REST/gRPC | Immediate response required |
| Asynchronous | RabbitMQ/Kafka | Decoupling, events |
Prefer asynchronous when possible for resilience.
Questions 11-20: Spring Cloud
Question 11: How to configure Eureka Server?
Answer:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication { }
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
Question 12: How to register a service in Eureka?
Answer:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Question 13: How to call another service with RestTemplate and load balancing?
Answer:
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Service
public class OrderService {
private final RestTemplate restTemplate;
public User getUser(Long id) {
// Use the service name, not the URL
return restTemplate.getForObject(
"http://user-service/api/users/" + id, User.class);
}
}
Question 14: How to use OpenFeign for inter-service calls?
Answer:
@EnableFeignClients
@SpringBootApplication
public class OrderApplication { }
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/api/users/{id}")
User getUser(@PathVariable Long id);
}
@Service
public class OrderService {
private final UserClient userClient;
public Order createOrder(OrderRequest req) {
User user = userClient.getUser(req.getUserId());
// ...
}
}
Question 15: How to configure Spring Cloud Config Server?
Answer:
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication { }
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/org/config-repo
default-label: main
Question 16: How does a client service use Config Server?
Answer:
# bootstrap.yml
spring:
application:
name: user-service
cloud:
config:
uri: http://localhost:8888
The service retrieves user-service.yml from the Config Server.
Question 17: How to configure Spring Cloud Gateway?
Answer:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
- Method=GET,POST
Question 18: How to add a global filter in Gateway?
Answer:
@Component
public class LoggingFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("Request: {} {}",
exchange.getRequest().getMethod(),
exchange.getRequest().getPath());
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("Response: {}",
exchange.getResponse().getStatusCode());
}));
}
@Override
public int getOrder() {
return -1;
}
}
Question 19: How to configure Resilience4j Circuit Breaker?
Answer:
resilience4j:
circuitbreaker:
instances:
userService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10000
permittedNumberOfCallsInHalfOpenState: 3
@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public User getUser(Long id) {
return userClient.getUser(id);
}
public User fallback(Long id, Exception ex) {
return new User(id, "Fallback User", "N/A");
}
Question 20: How to configure retry with Resilience4j?
Answer:
resilience4j:
retry:
instances:
userService:
maxAttempts: 3
waitDuration: 1000
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
@Retry(name = "userService")
@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public User getUser(Long id) {
return userClient.getUser(id);
}
Questions 21-30: Advanced Patterns
Question 21: How to implement a fallback with Feign?
Answer:
@FeignClient(name = "user-service", fallbackFactory = UserClientFallback.class)
public interface UserClient {
@GetMapping("/api/users/{id}")
User getUser(@PathVariable Long id);
}
@Component
public class UserClientFallback implements FallbackFactory<UserClient> {
@Override
public UserClient create(Throwable cause) {
return id -> new User(id, "Fallback", "N/A");
}
}
Question 22: How to implement rate limiting in Gateway?
Answer:
spring:
cloud:
gateway:
routes:
- id: api-route
uri: lb://api-service
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
key-resolver: "#{@userKeyResolver}"
@Bean
public KeyResolver userKeyResolver() {
return exchange -> Mono.just(
exchange.getRequest().getRemoteAddress().getHostName()
);
}
Question 23: How to refresh configuration on the fly?
Answer:
@RefreshScope
@RestController
public class ConfigController {
@Value("${app.message}")
private String message;
@GetMapping("/message")
public String getMessage() {
return message;
}
}
# Trigger the refresh
curl -X POST http://localhost:8080/actuator/refresh
Or with Spring Cloud Bus to propagate to all services.
Question 24: How to trace distributed requests?
Answer: With Micrometer Tracing (ex-Sleuth) + Zipkin:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.reporter2</groupId>
<artifactId>zipkin-reporter-brave</artifactId>
</dependency>
management:
tracing:
sampling:
probability: 1.0
zipkin:
tracing:
endpoint: http://zipkin:9411/api/v2/spans
Each request has a unique traceId propagated between services.
Question 25: How to secure inter-service communications?
Answer:
- mTLS: mutual certificates
- JWT propagation: token passed between services
- Service mesh: Istio, Linkerd
- Network policies: Kubernetes
// JWT propagation with Feign
@Configuration
public class FeignConfig {
@Bean
public RequestInterceptor authInterceptor() {
return template -> {
String token = SecurityContextHolder.getContext()
.getAuthentication().getCredentials().toString();
template.header("Authorization", "Bearer " + token);
};
}
}
Question 26: How to manage secrets in microservices?
Answer:
- Spring Cloud Config with encryption
- Vault (HashiCorp)
- Kubernetes Secrets
- AWS Secrets Manager / Azure Key Vault
# Config Server with encryption
spring:
cloud:
config:
server:
encrypt:
enabled: true
encrypt:
key: ${ENCRYPT_KEY}
Question 27: How to manage API versions?
Answer:
- URL versioning:
/api/v1/users - Header versioning:
Accept: application/vnd.api.v1+json - Query param:
/api/users?version=1
@RestController
@RequestMapping("/api/v1/users")
public class UserControllerV1 { }
@RestController
@RequestMapping("/api/v2/users")
public class UserControllerV2 { }
Question 28: How to deploy microservices with Kubernetes?
Answer:
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
spec:
replicas: 3
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
spec:
containers:
- name: user-service
image: user-service:1.0
ports:
- containerPort: 8080
env:
- name: EUREKA_SERVER
value: "http://eureka:8761/eureka"
---
apiVersion: v1
kind: Service
metadata:
name: user-service
spec:
selector:
app: user-service
ports:
- port: 80
targetPort: 8080
Question 29: How to monitor microservices?
Answer:
- Metrics: Prometheus + Grafana
- Logs: ELK Stack (Elasticsearch, Logstash, Kibana)
- Traces: Zipkin / Jaeger
- Alerting: Prometheus Alertmanager
Centralized dashboard with:
- Latency per service
- Error rate
- Throughput
- Dependencies
Question 30: What are the best practices for microservices?
Answer:
- Bounded context: one service = one business domain
- Database per service: no shared DB
- API contracts: OpenAPI/Swagger
- Idempotence: repeatable operations without effect
- Healthchecks: Actuator for each service
- Circuit breakers: protection against failures
- Async communication: prefer when possible
- Centralized logging: correlation by traceId
- Infrastructure as Code: Terraform, Helm
- Feature flags: progressive deployment
Score
| Score | Level |
|---|---|
| 27-30 | Excellent - Mastered microservices |
| 21-26 | Good - Some revisions needed |
| 15-20 | Average - Review the chapters |
| Less than 15 | Needs improvement |