Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 9

Request Lifecycle in Backend Applications

Recommended resources

Welcome to the third lesson in our module on Core Backend Components. In our last session, we followed an incoming request to the edge of our system, where a reverse proxy intelligently routed it to a specific backend application server. Now, we'll step inside that server and trace the request's journey through the application itself.

Your goal for this lesson is to describe how a backend application processes an incoming request, moving it through stages of validation, business logic, and finally, response generation. For a QA professional aiming to understand system architecture, this internal flow is paramount. It reveals the precise locations where different types of logic are executed, which is essential for designing targeted tests, diagnosing bugs, and evaluating the system's overall robustness and maintainability.

The Application's Internal Pipeline

Once a request arrives from the reverse proxy, it doesn't just land in a random piece of code. It enters a well-defined, structured pipeline. Most modern backend frameworks organize this pipeline using a layered architecture to enforce a crucial principle: separation of concerns. This means each part of the application has a single, well-defined responsibility.

A common and highly effective pattern for this is the three-layer architecture: Controller, Service, and Repository.

This diagram illustrates the typical stages an incoming request passes through within a backend application. The request is handled first by cross-cutting concerns and controllers, then processed by business service classes, which interact with repositories for data access, before a response is generated.

Let's break down this journey step-by-step, starting from the moment the application first receives the HTTP request.


The Entry Point: Middleware and Routing

Before your application's primary logic even sees the request, it often passes through a series of pre-processing steps handled by middleware. Think of middleware as a chain of guards and helpers standing between the server's front door and the main office. Each one inspects or modifies the request before passing it to the next in line.

What is Middleware and HTTP Request Pipeline | Asp.Net Core Web API tutorial

The video "What is Middleware and HTTP Request Pipeline" from WebGentle provides an excellent conceptual overview of this pipeline model. Although the examples are from ASP.NET Core, the principles are universal across backend frameworks.

Watch the following segments to understand the core idea: The introduction explains the concept of a pipeline that processes requests before they hit the main application logic. The next part illustrates how requests flow forward through the middleware chain and how responses flow back. The definition formally defines middleware and notes that the order is critical. Finally, the examples show how middleware is used for cross-cutting concerns like routing, authentication, and exception handling.

As the video explains, middleware is perfect for handling tasks that apply to many different requests, such as:

  • Logging: Recording details of every incoming request.
  • Authentication: Verifying the user's identity via a token or session cookie.
  • CORS (Cross-Origin Resource Sharing): Handling security headers for web browser clients.
  • Error Handling: Catching any unhandled errors and formatting a consistent error response.

After passing through this initial gauntlet, the request reaches a special piece of middleware: the router. The router's job is to inspect the request's URL and HTTP method (e.g., GET /users/123) and decide which specific piece of your code should handle it. This designated code is typically a method within a Controller.


The Layered Architecture: A Hospital Analogy

To understand the roles of the Controller, Service, and Repository layers, it's helpful to use an analogy. The following article presents a powerful one: a hospital emergency room.

Anatomy of Back-end Frameworks. How Controller, Service & Repository layers work in Production?

This LinkedIn article by Marjan Rafi uses a clear analogy to explain why separation of concerns is vital for production systems.

Please read the introduction and the section titled The Hospital Analogy. This will give you a strong mental model for the roles of each layer.

Keeping this analogy in mind—Receptionist (Controller), Doctor (Service), and Lab (Repository)—let's formally define the contract for each layer.

Layer 1: The Controller (The Receptionist)

The Controller is the HTTP-aware entry point for a specific request. Its job is to manage the interaction with the web, not to perform any core business logic.

  • Responsibilities:
    1. Request Handling: It takes the raw HTTP request, extracts relevant data from the URL path, query parameters, headers, and body.
    2. Deserialization: It converts the request body (e.g., JSON) into structured data objects that the rest of the application can use.
    3. Input Validation (Syntactic): It performs initial checks on the data. Is an email field actually a valid email format? Is a required field present? This is trivial or superficial validation.
    4. Delegation: It calls the appropriate method in the Service layer, passing the validated data.
    5. Response Generation: It takes the result from the Service layer, packages it into an HTTP response with the correct status code (e.g., 200 OK, 201 Created, 404 Not Found) and body, and sends it back to the client.

The key takeaway is that the Controller acts as a thin adapter between the messy world of HTTP and the clean, organized world of your business logic.

Layer 2: The Service Layer (The Doctor)

This is the heart of your application. The Service layer contains the core business logic—the rules and processes that define what your application actually does. It is completely unaware of HTTP; it just works with data and performs tasks.

  • Responsibilities:
    1. Business Rule Enforcement (Semantic Validation): Unlike the Controller's simple validation, the Service layer enforces rules that depend on the application's state. For example, "Is this user's subscription level allowed to create a new project?" or "Is there enough stock to fulfill this order?". This often requires fetching data from the database.
    2. Orchestration: It coordinates operations across different parts of the system. A single business process, like "register user," might involve creating a user record, setting up a profile, and sending a welcome email. The service layer orchestrates all these steps.
    3. Transaction Management: It ensures that a series of related data changes happens atomically (all or nothing). If creating a user's profile fails, the service layer should ensure the initial user record is also rolled back.
    4. Calling the Repository: It communicates with the data layer (the Repository) to fetch or save information.

Distinguishing between the Controller's validation and the Service's business rules is a crucial architectural concept. The following video explains this distinction clearly.

What are Business Rules? It's not this.

This video, "What are Business Rules? It's not this." from the CodeOpinion channel, provides a sharp analysis of the difference between trivial validation and genuine business rules.

Focus on these key segments: The introduction frames the core problem. Trivial validation is defined as static, deterministic, and related to input/output formats. This belongs closer to the edge of your application (like the Controller). Business rules are defined as evolving, expanding, and often based on the system's current state. This is the domain of the Service layer. The explanation of why checking inventory is a business rule (it can evolve, depends on state) is a perfect example. The summary reinforces why separating these concerns makes the codebase cleaner and more maintainable.

Layer 3: The Repository (The Lab / Medical Records)

The Repository layer's sole responsibility is data persistence. It's an abstraction layer that isolates the Service layer from the specifics of the database (or any other data store).

  • Responsibilities:
    1. Data Access Logic: It contains the code to query the database (e.g., writing SQL queries or using an ORM like Entity Framework or Hibernate).
    2. Data Mapping: It translates data between the format used by the database (e.g., rows and columns) and the domain objects used by the Service layer.

The Service layer asks the Repository, "Get me the user with ID 5," and the Repository is responsible for figuring out how to do that. This separation means you could, in theory, swap your database from PostgreSQL to MongoDB by only changing the Repository layer, without touching any business logic in the Service layer.

For a definitive guide on the contract of each layer, refer back to the "Anatomy of Back-end Frameworks" article.

Anatomy of Back-end Frameworks. How Controller, Service & Repository layers work in Production?

This article provides a strict definition of what belongs in each layer. Mastering this is key to architectural discussions.

Please read the section The Layer Contract very carefully. Pay close attention to the "What belongs here" and "What never belongs here" lists for the Controller, Service, and Repository layers. As a QA engineer, the "test signal" for each layer is particularly insightful.


A Complete Example: User Signup

Let's trace a POST /api/signup request through this entire pipeline to solidify the concept.

This diagram shows the flow of a user signup request, from the client through the application server and its internal components, to the database management system and persistent storage.
  1. Incoming Request: A client sends a POST request to /api/signup with a JSON body containing {"name": "Bayo", "email": "bayo@example.com", "password": "..."}.
  2. Middleware Pipeline:
    • LoggingMiddleware logs the request details.
    • BodyParserMiddleware reads the request body and parses the JSON.
    • Router sees POST /api/signup and directs the request to the signup method on the AuthController.
  3. AuthController.signup() (Controller):
    • Validation: Checks if email is a valid email format and if password meets complexity requirements (e.g., min 8 characters).
    • Delegation: If validation passes, it calls authService.registerUser({name, email, password}).
  4. AuthService.registerUser() (Service):
    • Business Rule: Calls userRepository.findByEmail(email) to check if a user with that email already exists. This is semantic validation—it depends on the current state of the database.
    • If a user exists, it throws an error (e.g., UserAlreadyExistsError).
    • Business Logic: If no user exists, it hashes the password using a secure algorithm.
    • Orchestration: It calls userRepository.createUser({name, email, hashedPassword}) to save the new user.
    • Side Effect: It might call a notificationService to enqueue a welcome email.
    • It returns the newly created user object (importantly, without the password hash).
  5. UserRepository (Repository):
    • The findByEmail method executes a query like SELECT * FROM users WHERE email = ?.
    • The createUser method executes INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?).
  6. Response Flow:
    • The user object is returned from the AuthService to the AuthController.
    • The AuthController creates a 201 Created HTTP response, placing the user object in the response body.
    • The response travels back through the middleware (e.g., for logging) and is sent to the client.

This clear separation makes the system easier to test—you can test the AuthService's logic by mocking the repository, without needing a real database. It also makes it easier to maintain and scale.


Conclusion

In this lesson, we've journeyed deep inside a backend application to see how it handles a request. We've moved from the server's entry point through a pipeline of middleware and into a structured, layered architecture.

Here are your key takeaways:

  • Request Pipeline: Incoming requests are processed by a chain of middleware that handles cross-cutting concerns like logging, authentication, and error handling before the main logic is executed.
  • Layered Architecture: A robust backend separates concerns into distinct layers, most commonly the Controller, Service, and Repository.
  • Controller: Manages HTTP interaction, performs basic input validation, and delegates to the service layer. It's the "Receptionist."
  • Service Layer: Contains the core business logic, orchestrates tasks, and enforces rules that depend on the application's state. It's the "Doctor."
  • Repository Layer: Manages all communication with the data store, abstracting away the details of persistence. It's the "Lab."
  • Separation of Concerns: This principle is not just an organizational preference; it is a survival mechanism for building testable, maintainable, and scalable systems.

You now have a clear mental model for the lifecycle of a request both outside and inside an application server. In our next lesson, we will discuss a fundamental design choice that profoundly impacts how these applications are built and scaled: the difference between stateful and stateless server design.