Skip to main content

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:

MonolithMicroservices
Single applicationIndependent services
One databaseDB per service
Global deploymentIndependent deployment
Global scalingScaling per service
Simple at firstComplex at first
Strong couplingLoose 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:

  1. Codebase: one repo, multiple deployments
  2. Dependencies: declared and isolated
  3. Config: in the environment
  4. Backing services: treated as attached resources
  5. Build, release, run: strictly separated stages
  6. Processes: stateless
  7. Port binding: self-contained
  8. Concurrency: horizontal scale
  9. Disposability: fast startup/shutdown
  10. Dev/prod parity: similar environments
  11. Logs: event streams
  12. Admin processes: one-off tasks

Question 10: How to manage inter-service communication?

Answer:

TypeProtocolUsage
SynchronousREST/gRPCImmediate response required
AsynchronousRabbitMQ/KafkaDecoupling, 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:

  1. mTLS: mutual certificates
  2. JWT propagation: token passed between services
  3. Service mesh: Istio, Linkerd
  4. 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:

  1. Spring Cloud Config with encryption
  2. Vault (HashiCorp)
  3. Kubernetes Secrets
  4. 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:

  1. URL versioning: /api/v1/users
  2. Header versioning: Accept: application/vnd.api.v1+json
  3. 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:

  1. Metrics: Prometheus + Grafana
  2. Logs: ELK Stack (Elasticsearch, Logstash, Kibana)
  3. Traces: Zipkin / Jaeger
  4. Alerting: Prometheus Alertmanager

Centralized dashboard with:

  • Latency per service
  • Error rate
  • Throughput
  • Dependencies

Question 30: What are the best practices for microservices?

Answer:

  1. Bounded context: one service = one business domain
  2. Database per service: no shared DB
  3. API contracts: OpenAPI/Swagger
  4. Idempotence: repeatable operations without effect
  5. Healthchecks: Actuator for each service
  6. Circuit breakers: protection against failures
  7. Async communication: prefer when possible
  8. Centralized logging: correlation by traceId
  9. Infrastructure as Code: Terraform, Helm
  10. Feature flags: progressive deployment

Score​

ScoreLevel
27-30Excellent - Mastered microservices
21-26Good - Some revisions needed
15-20Average - Review the chapters
Less than 15Needs improvement

Back to Module 13