Polski

Article · Solution Architect – role and craft · Event-Driven Architecture

Integrations and contracts: APIs, events and cross-team dependencies without surprises

Integrations are where projects most often fall apart. How a solution architect chooses between synchronous and asynchronous communication, designs contracts in OpenAPI and AsyncAPI, versions them without breaking consumers, ensures idempotency and reliable event publishing (outbox), plans cross-team dependencies (RACI, schedule) and verifies contracts with tests (Pact) – on the example of a marketplace order system.

By · · 19 min read

Three weeks before go-live the ERP team says: "your event has the amount as a floating-point number, and we book in pennies – and by the way, our consumer will be ready in May". Anyone who has run an integration project knows this scene. Each team's code usually works – what breaks is what lies in between: contracts, dates, assumptions about availability. That is why integrations and dependencies are one of a solution architect's main duties: agreeing API and event contracts with other teams and systems, and keeping track of who delivers what to whom and when.

99.0%
availability of a chain of 10 services at 99.9% – 0.999¹⁰ – the product of availabilities
3.0
the current major version of AsyncAPI – channels and operations described separately
RFC 9457
Problem Details for HTTP APIs – a common error format

The integration map – the first artefact

Before you start discussing REST and Kafka, build an integration map: every system you talk to, one row each. For OrderFlow – the new order system of the Bazario marketplace from the previous articles – it looks like this:

SystemDirectionStyleContractOwnerDue
Channels (app, website, call-centre agent)→ OrderFlowREST, synchronousOpenAPI orderflow-apicheckout team15.12 (v1)
Payment operatorOrderFlow →REST, synchronous, 900 ms limitoperator's specificationexternal vendorexists
AntifraudOrderFlow →REST, synchronousOpenAPI fraudpayments teamexists (limit 20/s)
WMS (stock)→ OrderFlowevent, KafkaAsyncAPI stock-levelswarehouse team15.01
ERPOrderFlow →event, KafkaAsyncAPI order-eventsERP teamconsumer by the end of Q1
WMS, seller panel, notifications, warehouseOrderFlow →event, KafkaAsyncAPI order-eventsconsumer teamsbefore go-live

This table alone answers the questions that will hurt in three months: who owns the contract, where it lives and when it is needed.

Synchronous or asynchronous

The rule of thumb: ask synchronously, inform asynchronously. OrderFlow needs the payment authorisation now – without it there is no order confirmation. But the ERP, the warehouse, the seller panel and notifications don't have to answer before the customer sees the confirmation – it is enough that they learn about the order.

Diagram: Synchronous: the caller waits for the answer – and for every failure along the way
Diagram: Asynchronous: the sender publishes a fact, receivers react at their own pace
PropertySynchronous (REST, gRPC)Asynchronous (events, queues)
Temporal couplingboth sides must be up at the same timethe receiver may be temporarily down
Responseimmediate, with the resultnone – or via a separate channel (async request-reply)
Consistencyimmediate within the calleventual – with a delay
Failurespropagate up the chainbuffered in the broker
New receivera change on the sender's sidesubscribes to the topic, the sender is unchanged
Diagnosticssimple: request and responseharder: distributed tracing, consumer lag
Operational costlowbroker, schemas, outbox, deduplication

Why be so careful with chains of synchronous calls? Because the availability of a chain is roughly the product of the availabilities of its links. Ten services at 99.9% give 99.0% – more than 7 hours of downtime a month instead of 43 minutes. With dependencies at 99.5% it gets even worse:

Availability of a chain of synchronous calls – Calculation: the availability of one link raised to the power of the number of links (assuming independent failures). Fallback paths and asynchrony break this product.
Links at 99.9%Links at 99.5%
199.9 % availability99.5 % availability
299.8 % availability99 % availability
399.7 % availability98.51 % availability
499.6 % availability98.02 % availability
599.5 % availability97.52 % availability
699.4 % availability97.04 % availability
799.3 % availability96.55 % availability
899.2 % availability96.07 % availability
999.1 % availability95.59 % availability
1099 % availability95.11 % availability

Every synchronous call in a project therefore needs three things: a timeout (never wait forever), a decision about what we do when it fails (a fallback path, not an exception thrown at the customer) and often a circuit breaker that stops hammering a dependency that is down.

Contract first: OpenAPI and AsyncAPI

A contract is an agreement between teams – and like any agreement it should be made before the work, not after it. The contract-first approach looks like this:

  1. The provider drafts the contract as a pull request in the contracts repository.
  2. Consumers review it: do they have all the fields, do they understand the meaning, do the formats fit (amounts, dates, time zones).
  3. Once accepted, the contract produces a mock server – consumers can work before the provider is done.
  4. Linters (e.g. Spectral) enforce company style rules, and CI checks for breaking changes.
  5. The implementation is verified against the contract – with contract tests.

For REST the standard is OpenAPI (version 3.1 is aligned with JSON Schema 2020-12); for events and queues it is AsyncAPI (version 3.0 describes channels and operations separately). Below are complete, valid OrderFlow contracts: the order placement API with an Idempotency-Key header and errors in the Problem Details format (RFC 9457), and the OrderConfirmed event in Kafka:

OrderFlow contracts: OpenAPI 3.1 and AsyncAPI 3.0

contracts/orderflow-api.openapi.yaml
openapi: 3.1.0
info:
  title: OrderFlow Orders API
  version: 1.2.0
  description: Placing orders on the Bazario marketplace and reading their status.
servers:
  - url: https://api.bazario.example/orderflow/v1
paths:
  /orders:
    post:
      operationId: placeOrder
      summary: Place an order and receive a confirmation
      security:
        - oidc: [orders:write]
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PlaceOrderRequest'
      responses:
        '201':
          description: Order stored; the confirmation (or "payment pending") is included
          headers:
            Location:
              description: URL of the created order
              schema: { type: string, format: uri-reference }
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        '409':
          description: The same Idempotency-Key was used with a different body, or the first request is still running
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
        '422':
          description: Validation failed or an item is out of stock
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
  /orders/{orderId}:
    get:
      operationId: getOrder
      summary: Current state of an order
      security:
        - oidc: [orders:read]
      parameters:
        - name: orderId
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        '200':
          description: The order with its current status
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '404':
          description: No such order (or no access to it)
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
components:
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Client-generated UUID. Repeating the request with the same key returns the original response.
      schema: { type: string, format: uuid }
  schemas:
    Money:
      type: object
      required: [amount, currency]
      properties:
        amount: { type: string, pattern: '^\d+\.\d{2}$', examples: ['249.90'] }   # decimal as text, never float
        currency: { type: string, pattern: '^[A-Z]{3}$', examples: ['PLN'] }      # ISO 4217
    OrderLine:
      type: object
      required: [offerId, quantity]
      properties:
        offerId: { type: string, format: uuid }        # a seller's offer of a product
        quantity: { type: integer, minimum: 1, maximum: 99 }
    PlaceOrderRequest:
      type: object
      required: [customerId, lines, delivery, paymentToken]
      properties:
        customerId: { type: string, format: uuid }
        lines:
          type: array
          minItems: 1
          items: { $ref: '#/components/schemas/OrderLine' }
        delivery: { type: string, enum: [COURIER, PARCEL_LOCKER, PICKUP_POINT] }
        paymentToken: { type: string, description: Token issued by the payment operator – never a card number }
    Order:
      type: object
      required: [orderId, status, total, placedAt]
      properties:
        orderId: { type: string, format: uuid }
        status: { type: string, enum: [CONFIRMED, PAYMENT_PENDING, PENDING_REVIEW, REJECTED] }
        total: { $ref: '#/components/schemas/Money' }
        placedAt: { type: string, format: date-time }
        confirmedAt: { type: string, format: date-time }
    Problem:   # RFC 9457 Problem Details for HTTP APIs
      type: object
      properties:
        type: { type: string, format: uri-reference }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
        instance: { type: string, format: uri-reference }
  securitySchemes:
    oidc:
      type: openIdConnect
      openIdConnectUrl: https://login.bazario.example/.well-known/openid-configuration
contracts/order-events.asyncapi.yaml
asyncapi: 3.0.0
info:
  title: OrderFlow order events
  version: 1.0.0
  description: Events published by OrderFlow whenever an order is confirmed.
defaultContentType: application/json
servers:
  production:
    host: kafka.bazario.example:9093
    protocol: kafka-secure
    description: Company Kafka cluster (TLS + SASL)
channels:
  orderEvents:
    address: orders.events.v1
    messages:
      orderConfirmed:
        $ref: '#/components/messages/OrderConfirmed'
    bindings:
      kafka:
        partitions: 12
        replicas: 3
operations:
  publishOrderConfirmed:
    action: send
    summary: OrderFlow publishes every confirmed order through the transactional outbox.
    channel:
      $ref: '#/channels/orderEvents'
    messages:
      - $ref: '#/channels/orderEvents/messages/orderConfirmed'
components:
  messages:
    OrderConfirmed:
      name: OrderConfirmed
      title: Order confirmed
      headers:
        type: object
        required: [eventId, eventType, occurredAt]
        properties:
          eventId: { type: string, format: uuid, description: Unique per event – consumers deduplicate on it }
          eventType: { type: string, const: OrderConfirmed }
          occurredAt: { type: string, format: date-time }
          correlationId: { type: string }
      payload:
        $ref: '#/components/schemas/OrderConfirmedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: orderId – keeps all events of one order in order
  schemas:
    OrderConfirmedPayload:
      type: object
      required: [orderId, customerId, lines, total, paymentStatus, confirmedAt]
      properties:
        orderId: { type: string, format: uuid }
        customerId: { type: string, format: uuid, description: Internal id only – no address, phone or e-mail }
        lines:
          type: array
          items:
            type: object
            required: [offerId, sellerId, quantity]
            properties:
              offerId: { type: string, format: uuid }
              sellerId: { type: string, format: uuid }
              quantity: { type: integer, minimum: 1 }
        total:
          type: object
          required: [amount, currency]
          properties:
            amount: { type: string, pattern: '^\d+\.\d{2}$' }
            currency: { type: string, pattern: '^[A-Z]{3}$' }
        paymentStatus: { type: string, enum: [AUTHORISED, PENDING] }
        confirmedAt: { type: string, format: date-time }

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Versioning contracts
  • Idempotency
  • The outbox – events that don't get lost
  • Cross-team dependencies: who delivers what to whom and when
  • Contract tests
  • Related
  • Check yourself

Create a free account · Sign in