Understanding Software Architecture
Refactoring a user-creation endpoint into components with clear boundaries, so new entry points, business rules, and integrations are easier to add.
What is a backend API, actually?
It’s really important to deconstruct what an API actually is. If you want to become a good software engineer, you have to stop seeing an API as a black box in your favorite language and framework that ends up returning and persisting what you want. You need to understand all the components that make it work like it does.
You may be comfortable enough with knowing that an API that receives POST /users does basically:

That’s not enough! You’re narrowed to the abstract idea of that API. If you want to make good architectural decisions, you must get the big picture.
This is what it actually looks like:

The diagram uses POST /assignments; the same path through these components applies to POST /users.
Notice that a request is handled by several components before reaching your code (the controller, service and repository).
- The HTTP request is captured by the OS and sent to the API process
- The application process then receives these requests and turns them into language-specific objects (such as a Java servlet request object).
- It’s important to understand that this object is full of HTTP and networking attributes, the actual payload and data the API needs is just a tiny portion. If you want details of an example object, check HttpServletRequest.
- Then the framework receives these objects and maps it to application code (the controller method associated with that URI, for instance).
- The controller receives the data it expects with no need to deserialize HTTP request objects. It is ready to do what it wants with the data that’s been given. In the image above, it delegates the operation to the service layer.
- The service layer applies the operation (business logic).
- The repository is responsible for interacting with persistent state, both fetching and writing data.
- If we consider the controller as the inbound connector that receives data from requests, we then consider the repository the outbound connector that triggers data exchange.
I encourage you to take every single component from that diagram and take a deeper look at what it does in your specific language, operating system and framework. It’s really interesting to see how everything connects and interacts. Nonetheless, the important lesson here is:
A system is built from cooperating pieces, each responsible for part of the behavior.
Notice that it seems pretty straightforward to understand the outwards of that architecture: the OS responsibility, the application process, the framework and why they matter. But understanding why we’re splitting our code into three more components inside our API may be unclear by now.
Each external component had well-defined boundaries (interact with the OS, HTTP object into user-defined object, etc), their scopes are well defined and we also don’t have to worry about them, they already exist. But when it comes to your API, you are the one to set these boundaries and responsibilities and things start getting fuzzy.
Why not write everything inside the controller?
Our POST /users endpoint has a well defined job: create a user.
Let’s say that this endpoint expects the following payload:
{
"name" : "John Doe",
"email": "arthurcarvalhorodrigues@gmail.com",
"age": 18,
"bio": "I like to cook and travel."
}
It’s a v1, we already know that we will be accepting more fields in the future.
We have some rules:
name,emailandagemust be given. Butbiois optional.- The email must not be already associated to an existing user.
- The user must be over 12.
That seems fairly easy. Only three checks are required. No complex logic or algorithm involved.
For a small endpoint, putting everything in one method may seem reasonable. Let’s see where that choice starts to get in the way.
@PostMapping
public ResponseEntity<?> createUser(@RequestBody Map<String, Object> payload) {
String name = (String) payload.get("name");
String email = (String) payload.get("email");
Integer age = payload.get("age") != null ? Integer.parseInt(payload.get("age").toString()) : null;
String bio = (String) payload.get("bio");
// 1. Input presence check
if (name == null || name.isBlank() || email == null || email.isBlank() || age == null) {
return ResponseEntity.badRequest().body("Name, email, and age are required.");
}
// 2. Business rule: age threshold
if (age <= 12) {
return ResponseEntity.badRequest().body("User must be older than 12.");
}
// 3. Database check: duplicate email
Integer count = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM users WHERE email = ?", Integer.class, email);
if (count != null && count > 0) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Email already registered.");
}
// 4. Persistence
jdbcTemplate.update(
"INSERT INTO users (name, email, age, bio) VALUES (?, ?, ?, ?)",
name, email, age, bio
);
return ResponseEntity.status(HttpStatus.CREATED).body("User created successfully.");
}
For the happy path, this endpoint does what we need. Input conversion and concurrent requests still need attention, but first let’s see what happens when the requirements grow. Then v2 arrives with new requirements:
- Users will also send their preferences as a list of keywords, that will be later used for user-matching by similar preferences.
- We need a CLI tool to create users in bulk from CSV files.
- We should send welcome emails for newly created users.
Let’s translate that into technical requirements:
- Since users have several preferences, we need a separate table to store them. This means that when creating a new user, we write to 2 tables. Those writes should succeed or fail together, so we need a transaction.
- The CLI tool is a completely different runtime than the API.
- Sending emails involves networking and external communication. What if an email fails?
The CLI could call the HTTP endpoint, but it cannot reuse this logic directly without depending on HTTP or duplicating the method. Adding preferences and email delivery here would mix even more responsibilities into the controller.
Let’s talk about boundaries. What is that endpoint bounded to in our own system context? Everything. It’s a god method, it handles every single step of the user creation process. It knows about:
- HTTP
- Database
- SQL
- Business Rules
- Error Handling
- Serialization
- External Systems
We say that this controller is highly coupled.
Coupling
Coupling is how much one part of the system needs to know about another.
You fix this issue by separating things into components.
Separation of concerns
Components, that’s what we’ve seen so far. We now understand the components of a backend system and also that it’s extremely important to build decoupled components.
Creating separate components that have well defined responsibilities is also called separation of concerns. The name is pretty straightforward. You separate each system concern into its own component.
So, what makes something a useful component?
It has a clear responsibility and a clear interface through which the rest of the system interacts with it.
Take the user creation endpoint. Stop thinking about Controllers, Services, Repositories and start thinking about responsibilities:
- Input Validation
- Business Logic
- Persistence
- External Communication
What should Business Logic be responsible for:
- Checking email existence
- Age Validation
- Constructing the user and deciding when a welcome notification is needed
What shouldn’t it be responsible for:
- HTTP Status Codes
- JSON
- SQL Syntax
- Network Requests
These are our boundaries. And those boundaries are defined by interfaces.
Interfaces - The Solution for Intercomponent Dependency
Architecturally, an interface describes what one component needs from another without requiring it to know how that responsibility is implemented.
Let’s say we create a component for the business logic called UserService and one for user persistence called UserRepository.
UserService needs to look for emails and create users in the database. That’s it. It doesn’t need database connections or SQL queries. It should trust that if it calls UserRepository for those two operations, they will happen. So they establish a contract through an interface.
UserService then defines that it will call UserRepository with the following methods:
- save(…) : the user will be persisted
- emailExists(email): will return true if there is a user with that email and false otherwise.
Just because it’s an interface, doesn’t mean that boundaries are good.
If you build something like a PostgresUserRepository interface with methods that require Postgres specific assumptions, then whoever calls it is still coupled to Postgres. What if you move to MySQL? Changing the repository will also require changing every service layer that calls it.
That’s why you build generic interfaces like UserRepository . If the contract preserves the behavior the service needs, moving from Postgres to MySQL can leave that service unchanged. Database migrations and differences in transaction behavior still need work, but they belong behind the persistence boundary. You can then have a PostgresUserRepository and MySQLUserRepository implementations of the UserRepository and simply change which one you’re using through dependency injection.
The lesson here is:
Make dependencies point toward stable concepts when that separation has value.
Decoupling our endpoint
Let’s take our existing endpoint and start breaking it into cohesive decoupled components. Remember our features:
bioandpreferencesare the only optional fieldsemailmust not be associated with any existing useragemust be over 12.- User creation must also work via CLI.
- Newly created users should receive a welcome email.
From that, we can create the following components:
| Component | Responsibility Category | What It Owns | What It Must NOT Know About |
|---|---|---|---|
| User Controller (HTTP Adapter) | Transport & Protocol | HTTP semantics (status codes, headers), JSON serialization, schema-level input validation (required fields present, formats). | SQL, table schemas, transactional boundaries, business rules (e.g., minimum age). |
| User CLI (Batch Adapter) | Transport & Protocol | Reading CSV rows, stream/file parsing, command-line exit codes, mapping raw strings to domain commands. | HTTP, network sockets, SQL queries. |
| User Service | Business Logic & Orchestration | Coordinating the use case, enforcing domain invariants (age limit, email uniqueness check), orchestrating side effects, transaction boundaries. | HTTP request/response objects, JSON, database connection details, third-party SMTP/API protocols. |
| User Repository (Port & Adapter) | Persistence & Storage | Abstracting persistence. Translating domain objects into two-table relational writes (users and preferences), querying for an existing email and enforcing uniqueness at write time. | HTTP semantics, business policy (e.g., deciding if age > 12 is valid), notification logic. |
| Notification Gateway (Port & Adapter) | External Communication | Abstracting external transport (SMTP, SendGrid, Amazon SES) to send emails and report delivery failures. Retry policy must be explicit. | User table schemas, HTTP controller flow, domain validation rules. |

Following the refactored flow
Both entry points now construct the same CreateUserCommand. The HTTP controller gets its values from JSON; the CLI gets them from a CSV row. Each adapter validates the input shape and converts it into the types the service expects. The service receives a command, not an HTTP request or a file handle.
The use case then has a small, explicit sequence:
- Apply the age rule and check whether the email is already registered.
- Construct the user, including any preferences.
- Persist the user and preferences as one atomic operation.
- Request a welcome notification after the database transaction commits.
- Return the created user or a meaningful application error to the caller.
The controller can map an email conflict to 409 Conflict; the CLI can report the affected CSV row. Neither needs to decide what makes a user valid. Both use the same decision in UserService.
For this use case, UserRepository.save(user) can promise to persist the user and preferences together, with its adapter implementing the transaction. If a later use case needs several repository operations in one transaction, the service can coordinate them through a unit-of-work interface. The database-specific transaction machinery stays behind that interface.
There are two details that moving code into separate classes does not solve by itself.
First, emailExists gives us an early, readable error, but two requests can both pass that check before either saves. The database still needs a unique constraint on the email. The repository adapter translates a uniqueness violation into the same application conflict the service and its callers understand.
Second, saving a user and sending an email are separate operations. If email delivery fails after the commit, the account still exists. We need to decide whether a failed welcome email is acceptable and how to retry it. Sending after commit avoids notifying a user whose transaction rolled back, but a process crash between the commit and the send can still lose the notification. If durable delivery becomes a requirement, we can store a notification job in the same transaction as the user, then let a worker deliver it. The worker also needs a strategy for retries and duplicate delivery. Clear boundaries give these decisions a home; they do not make the decisions disappear.
What becomes easier to change?
The useful result of this refactoring is that each requirement has a more predictable place to land. Let’s revisit the changes that made the original controller uncomfortable.
Add another way to create users
The CSV importer becomes an adapter around the existing use case. It parses a row, builds CreateUserCommand, calls UserService, and reports the result. We do not copy the age check, email check, or persistence flow into a second implementation.
If we later accept registrations from a message consumer, that consumer can call the same service too. These components can live in one application and share a library; separating responsibilities does not require separate network services.
Change a business rule
Suppose the minimum age changes from over 12 to over 16. We change the policy used by UserService and its tests. HTTP registrations and CSV imports then enforce the same rule without changes to SQL or email delivery.
A new input field has a wider scope: the command, adapters, domain model, and storage may all need to change. The architecture does not promise that every feature touches one file. It makes those dependencies explicit, so we can follow the change without searching through a controller that also owns unrelated details.
Evolve persistence and integrations
If preferences gain their own table or their storage layout changes, the repository adapter owns the mapping and atomic writes. The service can continue to save a user with preferences as long as that contract still fits the use case.
Changing email providers has a similar shape. We implement the existing NotificationGateway contract with the new provider and select that implementation where dependencies are wired together. Provider authentication, request formats, and network errors stay out of the user-creation policy. A move to queued delivery also needs a clear contract for what success means: accepting a job is different from delivering an email.
Test decisions without starting the whole system
We can give UserService an in-memory repository and a recording notification gateway. That lets us check that an underage user is rejected, an existing email produces a conflict, and a failed save never requests a welcome email, without running an HTTP server, database, or email provider.
Those tests do not prove that SQL transactions or provider integrations work. We still test the real repository against a database and the transport adapters against their contracts. The benefit is that a business-rule failure and an integration failure can be investigated separately.
Wrapping up
We started with a controller that knew how to receive a request, validate a user, query the database, and persist the result. Each new requirement pulled more details into the same method. After the refactoring, the user-creation use case has a clear interface, and transport, persistence, and notifications have their own responsibilities.
That gives us a practical way to evolve the system: reuse the use case when an entry point changes, update the policy when a rule changes, and work inside an adapter when an integration changes. We can reason about a smaller part of the system and test the assumptions at its boundary.
There is a cost: more components, contracts, and wiring to maintain. An interface earns its place when it separates a meaningful responsibility or a dependency we need to control. For this example, the HTTP endpoint, CSV importer, relational writes, and email provider already give us concrete reasons for those boundaries.
When the next requirement arrives, ask: which responsibility owns it, and does the existing contract still describe what we need? That question is more useful than choosing a folder structure first. It keeps the architecture connected to the behavior we are building and the changes we expect to make.