Service boundaries and contracts
What you will learn
A microservice owns a capability and its data, and is independently deployable. Unlike a modular monolith, calls between services can fail independently, even after the receiving service has changed state. Design the contract and failure behavior before introducing a network.
- Compare modular monoliths with independently deployed services.
- Define a versioned contract and distinguish rejection from an unknown outcome.
- Choose synchronous or asynchronous communication based on the use case.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Standalone Java 21 models; the companion Spring Cloud configuration is source-reviewed, not executed.
Distinguish rejection from an unknown result
public class Main { enum Reply { ACCEPTED, REJECTED, TIMEOUT } static String action(Reply r) { return switch(r) { case ACCEPTED -> "confirmed"; case REJECTED -> "declined"; case TIMEOUT -> "reconcile"; }; } public static void main(String[] args) { for (Reply r : Reply.values()) System.out.println(action(r)); }}Expected output:
confirmeddeclinedreconcileThe third result requires querying or retrying with the same operation identity. It must not be treated as a business rejection.
Choose the boundary
Start with a modular monolith when one deployment meets the ownership and scaling needs. Split when independent delivery, isolation or workload scaling outweigh network latency, operational costs and distributed consistency. A service owns its data; other services use contracts, not its tables. Avoid splitting a single invariant across services without a consistency design.
Communication and contracts
REST exposes resource operations using HTTP semantics; gRPC uses a typed RPC contract, typically Protocol Buffers over HTTP/2. Both can be synchronous from the caller perspective. Messaging separates send time from processing time, but adds delivery, ordering and deduplication concerns. Define timeouts, error shapes, authorization, version compatibility and units. Add optional fields before removing existing ones; clients should tolerate unknown fields where the contract allows it. A gateway routes and applies edge policy, not every domain rule. Discovery resolves logical service names to endpoints; stale registry entries and DNS results are possible.
Partial failure and tracing
Text diagram: Order → Inventory reservation API; Order → Billing authorization API. Each arrow crosses a failure boundary. If inventory commits but the reply is lost, the caller does not know the result. A timeout is not a rejection. A trace ID connects observations across boundaries; it is not a credential or an idempotency key. Propagate tracing metadata using trusted instrumentation, and never log tokens or personal data.
Adapt a versioned result
public class Main { record V2(String sku, int available, String location) {} record V1(String sku, int available) {} static V1 adapt(V2 v) { return new V1(v.sku(), v.available()); } public static void main(String[] args) { System.out.println(adapt(new V2("PEN", 3, "warehouse-a"))); }}Expected output:
V1[sku=PEN, available=3]The local adapter preserves the original meaning while discarding a new optional field. This is a Java model of compatibility, not a JSON schema test.
Route only a known service
public class Main { static String route(String service) { return java.util.Map.of("inventory", "local-inventory", "billing", "local-billing") .getOrDefault(service, "unavailable"); } public static void main(String[] args) { System.out.println(route("inventory")); System.out.println(route("unknown")); }}Expected output:
local-inventoryunavailableFixed logical names model discovery without resolving hosts or contacting external services. Do not accept arbitrary user-supplied upstream URLs.
Common mistakes
Do not interpret HTTP success as proof that downstream asynchronous work completed. Do not bypass a service API to change another service’s database. Design explicit pending and unknown states.
Practice
Implement an adapter for a billing reply with cents, currency and an optional diagnostic label. Return only cents for USD, reject other currencies. Print 1250 then rejected.
Expected output:
1250rejectedCompare with the manual review criteria.
Further reading: Cloud · Idempotency. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Service boundaries and contracts — knowledge check
Distributed systems and resilience reasoning.
What distinguishes a service from an internal module?
A timeout follows a reservation request. What is known?
What is a safe additive contract change?
What should own inventory writes?
What does a trace ID identify?