# Communication: Sync, Async and Contracts — Monolith vs Microservices

Source: https://www.skillbyai.com/en/monolith-microservices/d-comm

> Choose between synchronous and asynchronous communication and version APIs safely.

## How services talk

**Synchronous** communication (REST over HTTP, **gRPC** with Protocol Buffers, GraphQL at the edge) suits queries and commands where the caller needs an answer now; it is simple to reason about but creates temporal coupling: if the callee is down, the caller fails. **Asynchronous** communication (message queues, event streams) decouples services in time and suits notifications, propagation of facts and long-running work, at the cost of eventual consistency and harder debugging. Most systems use both: sync for reads and user-facing decisions, async for side effects and data propagation. Either way, the **contract** (API schema or event schema) is what lets teams deploy independently, so treat it seriously: document it with **OpenAPI**, protobuf files or AsyncAPI; make changes **backward compatible** (add optional fields, never rename or remove without a deprecation period); version breaking changes; and verify with **consumer-driven contract tests**.

## A backward-compatible API change

New clients use the new field; old clients keep working because nothing was removed.

```yaml
# OpenAPI excerpt for GET /orders/{id}
components:
  schemas:
    Order:
      type: object
      required: [id, status, totalMinor, currency]
      properties:
        id:          { type: string }
        status:      { type: string, enum: [PLACED, PAID, SHIPPED, CANCELLED] }
        totalMinor:  { type: integer }
        currency:    { type: string }
        # added in v1.4 - optional, so existing clients are unaffected
        estimatedDelivery:
          type: string
          format: date
# breaking changes (rename, remove, change type) -> new version (/v2) + deprecation period
```

## Adding enum values can break clients

A client with a strict `switch` over `status` may crash on a new value such as `RETURNED`. Document that clients must tolerate unknown enum values, and test for it.

**Quiz:** Which change to a public API response is usually backward compatible?

- [x] Adding a new optional field
- [ ] Renaming a required field
- [ ] Removing a field clients use
- [ ] Changing a field from integer to string

*Answer:* Adding a new optional field. Adding optional fields lets old clients ignore them while new clients use them.
