Skip to content
Spring Cloud Interview Mastery: Illustrated Guide to Nacos, Sentinel, Feign & Gateway

Spring Cloud Interview Mastery: Illustrated Guide to Nacos, Sentinel, Feign & Gateway

This comprehensive guide covers Spring Cloud microservices architecture, comparing Eureka, Nacos, and Consul for service discovery; details OpenFeign dynamic proxy and load balancing; explains Sentinel rate limiting, circuit breaking, and degradation; contrasts Sleuth/Zipkin with SkyWalking for distributed tracing; and provides production pitfalls and interview strategies for Spring Cloud Alibaba ecosystem.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Microservices vs Monolith Architecture

Microservices split a single application into small, independent, autonomously deployable services communicating via lightweight mechanisms (HTTP/REST). Each service runs in its own process with its own database. The article contrasts monolith (single WAR/JAR, shared database, coupled deployment) with microservices (independent processes, databases, deployment, tech stacks).

Key Comparison Dimensions

Code Organization : Monolith — single repo, high coupling; Microservices — independent repos, low coupling.

Deployment : Monolith — full redeploy for any change; Microservices — independent deployment.

Tech Stack : Monolith — uniform; Microservices — heterogeneous.

Team Structure : Monolith — by technical layer; Microservices — by business capability.

Scalability : Monolith — whole app scaling; Microservices — per-service horizontal scaling.

Fault Isolation : Monolith — single point of failure; Microservices — isolated failures.

Dev Efficiency : Monolith — fast initially, degrades; Microservices — slower start, stable later.

Ops Complexity : Monolith — low; Microservices — high (service discovery, config, tracing).

Data Consistency : Monolith — strong (local transactions); Microservices — eventual (distributed transactions).

Best Fit : Monolith — small teams, simple apps; Microservices — large complex systems, high concurrency.

Interview insight: Microservices trade complexity for flexibility. They introduce network latency, distributed transactions, service dependency management, debugging difficulty, and higher ops cost. Adopt when team >20, clear module boundaries, high concurrency/availability needs, heterogeneous tech stacks, or rapid iteration required. Stick with monolith for small teams (<10), simple stable business, short time-to-market, or insufficient ops capability.

Spring Cloud Core Components Landscape

Spring Cloud is a collection of components organized into five functional domains:

Service Governance : Eureka, Nacos, Consul, Zookeeper — service registration/discovery. Core: AP vs CP trade-offs, heartbeats, eviction. Nacos supports AP/CP switching; Eureka is AP with self-preservation (15-min, 85% threshold); Consul/Zookeeper are CP (Raft).

Fault Tolerance : Sentinel (rate limiting, circuit breaking, system load protection) and Hystrix (deprecated). Sentinel uses sliding window for rate limiting; circuit breaker strategies: error ratio, slow call ratio, exception count.

API Gateway : Spring Cloud Gateway (Netty, non-blocking, reactive) vs Zuul (deprecated). Core: routes, predicates, filters.

Messaging : Spring Cloud Stream (binder abstraction over RabbitMQ/Kafka) and Spring Cloud Bus (config refresh propagation).

Observability : Tracing (SkyWalking, Zipkin), Metrics (Prometheus+Grafana), Logs (ELK).

Service Registration & Discovery: Eureka vs Nacos vs Consul

Core Feature Comparison

CAP : Eureka — AP; Nacos — AP/CP switchable; Consul — CP.

Consistency Protocol : Eureka — peer-to-peer sync; Nacos — AP: Distro; CP: simplified Raft; Consul — Raft.

Health Checks : Eureka — client heartbeat; Nacos — TCP/HTTP/MySQL/heartbeat; Consul — TCP/HTTP/gRPC/script/TTL.

Config Center : Eureka — no; Nacos — yes (native); Consul — K/V store.

Dynamic Config Refresh : Eureka — no; Nacos — yes (push); Consul — watch needed.

Service Weight : Eureka — no; Nacos — yes; Consul — no.

Gray Release : Eureka — manual; Nacos — native; Consul — manual.

Multi-DC : Eureka — no; Nacos — yes; Consul — native.

Multi-language : Eureka — Java-centric; Nacos — multi-language SDK; Consul — multi-language SDK.

Community : Eureka — 2.x maintenance stopped; Nacos — very active; Consul — active.

Deep Dive

Eureka (AP)

Self-protection: if >85% heartbeats fail in 15 min, stop evicting instances — risks serving dead nodes.

Heartbeat: 30s interval, 90s eviction.

Cluster sync: async peer-to-peer replication, temporary inconsistency.

Deprecated; avoid for new projects.

Nacos (AP/CP)

Default temporary instances = AP (Distro protocol, high availability).

Persistent instances = CP (simplified Raft, strong consistency) — suitable for core payment services.

Health checks: temporary via client heartbeat; persistent via server-side active probes (HTTP, TCP, MySQL).

Metadata, namespaces, weight, proximity routing for gray/blue-green deployments.

Built-in config center with real-time push (<100ms).

Caveats: CP mode unavailable if majority nodes down; use 3+ node cluster; default embedded DB must be switched to MySQL in prod.

Consul (CP)

Raft-based strong consistency; leader election pauses writes.

Agent required on each host for health checks (sidecar pattern).

Native DNS interface, Service Mesh (Consul Connect), multi-datacenter federation.

Higher ops overhead; overkill for pure Java microservices.

Selection Guide

Spring Cloud Alibaba stack → Nacos.

Legacy Netflix stack → Eureka (short-term).

Multi-language, multi-DC, Service Mesh → Consul.

Strong config center need → Nacos.

Highest availability → Nacos (AP).

Strongest consistency → Consul.

Config Centers: Spring Cloud Config vs Nacos Config

Why Config Center?

Centralized management, dynamic refresh without restart, environment isolation (dev/test/prod), version control/audit.

Spring Cloud Config

Git/SVN backend; Config Server pulls and serves.

Integrates with @Value/@ConfigurationProperties.

Encryption support.

Dynamic refresh requires manual /actuator/refresh or Spring Cloud Bus (RabbitMQ/Kafka).

No UI; high latency (seconds to tens of seconds); no gray release; single-point risk.

Nacos Config

MySQL storage; cluster deployment.

Built-in UI console for edit/publish/rollback.

Real-time push via long-polling (millisecond latency).

Supports Properties, YAML, JSON, XML.

Gray release by IP/weight.

Version management & rollback.

Unified with service discovery.

Comparison

Storage : Spring Cloud Config — Git/SVN/local; Nacos Config — embedded MySQL.

Dynamic Refresh : Spring Cloud Config — manual/Bus; Nacos Config — auto push (<100ms).

Refresh Mechanism : Spring Cloud Config — polling + broadcast; Nacos Config — long-polling push.

Availability : Spring Cloud Config — low (single point); Nacos Config — high (cluster).

Version Control : Spring Cloud Config — native Git; Nacos Config — built-in.

Gray Release : Spring Cloud Config — no; Nacos Config — yes.

Ops Complexity : Spring Cloud Config — high (Git+Server+Bus); Nacos Config — low (all-in-one).

Interview Tips

Nacos client loads local snapshot at startup for resilience; long-polling tracks server MD5; getConfigAndSignListener for strong consistency.

Add @RefreshScope for dynamic bean refresh.

Best practice: hierarchy application-env-module, encrypt secrets, validate in test, approval flow for critical changes.

Remote Calls: OpenFeign & Load Balancing

OpenFeign Core

Declarative HTTP client: define interface + annotations, Feign generates JDK dynamic proxy ( FeignInvocationHandler) that intercepts calls, builds RequestTemplate via Contract parsing, encodes/decodes via Encoder/Decoder, executes via Client (default HttpURLConnection, swappable to OkHttp).

Load Balancing Integration

Feign wraps Client with load balancer: LoadBalancerFeignClient (Ribbon) or FeignBlockingLoadBalancerClient (Spring Cloud LoadBalancer). Flow: ServiceInstanceListSupplier fetches healthy instances from registry → RoundRobinLoadBalancer (default) picks one → request sent.

Load Balancer Evolution

Pre-2020.0.0: Netflix Ribbon — client-side, multiple algorithms, maintenance mode.

2020.0.0+: Spring Cloud LoadBalancer — official, lightweight, reactive support.

Algorithms

Round Robin (default) — simple, fair, ignores load.

Random — suitable for homogeneous instances.

Weighted — higher weight gets more traffic.

Least Connections — picks instance with fewest active connections.

Key Configs

spring.cloud.openfeign.client.config.order-service.connectTimeout=2000
spring.cloud.openfeign.client.config.order-service.readTimeout=5000
spring.cloud.openfeign.client.config.order-service.loggerLevel=full
spring.cloud.loadbalancer.ribbon.enabled=false
spring.cloud.openfeign.cache.ttl=30s

Interview Traps

Feign vs OpenFeign: OpenFeign adds Spring MVC annotations & auto-config.

Timeouts: configure both Feign and Ribbon/LoadBalancer.

Log levels: NONE, BASIC, HEADERS, FULL.

Custom LB: implement ReactorLoadBalancer or use @LoadBalancerClient.

API Gateway: Spring Cloud Gateway

Core Concepts

Route = ID + URI + Predicates + Filters. Predicates (AND) match requests; Filters modify request/response.

Predicates

Path=/user/**

, Method=GET,POST, Header=token,regex, Query=name,jack.*, After=2026-01-01T00:00:00+08:00[Asia/Shanghai], Cookie=chocolate,ch.p, Host=**.api.example.com, Weight=group1,8 for canary.

Filters

GatewayFilter (per-route) : configured in route filters. Examples: StripPrefix=1, AddRequestHeader=X-Color,blue, RequestRateLimiter, CircuitBreaker, Retry.

GlobalFilter (all routes) : auto-applied, ordered by @Order. Built-ins: NettyRoutingFilter (HTTP call), ReactiveLoadBalancerClientFilter (LB for lb://), NettyWriteResponseFilter.

Request Flow

RoutePredicateHandlerMapping

matches predicates → best route selected → FilteringWebHandler executes merged filter chain (global + route) sorted by Order.

Custom Filters

// Global auth filter
@Component
@Order(-1)
public class AuthGlobalFilter implements GlobalFilter {
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String token = exchange.getRequest().getHeaders().getFirst("token");
    if (path.startsWith("/user/login")) return chain.filter(exchange);
    if (invalid(token)) { exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); }
    ServerHttpRequest mutated = exchange.getRequest().mutate().header("userId", JwtUtil.getUserId(token)).build();
    return chain.filter(exchange.mutate().request(mutated).build());
  }
}

// Local filter factory
@Component
public class LogGatewayFilterFactory extends AbstractGatewayFilterFactory<LogGatewayFilterFactory.Config> {
  public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
      long start = System.currentTimeMillis();
      return chain.filter(exchange).then(Mono.fromRunnable(() ->
        System.out.println("Path: " + exchange.getRequest().getURI() + ", latency: " + (System.currentTimeMillis()-start) + "ms")));
    };
  }
  static class Config {}
}

Common Pitfalls

Gateway (Netty, non-blocking) vs Zuul (Servlet, blocking).

Filter order: global + local merged, ascending Order.

CORS centralized in Gateway.

Exception handling separate from downstream.

Gray release via Weight predicate + header propagation.

Service Protection: Sentinel Rate Limiting, Circuit Breaking, Degradation

Concept Distinction

Rate Limiting : Goal — protect self from overload; Trigger — QPS/thread count exceeded; Effect — reject/queue requests.

Circuit Breaking : Goal — protect self from slow dependencies; Trigger — downstream error/slow ratio high; Effect — fast fail, skip remote call.

Degradation : Goal — provide fallback result; Trigger — after limit/break/exception; Effect — return default/empty/cache.

Mnemonic: Limit = "I'll take less"; Break = "You're down, I'll stop calling"; Degrade = "Here's a fallback".

Rate Limiting

Sliding window (default 1s split into 10 slots of 100ms). Count passes per slot; sum = current QPS. If > threshold → block. Supports associate/link flow control, uniform queuing (leaky bucket effect).

Circuit Breaking

State machine: CLOSED → OPEN (tripped) → HALF_OPEN (probe) → CLOSED. Strategies:

Error ratio: exceptions/total > threshold.

Exception count: exceptions in 1min > threshold.

Slow call ratio: latency > maxRT ratio > threshold.

HALF_OPEN allows probe requests to verify recovery, preventing flapping.

Degradation

Triggered by BlockException ( FlowException / DegradeException). Handled via @SentinelResource(blockHandler=..., fallback=...) or framework adapters. Fallback returns cached data, empty object, or friendly message.

@SentinelResource(value="getOrder", blockHandler="handleFlowControl")
public Order getOrder(Long id) { return orderService.getById(id); }
public Order handleFlowControl(Long id, BlockException ex) { return Order.EMPTY; }

Advanced Features

SPI extension for custom slots.

Cluster rate limiting for distributed precision.

Hot parameter limiting (e.g., specific item ID).

Real-time dashboard.

Rule persistence to Nacos/Apollo.

Distributed Tracing: Sleuth+Zipkin vs SkyWalking

Core Concepts

TraceID : global request ID.

SpanID : per-service call ID.

ParentSpanID : builds call tree.

Sleuth + Zipkin

Sleuth: auto-injects TraceID/SpanID into logs and HTTP headers ( X-B3-TraceId). Zero code change.

Zipkin: collects, stores, visualizes traces. Reporters: HTTP, RabbitMQ, Kafka (async for high throughput). Storage: Elasticsearch recommended.

Pros: simple, Spring-native, low deploy cost.

Cons: only tracing; no metrics, JVM, slow SQL, alerts; UI basic; sampling trade-off.

SkyWalking

Java Agent ( -javaagent:skywalking-agent.jar) uses Byte Buddy for bytecode enhancement — zero code invasion.

Auto-instruments Spring MVC, Dubbo, Feign, JDBC, MQ, etc.

OAP (Observability Analysis Platform) computes metrics, triggers alerts.

Storage: Elasticsearch.

Multi-language: Java, .NET, Node.js, Go, Python; integrates with Istio/Envoy.

Features: global topology, slow SQL capture, built-in dashboards (QPS, RT, JVM, GC), alerting (Webhook, DingTalk, Lark).

Overhead ~5%.

Comparison

Tracing : Both ✅

Metrics/JVM : Sleuth+Zipkin ❌; SkyWalking ✅

Slow SQL : Sleuth+Zipkin ❌; SkyWalking ✅

Topology : Sleuth+Zipkin ❌; SkyWalking ✅

Alerting : Sleuth+Zipkin ❌; SkyWalking ✅

Code Invasion : Sleuth+Zipkin low (deps); SkyWalking none (agent)

Deploy Complexity : Sleuth+Zipkin low; SkyWalking medium-high (ES)

Tech Stack : Sleuth+Zipkin Spring Cloud only; SkyWalking polyglot

Selection

Small team, pure Spring Cloud, existing ELK → Sleuth+Zipkin.

Polyglot, need full APM (metrics, alerts, topology) → SkyWalking.

Spring Cloud Alibaba Ecosystem

Core Components

Nacos : Service registry + config center (AP/CP switch, real-time push, UI, namespaces/groups/clusters).

Sentinel : Flow control, circuit breaking, system protection, hot params, dashboard, cluster limiting.

Seata : Distributed transactions — AT (auto compensation), TCC (manual), SAGA (long), XA (strong).

RocketMQ : Messaging — sequential, transaction, delay messages; reliability via acks/persistence.

Dubbo : High-performance RPC — multiple protocols (Dubbo, HTTP, gRPC), rich LB strategies.

Gateway : Unified entry, routing, filtering, auth.

SkyWalking : Full-stack observability.

XXL-Job : Distributed task scheduling.

Collaboration

Nacos (coach) directs service locations; Sentinel (defender) guards traffic; Seata (referee) ensures data consistency; RocketMQ (passer) decouples async; Dubbo/Feign (striker) executes calls; Gateway (gate) exposes entry; SkyWalking (doctor) monitors health.

Production Tips

Version alignment: Spring Cloud Alibaba 2023.0.1+ with matching Spring Boot.

Nacos: cluster + MySQL persistence.

Sentinel: persist rules to Nacos.

Seata AT: ensure rollback column indexes.

Selective adoption: don't force full stack if existing middleware (e.g., RabbitMQ) works.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MicroservicesService DiscoveryNacosDistributed TracingSentinelSpring CloudOpenFeignSpring Cloud AlibabaCircuit BreakerSpring Cloud Gateway
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.