Java Interview Essentials: 10 Must‑Ask Microservice Questions

This article presents ten essential microservice interview questions, covering service registration and discovery, API gateways, fault tolerance, distributed transactions, tracing, configuration management, messaging, ID generation, and service decomposition, each explained with principles, diagrams, code snippets, and tips for impressing interviewers.

Coder Trainee
Coder Trainee
Coder Trainee
Java Interview Essentials: 10 Must‑Ask Microservice Questions

1. Why Service Registration & Discovery?

In microservice architectures, service instance IPs and ports change dynamically due to scaling or restarts. Service registration and discovery allow services to locate each other without hard‑coding addresses.

Core components

Service registration : services register their IP, port, and health status to a registry on startup.

Service discovery : consumers query the registry to obtain a list of target instances.

Heartbeat detection : the registry periodically checks health and removes unhealthy instances.

Bonus point : Mention the two discovery modes (client‑side vs server‑side) and that Nacos supports both CP and AP, showing awareness of trade‑offs.

2. Role of an API Gateway

An API gateway serves as the unified entry point for a microservice system. Its main functions are:

Routing : forward requests to the appropriate service based on the path.

Unified authentication : perform identity verification and permission checks centrally.

Rate limiting & circuit breaking : protect downstream services by controlling traffic.

CORS handling : configure cross‑origin policies in one place.

Typical request flow:

client → Gateway(:8080) ──► user‑service(:8081)
                               ├── order‑service(:8082)
                               └── product‑service(:8083)

Bonus point : Distinguish Spring Cloud Gateway (WebFlux, non‑blocking) from Zuul (Servlet‑based, blocking) and name its three core concepts (Route, Predicate, Filter).

3. Service Fault Tolerance (Circuit Breaker / Degradation / Rate Limiting)

Fault‑tolerance mechanisms protect a system when downstream services become unavailable.

Circuit Breaker : quickly fail when error rate exceeds a threshold (e.g., 50%). State machine: CLOSED → OPEN → HALF‑OPEN → CLOSED.

Degradation : return an alternative response when a circuit opens or a timeout occurs.

Rate Limiting : limit QPS to prevent overload.

Example using Sentinel:

@SentinelResource(value = "order:create", fallback = "fallback")
public Order createOrder() {
    // business logic
}

public Order fallback(BlockException ex) {
    return new Order("降级订单"); // fallback response
}

State‑machine diagram (textual): CLOSED → (error rate > threshold) → OPEN → (after half‑open period) → HALF‑OPEN → (success) → CLOSED.

Bonus point : Compare Sentinel (supports flow control, hotspot limiting, adaptive protection) with Hystrix (no longer maintained) and explain the three states of a circuit breaker.

4. Distributed Transaction Solutions

Common approaches and their trade‑offs:

2PC (Two‑Phase Commit) : strong consistency; suffers from poor performance and long lock times.

TCC (Try‑Confirm‑Cancel) : high performance and flexibility; higher development cost.

Transactional Message (RocketMQ) : decouples services, eventual consistency; adds latency.

Local Message Table : simple and reliable; introduces delay.

Saga : splits long transactions into compensable steps; requires compensation logic.

Seata provides three modes:

AT : automatic rollback via undo_log, suitable for most scenarios.

TCC : requires implementing three phases, fits high‑concurrency cases.

Saga : driven by a state machine, ideal for long‑running cross‑service processes.

Bonus point : Explain the flow of transactional messages (half‑message → local transaction → commit/rollback → check) and how AT mode uses undo_log for automatic rollback.

5. Distributed Tracing Principles

Tracing solves the difficulty of locating problems across multiple services. Core concepts:

Trace : a complete request chain identified by a globally unique Trace ID.

Span : an individual operation within the trace, identified by a Span ID.

Typical trace view:

user request → gateway → order‑service → user‑service → DB
                              │           │
                              ▼           ▼
                        comment‑service   points‑service

Tools: SkyWalking, Zipkin, Jaeger. SkyWalking’s architecture includes Agent, OAP, UI, and Elasticsearch for storage.

Bonus point : Describe SkyWalking’s agent‑less integration with Java applications.

6. Configuration Center

The config center centralizes configuration files, eliminating scattered configs, cumbersome modifications, and the need for restarts.

Architecture (Nacos example): all services retrieve their *.yml files from a central Nacos server, supporting dynamic refresh via @RefreshScope, environment isolation (namespace/group), and version rollback.

Core capabilities:

Unified management of all service configs.

Dynamic refresh without restart.

Environment isolation for dev/test/prod.

Version control and rollback.

Bonus point : Compare configuration priority (startup args > env vars > config center > local file) and differentiate Spring Cloud Config from Nacos Config.

7. Message Queue Role & Selection

MQ decouples services, smooths traffic spikes, enables asynchronous processing, and guarantees reliable delivery.

Typical features:

Decoupling: services communicate via messages instead of direct calls.

Peak‑shaving: buffers requests during traffic bursts.

Asynchronous handling: improves response times for non‑critical operations.

Reliability: persistence prevents loss.

Common comparisons:

RocketMQ : high throughput (≈100k QPS), supports ordering, transaction messages, and delayed messages.

Kafka : extremely high throughput (million‑level QPS), partition ordering, no native transaction support.

RabbitMQ : moderate throughput (≈10k QPS), supports ordering and delayed messages.

Bonus point : Explain RocketMQ’s four‑layer architecture (Producer, Consumer, NameServer, Broker) and why Kafka achieves high throughput (sequential writes, zero‑copy, batch compression).

8. Idempotency Design

Idempotency ensures that repeating an operation yields the same result as a single execution.

Common solutions:

Unique key : add a unique index (e.g., order_no) to the database.

Optimistic lock : use a version column and conditional update.

Distributed lock : acquire a Redis lock with a business identifier.

Token mechanism : generate a token before the request, store it, and validate/delete it on submission.

State machine : control state transitions so they are irreversible.

SQL examples:

-- Unique key
ALTER TABLE `order` ADD UNIQUE KEY uk_order_no (order_no);

-- Optimistic lock
UPDATE product SET stock = stock - 1, version = version + 1
WHERE id = 1 AND version = old_version;

Bonus point : Discuss how consumers achieve idempotency using message ID + Redis deduplication and the full token workflow.

9. Distributed ID Generation

Popular schemes:

Snowflake : 64‑bit IDs (1 sign bit, 41‑bit timestamp, 10‑bit machine ID, 12‑bit sequence), monotonic and DB‑independent.

UUID : globally unique but unordered, suitable for small scale.

Database auto‑increment : simple but introduces a single point of failure.

Meituan Leaf : supports both segment allocation and Snowflake.

Baidu UID : Snowflake‑based with more nodes, for massive scale.

Snowflake structure diagram:

┌───────────────────────────────────────────────────────┐
│ 1 bit │   41 bits   │ 10 bits │   12 bits            │
│ sign  │ timestamp   │ machine │ sequence            │
│ 0     │ ms‑level    │ 0‑1023  │ 0‑4095               │
└───────────────────────────────────────────────────────┘

Bonus point : Mention the clock‑rollback issue and mitigation (record last timestamp, wait or change machine ID).

10. Microservice Splitting Principles

Guidelines for carving services:

Single responsibility : each service handles one business domain.

High cohesion, low coupling : internal logic is complete; dependencies are minimal.

Data isolation : each service owns its database.

Business‑centric boundaries : split by capability, not by technology.

Team autonomy : a team owns one or more services.

When to split:

Startup phase – start with a monolith for rapid validation.

Team size > 10 – split by business domain.

Complex business – split by sub‑domains (DDD bounded contexts).

High traffic – split hot services based on QPS.

Bonus point : Reference Conway’s law (architecture mirrors team communication) and the “monolith first, then microservices” evolution path.

Series Summary

The series consists of six parts covering Java fundamentals, collections, concurrency, JVM, Spring, and finally microservices, each with ten high‑frequency interview questions, totaling 60 questions that span the core areas of Java backend interviews.

Next up: a fast‑track Git series (10 parts) announced by the author.

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.

BackendDistributed SystemsjavaMicroservicesSpringInterview
Coder Trainee
Written by

Coder Trainee

Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.

0 followers
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.