Microservice patterns
Explain API gateways, service discovery, sagas and circuit breakers.
By Invicly Tech, , in Backend Java Development. About 11 minutes to read.
In short
Microservices split a system into small services that deploy independently and own their data. That buys team autonomy and scaling, at the cost of network failures and distributed data to manage.
Explained simply
A monolith is one application that holds every feature, deployed as one unit. Microservices split the same system into several small applications, each owning one business area such as orders, payments or inventory, with its own database. They talk to each other over the network.
The main benefit is about people, not speed. Each team can change, test and deploy its own service without waiting for everyone else. You can also scale only the busy part: run ten copies of search and two of billing.
The cost is that a function call becomes a network call. Network calls can be slow, can fail, and can half-succeed. Data that used to live in one database is now spread out, so one database transaction can no longer cover a whole business action.
Microservice patterns are the standard answers to those new problems. A gateway gives clients one front door. Service discovery helps services find each other. Circuit breakers stop a failure from spreading. Sagas keep data consistent across services. Learn the problem each pattern solves, and only use it when you have that problem.
Press Play on a diagram to walk through it one step at a time.
- One deployable unit
- Simple local calls and transactions
- Easy to start and debug
- Scales as one block
- Many small deployable services
- Network calls that can fail
- Independent deploys and scaling
- Needs gateway, discovery, monitoring
- 1Closed
Calls flow normally while failures are counted
- 2Open
Failure rate too high: fail fast, use fallback
- 3Half-open
After a wait, allow a few trial calls
- 4Back to closed
Trial calls succeed; otherwise reopen
- Back to step 1
- Services react to each other's events
- No central coordinator
- Loose coupling
- Flow is hard to see as it grows
- One orchestrator sends commands
- State of each saga in one place
- Easier to monitor and debug
- Orchestrator becomes a key component
In depth
When a monolith is the better choice
Most successful systems start as a monolith, and many should stay one. A well-structured monolith, with clear modules and rules about which module may call which, gives you simple debugging, local transactions and one deployment. This is often called a modular monolith.
Split a service out when there is a real reason: a team that is blocked by others, a part with very different scaling needs, or a part that must be isolated for security or reliability. Draw the boundary around a business capability (bounded context), not a technical layer. A "database service" or a "validation service" just creates chatty calls.
A warning sign is the distributed monolith: services that must all be deployed together, share a database, or call each other in long synchronous chains. You pay the costs of both styles and get the benefits of neither.
- One database per service; others ask through its API or events
- Services should deploy independently
- Fewer, larger services are easier to start with
Gateways, discovery and central config
An API gateway is the single entry point for clients. It routes paths starting with /orders to the order service and /users to the user service, and it handles shared concerns once: validating the JWT, rate limiting, CORS and request logging. In Java the common choice is Spring Cloud Gateway; managed options include AWS API Gateway and Kubernetes ingress controllers.
Service discovery answers "where is the inventory service right now?" when instances come and go. With Spring Cloud Netflix Eureka, each instance registers itself and clients ask the registry by name. On Kubernetes you usually skip Eureka: a Service gives a stable DNS name like inventory.shop.svc.cluster.local that load balances across pods.
A config server keeps settings for every service in one place, often a Git repository, so you can change a timeout without rebuilding images. On Kubernetes, ConfigMaps and Secrets fill the same role.
- 1Client calls /orders/7
One public address
- 2Gateway
Checks the JWT, applies rate limits
- 3Discovery
Finds a healthy order-service instance
- 4Order service
Calls inventory with a timeout and breaker
- 5Response
Returns through the gateway to the client
Timeouts, retries and circuit breakers
Every remote call needs a timeout. Without one, a slow dependency ties up your threads until your own service stops answering, and the failure spreads upstream.
Resilience4j provides the standard tools. A retry repeats a call that failed for a temporary reason (default 3 attempts, 500 ms apart); only retry idempotent operations. A circuit breaker counts recent failures in a sliding window. When the failure rate passes a threshold (50% by default) it opens and fails calls instantly for a wait period (60 seconds by default), then lets a few trial calls through. A bulkhead limits how many calls may run at once, so one slow dependency cannot use every thread. A time limiter enforces the timeout for asynchronous calls.
Tune with real numbers. The defaults need 100 calls before the breaker can open, which is too many for a low-traffic service.
- resilience4j.circuitbreaker.instances.inventory.failure-rate-threshold=50
- resilience4j.circuitbreaker.instances.inventory.minimum-number-of-calls=10
- resilience4j.circuitbreaker.instances.inventory.wait-duration-in-open-state=30s
Sagas and the outbox pattern
Placing an order may need three services: reserve stock, charge the card, create the shipment. A saga runs each step as a local transaction in its own service. If a later step fails, earlier steps are undone with compensating actions, such as releasing the stock or refunding the card. Compensations must be safe to repeat.
In choreography, each service reacts to events from the others (StockReserved triggers the charge). It has no central brain, but the flow is spread across services and hard to follow. In orchestration, one orchestrator tells each service what to do and tracks the state, which is easier to monitor for longer flows.
One trap: saving to your database and then publishing an event can half-fail. The outbox pattern fixes this by writing the event to an outbox table in the same local transaction, and a separate relay (or a tool like Debezium) publishes it afterwards.
- Order saga to Inventory: Reserve 2 units1Reserve 2 units
- Inventory to Order saga: Reserved2Reserved
- Order saga to Payment: Charge 40 EUR3Charge 40 EUR
- Payment to Order saga: Card declined4Card declined
- Order saga to Inventory: Compensate: release 2 units5Compensate: release 2 units
- Inventory to Order saga: Released, order marked failed6Released, order marked failed
Learn it in 6 short steps
About 1h 20m each. Track them with a timer in your plan.
- 1Compare monoliths and microservices~1h 20m
- 2Route traffic through an API gateway~1h 20m
- 3Use service discovery and config servers~1h 20m
- 4Add circuit breakers with Resilience4j~1h 20m
- 5Coordinate transactions with sagas~1h 20m
- 6Design a small two-service system~1h 20m
Key points
- An API gateway is the single entry point that routes, authenticates and rate limits.
- Service discovery lets services find each other without hard-coded addresses.
- Circuit breakers stop one slow service from dragging down its callers.
- Sagas replace distributed transactions with local steps plus compensating actions.
Key terms
Tap a card to flip it. 0/5 known
Examples
@Service
class StockChecker {
private final InventoryClient inventory;
StockChecker(InventoryClient inventory) { this.inventory = inventory; }
@CircuitBreaker(name = "inventory", fallbackMethod = "stockUnknown")
public Stock check(String sku) {
return inventory.getStock(sku); // remote HTTP call
}
private Stock stockUnknown(String sku, Throwable ex) {
return Stock.unknown(sku); // degrade instead of failing
}
}Tune a circuit breaker for a low-traffic call
The order service calls inventory a few times per minute, so the default window of 100 calls would take hours to fill. Step 1: shrink the window and minimum calls. Step 2: treat slow calls as failures too. Step 3: shorten the open wait so recovery is noticed sooner. Step 4: check the breaker state at /actuator/circuitbreakers once register-health-indicator is on and the endpoint is exposed.
resilience4j:
circuitbreaker:
instances:
inventory:
sliding-window-size: 20
minimum-number-of-calls: 10
failure-rate-threshold: 50
slow-call-duration-threshold: 2s
slow-call-rate-threshold: 50
wait-duration-in-open-state: 30s
permitted-number-of-calls-in-half-open-state: 3
register-health-indicator: trueDesign a small two-service system
A shop needs orders and inventory. Step 1: give each its own database; order-service never reads the inventory tables. Step 2: for the user-facing stock check, order-service calls GET /stock/{sku} with a 1 second timeout and a circuit breaker, falling back to "stock unknown". Step 3: when an order is placed, order-service writes the order and an OrderPlaced row to its outbox in one transaction. Step 4: a relay publishes it to Kafka; inventory consumes it and reserves stock, emitting StockReserved or StockRejected. Step 5: order-service listens and marks the order confirmed or cancelled. Now inventory can be down for a minute and orders are still accepted.
Quick reference
- Start with a modular monolith; split a service only for a clear team or scaling reason
- One database per service; share data through APIs or events, never shared tables
- Every remote call needs a timeout; retry only idempotent operations
- Resilience4j breaker defaults: 50% failure rate, window of 100 calls, 60 s open
- On Kubernetes, Service DNS names usually replace a Eureka registry
- Saga = local transactions plus compensating actions, no distributed lock
- Outbox table + relay publishes events reliably after the local commit
Common mistakes
- Splitting into microservices too early, before the domain is understood.
- Several services sharing one database, coupling them tightly.
- Chains of synchronous calls with no timeouts.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List three signs that a system has become a distributed monolith.
- Exercise 2medium
Wrap a RestClient call to the inventory service with a retry and a circuit breaker, plus a fallback that returns an unknown stock value.
- Exercise 3hard
Design an orchestrated saga for booking a trip (hotel, flight, payment). Write the steps and the compensation for each.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Are microservices faster than a monolith?
- Not by themselves. Network calls add latency. Their gains are independent deployment and scaling of busy parts, which matter at larger team and traffic sizes.
- Do I need Eureka on Kubernetes?
- Usually not. Kubernetes Services give each service a stable DNS name and spread traffic over healthy pods.
- What replaced Netflix Hystrix?
- Hystrix is in maintenance mode. Resilience4j is the common replacement in Spring Boot, through Spring Cloud Circuit Breaker or its own starter.
- How small should a microservice be?
- Small enough for one team to own and understand, and aligned with one business capability. Size in lines of code is not a useful rule.