DEV Community

Akhileswar Sathivada
Akhileswar Sathivada

Posted on

Understanding the Backend Request Lifecycle

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Each route can be associated with a different handler.

For example:

GET /users       → getAllUsers()
GET /users/123   → getUserById()
Enter fullscreen mode Exit fullscreen mode

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:

  1. Receives the request and response objects.
  2. Extracts the required information from the request.
  3. Passes incoming data through validation and transformation.
  4. Calls the appropriate service function.
  5. Receives the result from the service.
  6. 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
Enter fullscreen mode Exit fullscreen mode

Here:

  • 123 is a route parameter.
  • sort and page are query parameters.

POST, PUT, and PATCH requests

These methods commonly carry information in the request body.

For example:

POST /users
Enter fullscreen mode Exit fullscreen mode
{
  "name": "Alex",
  "email": "alex@example.com"
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

It can be bound to an application-level structure:

UserInput {
    name: "Alex",
    age: 24
}
Enter fullscreen mode Exit fullscreen mode

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:

  1. Check whether the user already exists.
  2. Apply the required business rules.
  3. Coordinate the user creation process.
  4. 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)
Enter fullscreen mode Exit fullscreen mode

Each function is responsible for a specific data-access operation.

What does a repository function do?

A repository function generally:

  1. Receives the required parameters from the service.
  2. Constructs the appropriate database query.
  3. Executes the query.
  4. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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:

  1. Extract the token.
  2. Verify the token.
  3. Decode its contents.
  4. Determine whether the user is authenticated.
  5. 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
Enter fullscreen mode Exit fullscreen mode

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:

  1. Request: Contains information about the incoming request.
  2. Response: Allows the middleware to send a response.
  3. Next: Represents the next step in the request-processing pipeline.

Conceptually:

middleware(request, response, next)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)