When building a backend application, handling an incoming request involves much more than writing a function that receives data and returns a response.
As an application grows, putting everything inside a single function quickly becomes difficult to maintain. Request handling, validation, business logic, database operations, authentication, and other responsibilities can become mixed together.
To avoid this, backend applications are commonly organized into different components, each responsible for a specific part of the request lifecycle.
In this article, we'll explore five important concepts:
- Handlers (Controllers)
- Services
- Repositories
- Middlewares
- Request Context
We'll also understand how these components work together when a client sends a request to a backend application.
1. Understanding the Request Lifecycle
Before looking at individual components, let's understand the overall flow of a request.
Imagine a client sends a request to retrieve a list of books from an application.
The request doesn't necessarily go directly to the database. It passes through several components, each performing a particular responsibility.
A simplified request lifecycle looks like this:
Client
|
v
Request
|
v
Middleware
|
v
Handler / Controller
|
v
Validation & Transformation
|
v
Service Layer
|
v
Repository Layer
|
v
Database
After the required operation is completed, the result travels back through the application and is eventually returned to the client.
Each component has a different responsibility:
| Component | Responsibility |
|---|---|
| Middleware | Performs operations during request processing, often before the handler |
| Handler / Controller | Handles the route, extracts request data, and prepares the response |
| Validation & Transformation | Checks and prepares incoming data |
| Service | Contains business logic |
| Repository | Handles database operations |
| Request Context | Stores information scoped to the current request |
Let's understand each component in detail.
2. Handlers (Controllers)
A handler, also commonly called a controller, is a function associated with a particular route in an application.
For example, consider these API routes:
GET /users
GET /users/123
POST /users
PUT /users/123
DELETE /users/123
Each route can be associated with a different handler.
For example:
GET /users → getAllUsers()
GET /users/123 → getUserById()
The handler is responsible for receiving the incoming request and producing the appropriate response.
What does a handler do?
A handler generally performs the following operations:
- Receives the request and response objects.
- Extracts the required information from the request.
- Passes incoming data through validation and transformation.
- Calls the appropriate service function.
- Receives the result from the service.
- Sends the response back to the client.
A handler typically works with two important objects:
- Request: Contains information sent by the client, such as route parameters, query parameters, headers, and request body.
- Response: Provides the mechanism for sending data and status information back to the client.
Extracting data from a request
The way a handler extracts data depends on the HTTP method and the type of information being sent.
GET requests
A GET request commonly uses route parameters and query parameters.
For example:
GET /users/123
GET /users?sort=asc&page=2
Here:
-
123is a route parameter. -
sortandpageare query parameters.
POST, PUT, and PATCH requests
These methods commonly carry information in the request body.
For example:
POST /users
{
"name": "Alex",
"email": "alex@example.com"
}
The handler extracts the relevant information from the request and passes it through the appropriate processing steps.
What is data binding?
The request body is commonly received in a serialized format such as JSON.
However, an application works with language-specific data structures, such as objects, structures, or models.
The process of converting incoming request data into the corresponding application-level structure is commonly called data binding.
For example, consider this JSON:
{
"name": "Alex",
"age": 24
}
It can be bound to an application-level structure:
UserInput {
name: "Alex",
age: 24
}
This makes it easier for the application to work with incoming data.
If the request body cannot be correctly interpreted or bound, the application can reject it with an appropriate client error, such as 400 Bad Request.
What should a handler not do?
A handler should not become the place where all application logic lives.
Imagine a handler that:
- Extracts request data.
- Checks business rules.
- Constructs database queries.
- Updates database records.
- Sends emails.
- Prepares the final response.
This mixes several responsibilities into one function.
As the application grows, such handlers become difficult to test, understand, and maintain.
This is why we introduce separate layers for business logic and database operations.
3. Service Layer
The service layer contains the business logic of an application.
Once incoming data has been validated and transformed, the handler passes the required information to the service layer.
The service decides what needs to happen to fulfil the requested operation.
For example, consider a user registration operation.
The handler receives the registration request and prepares the required data.
The service might then:
- Check whether the user already exists.
- Apply the required business rules.
- Coordinate the user creation process.
- Trigger other required operations.
These decisions belong to the service because they represent application behaviour rather than HTTP request handling.
Why should the service layer be independent of HTTP?
A service should not need to know whether the request came from:
- An HTTP API
- A background job
- A scheduled task
- Another internal component
Its responsibility is to execute business logic using the information provided to it.
For this reason, the service layer should remain isolated from HTTP-specific concerns.
For example, it should not need to know about HTTP request objects, response objects, route parameters, or HTTP status codes.
The handler deals with HTTP communication, while the service focuses on the actual operation.
Does every service need database access?
No.
A service may perform an operation that doesn't require interacting with a database.
For example:
- Sending an email notification
- Sending a push notification
- Performing a calculation
- Calling an external service
In these cases, the service can perform its work without using the repository layer.
However, when a service needs to read or modify application data stored in a database, it can use repository functions.
This brings us to the next layer.
4. Repository Layer
The repository layer is responsible for database operations.
It acts as an abstraction between the service layer and the database.
Instead of writing database queries directly inside services, we move those operations into repository functions.
For example, consider an application that manages books.
A repository might expose functions such as:
getAllBooks()
getBookById(id)
createBook(data)
updateBook(id, data)
deleteBook(id)
Each function is responsible for a specific data-access operation.
What does a repository function do?
A repository function generally:
- Receives the required parameters from the service.
- Constructs the appropriate database query.
- Executes the query.
- Returns the resulting data or operation result to the service.
For example:
Service:
getBookById(id)
|
v
Repository:
findBookById(id)
|
v
Database:
Execute query
|
v
Repository:
Return book data
|
v
Service:
Process result
|
v
Handler:
Send response
The service decides what data it needs and when it needs it. The repository is responsible for retrieving or modifying that data.
Why separate repositories from services?
Imagine changing the database technology or modifying the way a particular query is constructed.
If database operations are scattered throughout service functions, making these changes becomes difficult.
By keeping database operations inside repositories:
- Database-related code stays in one place.
- Services focus on business logic.
- Repository functions can be reused.
- Database operations become easier to test independently.
A service can also use multiple repository functions when an operation requires multiple database interactions.
The important idea is to keep each layer focused on its responsibility.
5. Middlewares
So far, we've discussed what happens when a request reaches a handler.
But what if we need to perform certain operations before the handler executes?
For example, imagine an application with multiple routes:
GET /books
POST /books
GET /movies
POST /movies
Suppose all these routes require authentication.
One approach would be to decode and verify the authentication token separately inside every handler.
However, this would duplicate the same logic across multiple endpoints.
Instead, we can use middleware.
Middleware consists of functions that execute as part of the request-processing pipeline, commonly before the handler.
Example: Authentication middleware
Imagine a client sends an authentication token with a request.
Before allowing the request to continue, we need to:
- Extract the token.
- Verify the token.
- Decode its contents.
- Determine whether the user is authenticated.
- Allow the request to continue or reject it.
We don't want to repeat these steps in every handler.
Instead, we define an authentication middleware and execute it before the handler.
Client
|
v
GET /books
|
v
Authentication Middleware
|
|-- Token valid? --> Continue
|
|-- Token invalid? --> Return error
|
v
Books Handler
|
v
Service
|
v
Repository
If authentication fails, the middleware can immediately send an appropriate response to the client.
If authentication succeeds, it allows the request to proceed.
What arguments does middleware receive?
A typical middleware function works with three arguments:
- Request: Contains information about the incoming request.
- Response: Allows the middleware to send a response.
- Next: Represents the next step in the request-processing pipeline.
Conceptually:
middleware(request, response, next)
The next function is particularly important.
It tells the application to continue processing the request.
For example:
function authenticationMiddleware(request, response, next):
token = extractToken(request)
if token is invalid:
return error response
next()
If the middleware calls next(), the application proceeds to the next middleware or handler.
If it sends a response instead, the request-processing pipeline can stop there.
Where are middlewares commonly used?
Middleware is useful for operations that need to happen across multiple routes or requests.
Some common examples include:
1. Security
- CORS handling
- Security headers
- Authentication
- Rate limiting
2. Logging and Monitoring
- Recording incoming requests
- Tracking response times
- Monitoring application activity
3. Global Error Handling
- Handling errors raised during request processing
- Returning consistent error responses
4. Compression
- Compressing response data to reduce its size
5. Data Parsing
- Parsing incoming request bodies
- Making request data available to subsequent components
Why does middleware ordering matter?
The order in which middleware functions execute is important.
Consider this example:
Request
|
v
Logging Middleware
|
v
Authentication Middleware
|
v
Handler
Here, logging runs before authentication.
If we change the order, the behaviour may change.
For example, if authentication middleware rejects a request before a later middleware executes, that later middleware may never get the opportunity to process it.
Similarly, middleware responsible for parsing request data must execute before components that depend on that parsed data.
Therefore, middleware should be registered in an order that matches the application's requirements.
6. Request Context
While processing a request, different components may need access to information generated by earlier components.
For example, consider the authentication middleware we discussed earlier.
After decoding and verifying the token, it may identify the authenticated user.
The handler or service may need that user's information to perform the requested operation.
Should we decode the token again inside every component?
No.
Instead, we can store the required information in the request context.
What is request context?
Request context is a mechanism for storing data associated with a particular request.
The important part is that this data is scoped to the request's lifecycle.
It exists while that request is being processed and is no longer needed once the request finishes.
For example:
Client sends request
|
v
Authentication Middleware
|
v
Decode and verify token
|
v
Identify authenticated user
|
v
Store user information
in request context
|
v
Handler and other components
can access the information
Now, subsequent components can access the authenticated user's information without repeating the authentication process.
What can request context store?
Depending on the application, request context may contain:
- Authenticated user information
- Request identifiers
- Correlation identifiers
- Request-specific metadata
- Other values needed by components during that request
For example:
Request Context:
{
userId: "123",
role: "admin",
requestId: "req-456"
}
This is only an illustrative representation. The actual structure depends on the application and programming language.
Why is request context useful?
Request context helps different components share request-specific information without repeatedly passing the same values through every function.
It is particularly useful when middleware prepares information that later components need.
One important distinction: request context is not a replacement for a database or permanent storage. It is intended for information associated with the current request.
Its lifetime is generally limited to the request cycle.
7. Putting Everything Together
Now that we understand each component individually, let's connect them through a practical example.
Imagine a client wants to retrieve a particular user's profile.
It sends:
GET /users/123
Here's what happens.
Step 1: The request reaches middleware
The authentication middleware receives the request.
It extracts and verifies the authentication token.
If the token is invalid, it can immediately return an error response.
If the token is valid, it identifies the authenticated user and stores the relevant information in the request context.
Step 2: The handler receives the request
The request reaches the handler associated with:
GET /users/123
The handler extracts the user ID from the route parameter.
It can also access the request context if it needs information about the authenticated user.
Step 3: Validation and transformation
The incoming data is checked and converted into the expected application-level format.
For example, the route parameter "123" may need to be converted into a numeric identifier.
If the input is invalid, the application returns an appropriate error response instead of continuing.
Step 4: The handler calls the service
After preparing the required input, the handler calls the relevant service function.
getUserProfile(123)
The handler doesn't need to know how the user information is stored or retrieved.
Step 5: The service applies business logic
The service determines what needs to happen to fulfil the operation.
If it requires user data from the database, it calls the appropriate repository function.
Step 6: The repository interacts with the database
The repository constructs and executes the required database query.
It retrieves the user record and returns the result to the service.
Step 7: The response is sent
The service returns the result to the handler.
The handler prepares the appropriate HTTP response and sends it back to the client.
The complete flow looks like this:
CLIENT
|
v
REQUEST
|
v
MIDDLEWARE
|
Authentication
|
Store user in context
|
v
HANDLER / CONTROLLER
|
Extract route parameters
|
v
VALIDATION & TRANSFORMATION
|
v
SERVICE LAYER
|
Business Logic
|
v
REPOSITORY LAYER
|
Database Query
|
v
DATABASE
|
Return data
|
v
SERVICE LAYER
|
v
HANDLER / CONTROLLER
|
v
RESPONSE
|
v
CLIENT
Each component performs its own responsibility, making the overall application easier to understand and maintain.
8. Understanding the Separation of Responsibilities
Let's summarize the purpose of each component.
| Component | Main responsibility | Primary focus |
|---|---|---|
| Middleware | Pre-processes requests | Cross-cutting request operations |
| Handler | Handles routes and HTTP communication | Request and response |
| Validation / Transformation | Checks and prepares input | Input correctness and format |
| Service | Executes business logic | Application behaviour |
| Repository | Performs database operations | Data access |
| Request Context | Stores request-scoped information | Sharing data during a request |
The key principle behind this architecture is separation of concerns.
Each component should have a clear responsibility rather than handling everything itself.
This makes it easier to:
- Understand the application
- Test individual components.
- Reuse business logic.
- Maintain and modify existing functionality.
- Add new features without tightly coupling unrelated parts.
- It also makes the application less dependent on a particular framework or database implementation.
What's Next?
We've now explored how a backend application organizes and processes an incoming request using handlers, services, repositories, middlewares, and request context.
But how should we design the APIs that clients interact with in the first place?
How do we choose resource names, structure endpoints, use HTTP methods, and maintain consistency across an application?
In the next article, we'll explore REST API Design, understand its fundamental principles, and learn how to design APIs that are predictable, consistent, and easy to work with.
Top comments (0)