Backend Integration & API Engineering Review
One domain service owns the business rules while REST, GraphQL, and WebSocket adapters translate different protocols into the same authorized operations. Contract tests prove that interface changes do not silently change domain meaning.
- Explain Interface selection by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Shared domain architecture by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Contract verification by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
How to use this chapter
For Backend Integration & API Engineering Review, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the framework learning arc appropriate to this subject.
The problem this chapter solves
One domain service owns the business rules while REST, GraphQL, and WebSocket adapters translate different protocols into the same authorized operations. Contract tests prove that interface changes do not silently change domain meaning.
It minimizes translation between type declarations, runtime validation, documentation, and handler code while remaining close to the ASGI protocol.
Learning outcomes
- Explain Interface selection by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Shared domain architecture by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Contract verification by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
At startup FastAPI constructs route and dependency metadata. For a request, Starlette matches the route, FastAPI extracts values, resolves dependencies recursively, validates input with Pydantic Core, invokes the endpoint, serializes the response, and returns ASGI messages. Async endpoints run on the event loop; synchronous endpoints are delegated to a thread pool. In Backend Integration & API Engineering Review, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- A REST or GraphQL adapter validates protocol data and authenticates the caller.
- Both adapters construct the same domain command and call one service boundary.
- The service authorizes the action and protects invariants independently of transport.
- The repository commits authoritative state; a post-commit event may feed the WebSocket projection.
- Contract and integration tests compare interface behavior and failure semantics.
Memory and performance lens
Each in-flight coroutine retains its frame and referenced data but does not require an operating-system thread. Large request bodies, response models, unbounded queues, or per-request clients defeat this advantage. Pools for database and HTTP connections must be bounded and shared through lifespan state. For Backend Integration & API Engineering Review, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Backend Integration & API Engineering Review, measure request p50/p95/p99, validation failures, database query count, pool saturation, response size, and error rate by contract rather than optimizing from source-code appearance.
1. Interface selection
The Interface selection unit begins with REST resources vs GraphQL graph: Go structs compose values, interfaces describe behavior implicitly, goroutines run concurrent functions, and channels coordinate typed communication. Propagate context cancellation, define channel ownership, and keep interfaces small. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Interface selection
| Concept | Meaning | Engineering decision |
|---|---|---|
| REST resources vs GraphQL graph | Go structs compose values, interfaces describe behavior implicitly, goroutines run concurrent functions, and channels coordinate typed communication. | Propagate context cancellation, define channel ownership, and keep interfaces small. |
| request-response vs WebSocket push | Go structs compose values, interfaces describe behavior implicitly, goroutines run concurrent functions, and channels coordinate typed communication. | Propagate context cancellation, define channel ownership, and keep interfaces small. |
| Django vs FastAPI trade-offs | Go structs compose values, interfaces describe behavior implicitly, goroutines run concurrent functions, and channels coordinate typed communication. | Propagate context cancellation, define channel ownership, and keep interfaces small. |
| versioning and compatibility | Schema Registry gives events a versioned contract; Avro encodes data compactly against that schema. | Add optional fields with defaults and test producer-consumer compatibility in CI. |
Follow the request through the framework: Interface selection
REST resources vs GraphQL graph. The scheduler multiplexes goroutines; an unbuffered send synchronizes sender and receiver while a buffered send waits only when capacity is full. Closing broadcasts that no more values will arrive.
request-response vs WebSocket push. The scheduler multiplexes goroutines; an unbuffered send synchronizes sender and receiver while a buffered send waits only when capacity is full. Closing broadcasts that no more values will arrive.
Django vs FastAPI trade-offs. The scheduler multiplexes goroutines; an unbuffered send synchronizes sender and receiver while a buffered send waits only when capacity is full. Closing broadcasts that no more values will arrive.
versioning and compatibility. A wire header identifies the registered schema; readers resolve writer and reader schemas under compatibility rules.
Read these as one system: REST resources vs GraphQL graph establishes the starting contract, request-response vs WebSocket push changes how that contract is executed or represented, and versioning and compatibility exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Interface selection
1type Query { recipe(id: ID!): Recipe }2type Recipe { id: ID!, title: String!, reviews(first: Int!): ReviewConnection! }This Interface selection slice makes REST resources vs GraphQL graph observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward versioning and compatibility, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Interface selection
| Risk | Why it matters |
|---|---|
| REST resources vs GraphQL graph | Only senders should close channels; a goroutine blocked forever is a resource leak. |
| request-response vs WebSocket push | Only senders should close channels; a goroutine blocked forever is a resource leak. |
| Django vs FastAPI trade-offs | Only senders should close channels; a goroutine blocked forever is a resource leak. |
| versioning and compatibility | Changing meaning without changing a field name is still a breaking semantic change. |
Framework lab: Interface selection
- Foundation: implement or demonstrate REST resources vs GraphQL graph with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine REST resources vs GraphQL graph with request-response vs WebSocket push. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for versioning and compatibility. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Shared domain architecture
The Shared domain architecture unit begins with transport-independent service layer: A transport-independent service expresses an application use case with domain commands and results rather than HTTP, GraphQL, WebSocket, or framework request objects. Use it when several interfaces expose the same business operation or when domain behavior needs fast tests without a server. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Shared domain architecture
| Concept | Meaning | Engineering decision |
|---|---|---|
| transport-independent service layer | A transport-independent service expresses an application use case with domain commands and results rather than HTTP, GraphQL, WebSocket, or framework request objects. | Use it when several interfaces expose the same business operation or when domain behavior needs fast tests without a server. |
| Pydantic/serializer/domain model boundaries | Pydantic models parse untrusted input into typed values and serialize explicit output contracts. | Separate create, update, internal, and public schemas. |
| transaction and repository ownership | Transaction ownership belongs to the application use case that knows which state changes form one atomic business outcome; repositories perform persistence operations inside that boundary. | Use explicit ownership whenever a use case touches several rows or repository methods that must succeed together. |
| consistent authentication and object authorization | Authentication establishes the caller identity; object authorization checks whether that identity may perform this action on this resource, consistently across every transport. | Use one shared policy vocabulary and negative contract tests through REST, GraphQL, and WebSocket entry points. |
Follow the request through the framework: Shared domain architecture
transport-independent service layer. Each adapter authenticates and parses its protocol, constructs the same command, calls the service, and translates typed outcomes back to its protocol. The service owns the invariant and orchestration once.
Pydantic/serializer/domain model boundaries. Pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes.
transaction and repository ownership. The service opens a unit of work, calls one or more repositories with the same session, records outbox or idempotency state, and commits once. Exceptions roll the unit back before an adapter creates a response.
consistent authentication and object authorization. Adapters validate the credential and create a principal. The service or authorization policy evaluates action, tenant, ownership, current state, and sometimes field-level rules before the transaction changes data.
Read these as one system: transport-independent service layer establishes the starting contract, Pydantic/serializer/domain model boundaries changes how that contract is executed or represented, and consistent authentication and object authorization exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Shared domain architecture
1@router.post("/transport_independent_service_layer", status_code=202)2async def transport_independent_service_layer(payload: InputModel, service: Service = Depends(get_service)) -> OutputModel:3 result = await service.execute(payload)4 return OutputModel.model_validate(result)This Shared domain architecture slice makes transport-independent service layer observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward consistent authentication and object authorization, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Shared domain architecture
| Risk | Why it matters |
|---|---|
| transport-independent service layer | Copying validation and authorization into each adapter causes REST and GraphQL to disagree about the same action. |
| Pydantic/serializer/domain model boundaries | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. |
| transaction and repository ownership | Repositories that commit independently make partial success unavoidable and prevent reliable post-commit event publication. |
| consistent authentication and object authorization | Checking only roles, hiding UI controls, or filtering in one adapter lets another interface expose the protected object. |
Framework lab: Shared domain architecture
- Foundation: implement or demonstrate transport-independent service layer with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine transport-independent service layer with Pydantic/serializer/domain model boundaries. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for consistent authentication and object authorization. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Contract verification
The Contract verification unit begins with OpenAPI and GraphQL schema checks: Schema checks compare generated OpenAPI and GraphQL contracts against reviewed baselines and compatibility rules before interfaces are released. Version schema artifacts, review breaking and dangerous changes, and run representative clients/queries against the implementation in addition to static diffs. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Contract verification
| Concept | Meaning | Engineering decision |
|---|---|---|
| OpenAPI and GraphQL schema checks | Schema checks compare generated OpenAPI and GraphQL contracts against reviewed baselines and compatibility rules before interfaces are released. | Version schema artifacts, review breaking and dangerous changes, and run representative clients/queries against the implementation in addition to static diffs. |
| consumer-driven contract tests | Consumer-driven contract tests record the requests and responses a real consumer relies on, then verify the provider still satisfies those expectations. | Use them for independently deployed services, keep provider-state setup deterministic, and combine them with schema and a smaller number of end-to-end tests. |
| integration test database lifecycle | An integration-test database lifecycle creates an isolated schema or database, applies real migrations, loads minimal fixtures, runs the test transaction, and reliably removes or rolls back state. | Use the production database engine for database-specific behavior, generate unique worker resources, and fail closed if configuration points at non-test data. |
| performance and security baseline | A backend baseline records representative latency, throughput, query count, resource use, and essential security behavior before integration changes are accepted. | Set budgets for critical endpoints and contracts, retain raw results by commit, and investigate statistically meaningful regressions rather than one local run. |
Follow the request through the framework: Contract verification
OpenAPI and GraphQL schema checks. CI generates the schemas from the same commit, normalizes unstable ordering, computes a semantic diff, and classifies removed fields, narrowed inputs, nullability changes, enum changes, and operation changes according to consumer policy.
consumer-driven contract tests. Consumers publish versioned pacts or examples; the provider test runner provisions known state, replays interactions at the public boundary, and reports compatibility before deployment.
integration test database lifecycle. The test runner provisions a dedicated connection target, migrations establish production constraints, fixtures arrange known data, and transaction/savepoint policy isolates cases. Parallel workers require separate databases or schemas.
performance and security baseline. A repeatable harness drives authenticated success and denial cases under declared data and concurrency, while traces, database statistics, and process metrics attribute cost. Automated security checks exercise input bounds, object authorization, headers, and dependency/image findings.
Read these as one system: OpenAPI and GraphQL schema checks establishes the starting contract, consumer-driven contract tests changes how that contract is executed or represented, and performance and security baseline exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Contract verification
1type Query { recipe(id: ID!): Recipe }2type Recipe { id: ID!, title: String!, reviews(first: Int!): ReviewConnection! }This Contract verification slice makes OpenAPI and GraphQL schema checks observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward performance and security baseline, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Contract verification
| Risk | Why it matters |
|---|---|
| OpenAPI and GraphQL schema checks | A schema can remain syntactically compatible while permissions, defaults, error behavior, or field meaning changes incompatibly. |
| consumer-driven contract tests | Contracts that mirror every implementation field or omit authentication/error cases either block safe evolution or miss the failures consumers actually see. |
| integration test database lifecycle | Reusing a developer or shared database and relying on deletion order can destroy data and create nondeterministic test results. |
| performance and security baseline | A headline average without dataset, percentiles, warm-up, resource limits, authorization cases, or error rate cannot serve as a release gate. |
Framework lab: Contract verification
- Foundation: implement or demonstrate OpenAPI and GraphQL schema checks with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine OpenAPI and GraphQL schema checks with consumer-driven contract tests. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for performance and security baseline. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from dataclasses import dataclass2
3@dataclass(frozen=True)4class CreateProduct:5 name: str6 price_cents: int7
8class ProductService:9 def __init__(self, repository):10 self.repository = repository11
12 def create(self, command: CreateProduct, actor) -> dict:13 if not actor.can('product:create'):14 raise PermissionError('product:create required')15 name = command.name.strip()16 if not name or command.price_cents <= 0:17 raise ValueError('valid name and positive price required')18 return self.repository.create(name=name, price_cents=command.price_cents)19
20# REST and GraphQL adapters both construct CreateProduct and call this service.Expected result
1Every interface reaches the same authorization and validation rules; protocol adapters only translate input and output.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from dataclasses import dataclass | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | @dataclass(frozen=True) | Applies a decorator or framework annotation before the following definition is bound. |
| 4 | class CreateProduct: | Creates a class namespace and binds the resulting class object to this name. |
| 5 | name: str | Implements the next python statement in the example's data flow. |
| 6 | price_cents: int | Implements the next python statement in the example's data flow. |
| 8 | class ProductService: | Creates a class namespace and binds the resulting class object to this name. |
| 9 | def __init__(self, repository): | Defines a function; its parameters form the explicit input boundary. |
| 10 | self.repository = repository | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 12 | def create(self, command: CreateProduct, actor) -> dict: | Defines a function; its parameters form the explicit input boundary. |
| 13 | if not actor.can('product:create'): | Evaluates the condition and enters this branch only when it is truthy. |
| 14 | raise PermissionError('product:create required') | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 15 | name = command.name.strip() | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 16 | if not name or command.price_cents <= 0: | Evaluates the condition and enters this branch only when it is truthy. |
| 17 | raise ValueError('valid name and positive price required') | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 18 | return self.repository.create(name=name, price_cents=command.price_cents) | Returns the observable result to the caller and ends this invocation. |
| 20 | # REST and GraphQL adapters both construct CreateProduct and call this service. | Implements the next python statement in the example's data flow. |
Step-by-step execution
- A REST or GraphQL adapter validates protocol data and authenticates the caller.
- Both adapters construct the same domain command and call one service boundary.
- The service authorizes the action and protects invariants independently of transport.
- The repository commits authoritative state; a post-commit event may feed the WebSocket projection.
- Contract and integration tests compare interface behavior and failure semantics.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Interface selection | Only senders should close channels; a goroutine blocked forever is a resource leak. | Propagate context cancellation, define channel ownership, and keep interfaces small. |
| Shared domain architecture | Copying validation and authorization into each adapter causes REST and GraphQL to disagree about the same action. | Use it when several interfaces expose the same business operation or when domain behavior needs fast tests without a server. |
| Contract verification | A schema can remain syntactically compatible while permissions, defaults, error behavior, or field meaning changes incompatibly. | Version schema artifacts, review breaking and dangerous changes, and run representative clients/queries against the implementation in addition to static diffs. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Dual-Interface Product Service project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Interface selection: REST resources vs GraphQL graph
- To do: Interface selection: request-response vs WebSocket push
- To do: Interface selection: Django vs FastAPI trade-offs
- To do: Interface selection: versioning and compatibility
- To do: Shared domain architecture: transport-independent service layer
- To do: Shared domain architecture: Pydantic/serializer/domain model boundaries
- To do: Shared domain architecture: transaction and repository ownership
- To do: Shared domain architecture: consistent authentication and object authorization
- To do: Contract verification: OpenAPI and GraphQL schema checks
- To do: Contract verification: consumer-driven contract tests
- To do: Contract verification: integration test database lifecycle
- To do: Contract verification: performance and security baseline
Quick revision
- Interface selection: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Shared domain architecture: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Contract verification: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?